backend.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. package eth
  2. import (
  3. "crypto/ecdsa"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/ethereum/ethash"
  13. "github.com/ethereum/go-ethereum/accounts"
  14. "github.com/ethereum/go-ethereum/common"
  15. "github.com/ethereum/go-ethereum/core"
  16. "github.com/ethereum/go-ethereum/core/types"
  17. "github.com/ethereum/go-ethereum/core/vm"
  18. "github.com/ethereum/go-ethereum/crypto"
  19. "github.com/ethereum/go-ethereum/eth/downloader"
  20. "github.com/ethereum/go-ethereum/ethdb"
  21. "github.com/ethereum/go-ethereum/event"
  22. "github.com/ethereum/go-ethereum/logger"
  23. "github.com/ethereum/go-ethereum/logger/glog"
  24. "github.com/ethereum/go-ethereum/miner"
  25. "github.com/ethereum/go-ethereum/p2p"
  26. "github.com/ethereum/go-ethereum/p2p/discover"
  27. "github.com/ethereum/go-ethereum/p2p/nat"
  28. "github.com/ethereum/go-ethereum/whisper"
  29. )
  30. var (
  31. jsonlogger = logger.NewJsonLogger()
  32. defaultBootNodes = []*discover.Node{
  33. // ETH/DEV Go Bootnodes
  34. discover.MustParseNode("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@52.16.188.185:30303"),
  35. discover.MustParseNode("enode://7f25d3eab333a6b98a8b5ed68d962bb22c876ffcd5561fca54e3c2ef27f754df6f7fd7c9b74cc919067abac154fb8e1f8385505954f161ae440abc355855e034@54.207.93.166:30303"),
  36. // ETH/DEV cpp-ethereum (poc-9.ethdev.com)
  37. discover.MustParseNode("enode://487611428e6c99a11a9795a6abe7b529e81315ca6aad66e2a2fc76e3adf263faba0d35466c2f8f68d561dbefa8878d4df5f1f2ddb1fbeab7f42ffb8cd328bd4a@5.1.83.226:30303"),
  38. }
  39. staticNodes = "static-nodes.json" // Path within <datadir> to search for the static node list
  40. trustedNodes = "trusted-nodes.json" // Path within <datadir> to search for the trusted node list
  41. )
  42. type Config struct {
  43. Name string
  44. ProtocolVersion int
  45. NetworkId int
  46. BlockChainVersion int
  47. SkipBcVersionCheck bool // e.g. blockchain export
  48. DataDir string
  49. LogFile string
  50. LogLevel int
  51. LogJSON string
  52. VmDebug bool
  53. NatSpec bool
  54. MaxPeers int
  55. MaxPendingPeers int
  56. Port string
  57. // Space-separated list of discovery node URLs
  58. BootNodes string
  59. // This key is used to identify the node on the network.
  60. // If nil, an ephemeral key is used.
  61. NodeKey *ecdsa.PrivateKey
  62. NAT nat.Interface
  63. Shh bool
  64. Dial bool
  65. Etherbase string
  66. MinerThreads int
  67. AccountManager *accounts.Manager
  68. // NewDB is used to create databases.
  69. // If nil, the default is to create leveldb databases on disk.
  70. NewDB func(path string) (common.Database, error)
  71. }
  72. func (cfg *Config) parseBootNodes() []*discover.Node {
  73. if cfg.BootNodes == "" {
  74. return defaultBootNodes
  75. }
  76. var ns []*discover.Node
  77. for _, url := range strings.Split(cfg.BootNodes, " ") {
  78. if url == "" {
  79. continue
  80. }
  81. n, err := discover.ParseNode(url)
  82. if err != nil {
  83. glog.V(logger.Error).Infof("Bootstrap URL %s: %v\n", url, err)
  84. continue
  85. }
  86. ns = append(ns, n)
  87. }
  88. return ns
  89. }
  90. // parseNodes parses a list of discovery node URLs loaded from a .json file.
  91. func (cfg *Config) parseNodes(file string) []*discover.Node {
  92. // Short circuit if no node config is present
  93. path := filepath.Join(cfg.DataDir, file)
  94. if _, err := os.Stat(path); err != nil {
  95. return nil
  96. }
  97. // Load the nodes from the config file
  98. blob, err := ioutil.ReadFile(path)
  99. if err != nil {
  100. glog.V(logger.Error).Infof("Failed to access nodes: %v", err)
  101. return nil
  102. }
  103. nodelist := []string{}
  104. if err := json.Unmarshal(blob, &nodelist); err != nil {
  105. glog.V(logger.Error).Infof("Failed to load nodes: %v", err)
  106. return nil
  107. }
  108. // Interpret the list as a discovery node array
  109. var nodes []*discover.Node
  110. for _, url := range nodelist {
  111. if url == "" {
  112. continue
  113. }
  114. node, err := discover.ParseNode(url)
  115. if err != nil {
  116. glog.V(logger.Error).Infof("Node URL %s: %v\n", url, err)
  117. continue
  118. }
  119. nodes = append(nodes, node)
  120. }
  121. return nodes
  122. }
  123. func (cfg *Config) nodeKey() (*ecdsa.PrivateKey, error) {
  124. // use explicit key from command line args if set
  125. if cfg.NodeKey != nil {
  126. return cfg.NodeKey, nil
  127. }
  128. // use persistent key if present
  129. keyfile := path.Join(cfg.DataDir, "nodekey")
  130. key, err := crypto.LoadECDSA(keyfile)
  131. if err == nil {
  132. return key, nil
  133. }
  134. // no persistent key, generate and store a new one
  135. if key, err = crypto.GenerateKey(); err != nil {
  136. return nil, fmt.Errorf("could not generate server key: %v", err)
  137. }
  138. if err := crypto.SaveECDSA(keyfile, key); err != nil {
  139. glog.V(logger.Error).Infoln("could not persist nodekey: ", err)
  140. }
  141. return key, nil
  142. }
  143. type Ethereum struct {
  144. // Channel for shutting down the ethereum
  145. shutdownChan chan bool
  146. // DB interfaces
  147. blockDb common.Database // Block chain database
  148. stateDb common.Database // State changes database
  149. extraDb common.Database // Extra database (txs, etc)
  150. // Closed when databases are flushed and closed
  151. databasesClosed chan bool
  152. //*** SERVICES ***
  153. // State manager for processing new blocks and managing the over all states
  154. blockProcessor *core.BlockProcessor
  155. txPool *core.TxPool
  156. chainManager *core.ChainManager
  157. accountManager *accounts.Manager
  158. whisper *whisper.Whisper
  159. pow *ethash.Ethash
  160. protocolManager *ProtocolManager
  161. downloader *downloader.Downloader
  162. net *p2p.Server
  163. eventMux *event.TypeMux
  164. txSub event.Subscription
  165. miner *miner.Miner
  166. // logger logger.LogSystem
  167. Mining bool
  168. NatSpec bool
  169. DataDir string
  170. etherbase common.Address
  171. clientVersion string
  172. ethVersionId int
  173. netVersionId int
  174. shhVersionId int
  175. }
  176. func New(config *Config) (*Ethereum, error) {
  177. // Bootstrap database
  178. logger.New(config.DataDir, config.LogFile, config.LogLevel)
  179. if len(config.LogJSON) > 0 {
  180. logger.NewJSONsystem(config.DataDir, config.LogJSON)
  181. }
  182. newdb := config.NewDB
  183. if newdb == nil {
  184. newdb = func(path string) (common.Database, error) { return ethdb.NewLDBDatabase(path) }
  185. }
  186. blockDb, err := newdb(path.Join(config.DataDir, "blockchain"))
  187. if err != nil {
  188. return nil, err
  189. }
  190. stateDb, err := newdb(path.Join(config.DataDir, "state"))
  191. if err != nil {
  192. return nil, err
  193. }
  194. extraDb, err := newdb(path.Join(config.DataDir, "extra"))
  195. if err != nil {
  196. return nil, err
  197. }
  198. nodeDb := path.Join(config.DataDir, "nodes")
  199. // Perform database sanity checks
  200. d, _ := blockDb.Get([]byte("ProtocolVersion"))
  201. protov := int(common.NewValue(d).Uint())
  202. if protov != config.ProtocolVersion && protov != 0 {
  203. path := path.Join(config.DataDir, "blockchain")
  204. return nil, fmt.Errorf("Database version mismatch. Protocol(%d / %d). `rm -rf %s`", protov, config.ProtocolVersion, path)
  205. }
  206. saveProtocolVersion(blockDb, config.ProtocolVersion)
  207. glog.V(logger.Info).Infof("Protocol Version: %v, Network Id: %v", config.ProtocolVersion, config.NetworkId)
  208. if !config.SkipBcVersionCheck {
  209. b, _ := blockDb.Get([]byte("BlockchainVersion"))
  210. bcVersion := int(common.NewValue(b).Uint())
  211. if bcVersion != config.BlockChainVersion && bcVersion != 0 {
  212. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, config.BlockChainVersion)
  213. }
  214. saveBlockchainVersion(blockDb, config.BlockChainVersion)
  215. }
  216. glog.V(logger.Info).Infof("Blockchain DB Version: %d", config.BlockChainVersion)
  217. eth := &Ethereum{
  218. shutdownChan: make(chan bool),
  219. databasesClosed: make(chan bool),
  220. blockDb: blockDb,
  221. stateDb: stateDb,
  222. extraDb: extraDb,
  223. eventMux: &event.TypeMux{},
  224. accountManager: config.AccountManager,
  225. DataDir: config.DataDir,
  226. etherbase: common.HexToAddress(config.Etherbase),
  227. clientVersion: config.Name, // TODO should separate from Name
  228. ethVersionId: config.ProtocolVersion,
  229. netVersionId: config.NetworkId,
  230. NatSpec: config.NatSpec,
  231. }
  232. eth.chainManager = core.NewChainManager(blockDb, stateDb, eth.EventMux())
  233. eth.downloader = downloader.New(eth.chainManager.HasBlock, eth.chainManager.GetBlock)
  234. eth.pow = ethash.New()
  235. eth.txPool = core.NewTxPool(eth.EventMux(), eth.chainManager.State, eth.chainManager.GasLimit)
  236. eth.blockProcessor = core.NewBlockProcessor(stateDb, extraDb, eth.pow, eth.txPool, eth.chainManager, eth.EventMux())
  237. eth.chainManager.SetProcessor(eth.blockProcessor)
  238. eth.miner = miner.New(eth, eth.pow, config.MinerThreads)
  239. eth.protocolManager = NewProtocolManager(config.ProtocolVersion, config.NetworkId, eth.eventMux, eth.txPool, eth.chainManager, eth.downloader)
  240. if config.Shh {
  241. eth.whisper = whisper.New()
  242. eth.shhVersionId = int(eth.whisper.Version())
  243. }
  244. netprv, err := config.nodeKey()
  245. if err != nil {
  246. return nil, err
  247. }
  248. protocols := []p2p.Protocol{eth.protocolManager.SubProtocol}
  249. if config.Shh {
  250. protocols = append(protocols, eth.whisper.Protocol())
  251. }
  252. eth.net = &p2p.Server{
  253. PrivateKey: netprv,
  254. Name: config.Name,
  255. MaxPeers: config.MaxPeers,
  256. MaxPendingPeers: config.MaxPendingPeers,
  257. Protocols: protocols,
  258. NAT: config.NAT,
  259. NoDial: !config.Dial,
  260. BootstrapNodes: config.parseBootNodes(),
  261. StaticNodes: config.parseNodes(staticNodes),
  262. TrustedNodes: config.parseNodes(trustedNodes),
  263. NodeDatabase: nodeDb,
  264. }
  265. if len(config.Port) > 0 {
  266. eth.net.ListenAddr = ":" + config.Port
  267. }
  268. vm.Debug = config.VmDebug
  269. return eth, nil
  270. }
  271. type NodeInfo struct {
  272. Name string
  273. NodeUrl string
  274. NodeID string
  275. IP string
  276. DiscPort int // UDP listening port for discovery protocol
  277. TCPPort int // TCP listening port for RLPx
  278. Td string
  279. ListenAddr string
  280. }
  281. func (s *Ethereum) NodeInfo() *NodeInfo {
  282. node := s.net.Self()
  283. return &NodeInfo{
  284. Name: s.Name(),
  285. NodeUrl: node.String(),
  286. NodeID: node.ID.String(),
  287. IP: node.IP.String(),
  288. DiscPort: int(node.UDP),
  289. TCPPort: int(node.TCP),
  290. ListenAddr: s.net.ListenAddr,
  291. Td: s.ChainManager().Td().String(),
  292. }
  293. }
  294. type PeerInfo struct {
  295. ID string
  296. Name string
  297. Caps string
  298. RemoteAddress string
  299. LocalAddress string
  300. }
  301. func newPeerInfo(peer *p2p.Peer) *PeerInfo {
  302. var caps []string
  303. for _, cap := range peer.Caps() {
  304. caps = append(caps, cap.String())
  305. }
  306. return &PeerInfo{
  307. ID: peer.ID().String(),
  308. Name: peer.Name(),
  309. Caps: strings.Join(caps, ", "),
  310. RemoteAddress: peer.RemoteAddr().String(),
  311. LocalAddress: peer.LocalAddr().String(),
  312. }
  313. }
  314. // PeersInfo returns an array of PeerInfo objects describing connected peers
  315. func (s *Ethereum) PeersInfo() (peersinfo []*PeerInfo) {
  316. for _, peer := range s.net.Peers() {
  317. if peer != nil {
  318. peersinfo = append(peersinfo, newPeerInfo(peer))
  319. }
  320. }
  321. return
  322. }
  323. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  324. s.chainManager.ResetWithGenesisBlock(gb)
  325. }
  326. func (s *Ethereum) StartMining() error {
  327. eb, err := s.Etherbase()
  328. if err != nil {
  329. err = fmt.Errorf("Cannot start mining without etherbase address: %v", err)
  330. glog.V(logger.Error).Infoln(err)
  331. return err
  332. }
  333. go s.miner.Start(eb)
  334. return nil
  335. }
  336. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  337. eb = s.etherbase
  338. if (eb == common.Address{}) {
  339. var ebbytes []byte
  340. ebbytes, err = s.accountManager.Primary()
  341. eb = common.BytesToAddress(ebbytes)
  342. if (eb == common.Address{}) {
  343. err = fmt.Errorf("no accounts found")
  344. }
  345. }
  346. return
  347. }
  348. func (s *Ethereum) StopMining() { s.miner.Stop() }
  349. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  350. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  351. // func (s *Ethereum) Logger() logger.LogSystem { return s.logger }
  352. func (s *Ethereum) Name() string { return s.net.Name }
  353. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  354. func (s *Ethereum) ChainManager() *core.ChainManager { return s.chainManager }
  355. func (s *Ethereum) BlockProcessor() *core.BlockProcessor { return s.blockProcessor }
  356. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  357. func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper }
  358. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  359. func (s *Ethereum) BlockDb() common.Database { return s.blockDb }
  360. func (s *Ethereum) StateDb() common.Database { return s.stateDb }
  361. func (s *Ethereum) ExtraDb() common.Database { return s.extraDb }
  362. func (s *Ethereum) IsListening() bool { return true } // Always listening
  363. func (s *Ethereum) PeerCount() int { return s.net.PeerCount() }
  364. func (s *Ethereum) Peers() []*p2p.Peer { return s.net.Peers() }
  365. func (s *Ethereum) MaxPeers() int { return s.net.MaxPeers }
  366. func (s *Ethereum) ClientVersion() string { return s.clientVersion }
  367. func (s *Ethereum) EthVersion() int { return s.ethVersionId }
  368. func (s *Ethereum) NetVersion() int { return s.netVersionId }
  369. func (s *Ethereum) ShhVersion() int { return s.shhVersionId }
  370. func (s *Ethereum) Downloader() *downloader.Downloader { return s.downloader }
  371. // Start the ethereum
  372. func (s *Ethereum) Start() error {
  373. jsonlogger.LogJson(&logger.LogStarting{
  374. ClientString: s.net.Name,
  375. ProtocolVersion: ProtocolVersion,
  376. })
  377. if s.net.MaxPeers > 0 {
  378. err := s.net.Start()
  379. if err != nil {
  380. return err
  381. }
  382. }
  383. // periodically flush databases
  384. go s.syncDatabases()
  385. // Start services
  386. go s.txPool.Start()
  387. s.protocolManager.Start()
  388. if s.whisper != nil {
  389. s.whisper.Start()
  390. }
  391. // broadcast transactions
  392. s.txSub = s.eventMux.Subscribe(core.TxPreEvent{})
  393. go s.txBroadcastLoop()
  394. glog.V(logger.Info).Infoln("Server started")
  395. return nil
  396. }
  397. func (s *Ethereum) syncDatabases() {
  398. ticker := time.NewTicker(1 * time.Minute)
  399. done:
  400. for {
  401. select {
  402. case <-ticker.C:
  403. // don't change the order of database flushes
  404. if err := s.extraDb.Flush(); err != nil {
  405. glog.V(logger.Error).Infof("error: flush extraDb: %v\n", err)
  406. }
  407. if err := s.stateDb.Flush(); err != nil {
  408. glog.V(logger.Error).Infof("error: flush stateDb: %v\n", err)
  409. }
  410. if err := s.blockDb.Flush(); err != nil {
  411. glog.V(logger.Error).Infof("error: flush blockDb: %v\n", err)
  412. }
  413. case <-s.shutdownChan:
  414. break done
  415. }
  416. }
  417. s.blockDb.Close()
  418. s.stateDb.Close()
  419. s.extraDb.Close()
  420. close(s.databasesClosed)
  421. }
  422. func (s *Ethereum) StartForTest() {
  423. jsonlogger.LogJson(&logger.LogStarting{
  424. ClientString: s.net.Name,
  425. ProtocolVersion: ProtocolVersion,
  426. })
  427. // Start services
  428. s.txPool.Start()
  429. }
  430. // AddPeer connects to the given node and maintains the connection until the
  431. // server is shut down. If the connection fails for any reason, the server will
  432. // attempt to reconnect the peer.
  433. func (self *Ethereum) AddPeer(nodeURL string) error {
  434. n, err := discover.ParseNode(nodeURL)
  435. if err != nil {
  436. return fmt.Errorf("invalid node URL: %v", err)
  437. }
  438. self.net.AddPeer(n)
  439. return nil
  440. }
  441. func (s *Ethereum) Stop() {
  442. s.txSub.Unsubscribe() // quits txBroadcastLoop
  443. s.protocolManager.Stop()
  444. s.chainManager.Stop()
  445. s.txPool.Stop()
  446. s.eventMux.Stop()
  447. if s.whisper != nil {
  448. s.whisper.Stop()
  449. }
  450. glog.V(logger.Info).Infoln("Server stopped")
  451. close(s.shutdownChan)
  452. }
  453. // This function will wait for a shutdown and resumes main thread execution
  454. func (s *Ethereum) WaitForShutdown() {
  455. <-s.databasesClosed
  456. <-s.shutdownChan
  457. }
  458. func (self *Ethereum) txBroadcastLoop() {
  459. // automatically stops if unsubscribe
  460. for obj := range self.txSub.Chan() {
  461. event := obj.(core.TxPreEvent)
  462. self.syncAccounts(event.Tx)
  463. }
  464. }
  465. // keep accounts synced up
  466. func (self *Ethereum) syncAccounts(tx *types.Transaction) {
  467. from, err := tx.From()
  468. if err != nil {
  469. return
  470. }
  471. if self.accountManager.HasAccount(from.Bytes()) {
  472. if self.chainManager.TxState().GetNonce(from) < tx.Nonce() {
  473. self.chainManager.TxState().SetNonce(from, tx.Nonce())
  474. }
  475. }
  476. }
  477. func saveProtocolVersion(db common.Database, protov int) {
  478. d, _ := db.Get([]byte("ProtocolVersion"))
  479. protocolVersion := common.NewValue(d).Uint()
  480. if protocolVersion == 0 {
  481. db.Put([]byte("ProtocolVersion"), common.NewValue(protov).Bytes())
  482. }
  483. }
  484. func saveBlockchainVersion(db common.Database, bcVersion int) {
  485. d, _ := db.Get([]byte("BlockchainVersion"))
  486. blockchainVersion := common.NewValue(d).Uint()
  487. if blockchainVersion == 0 {
  488. db.Put([]byte("BlockchainVersion"), common.NewValue(bcVersion).Bytes())
  489. }
  490. }