backend.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. ethlogger "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. logger = ethlogger.NewLogger("SERV")
  24. jsonlogger = ethlogger.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. logger.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. logger.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. WsServer rpc.RpcServer
  113. keyManager *crypto.KeyManager
  114. logger ethlogger.LogSystem
  115. Mining bool
  116. }
  117. func New(config *Config) (*Ethereum, error) {
  118. // Boostrap database
  119. logger := ethlogger.New(config.DataDir, config.LogFile, config.LogLevel, config.LogFormat)
  120. db, err := ethdb.NewLDBDatabase("blockchain")
  121. if err != nil {
  122. return nil, err
  123. }
  124. // Perform database sanity checks
  125. d, _ := db.Get([]byte("ProtocolVersion"))
  126. protov := ethutil.NewValue(d).Uint()
  127. if protov != ProtocolVersion && protov != 0 {
  128. path := path.Join(config.DataDir, "database")
  129. return nil, fmt.Errorf("Database version mismatch. Protocol(%d / %d). `rm -rf %s`", protov, ProtocolVersion, path)
  130. }
  131. // Create new keymanager
  132. var keyManager *crypto.KeyManager
  133. switch config.KeyStore {
  134. case "db":
  135. keyManager = crypto.NewDBKeyManager(db)
  136. case "file":
  137. keyManager = crypto.NewFileKeyManager(config.DataDir)
  138. default:
  139. return nil, fmt.Errorf("unknown keystore type: %s", config.KeyStore)
  140. }
  141. // Initialise the keyring
  142. keyManager.Init(config.KeyRing, 0, false)
  143. saveProtocolVersion(db)
  144. //ethutil.Config.Db = db
  145. eth := &Ethereum{
  146. shutdownChan: make(chan bool),
  147. quit: make(chan bool),
  148. db: db,
  149. keyManager: keyManager,
  150. blacklist: p2p.NewBlacklist(),
  151. eventMux: &event.TypeMux{},
  152. logger: logger,
  153. }
  154. eth.chainManager = core.NewChainManager(db, eth.EventMux())
  155. eth.txPool = core.NewTxPool(eth.EventMux())
  156. eth.blockProcessor = core.NewBlockProcessor(db, eth.txPool, eth.chainManager, eth.EventMux())
  157. eth.chainManager.SetProcessor(eth.blockProcessor)
  158. eth.whisper = whisper.New()
  159. eth.miner = miner.New(keyManager.Address(), eth, config.MinerThreads)
  160. hasBlock := eth.chainManager.HasBlock
  161. insertChain := eth.chainManager.InsertChain
  162. eth.blockPool = NewBlockPool(hasBlock, insertChain, ezp.Verify)
  163. netprv, err := config.nodeKey()
  164. if err != nil {
  165. return nil, err
  166. }
  167. ethProto := EthProtocol(eth.txPool, eth.chainManager, eth.blockPool)
  168. protocols := []p2p.Protocol{ethProto}
  169. if config.Shh {
  170. protocols = append(protocols, eth.whisper.Protocol())
  171. }
  172. eth.net = &p2p.Server{
  173. PrivateKey: netprv,
  174. Name: config.Name,
  175. MaxPeers: config.MaxPeers,
  176. Protocols: protocols,
  177. Blacklist: eth.blacklist,
  178. NAT: config.NAT,
  179. NoDial: !config.Dial,
  180. BootstrapNodes: config.parseBootNodes(),
  181. }
  182. if len(config.Port) > 0 {
  183. eth.net.ListenAddr = ":" + config.Port
  184. }
  185. return eth, nil
  186. }
  187. func (s *Ethereum) KeyManager() *crypto.KeyManager { return s.keyManager }
  188. func (s *Ethereum) Logger() ethlogger.LogSystem { return s.logger }
  189. func (s *Ethereum) Name() string { return s.net.Name }
  190. func (s *Ethereum) ChainManager() *core.ChainManager { return s.chainManager }
  191. func (s *Ethereum) BlockProcessor() *core.BlockProcessor { return s.blockProcessor }
  192. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  193. func (s *Ethereum) BlockPool() *BlockPool { return s.blockPool }
  194. func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper }
  195. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  196. func (s *Ethereum) Db() ethutil.Database { return s.db }
  197. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  198. func (s *Ethereum) IsListening() bool { return true } // Always listening
  199. func (s *Ethereum) PeerCount() int { return s.net.PeerCount() }
  200. func (s *Ethereum) Peers() []*p2p.Peer { return s.net.Peers() }
  201. func (s *Ethereum) MaxPeers() int { return s.net.MaxPeers }
  202. func (s *Ethereum) Coinbase() []byte { return nil } // TODO
  203. // Start the ethereum
  204. func (s *Ethereum) Start() error {
  205. jsonlogger.LogJson(&ethlogger.LogStarting{
  206. ClientString: s.net.Name,
  207. ProtocolVersion: ProtocolVersion,
  208. })
  209. err := s.net.Start()
  210. if err != nil {
  211. return err
  212. }
  213. // Start services
  214. s.txPool.Start()
  215. s.blockPool.Start()
  216. if s.whisper != nil {
  217. s.whisper.Start()
  218. }
  219. // broadcast transactions
  220. s.txSub = s.eventMux.Subscribe(core.TxPreEvent{})
  221. go s.txBroadcastLoop()
  222. // broadcast mined blocks
  223. s.blockSub = s.eventMux.Subscribe(core.NewMinedBlockEvent{})
  224. go s.blockBroadcastLoop()
  225. logger.Infoln("Server started")
  226. return nil
  227. }
  228. func (self *Ethereum) SuggestPeer(nodeURL string) error {
  229. n, err := discover.ParseNode(nodeURL)
  230. if err != nil {
  231. return fmt.Errorf("invalid node URL: %v", err)
  232. }
  233. self.net.SuggestPeer(n)
  234. return nil
  235. }
  236. func (s *Ethereum) Stop() {
  237. // Close the database
  238. defer s.db.Close()
  239. close(s.quit)
  240. s.txSub.Unsubscribe() // quits txBroadcastLoop
  241. s.blockSub.Unsubscribe() // quits blockBroadcastLoop
  242. if s.RpcServer != nil {
  243. s.RpcServer.Stop()
  244. }
  245. if s.WsServer != nil {
  246. s.WsServer.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. logger.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. }