OSDN Git Service

Merge pull request #701 from Bytom/dev-pool
[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/crypto/ed25519/chainkd"
23         "github.com/bytom/database/leveldb"
24         "github.com/bytom/env"
25         "github.com/bytom/mining/cpuminer"
26         "github.com/bytom/mining/miningpool"
27         "github.com/bytom/netsync"
28         "github.com/bytom/protocol"
29         "github.com/bytom/protocol/bc"
30         "github.com/bytom/types"
31         w "github.com/bytom/wallet"
32 )
33
34 const (
35         webAddress               = "http://127.0.0.1:9888"
36         expireReservationsPeriod = time.Second
37         maxNewBlockChSize        = 1024
38 )
39
40 type Node struct {
41         cmn.BaseService
42
43         // config
44         config *cfg.Config
45
46         syncManager *netsync.SyncManager
47
48         evsw types.EventSwitch // pub/sub for services
49         //bcReactor    *bc.BlockchainReactor
50         wallet       *w.Wallet
51         accessTokens *accesstoken.CredentialStore
52         api          *api.API
53         chain        *protocol.Chain
54         txfeed       *txfeed.Tracker
55         cpuMiner     *cpuminer.CPUMiner
56         miningPool   *miningpool.MiningPool
57         miningEnable bool
58 }
59
60 func NewNode(config *cfg.Config) *Node {
61         ctx := context.Background()
62         initActiveNetParams(config)
63         // Get store
64         txDB := dbm.NewDB("txdb", config.DBBackend, config.DBDir())
65         store := leveldb.NewStore(txDB)
66
67         tokenDB := dbm.NewDB("accesstoken", config.DBBackend, config.DBDir())
68         accessTokens := accesstoken.NewStore(tokenDB)
69
70         // Make event switch
71         eventSwitch := types.NewEventSwitch()
72         _, err := eventSwitch.Start()
73         if err != nil {
74                 cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
75         }
76
77         txPool := protocol.NewTxPool()
78         chain, err := protocol.NewChain(store, txPool)
79         if err != nil {
80                 cmn.Exit(cmn.Fmt("Failed to create chain structure: %v", err))
81         }
82
83         var accounts *account.Manager = nil
84         var assets *asset.Registry = nil
85         var wallet *w.Wallet = nil
86         var txFeed *txfeed.Tracker = nil
87
88         txFeedDB := dbm.NewDB("txfeeds", config.DBBackend, config.DBDir())
89         txFeed = txfeed.NewTracker(txFeedDB, chain)
90
91         if err = txFeed.Prepare(ctx); err != nil {
92                 log.WithField("error", err).Error("start txfeed")
93                 return nil
94         }
95
96         hsm, err := pseudohsm.New(config.KeysDir())
97         if err != nil {
98                 cmn.Exit(cmn.Fmt("initialize HSM failed: %v", err))
99         }
100
101         if !config.Wallet.Disable {
102                 walletDB := dbm.NewDB("wallet", config.DBBackend, config.DBDir())
103                 accounts = account.NewManager(walletDB, chain)
104                 assets = asset.NewRegistry(walletDB, chain)
105                 wallet, err = w.NewWallet(walletDB, accounts, assets, hsm, chain)
106                 if err != nil {
107                         log.WithField("error", err).Error("init NewWallet")
108                 }
109
110                 if err := initOrRecoverAccount(hsm, wallet); err != nil {
111                         log.WithField("error", err).Error("initialize or recover account")
112                 }
113
114                 // Clean up expired UTXO reservations periodically.
115                 go accounts.ExpireReservations(ctx, expireReservationsPeriod)
116         }
117         newBlockCh := make(chan *bc.Hash, maxNewBlockChSize)
118
119         syncManager, _ := netsync.NewSyncManager(config, chain, txPool, newBlockCh)
120
121         // run the profile server
122         profileHost := config.ProfListenAddress
123         if profileHost != "" {
124                 // Profiling bytomd programs.see (https://blog.golang.org/profiling-go-programs)
125                 // go tool pprof http://profileHose/debug/pprof/heap
126                 go func() {
127                         http.ListenAndServe(profileHost, nil)
128                 }()
129         }
130
131         node := &Node{
132                 config:       config,
133                 syncManager:  syncManager,
134                 evsw:         eventSwitch,
135                 accessTokens: accessTokens,
136                 wallet:       wallet,
137                 chain:        chain,
138                 txfeed:       txFeed,
139                 miningEnable: config.Mining,
140         }
141
142         node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
143         node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
144
145         node.BaseService = *cmn.NewBaseService(nil, "Node", node)
146
147         return node
148 }
149
150 func initActiveNetParams(config *cfg.Config) {
151         var exist bool
152         consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
153         if !exist {
154                 cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
155         }
156 }
157
158 func initOrRecoverAccount(hsm *pseudohsm.HSM, wallet *w.Wallet) error {
159         xpubs := hsm.ListKeys()
160
161         if len(xpubs) == 0 {
162                 xpub, err := hsm.XCreate("default", "123456")
163                 if err != nil {
164                         return err
165                 }
166
167                 wallet.AccountMgr.Create(nil, []chainkd.XPub{xpub.XPub}, 1, "default")
168                 return nil
169         }
170
171         if _, err := wallet.AccountMgr.ListAccounts(""); err != nil {
172                 return err
173         }
174
175         return nil
176 }
177
178 // Lanch web broser or not
179 func lanchWebBroser() {
180         log.Info("Launching System Browser with :", webAddress)
181         if err := browser.Open(webAddress); err != nil {
182                 log.Error(err.Error())
183                 return
184         }
185 }
186
187 func (n *Node) initAndstartApiServer() {
188         n.api = api.NewAPI(n.syncManager, n.wallet, n.txfeed, n.cpuMiner, n.miningPool, n.chain, n.config, n.accessTokens)
189
190         listenAddr := env.String("LISTEN", n.config.ApiAddress)
191         env.Parse()
192         n.api.StartServer(*listenAddr)
193 }
194
195 func (n *Node) OnStart() error {
196         if n.miningEnable {
197                 n.cpuMiner.Start()
198         }
199         n.syncManager.Start()
200         n.initAndstartApiServer()
201         if !n.config.Web.Closed {
202                 lanchWebBroser()
203         }
204
205         return nil
206 }
207
208 func (n *Node) OnStop() {
209         n.BaseService.OnStop()
210         if n.miningEnable {
211                 n.cpuMiner.Stop()
212         }
213         n.syncManager.Stop()
214         log.Info("Stopping Node")
215         // TODO: gracefully disconnect from peers.
216 }
217
218 func (n *Node) RunForever() {
219         // Sleep forever and then...
220         cmn.TrapSignal(func() {
221                 n.Stop()
222         })
223 }
224
225 func (n *Node) EventSwitch() types.EventSwitch {
226         return n.evsw
227 }
228
229 func (n *Node) SyncManager() *netsync.SyncManager {
230         return n.syncManager
231 }
232
233 func (n *Node) MiningPool() *miningpool.MiningPool {
234         return n.miningPool
235 }