backend.go 9.0 KB

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