backend.go 14 KB

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