backend.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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/core/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. 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. 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. logger.New(config.DataDir, config.LogFile, config.LogLevel)
  130. if len(config.LogJSON) > 0 {
  131. logger.NewJSONsystem(config.DataDir, config.LogJSON)
  132. }
  133. newdb := config.NewDB
  134. if newdb == nil {
  135. newdb = func(path string) (common.Database, error) { return ethdb.NewLDBDatabase(path) }
  136. }
  137. blockDb, err := newdb(path.Join(config.DataDir, "blockchain"))
  138. if err != nil {
  139. return nil, err
  140. }
  141. stateDb, err := newdb(path.Join(config.DataDir, "state"))
  142. if err != nil {
  143. return nil, err
  144. }
  145. extraDb, err := ethdb.NewLDBDatabase(path.Join(config.DataDir, "extra"))
  146. // Perform database sanity checks
  147. d, _ := extraDb.Get([]byte("ProtocolVersion"))
  148. protov := int(common.NewValue(d).Uint())
  149. if protov != config.ProtocolVersion && protov != 0 {
  150. path := path.Join(config.DataDir, "blockchain")
  151. return nil, fmt.Errorf("Database version mismatch. Protocol(%d / %d). `rm -rf %s`", protov, config.ProtocolVersion, path)
  152. }
  153. saveProtocolVersion(extraDb, config.ProtocolVersion)
  154. servlogger.Infof("Protocol Version: %v, Network Id: %v", config.ProtocolVersion, config.NetworkId)
  155. eth := &Ethereum{
  156. shutdownChan: make(chan bool),
  157. blockDb: blockDb,
  158. stateDb: stateDb,
  159. extraDb: extraDb,
  160. eventMux: &event.TypeMux{},
  161. // logger: servlogsystem,
  162. accountManager: config.AccountManager,
  163. DataDir: config.DataDir,
  164. version: config.Name, // TODO should separate from Name
  165. }
  166. eth.chainManager = core.NewChainManager(blockDb, stateDb, eth.EventMux())
  167. eth.pow = ethash.New(eth.chainManager)
  168. eth.txPool = core.NewTxPool(eth.EventMux())
  169. eth.blockProcessor = core.NewBlockProcessor(stateDb, extraDb, eth.pow, eth.txPool, eth.chainManager, eth.EventMux())
  170. eth.chainManager.SetProcessor(eth.blockProcessor)
  171. eth.whisper = whisper.New()
  172. eth.miner = miner.New(eth, eth.pow, config.MinerThreads)
  173. hasBlock := eth.chainManager.HasBlock
  174. insertChain := eth.chainManager.InsertChain
  175. td := eth.chainManager.Td()
  176. eth.blockPool = blockpool.New(hasBlock, insertChain, eth.pow.Verify, eth.EventMux(), td)
  177. netprv, err := config.nodeKey()
  178. if err != nil {
  179. return nil, err
  180. }
  181. ethProto := EthProtocol(config.ProtocolVersion, config.NetworkId, eth.txPool, eth.chainManager, eth.blockPool)
  182. protocols := []p2p.Protocol{ethProto}
  183. if config.Shh {
  184. protocols = append(protocols, eth.whisper.Protocol())
  185. }
  186. eth.net = &p2p.Server{
  187. PrivateKey: netprv,
  188. Name: config.Name,
  189. MaxPeers: config.MaxPeers,
  190. Protocols: protocols,
  191. NAT: config.NAT,
  192. NoDial: !config.Dial,
  193. BootstrapNodes: config.parseBootNodes(),
  194. }
  195. if len(config.Port) > 0 {
  196. eth.net.ListenAddr = ":" + config.Port
  197. }
  198. vm.Debug = config.VmDebug
  199. return eth, nil
  200. }
  201. type NodeInfo struct {
  202. Name string
  203. NodeUrl string
  204. NodeID string
  205. IP string
  206. DiscPort int // UDP listening port for discovery protocol
  207. TCPPort int // TCP listening port for RLPx
  208. Td string
  209. ListenAddr string
  210. }
  211. func (s *Ethereum) NodeInfo() *NodeInfo {
  212. node := s.net.Self()
  213. return &NodeInfo{
  214. Name: s.Name(),
  215. NodeUrl: node.String(),
  216. NodeID: node.ID.String(),
  217. IP: node.IP.String(),
  218. DiscPort: node.DiscPort,
  219. TCPPort: node.TCPPort,
  220. ListenAddr: s.net.ListenAddr,
  221. Td: s.ChainManager().Td().String(),
  222. }
  223. }
  224. type PeerInfo struct {
  225. ID string
  226. Name string
  227. Caps string
  228. RemoteAddress string
  229. LocalAddress string
  230. }
  231. func newPeerInfo(peer *p2p.Peer) *PeerInfo {
  232. var caps []string
  233. for _, cap := range peer.Caps() {
  234. caps = append(caps, cap.String())
  235. }
  236. return &PeerInfo{
  237. ID: peer.ID().String(),
  238. Name: peer.Name(),
  239. Caps: strings.Join(caps, ", "),
  240. RemoteAddress: peer.RemoteAddr().String(),
  241. LocalAddress: peer.LocalAddr().String(),
  242. }
  243. }
  244. // PeersInfo returns an array of PeerInfo objects describing connected peers
  245. func (s *Ethereum) PeersInfo() (peersinfo []*PeerInfo) {
  246. for _, peer := range s.net.Peers() {
  247. if peer != nil {
  248. peersinfo = append(peersinfo, newPeerInfo(peer))
  249. }
  250. }
  251. return
  252. }
  253. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  254. s.chainManager.ResetWithGenesisBlock(gb)
  255. s.pow.UpdateCache(true)
  256. }
  257. func (s *Ethereum) StartMining() error {
  258. cb, err := s.accountManager.Coinbase()
  259. if err != nil {
  260. servlogger.Errorf("Cannot start mining without coinbase: %v\n", err)
  261. return fmt.Errorf("no coinbase: %v", err)
  262. }
  263. s.miner.Start(common.BytesToAddress(cb))
  264. return nil
  265. }
  266. func (s *Ethereum) StopMining() { s.miner.Stop() }
  267. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  268. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  269. // func (s *Ethereum) Logger() logger.LogSystem { return s.logger }
  270. func (s *Ethereum) Name() string { return s.net.Name }
  271. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  272. func (s *Ethereum) ChainManager() *core.ChainManager { return s.chainManager }
  273. func (s *Ethereum) BlockProcessor() *core.BlockProcessor { return s.blockProcessor }
  274. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  275. func (s *Ethereum) BlockPool() *blockpool.BlockPool { return s.blockPool }
  276. func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper }
  277. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  278. func (s *Ethereum) BlockDb() common.Database { return s.blockDb }
  279. func (s *Ethereum) StateDb() common.Database { return s.stateDb }
  280. func (s *Ethereum) ExtraDb() common.Database { return s.extraDb }
  281. func (s *Ethereum) IsListening() bool { return true } // Always listening
  282. func (s *Ethereum) PeerCount() int { return s.net.PeerCount() }
  283. func (s *Ethereum) Peers() []*p2p.Peer { return s.net.Peers() }
  284. func (s *Ethereum) MaxPeers() int { return s.net.MaxPeers }
  285. func (s *Ethereum) Version() string { return s.version }
  286. // Start the ethereum
  287. func (s *Ethereum) Start() error {
  288. jsonlogger.LogJson(&logger.LogStarting{
  289. ClientString: s.net.Name,
  290. ProtocolVersion: ProtocolVersion,
  291. })
  292. if s.net.MaxPeers > 0 {
  293. err := s.net.Start()
  294. if err != nil {
  295. return err
  296. }
  297. }
  298. // Start services
  299. s.txPool.Start()
  300. s.blockPool.Start()
  301. if s.whisper != nil {
  302. s.whisper.Start()
  303. }
  304. // broadcast transactions
  305. s.txSub = s.eventMux.Subscribe(core.TxPreEvent{})
  306. go s.txBroadcastLoop()
  307. // broadcast mined blocks
  308. s.blockSub = s.eventMux.Subscribe(core.NewMinedBlockEvent{})
  309. go s.blockBroadcastLoop()
  310. servlogger.Infoln("Server started")
  311. return nil
  312. }
  313. func (s *Ethereum) StartForTest() {
  314. jsonlogger.LogJson(&logger.LogStarting{
  315. ClientString: s.net.Name,
  316. ProtocolVersion: ProtocolVersion,
  317. })
  318. // Start services
  319. s.txPool.Start()
  320. s.blockPool.Start()
  321. }
  322. func (self *Ethereum) SuggestPeer(nodeURL string) error {
  323. n, err := discover.ParseNode(nodeURL)
  324. if err != nil {
  325. return fmt.Errorf("invalid node URL: %v", err)
  326. }
  327. self.net.SuggestPeer(n)
  328. return nil
  329. }
  330. func (s *Ethereum) Stop() {
  331. // Close the database
  332. defer s.blockDb.Close()
  333. defer s.stateDb.Close()
  334. defer s.extraDb.Close()
  335. s.txSub.Unsubscribe() // quits txBroadcastLoop
  336. s.blockSub.Unsubscribe() // quits blockBroadcastLoop
  337. s.txPool.Stop()
  338. s.eventMux.Stop()
  339. s.blockPool.Stop()
  340. if s.whisper != nil {
  341. s.whisper.Stop()
  342. }
  343. servlogger.Infoln("Server stopped")
  344. close(s.shutdownChan)
  345. }
  346. // This function will wait for a shutdown and resumes main thread execution
  347. func (s *Ethereum) WaitForShutdown() {
  348. <-s.shutdownChan
  349. }
  350. // now tx broadcasting is taken out of txPool
  351. // handled here via subscription, efficiency?
  352. func (self *Ethereum) txBroadcastLoop() {
  353. // automatically stops if unsubscribe
  354. for obj := range self.txSub.Chan() {
  355. event := obj.(core.TxPreEvent)
  356. self.net.Broadcast("eth", TxMsg, []*types.Transaction{event.Tx})
  357. }
  358. }
  359. func (self *Ethereum) blockBroadcastLoop() {
  360. // automatically stops if unsubscribe
  361. for obj := range self.blockSub.Chan() {
  362. switch ev := obj.(type) {
  363. case core.NewMinedBlockEvent:
  364. self.net.Broadcast("eth", NewBlockMsg, []interface{}{ev.Block, ev.Block.Td})
  365. }
  366. }
  367. }
  368. func saveProtocolVersion(db common.Database, protov int) {
  369. d, _ := db.Get([]byte("ProtocolVersion"))
  370. protocolVersion := common.NewValue(d).Uint()
  371. if protocolVersion == 0 {
  372. db.Put([]byte("ProtocolVersion"), common.NewValue(protov).Bytes())
  373. }
  374. }