backend.go 17 KB

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