backend.go 10 KB

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