backend.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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/vm"
  22. "github.com/ethereum/go-ethereum/whisper"
  23. )
  24. var (
  25. ethlogger = 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. KeyStore string
  37. DataDir string
  38. LogFile string
  39. LogLevel int
  40. KeyRing string
  41. LogFormat string
  42. VmDebug bool
  43. MaxPeers int
  44. Port string
  45. // This should be a space-separated list of
  46. // discovery node URLs.
  47. BootNodes string
  48. // This key is used to identify the node on the network.
  49. // If nil, an ephemeral key is used.
  50. NodeKey *ecdsa.PrivateKey
  51. NAT nat.Interface
  52. Shh bool
  53. Dial bool
  54. MinerThreads int
  55. KeyManager *crypto.KeyManager
  56. }
  57. func (cfg *Config) parseBootNodes() []*discover.Node {
  58. if cfg.BootNodes == "" {
  59. return defaultBootNodes
  60. }
  61. var ns []*discover.Node
  62. for _, url := range strings.Split(cfg.BootNodes, " ") {
  63. if url == "" {
  64. continue
  65. }
  66. n, err := discover.ParseNode(url)
  67. if err != nil {
  68. ethlogger.Errorf("Bootstrap URL %s: %v\n", url, err)
  69. continue
  70. }
  71. ns = append(ns, n)
  72. }
  73. return ns
  74. }
  75. func (cfg *Config) nodeKey() (*ecdsa.PrivateKey, error) {
  76. // use explicit key from command line args if set
  77. if cfg.NodeKey != nil {
  78. return cfg.NodeKey, nil
  79. }
  80. // use persistent key if present
  81. keyfile := path.Join(cfg.DataDir, "nodekey")
  82. key, err := crypto.LoadECDSA(keyfile)
  83. if err == nil {
  84. return key, nil
  85. }
  86. // no persistent key, generate and store a new one
  87. if key, err = crypto.GenerateKey(); err != nil {
  88. return nil, fmt.Errorf("could not generate server key: %v", err)
  89. }
  90. if err := ioutil.WriteFile(keyfile, crypto.FromECDSA(key), 0600); err != nil {
  91. ethlogger.Errorln("could not persist nodekey: ", err)
  92. }
  93. return key, nil
  94. }
  95. type Ethereum struct {
  96. // Channel for shutting down the ethereum
  97. shutdownChan chan bool
  98. // DB interface
  99. blockDb ethutil.Database
  100. stateDb ethutil.Database
  101. //*** SERVICES ***
  102. // State manager for processing new blocks and managing the over all states
  103. blockProcessor *core.BlockProcessor
  104. txPool *core.TxPool
  105. chainManager *core.ChainManager
  106. blockPool *blockpool.BlockPool
  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. RpcServer rpc.RpcServer
  114. keyManager *crypto.KeyManager
  115. logger logger.LogSystem
  116. Mining bool
  117. DataDir string
  118. }
  119. func New(config *Config) (*Ethereum, error) {
  120. // Boostrap database
  121. ethlogger := logger.New(config.DataDir, config.LogFile, config.LogLevel, config.LogFormat)
  122. blockDb, err := ethdb.NewLDBDatabase(path.Join(config.DataDir, "blockchain"))
  123. if err != nil {
  124. return nil, err
  125. }
  126. stateDb, err := ethdb.NewLDBDatabase(path.Join(config.DataDir, "state"))
  127. if err != nil {
  128. return nil, err
  129. }
  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. // Create new keymanager
  138. var keyManager *crypto.KeyManager
  139. switch config.KeyStore {
  140. case "db":
  141. keyManager = crypto.NewDBKeyManager(blockDb)
  142. case "file":
  143. keyManager = crypto.NewFileKeyManager(config.DataDir)
  144. default:
  145. return nil, fmt.Errorf("unknown keystore type: %s", config.KeyStore)
  146. }
  147. // Initialise the keyring
  148. keyManager.Init(config.KeyRing, 0, false)
  149. saveProtocolVersion(blockDb)
  150. //ethutil.Config.Db = db
  151. eth := &Ethereum{
  152. shutdownChan: make(chan bool),
  153. blockDb: blockDb,
  154. stateDb: stateDb,
  155. keyManager: keyManager,
  156. eventMux: &event.TypeMux{},
  157. logger: ethlogger,
  158. DataDir: config.DataDir,
  159. }
  160. eth.chainManager = core.NewChainManager(blockDb, stateDb, eth.EventMux())
  161. pow := ethash.New(eth.chainManager)
  162. eth.txPool = core.NewTxPool(eth.EventMux())
  163. eth.blockProcessor = core.NewBlockProcessor(stateDb, pow, eth.txPool, eth.chainManager, eth.EventMux())
  164. eth.chainManager.SetProcessor(eth.blockProcessor)
  165. eth.whisper = whisper.New()
  166. eth.miner = miner.New(keyManager.Address(), eth, pow, config.MinerThreads)
  167. hasBlock := eth.chainManager.HasBlock
  168. insertChain := eth.chainManager.InsertChain
  169. eth.blockPool = blockpool.New(hasBlock, insertChain, pow.Verify)
  170. netprv, err := config.nodeKey()
  171. if err != nil {
  172. return nil, err
  173. }
  174. ethProto := EthProtocol(eth.txPool, eth.chainManager, eth.blockPool)
  175. protocols := []p2p.Protocol{ethProto}
  176. if config.Shh {
  177. protocols = append(protocols, eth.whisper.Protocol())
  178. }
  179. eth.net = &p2p.Server{
  180. PrivateKey: netprv,
  181. Name: config.Name,
  182. MaxPeers: config.MaxPeers,
  183. Protocols: protocols,
  184. NAT: config.NAT,
  185. NoDial: !config.Dial,
  186. BootstrapNodes: config.parseBootNodes(),
  187. }
  188. if len(config.Port) > 0 {
  189. eth.net.ListenAddr = ":" + config.Port
  190. }
  191. vm.Debug = config.VmDebug
  192. return eth, nil
  193. }
  194. func (s *Ethereum) KeyManager() *crypto.KeyManager { return s.keyManager }
  195. func (s *Ethereum) Logger() logger.LogSystem { return s.logger }
  196. func (s *Ethereum) Name() string { return s.net.Name }
  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) Miner() *miner.Miner { return s.miner }
  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) Coinbase() []byte { return nil } // TODO
  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. ethlogger.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. if s.RpcServer != nil {
  260. s.RpcServer.Stop()
  261. }
  262. s.txPool.Stop()
  263. s.eventMux.Stop()
  264. s.blockPool.Stop()
  265. if s.whisper != nil {
  266. s.whisper.Stop()
  267. }
  268. ethlogger.Infoln("Server stopped")
  269. close(s.shutdownChan)
  270. }
  271. // This function will wait for a shutdown and resumes main thread execution
  272. func (s *Ethereum) WaitForShutdown() {
  273. <-s.shutdownChan
  274. }
  275. // now tx broadcasting is taken out of txPool
  276. // handled here via subscription, efficiency?
  277. func (self *Ethereum) txBroadcastLoop() {
  278. // automatically stops if unsubscribe
  279. for obj := range self.txSub.Chan() {
  280. event := obj.(core.TxPreEvent)
  281. self.net.Broadcast("eth", TxMsg, event.Tx.RlpData())
  282. }
  283. }
  284. func (self *Ethereum) blockBroadcastLoop() {
  285. // automatically stops if unsubscribe
  286. for obj := range self.blockSub.Chan() {
  287. switch ev := obj.(type) {
  288. case core.NewMinedBlockEvent:
  289. self.net.Broadcast("eth", NewBlockMsg, ev.Block.RlpData(), ev.Block.Td)
  290. }
  291. }
  292. }
  293. func saveProtocolVersion(db ethutil.Database) {
  294. d, _ := db.Get([]byte("ProtocolVersion"))
  295. protocolVersion := ethutil.NewValue(d).Uint()
  296. if protocolVersion == 0 {
  297. db.Put([]byte("ProtocolVersion"), ethutil.NewValue(ProtocolVersion).Bytes())
  298. }
  299. }