OSDN Git Service

Fix typos
[bytom/bytom.git] / node / node.go
1 package node
2
3 import (
4         "context"
5         "net/http"
6         _ "net/http/pprof"
7         "time"
8
9         log "github.com/sirupsen/logrus"
10         cmn "github.com/tendermint/tmlibs/common"
11         dbm "github.com/tendermint/tmlibs/db"
12         browser "github.com/toqueteos/webbrowser"
13
14         "github.com/bytom/accesstoken"
15         "github.com/bytom/account"
16         "github.com/bytom/api"
17         "github.com/bytom/asset"
18         "github.com/bytom/blockchain/pseudohsm"
19         "github.com/bytom/blockchain/txfeed"
20         cfg "github.com/bytom/config"
21         "github.com/bytom/consensus"
22         "github.com/bytom/database/leveldb"
23         "github.com/bytom/env"
24         "github.com/bytom/mining/cpuminer"
25         "github.com/bytom/mining/miningpool"
26         "github.com/bytom/netsync"
27         "github.com/bytom/protocol"
28         "github.com/bytom/protocol/bc"
29         "github.com/bytom/types"
30         w "github.com/bytom/wallet"
31 )
32
33 const (
34         webAddress               = "http://127.0.0.1:9888"
35         expireReservationsPeriod = time.Second
36         maxNewBlockChSize        = 1024
37 )
38
39 type Node struct {
40         cmn.BaseService
41
42         // config
43         config *cfg.Config
44
45         syncManager *netsync.SyncManager
46
47         evsw types.EventSwitch // pub/sub for services
48         //bcReactor    *bc.BlockchainReactor
49         wallet       *w.Wallet
50         accessTokens *accesstoken.CredentialStore
51         api          *api.API
52         chain        *protocol.Chain
53         txfeed       *txfeed.Tracker
54         cpuMiner     *cpuminer.CPUMiner
55         miningPool   *miningpool.MiningPool
56         miningEnable bool
57 }
58
59 func NewNode(config *cfg.Config) *Node {
60         ctx := context.Background()
61         initActiveNetParams(config)
62         // Get store
63         coreDB := dbm.NewDB("core", config.DBBackend, config.DBDir())
64         store := leveldb.NewStore(coreDB)
65
66         tokenDB := dbm.NewDB("accesstoken", config.DBBackend, config.DBDir())
67         accessTokens := accesstoken.NewStore(tokenDB)
68
69         // Make event switch
70         eventSwitch := types.NewEventSwitch()
71         if _, err := eventSwitch.Start(); err != nil {
72                 cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
73         }
74
75         txPool := protocol.NewTxPool()
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                 // Clean up expired UTXO reservations periodically.
109                 go accounts.ExpireReservations(ctx, expireReservationsPeriod)
110         }
111         newBlockCh := make(chan *bc.Hash, maxNewBlockChSize)
112
113         syncManager, _ := netsync.NewSyncManager(config, chain, txPool, newBlockCh)
114
115         // run the profile server
116         profileHost := config.ProfListenAddress
117         if profileHost != "" {
118                 // Profiling bytomd programs.see (https://blog.golang.org/profiling-go-programs)
119                 // go tool pprof http://profileHose/debug/pprof/heap
120                 go func() {
121                         http.ListenAndServe(profileHost, nil)
122                 }()
123         }
124
125         node := &Node{
126                 config:       config,
127                 syncManager:  syncManager,
128                 evsw:         eventSwitch,
129                 accessTokens: accessTokens,
130                 wallet:       wallet,
131                 chain:        chain,
132                 txfeed:       txFeed,
133                 miningEnable: config.Mining,
134         }
135
136         node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
137         node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
138
139         node.BaseService = *cmn.NewBaseService(nil, "Node", node)
140
141         return node
142 }
143
144 func initActiveNetParams(config *cfg.Config) {
145         var exist bool
146         consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
147         if !exist {
148                 cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
149         }
150 }
151
152 // Launch web browser or not
153 func launchWebBrowser() {
154         log.Info("Launching System Browser with :", webAddress)
155         if err := browser.Open(webAddress); err != nil {
156                 log.Error(err.Error())
157                 return
158         }
159 }
160
161 func (n *Node) initAndstartApiServer() {
162         n.api = api.NewAPI(n.syncManager, n.wallet, n.txfeed, n.cpuMiner, n.miningPool, n.chain, n.config, n.accessTokens)
163
164         listenAddr := env.String("LISTEN", n.config.ApiAddress)
165         env.Parse()
166         n.api.StartServer(*listenAddr)
167 }
168
169 func (n *Node) OnStart() error {
170         if n.miningEnable {
171                 n.cpuMiner.Start()
172         }
173         n.syncManager.Start()
174         n.initAndstartApiServer()
175         if !n.config.Web.Closed {
176                 launchWebBrowser()
177         }
178
179         return nil
180 }
181
182 func (n *Node) OnStop() {
183         n.BaseService.OnStop()
184         if n.miningEnable {
185                 n.cpuMiner.Stop()
186         }
187         n.syncManager.Stop()
188         log.Info("Stopping Node")
189         // TODO: gracefully disconnect from peers.
190 }
191
192 func (n *Node) RunForever() {
193         // Sleep forever and then...
194         cmn.TrapSignal(func() {
195                 n.Stop()
196         })
197 }
198
199 func (n *Node) EventSwitch() types.EventSwitch {
200         return n.evsw
201 }
202
203 func (n *Node) SyncManager() *netsync.SyncManager {
204         return n.syncManager
205 }
206
207 func (n *Node) MiningPool() *miningpool.MiningPool {
208         return n.miningPool
209 }