backend.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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/blockpool"
  10. "github.com/ethereum/go-ethereum/core"
  11. "github.com/ethereum/go-ethereum/crypto"
  12. "github.com/ethereum/go-ethereum/ethdb"
  13. "github.com/ethereum/go-ethereum/ethutil"
  14. "github.com/ethereum/go-ethereum/event"
  15. "github.com/ethereum/go-ethereum/logger"
  16. "github.com/ethereum/go-ethereum/miner"
  17. "github.com/ethereum/go-ethereum/p2p"
  18. "github.com/ethereum/go-ethereum/p2p/discover"
  19. "github.com/ethereum/go-ethereum/p2p/nat"
  20. "github.com/ethereum/go-ethereum/rpc"
  21. "github.com/ethereum/go-ethereum/whisper"
  22. )
  23. var (
  24. ethlogger = logger.NewLogger("SERV")
  25. jsonlogger = logger.NewJsonLogger()
  26. defaultBootNodes = []*discover.Node{
  27. // ETH/DEV cmd/bootnode
  28. discover.MustParseNode("enode://6cdd090303f394a1cac34ecc9f7cda18127eafa2a3a06de39f6d920b0e583e062a7362097c7c65ee490a758b442acd5c80c6fce4b148c6a391e946b45131365b@54.169.166.226:30303"),
  29. // ETH/DEV cpp-ethereum (poc-8.ethdev.com)
  30. discover.MustParseNode("enode://4a44599974518ea5b0f14c31c4463692ac0329cb84851f3435e6d1b18ee4eae4aa495f846a0fa1219bd58035671881d44423876e57db2abd57254d0197da0ebe@5.1.83.226:30303"),
  31. }
  32. )
  33. type Config struct {
  34. Name string
  35. KeyStore string
  36. DataDir string
  37. LogFile string
  38. LogLevel int
  39. KeyRing string
  40. LogFormat string
  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. KeyManager *crypto.KeyManager
  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. ethlogger.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. ethlogger.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. quit chan bool
  97. // DB interface
  98. db ethutil.Database
  99. blacklist p2p.Blacklist
  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. whisper *whisper.Whisper
  107. net *p2p.Server
  108. eventMux *event.TypeMux
  109. txSub event.Subscription
  110. blockSub event.Subscription
  111. miner *miner.Miner
  112. RpcServer rpc.RpcServer
  113. keyManager *crypto.KeyManager
  114. logger logger.LogSystem
  115. Mining bool
  116. DataDir string
  117. }
  118. func New(config *Config) (*Ethereum, error) {
  119. // Boostrap database
  120. ethlogger := logger.New(config.DataDir, config.LogFile, config.LogLevel, config.LogFormat)
  121. db, err := ethdb.NewLDBDatabase(path.Join(config.DataDir, "blockchain"))
  122. if err != nil {
  123. return nil, err
  124. }
  125. // Perform database sanity checks
  126. d, _ := db.Get([]byte("ProtocolVersion"))
  127. protov := ethutil.NewValue(d).Uint()
  128. if protov != ProtocolVersion && protov != 0 {
  129. path := path.Join(config.DataDir, "blockchain")
  130. return nil, fmt.Errorf("Database version mismatch. Protocol(%d / %d). `rm -rf %s`", protov, ProtocolVersion, path)
  131. }
  132. // Create new keymanager
  133. var keyManager *crypto.KeyManager
  134. switch config.KeyStore {
  135. case "db":
  136. keyManager = crypto.NewDBKeyManager(db)
  137. case "file":
  138. keyManager = crypto.NewFileKeyManager(config.DataDir)
  139. default:
  140. return nil, fmt.Errorf("unknown keystore type: %s", config.KeyStore)
  141. }
  142. // Initialise the keyring
  143. keyManager.Init(config.KeyRing, 0, false)
  144. saveProtocolVersion(db)
  145. //ethutil.Config.Db = db
  146. eth := &Ethereum{
  147. shutdownChan: make(chan bool),
  148. quit: make(chan bool),
  149. db: db,
  150. keyManager: keyManager,
  151. blacklist: p2p.NewBlacklist(),
  152. eventMux: &event.TypeMux{},
  153. logger: ethlogger,
  154. DataDir: config.DataDir,
  155. }
  156. eth.chainManager = core.NewChainManager(db, eth.EventMux())
  157. pow := ethash.New(eth.chainManager)
  158. eth.txPool = core.NewTxPool(eth.EventMux())
  159. eth.blockProcessor = core.NewBlockProcessor(db, pow, eth.txPool, eth.chainManager, eth.EventMux())
  160. eth.chainManager.SetProcessor(eth.blockProcessor)
  161. eth.whisper = whisper.New()
  162. eth.miner = miner.New(keyManager.Address(), eth, pow, config.MinerThreads)
  163. hasBlock := eth.chainManager.HasBlock
  164. insertChain := eth.chainManager.InsertChain
  165. eth.blockPool = blockpool.New(hasBlock, insertChain, pow.Verify)
  166. netprv, err := config.nodeKey()
  167. if err != nil {
  168. return nil, err
  169. }
  170. ethProto := EthProtocol(eth.txPool, eth.chainManager, eth.blockPool)
  171. protocols := []p2p.Protocol{ethProto}
  172. if config.Shh {
  173. protocols = append(protocols, eth.whisper.Protocol())
  174. }
  175. eth.net = &p2p.Server{
  176. PrivateKey: netprv,
  177. Name: config.Name,
  178. MaxPeers: config.MaxPeers,
  179. Protocols: protocols,
  180. Blacklist: eth.blacklist,
  181. NAT: config.NAT,
  182. NoDial: !config.Dial,
  183. BootstrapNodes: config.parseBootNodes(),
  184. }
  185. if len(config.Port) > 0 {
  186. eth.net.ListenAddr = ":" + config.Port
  187. }
  188. return eth, nil
  189. }
  190. func (s *Ethereum) KeyManager() *crypto.KeyManager { return s.keyManager }
  191. func (s *Ethereum) Logger() logger.LogSystem { return s.logger }
  192. func (s *Ethereum) Name() string { return s.net.Name }
  193. func (s *Ethereum) ChainManager() *core.ChainManager { return s.chainManager }
  194. func (s *Ethereum) BlockProcessor() *core.BlockProcessor { return s.blockProcessor }
  195. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  196. func (s *Ethereum) BlockPool() *blockpool.BlockPool { return s.blockPool }
  197. func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper }
  198. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  199. func (s *Ethereum) Db() ethutil.Database { return s.db }
  200. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  201. func (s *Ethereum) IsListening() bool { return true } // Always listening
  202. func (s *Ethereum) PeerCount() int { return s.net.PeerCount() }
  203. func (s *Ethereum) Peers() []*p2p.Peer { return s.net.Peers() }
  204. func (s *Ethereum) MaxPeers() int { return s.net.MaxPeers }
  205. func (s *Ethereum) Coinbase() []byte { return nil } // TODO
  206. // Start the ethereum
  207. func (s *Ethereum) Start() error {
  208. jsonlogger.LogJson(&logger.LogStarting{
  209. ClientString: s.net.Name,
  210. ProtocolVersion: ProtocolVersion,
  211. })
  212. err := s.net.Start()
  213. if err != nil {
  214. return err
  215. }
  216. // Start services
  217. s.txPool.Start()
  218. s.blockPool.Start()
  219. if s.whisper != nil {
  220. s.whisper.Start()
  221. }
  222. // broadcast transactions
  223. s.txSub = s.eventMux.Subscribe(core.TxPreEvent{})
  224. go s.txBroadcastLoop()
  225. // broadcast mined blocks
  226. s.blockSub = s.eventMux.Subscribe(core.NewMinedBlockEvent{})
  227. go s.blockBroadcastLoop()
  228. ethlogger.Infoln("Server started")
  229. return nil
  230. }
  231. func (self *Ethereum) SuggestPeer(nodeURL string) error {
  232. n, err := discover.ParseNode(nodeURL)
  233. if err != nil {
  234. return fmt.Errorf("invalid node URL: %v", err)
  235. }
  236. self.net.SuggestPeer(n)
  237. return nil
  238. }
  239. func (s *Ethereum) Stop() {
  240. // Close the database
  241. defer s.db.Close()
  242. close(s.quit)
  243. s.txSub.Unsubscribe() // quits txBroadcastLoop
  244. s.blockSub.Unsubscribe() // quits blockBroadcastLoop
  245. if s.RpcServer != nil {
  246. s.RpcServer.Stop()
  247. }
  248. s.txPool.Stop()
  249. s.eventMux.Stop()
  250. s.blockPool.Stop()
  251. if s.whisper != nil {
  252. s.whisper.Stop()
  253. }
  254. ethlogger.Infoln("Server stopped")
  255. close(s.shutdownChan)
  256. }
  257. // This function will wait for a shutdown and resumes main thread execution
  258. func (s *Ethereum) WaitForShutdown() {
  259. <-s.shutdownChan
  260. }
  261. // now tx broadcasting is taken out of txPool
  262. // handled here via subscription, efficiency?
  263. func (self *Ethereum) txBroadcastLoop() {
  264. // automatically stops if unsubscribe
  265. for obj := range self.txSub.Chan() {
  266. event := obj.(core.TxPreEvent)
  267. self.net.Broadcast("eth", TxMsg, event.Tx.RlpData())
  268. }
  269. }
  270. func (self *Ethereum) blockBroadcastLoop() {
  271. // automatically stops if unsubscribe
  272. for obj := range self.blockSub.Chan() {
  273. switch ev := obj.(type) {
  274. case core.NewMinedBlockEvent:
  275. self.net.Broadcast("eth", NewBlockMsg, ev.Block.RlpData(), ev.Block.Td)
  276. }
  277. }
  278. }
  279. func saveProtocolVersion(db ethutil.Database) {
  280. d, _ := db.Get([]byte("ProtocolVersion"))
  281. protocolVersion := ethutil.NewValue(d).Uint()
  282. if protocolVersion == 0 {
  283. db.Put([]byte("ProtocolVersion"), ethutil.NewValue(ProtocolVersion).Bytes())
  284. }
  285. }