You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

451 lines
13 KiB

10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
8 years ago
8 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net"
  6. "net/http"
  7. "strings"
  8. "time"
  9. . "github.com/tendermint/go-common"
  10. cfg "github.com/tendermint/go-config"
  11. "github.com/tendermint/go-crypto"
  12. dbm "github.com/tendermint/go-db"
  13. "github.com/tendermint/go-p2p"
  14. "github.com/tendermint/go-rpc"
  15. "github.com/tendermint/go-rpc/server"
  16. "github.com/tendermint/go-wire"
  17. bc "github.com/tendermint/tendermint/blockchain"
  18. "github.com/tendermint/tendermint/consensus"
  19. mempl "github.com/tendermint/tendermint/mempool"
  20. "github.com/tendermint/tendermint/proxy"
  21. rpccore "github.com/tendermint/tendermint/rpc/core"
  22. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  23. sm "github.com/tendermint/tendermint/state"
  24. "github.com/tendermint/tendermint/types"
  25. "github.com/tendermint/tendermint/version"
  26. )
  27. import _ "net/http/pprof"
  28. type Node struct {
  29. config cfg.Config
  30. sw *p2p.Switch
  31. evsw types.EventSwitch
  32. blockStore *bc.BlockStore
  33. bcReactor *bc.BlockchainReactor
  34. mempoolReactor *mempl.MempoolReactor
  35. consensusState *consensus.ConsensusState
  36. consensusReactor *consensus.ConsensusReactor
  37. privValidator *types.PrivValidator
  38. genesisDoc *types.GenesisDoc
  39. privKey crypto.PrivKeyEd25519
  40. proxyApp proxy.AppConns
  41. }
  42. func NewNodeDefault(config cfg.Config) *Node {
  43. // Get PrivValidator
  44. privValidatorFile := config.GetString("priv_validator_file")
  45. privValidator := types.LoadOrGenPrivValidator(privValidatorFile)
  46. return NewNode(config, privValidator, proxy.DefaultClientCreator(config))
  47. }
  48. func NewNode(config cfg.Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node {
  49. // Get BlockStore
  50. blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir"))
  51. blockStore := bc.NewBlockStore(blockStoreDB)
  52. // Get State db
  53. stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir"))
  54. // Get State
  55. state := sm.GetState(config, stateDB)
  56. // Create the proxyApp, which manages connections (consensus, mempool, query)
  57. proxyApp := proxy.NewAppConns(config, clientCreator, sm.NewHandshaker(config, state, blockStore))
  58. if _, err := proxyApp.Start(); err != nil {
  59. Exit(Fmt("Error starting proxy app connections: %v", err))
  60. }
  61. // add the chainid and number of validators to the global config
  62. config.Set("chain_id", state.ChainID)
  63. config.Set("num_vals", state.Validators.Size())
  64. // Generate node PrivKey
  65. privKey := crypto.GenPrivKeyEd25519()
  66. // Make event switch
  67. eventSwitch := types.NewEventSwitch()
  68. _, err := eventSwitch.Start()
  69. if err != nil {
  70. Exit(Fmt("Failed to start switch: %v", err))
  71. }
  72. // Decide whether to fast-sync or not
  73. // We don't fast-sync when the only validator is us.
  74. fastSync := config.GetBool("fast_sync")
  75. if state.Validators.Size() == 1 {
  76. addr, _ := state.Validators.GetByIndex(0)
  77. if bytes.Equal(privValidator.Address, addr) {
  78. fastSync = false
  79. }
  80. }
  81. // Make BlockchainReactor
  82. bcReactor := bc.NewBlockchainReactor(config, state.Copy(), proxyApp.Consensus(), blockStore, fastSync)
  83. // Make MempoolReactor
  84. mempool := mempl.NewMempool(config, proxyApp.Mempool())
  85. mempoolReactor := mempl.NewMempoolReactor(config, mempool)
  86. // Make ConsensusReactor
  87. consensusState := consensus.NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  88. if privValidator != nil {
  89. consensusState.SetPrivValidator(privValidator)
  90. }
  91. consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync)
  92. // Make p2p network switch
  93. sw := p2p.NewSwitch(config.GetConfig("p2p"))
  94. sw.AddReactor("MEMPOOL", mempoolReactor)
  95. sw.AddReactor("BLOCKCHAIN", bcReactor)
  96. sw.AddReactor("CONSENSUS", consensusReactor)
  97. // Optionally, start the pex reactor
  98. // TODO: this is a dev feature, it needs some love
  99. if config.GetBool("pex_reactor") {
  100. addrBook := p2p.NewAddrBook(config.GetString("addrbook_file"), config.GetBool("addrbook_strict"))
  101. addrBook.Start()
  102. pexReactor := p2p.NewPEXReactor(addrBook)
  103. sw.AddReactor("PEX", pexReactor)
  104. }
  105. // filter peers by addr or pubkey with a abci query.
  106. // if the query return code is OK, add peer
  107. // XXX: query format subject to change
  108. if config.GetBool("filter_peers") {
  109. // NOTE: addr is ip:port
  110. sw.SetAddrFilter(func(addr net.Addr) error {
  111. res := proxyApp.Query().QuerySync([]byte(Fmt("p2p/filter/addr/%s", addr.String())))
  112. if res.IsOK() {
  113. return nil
  114. }
  115. return res
  116. })
  117. sw.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
  118. res := proxyApp.Query().QuerySync([]byte(Fmt("p2p/filter/pubkey/%X", pubkey.Bytes())))
  119. if res.IsOK() {
  120. return nil
  121. }
  122. return res
  123. })
  124. }
  125. // add the event switch to all services
  126. // they should all satisfy events.Eventable
  127. SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor)
  128. // run the profile server
  129. profileHost := config.GetString("prof_laddr")
  130. if profileHost != "" {
  131. go func() {
  132. log.Warn("Profile server", "error", http.ListenAndServe(profileHost, nil))
  133. }()
  134. }
  135. return &Node{
  136. config: config,
  137. sw: sw,
  138. evsw: eventSwitch,
  139. blockStore: blockStore,
  140. bcReactor: bcReactor,
  141. mempoolReactor: mempoolReactor,
  142. consensusState: consensusState,
  143. consensusReactor: consensusReactor,
  144. privValidator: privValidator,
  145. genesisDoc: state.GenesisDoc,
  146. privKey: privKey,
  147. proxyApp: proxyApp,
  148. }
  149. }
  150. // Call Start() after adding the listeners.
  151. func (n *Node) Start() error {
  152. n.sw.SetNodeInfo(makeNodeInfo(n.config, n.sw, n.privKey))
  153. n.sw.SetNodePrivKey(n.privKey)
  154. _, err := n.sw.Start()
  155. return err
  156. }
  157. func (n *Node) Stop() {
  158. log.Notice("Stopping Node")
  159. // TODO: gracefully disconnect from peers.
  160. n.sw.Stop()
  161. }
  162. // Add the event switch to reactors, mempool, etc.
  163. func SetEventSwitch(evsw types.EventSwitch, eventables ...types.Eventable) {
  164. for _, e := range eventables {
  165. e.SetEventSwitch(evsw)
  166. }
  167. }
  168. // Add a Listener to accept inbound peer connections.
  169. // Add listeners before starting the Node.
  170. // The first listener is the primary listener (in NodeInfo)
  171. func (n *Node) AddListener(l p2p.Listener) {
  172. log.Notice(Fmt("Added %v", l))
  173. n.sw.AddListener(l)
  174. }
  175. func (n *Node) StartRPC() ([]net.Listener, error) {
  176. rpccore.SetConfig(n.config)
  177. rpccore.SetEventSwitch(n.evsw)
  178. rpccore.SetBlockStore(n.blockStore)
  179. rpccore.SetConsensusState(n.consensusState)
  180. rpccore.SetMempool(n.mempoolReactor.Mempool)
  181. rpccore.SetSwitch(n.sw)
  182. rpccore.SetPubKey(n.privValidator.PubKey)
  183. rpccore.SetGenesisDoc(n.genesisDoc)
  184. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  185. listenAddrs := strings.Split(n.config.GetString("rpc_laddr"), ",")
  186. // we may expose the rpc over both a unix and tcp socket
  187. listeners := make([]net.Listener, len(listenAddrs))
  188. for i, listenAddr := range listenAddrs {
  189. mux := http.NewServeMux()
  190. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  191. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  192. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  193. listener, err := rpcserver.StartHTTPServer(listenAddr, mux)
  194. if err != nil {
  195. return nil, err
  196. }
  197. listeners[i] = listener
  198. }
  199. // we expose a simplified api over grpc for convenience to app devs
  200. grpcListenAddr := n.config.GetString("grpc_laddr")
  201. if grpcListenAddr != "" {
  202. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  203. if err != nil {
  204. return nil, err
  205. }
  206. listeners = append(listeners, listener)
  207. }
  208. return listeners, nil
  209. }
  210. func (n *Node) Switch() *p2p.Switch {
  211. return n.sw
  212. }
  213. func (n *Node) BlockStore() *bc.BlockStore {
  214. return n.blockStore
  215. }
  216. func (n *Node) ConsensusState() *consensus.ConsensusState {
  217. return n.consensusState
  218. }
  219. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  220. return n.consensusReactor
  221. }
  222. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  223. return n.mempoolReactor
  224. }
  225. func (n *Node) EventSwitch() types.EventSwitch {
  226. return n.evsw
  227. }
  228. // XXX: for convenience
  229. func (n *Node) PrivValidator() *types.PrivValidator {
  230. return n.privValidator
  231. }
  232. func (n *Node) GenesisDoc() *types.GenesisDoc {
  233. return n.genesisDoc
  234. }
  235. func (n *Node) ProxyApp() proxy.AppConns {
  236. return n.proxyApp
  237. }
  238. func makeNodeInfo(config cfg.Config, sw *p2p.Switch, privKey crypto.PrivKeyEd25519) *p2p.NodeInfo {
  239. nodeInfo := &p2p.NodeInfo{
  240. PubKey: privKey.PubKey().(crypto.PubKeyEd25519),
  241. Moniker: config.GetString("moniker"),
  242. Network: config.GetString("chain_id"),
  243. Version: version.Version,
  244. Other: []string{
  245. Fmt("wire_version=%v", wire.Version),
  246. Fmt("p2p_version=%v", p2p.Version),
  247. Fmt("consensus_version=%v", consensus.Version),
  248. Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  249. },
  250. }
  251. // include git hash in the nodeInfo if available
  252. if rev, err := ReadFile(config.GetString("revision_file")); err == nil {
  253. nodeInfo.Other = append(nodeInfo.Other, Fmt("revision=%v", string(rev)))
  254. }
  255. if !sw.IsListening() {
  256. return nodeInfo
  257. }
  258. p2pListener := sw.Listeners()[0]
  259. p2pHost := p2pListener.ExternalAddress().IP.String()
  260. p2pPort := p2pListener.ExternalAddress().Port
  261. rpcListenAddr := config.GetString("rpc_laddr")
  262. // We assume that the rpcListener has the same ExternalAddress.
  263. // This is probably true because both P2P and RPC listeners use UPnP,
  264. // except of course if the rpc is only bound to localhost
  265. nodeInfo.ListenAddr = Fmt("%v:%v", p2pHost, p2pPort)
  266. nodeInfo.Other = append(nodeInfo.Other, Fmt("rpc_addr=%v", rpcListenAddr))
  267. return nodeInfo
  268. }
  269. //------------------------------------------------------------------------------
  270. // Users wishing to:
  271. // * use an external signer for their validators
  272. // * supply an in-proc abci app
  273. // should fork tendermint/tendermint and implement RunNode to
  274. // call NewNode with their custom priv validator and/or custom
  275. // proxy.ClientCreator interface
  276. func RunNode(config cfg.Config) {
  277. // Wait until the genesis doc becomes available
  278. genDocFile := config.GetString("genesis_file")
  279. if !FileExists(genDocFile) {
  280. log.Notice(Fmt("Waiting for genesis file %v...", genDocFile))
  281. for {
  282. time.Sleep(time.Second)
  283. if !FileExists(genDocFile) {
  284. continue
  285. }
  286. jsonBlob, err := ioutil.ReadFile(genDocFile)
  287. if err != nil {
  288. Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
  289. }
  290. genDoc := types.GenesisDocFromJSON(jsonBlob)
  291. if genDoc.ChainID == "" {
  292. PanicSanity(Fmt("Genesis doc %v must include non-empty chain_id", genDocFile))
  293. }
  294. config.Set("chain_id", genDoc.ChainID)
  295. }
  296. }
  297. // Create & start node
  298. n := NewNodeDefault(config)
  299. protocol, address := ProtocolAndAddress(config.GetString("node_laddr"))
  300. l := p2p.NewDefaultListener(protocol, address, config.GetBool("skip_upnp"))
  301. n.AddListener(l)
  302. err := n.Start()
  303. if err != nil {
  304. Exit(Fmt("Failed to start node: %v", err))
  305. }
  306. log.Notice("Started node", "nodeInfo", n.sw.NodeInfo())
  307. // If seedNode is provided by config, dial out.
  308. if config.GetString("seeds") != "" {
  309. seeds := strings.Split(config.GetString("seeds"), ",")
  310. n.sw.DialSeeds(seeds)
  311. }
  312. // Run the RPC server.
  313. if config.GetString("rpc_laddr") != "" {
  314. _, err := n.StartRPC()
  315. if err != nil {
  316. PanicCrisis(err)
  317. }
  318. }
  319. // Sleep forever and then...
  320. TrapSignal(func() {
  321. n.Stop()
  322. })
  323. }
  324. func (n *Node) NodeInfo() *p2p.NodeInfo {
  325. return n.sw.NodeInfo()
  326. }
  327. func (n *Node) DialSeeds(seeds []string) {
  328. n.sw.DialSeeds(seeds)
  329. }
  330. //------------------------------------------------------------------------------
  331. // replay
  332. // convenience for replay mode
  333. func newConsensusState(config cfg.Config) *consensus.ConsensusState {
  334. // Get BlockStore
  335. blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir"))
  336. blockStore := bc.NewBlockStore(blockStoreDB)
  337. // Get State
  338. stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir"))
  339. state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  340. // Create proxyAppConn connection (consensus, mempool, query)
  341. proxyApp := proxy.NewAppConns(config, proxy.DefaultClientCreator(config), sm.NewHandshaker(config, state, blockStore))
  342. _, err := proxyApp.Start()
  343. if err != nil {
  344. Exit(Fmt("Error starting proxy app conns: %v", err))
  345. }
  346. // add the chainid to the global config
  347. config.Set("chain_id", state.ChainID)
  348. // Make event switch
  349. eventSwitch := types.NewEventSwitch()
  350. if _, err := eventSwitch.Start(); err != nil {
  351. Exit(Fmt("Failed to start event switch: %v", err))
  352. }
  353. mempool := mempl.NewMempool(config, proxyApp.Mempool())
  354. consensusState := consensus.NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  355. consensusState.SetEventSwitch(eventSwitch)
  356. return consensusState
  357. }
  358. func RunReplayConsole(config cfg.Config, walFile string) {
  359. consensusState := newConsensusState(config)
  360. if err := consensusState.ReplayConsole(walFile); err != nil {
  361. Exit(Fmt("Error during consensus replay: %v", err))
  362. }
  363. }
  364. func RunReplay(config cfg.Config, walFile string) {
  365. consensusState := newConsensusState(config)
  366. if err := consensusState.ReplayMessages(walFile); err != nil {
  367. Exit(Fmt("Error during consensus replay: %v", err))
  368. }
  369. log.Notice("Replay run successfully")
  370. }
  371. // Defaults to tcp
  372. func ProtocolAndAddress(listenAddr string) (string, string) {
  373. protocol, address := "tcp", listenAddr
  374. parts := strings.SplitN(address, "://", 2)
  375. if len(parts) == 2 {
  376. protocol, address = parts[0], parts[1]
  377. }
  378. return protocol, address
  379. }