backend.go 13 KB

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