backend.go 12 KB

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