backend.go 14 KB

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