backend.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. package eth
  2. import (
  3. "crypto/ecdsa"
  4. "fmt"
  5. "io/ioutil"
  6. "path"
  7. "strings"
  8. "github.com/ethereum/ethash"
  9. "github.com/ethereum/go-ethereum/accounts"
  10. "github.com/ethereum/go-ethereum/blockpool"
  11. "github.com/ethereum/go-ethereum/core"
  12. "github.com/ethereum/go-ethereum/crypto"
  13. "github.com/ethereum/go-ethereum/ethdb"
  14. "github.com/ethereum/go-ethereum/ethutil"
  15. "github.com/ethereum/go-ethereum/event"
  16. "github.com/ethereum/go-ethereum/logger"
  17. "github.com/ethereum/go-ethereum/miner"
  18. "github.com/ethereum/go-ethereum/p2p"
  19. "github.com/ethereum/go-ethereum/p2p/discover"
  20. "github.com/ethereum/go-ethereum/p2p/nat"
  21. "github.com/ethereum/go-ethereum/vm"
  22. "github.com/ethereum/go-ethereum/whisper"
  23. )
  24. var (
  25. servlogger = logger.NewLogger("SERV")
  26. jsonlogger = logger.NewJsonLogger()
  27. defaultBootNodes = []*discover.Node{
  28. // ETH/DEV cmd/bootnode
  29. discover.MustParseNode("enode://6cdd090303f394a1cac34ecc9f7cda18127eafa2a3a06de39f6d920b0e583e062a7362097c7c65ee490a758b442acd5c80c6fce4b148c6a391e946b45131365b@54.169.166.226:30303"),
  30. // ETH/DEV cpp-ethereum (poc-8.ethdev.com)
  31. discover.MustParseNode("enode://4a44599974518ea5b0f14c31c4463692ac0329cb84851f3435e6d1b18ee4eae4aa495f846a0fa1219bd58035671881d44423876e57db2abd57254d0197da0ebe@5.1.83.226:30303"),
  32. }
  33. )
  34. type Config struct {
  35. Name string
  36. DataDir string
  37. LogFile string
  38. LogLevel int
  39. LogFormat string
  40. VmDebug bool
  41. MaxPeers int
  42. Port string
  43. // This should be a space-separated list of
  44. // discovery node URLs.
  45. BootNodes string
  46. // This key is used to identify the node on the network.
  47. // If nil, an ephemeral key is used.
  48. NodeKey *ecdsa.PrivateKey
  49. NAT nat.Interface
  50. Shh bool
  51. Dial bool
  52. MinerThreads int
  53. AccountManager *accounts.Manager
  54. }
  55. func (cfg *Config) parseBootNodes() []*discover.Node {
  56. if cfg.BootNodes == "" {
  57. return defaultBootNodes
  58. }
  59. var ns []*discover.Node
  60. for _, url := range strings.Split(cfg.BootNodes, " ") {
  61. if url == "" {
  62. continue
  63. }
  64. n, err := discover.ParseNode(url)
  65. if err != nil {
  66. servlogger.Errorf("Bootstrap URL %s: %v\n", url, err)
  67. continue
  68. }
  69. ns = append(ns, n)
  70. }
  71. return ns
  72. }
  73. func (cfg *Config) nodeKey() (*ecdsa.PrivateKey, error) {
  74. // use explicit key from command line args if set
  75. if cfg.NodeKey != nil {
  76. return cfg.NodeKey, nil
  77. }
  78. // use persistent key if present
  79. keyfile := path.Join(cfg.DataDir, "nodekey")
  80. key, err := crypto.LoadECDSA(keyfile)
  81. if err == nil {
  82. return key, nil
  83. }
  84. // no persistent key, generate and store a new one
  85. if key, err = crypto.GenerateKey(); err != nil {
  86. return nil, fmt.Errorf("could not generate server key: %v", err)
  87. }
  88. if err := ioutil.WriteFile(keyfile, crypto.FromECDSA(key), 0600); err != nil {
  89. servlogger.Errorln("could not persist nodekey: ", err)
  90. }
  91. return key, nil
  92. }
  93. type Ethereum struct {
  94. // Channel for shutting down the ethereum
  95. shutdownChan chan bool
  96. // DB interfaces
  97. blockDb ethutil.Database // Block chain database
  98. stateDb ethutil.Database // State changes database
  99. extraDb ethutil.Database // Extra database (txs, etc)
  100. //*** SERVICES ***
  101. // State manager for processing new blocks and managing the over all states
  102. blockProcessor *core.BlockProcessor
  103. txPool *core.TxPool
  104. chainManager *core.ChainManager
  105. blockPool *blockpool.BlockPool
  106. accountManager *accounts.Manager
  107. whisper *whisper.Whisper
  108. net *p2p.Server
  109. eventMux *event.TypeMux
  110. txSub event.Subscription
  111. blockSub event.Subscription
  112. miner *miner.Miner
  113. logger logger.LogSystem
  114. Mining bool
  115. DataDir string
  116. version string
  117. }
  118. func New(config *Config) (*Ethereum, error) {
  119. // Boostrap database
  120. servlogger := logger.New(config.DataDir, config.LogFile, config.LogLevel, config.LogFormat)
  121. blockDb, err := ethdb.NewLDBDatabase(path.Join(config.DataDir, "blockchain"))
  122. if err != nil {
  123. return nil, err
  124. }
  125. stateDb, err := ethdb.NewLDBDatabase(path.Join(config.DataDir, "state"))
  126. if err != nil {
  127. return nil, err
  128. }
  129. extraDb, err := ethdb.NewLDBDatabase(path.Join(config.DataDir, "extra"))
  130. // Perform database sanity checks
  131. d, _ := blockDb.Get([]byte("ProtocolVersion"))
  132. protov := ethutil.NewValue(d).Uint()
  133. if protov != ProtocolVersion && protov != 0 {
  134. path := path.Join(config.DataDir, "blockchain")
  135. return nil, fmt.Errorf("Database version mismatch. Protocol(%d / %d). `rm -rf %s`", protov, ProtocolVersion, path)
  136. }
  137. saveProtocolVersion(extraDb)
  138. eth := &Ethereum{
  139. shutdownChan: make(chan bool),
  140. blockDb: blockDb,
  141. stateDb: stateDb,
  142. extraDb: extraDb,
  143. eventMux: &event.TypeMux{},
  144. logger: servlogger,
  145. accountManager: config.AccountManager,
  146. DataDir: config.DataDir,
  147. version: config.Name, // TODO should separate from Name
  148. }
  149. eth.chainManager = core.NewChainManager(blockDb, stateDb, eth.EventMux())
  150. pow := ethash.New(eth.chainManager)
  151. eth.txPool = core.NewTxPool(eth.EventMux())
  152. eth.blockProcessor = core.NewBlockProcessor(stateDb, extraDb, pow, eth.txPool, eth.chainManager, eth.EventMux())
  153. eth.chainManager.SetProcessor(eth.blockProcessor)
  154. eth.whisper = whisper.New()
  155. eth.miner = miner.New(eth, pow, config.MinerThreads)
  156. hasBlock := eth.chainManager.HasBlock
  157. insertChain := eth.chainManager.InsertChain
  158. eth.blockPool = blockpool.New(hasBlock, insertChain, pow.Verify)
  159. netprv, err := config.nodeKey()
  160. if err != nil {
  161. return nil, err
  162. }
  163. ethProto := EthProtocol(eth.txPool, eth.chainManager, eth.blockPool)
  164. protocols := []p2p.Protocol{ethProto}
  165. if config.Shh {
  166. protocols = append(protocols, eth.whisper.Protocol())
  167. }
  168. eth.net = &p2p.Server{
  169. PrivateKey: netprv,
  170. Name: config.Name,
  171. MaxPeers: config.MaxPeers,
  172. Protocols: protocols,
  173. NAT: config.NAT,
  174. NoDial: !config.Dial,
  175. BootstrapNodes: config.parseBootNodes(),
  176. }
  177. if len(config.Port) > 0 {
  178. eth.net.ListenAddr = ":" + config.Port
  179. }
  180. vm.Debug = config.VmDebug
  181. return eth, nil
  182. }
  183. func (s *Ethereum) StartMining() error {
  184. cb, err := s.accountManager.Coinbase()
  185. if err != nil {
  186. servlogger.Errorf("Cannot start mining without coinbase: %v\n", err)
  187. return fmt.Errorf("no coinbase: %v", err)
  188. }
  189. s.miner.Start(cb)
  190. return nil
  191. }
  192. func (s *Ethereum) StopMining() { s.miner.Stop() }
  193. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  194. func (s *Ethereum) Logger() logger.LogSystem { return s.logger }
  195. func (s *Ethereum) Name() string { return s.net.Name }
  196. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  197. func (s *Ethereum) ChainManager() *core.ChainManager { return s.chainManager }
  198. func (s *Ethereum) BlockProcessor() *core.BlockProcessor { return s.blockProcessor }
  199. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  200. func (s *Ethereum) BlockPool() *blockpool.BlockPool { return s.blockPool }
  201. func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper }
  202. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  203. func (s *Ethereum) BlockDb() ethutil.Database { return s.blockDb }
  204. func (s *Ethereum) StateDb() ethutil.Database { return s.stateDb }
  205. func (s *Ethereum) ExtraDb() ethutil.Database { return s.extraDb }
  206. func (s *Ethereum) IsListening() bool { return true } // Always listening
  207. func (s *Ethereum) PeerCount() int { return s.net.PeerCount() }
  208. func (s *Ethereum) Peers() []*p2p.Peer { return s.net.Peers() }
  209. func (s *Ethereum) MaxPeers() int { return s.net.MaxPeers }
  210. func (s *Ethereum) Version() string { return s.version }
  211. // Start the ethereum
  212. func (s *Ethereum) Start() error {
  213. jsonlogger.LogJson(&logger.LogStarting{
  214. ClientString: s.net.Name,
  215. ProtocolVersion: ProtocolVersion,
  216. })
  217. err := s.net.Start()
  218. if err != nil {
  219. return err
  220. }
  221. // Start services
  222. s.txPool.Start()
  223. s.blockPool.Start()
  224. if s.whisper != nil {
  225. s.whisper.Start()
  226. }
  227. // broadcast transactions
  228. s.txSub = s.eventMux.Subscribe(core.TxPreEvent{})
  229. go s.txBroadcastLoop()
  230. // broadcast mined blocks
  231. s.blockSub = s.eventMux.Subscribe(core.NewMinedBlockEvent{})
  232. go s.blockBroadcastLoop()
  233. servlogger.Infoln("Server started")
  234. return nil
  235. }
  236. func (s *Ethereum) StartForTest() {
  237. jsonlogger.LogJson(&logger.LogStarting{
  238. ClientString: s.net.Name,
  239. ProtocolVersion: ProtocolVersion,
  240. })
  241. // Start services
  242. s.txPool.Start()
  243. s.blockPool.Start()
  244. }
  245. func (self *Ethereum) SuggestPeer(nodeURL string) error {
  246. n, err := discover.ParseNode(nodeURL)
  247. if err != nil {
  248. return fmt.Errorf("invalid node URL: %v", err)
  249. }
  250. self.net.SuggestPeer(n)
  251. return nil
  252. }
  253. func (s *Ethereum) Stop() {
  254. // Close the database
  255. defer s.blockDb.Close()
  256. defer s.stateDb.Close()
  257. s.txSub.Unsubscribe() // quits txBroadcastLoop
  258. s.blockSub.Unsubscribe() // quits blockBroadcastLoop
  259. s.txPool.Stop()
  260. s.eventMux.Stop()
  261. s.blockPool.Stop()
  262. if s.whisper != nil {
  263. s.whisper.Stop()
  264. }
  265. servlogger.Infoln("Server stopped")
  266. close(s.shutdownChan)
  267. }
  268. // This function will wait for a shutdown and resumes main thread execution
  269. func (s *Ethereum) WaitForShutdown() {
  270. <-s.shutdownChan
  271. }
  272. // now tx broadcasting is taken out of txPool
  273. // handled here via subscription, efficiency?
  274. func (self *Ethereum) txBroadcastLoop() {
  275. // automatically stops if unsubscribe
  276. for obj := range self.txSub.Chan() {
  277. event := obj.(core.TxPreEvent)
  278. self.net.Broadcast("eth", TxMsg, event.Tx.RlpData())
  279. }
  280. }
  281. func (self *Ethereum) blockBroadcastLoop() {
  282. // automatically stops if unsubscribe
  283. for obj := range self.blockSub.Chan() {
  284. switch ev := obj.(type) {
  285. case core.NewMinedBlockEvent:
  286. self.net.Broadcast("eth", NewBlockMsg, ev.Block.RlpData(), ev.Block.Td)
  287. }
  288. }
  289. }
  290. func saveProtocolVersion(db ethutil.Database) {
  291. d, _ := db.Get([]byte("ProtocolVersion"))
  292. protocolVersion := ethutil.NewValue(d).Uint()
  293. if protocolVersion == 0 {
  294. db.Put([]byte("ProtocolVersion"), ethutil.NewValue(ProtocolVersion).Bytes())
  295. }
  296. }