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.

442 lines
13 KiB

10 years ago
10 years ago
10 years ago
11 years ago
8 years ago
11 years ago
8 years ago
11 years ago
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
9 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 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. // filter peers by addr or pubkey with a tmsp query.
  98. // if the query return code is OK, add peer
  99. // XXX: query format subject to change
  100. if config.GetBool("filter_peers") {
  101. // NOTE: addr is ip:port
  102. sw.SetAddrFilter(func(addr net.Addr) error {
  103. res := proxyApp.Query().QuerySync([]byte(Fmt("p2p/filter/addr/%s", addr.String())))
  104. if res.IsOK() {
  105. return nil
  106. }
  107. return res
  108. })
  109. sw.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
  110. res := proxyApp.Query().QuerySync([]byte(Fmt("p2p/filter/pubkey/%X", pubkey.Bytes())))
  111. if res.IsOK() {
  112. return nil
  113. }
  114. return res
  115. })
  116. }
  117. // add the event switch to all services
  118. // they should all satisfy events.Eventable
  119. SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor)
  120. // run the profile server
  121. profileHost := config.GetString("prof_laddr")
  122. if profileHost != "" {
  123. go func() {
  124. log.Warn("Profile server", "error", http.ListenAndServe(profileHost, nil))
  125. }()
  126. }
  127. return &Node{
  128. config: config,
  129. sw: sw,
  130. evsw: eventSwitch,
  131. blockStore: blockStore,
  132. bcReactor: bcReactor,
  133. mempoolReactor: mempoolReactor,
  134. consensusState: consensusState,
  135. consensusReactor: consensusReactor,
  136. privValidator: privValidator,
  137. genesisDoc: state.GenesisDoc,
  138. privKey: privKey,
  139. proxyApp: proxyApp,
  140. }
  141. }
  142. // Call Start() after adding the listeners.
  143. func (n *Node) Start() error {
  144. n.sw.SetNodeInfo(makeNodeInfo(n.config, n.sw, n.privKey))
  145. n.sw.SetNodePrivKey(n.privKey)
  146. _, err := n.sw.Start()
  147. return err
  148. }
  149. func (n *Node) Stop() {
  150. log.Notice("Stopping Node")
  151. // TODO: gracefully disconnect from peers.
  152. n.sw.Stop()
  153. }
  154. // Add the event switch to reactors, mempool, etc.
  155. func SetEventSwitch(evsw types.EventSwitch, eventables ...types.Eventable) {
  156. for _, e := range eventables {
  157. e.SetEventSwitch(evsw)
  158. }
  159. }
  160. // Add a Listener to accept inbound peer connections.
  161. // Add listeners before starting the Node.
  162. // The first listener is the primary listener (in NodeInfo)
  163. func (n *Node) AddListener(l p2p.Listener) {
  164. log.Notice(Fmt("Added %v", l))
  165. n.sw.AddListener(l)
  166. }
  167. func (n *Node) StartRPC() ([]net.Listener, error) {
  168. rpccore.SetConfig(n.config)
  169. rpccore.SetEventSwitch(n.evsw)
  170. rpccore.SetBlockStore(n.blockStore)
  171. rpccore.SetConsensusState(n.consensusState)
  172. rpccore.SetMempool(n.mempoolReactor.Mempool)
  173. rpccore.SetSwitch(n.sw)
  174. rpccore.SetPubKey(n.privValidator.PubKey)
  175. rpccore.SetGenesisDoc(n.genesisDoc)
  176. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  177. listenAddrs := strings.Split(n.config.GetString("rpc_laddr"), ",")
  178. // we may expose the rpc over both a unix and tcp socket
  179. listeners := make([]net.Listener, len(listenAddrs))
  180. for i, listenAddr := range listenAddrs {
  181. mux := http.NewServeMux()
  182. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  183. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  184. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  185. listener, err := rpcserver.StartHTTPServer(listenAddr, mux)
  186. if err != nil {
  187. return nil, err
  188. }
  189. listeners[i] = listener
  190. }
  191. // we expose a simplified api over grpc for convenience to app devs
  192. grpcListenAddr := n.config.GetString("grpc_laddr")
  193. if grpcListenAddr != "" {
  194. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  195. if err != nil {
  196. return nil, err
  197. }
  198. listeners = append(listeners, listener)
  199. }
  200. return listeners, nil
  201. }
  202. func (n *Node) Switch() *p2p.Switch {
  203. return n.sw
  204. }
  205. func (n *Node) BlockStore() *bc.BlockStore {
  206. return n.blockStore
  207. }
  208. func (n *Node) ConsensusState() *consensus.ConsensusState {
  209. return n.consensusState
  210. }
  211. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  212. return n.consensusReactor
  213. }
  214. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  215. return n.mempoolReactor
  216. }
  217. func (n *Node) EventSwitch() types.EventSwitch {
  218. return n.evsw
  219. }
  220. // XXX: for convenience
  221. func (n *Node) PrivValidator() *types.PrivValidator {
  222. return n.privValidator
  223. }
  224. func (n *Node) GenesisDoc() *types.GenesisDoc {
  225. return n.genesisDoc
  226. }
  227. func (n *Node) ProxyApp() proxy.AppConns {
  228. return n.proxyApp
  229. }
  230. func makeNodeInfo(config cfg.Config, sw *p2p.Switch, privKey crypto.PrivKeyEd25519) *p2p.NodeInfo {
  231. nodeInfo := &p2p.NodeInfo{
  232. PubKey: privKey.PubKey().(crypto.PubKeyEd25519),
  233. Moniker: config.GetString("moniker"),
  234. Network: config.GetString("chain_id"),
  235. Version: version.Version,
  236. Other: []string{
  237. Fmt("wire_version=%v", wire.Version),
  238. Fmt("p2p_version=%v", p2p.Version),
  239. Fmt("consensus_version=%v", consensus.Version),
  240. Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  241. },
  242. }
  243. // include git hash in the nodeInfo if available
  244. if rev, err := ReadFile(config.GetString("revision_file")); err == nil {
  245. nodeInfo.Other = append(nodeInfo.Other, Fmt("revision=%v", string(rev)))
  246. }
  247. if !sw.IsListening() {
  248. return nodeInfo
  249. }
  250. p2pListener := sw.Listeners()[0]
  251. p2pHost := p2pListener.ExternalAddress().IP.String()
  252. p2pPort := p2pListener.ExternalAddress().Port
  253. rpcListenAddr := config.GetString("rpc_laddr")
  254. // We assume that the rpcListener has the same ExternalAddress.
  255. // This is probably true because both P2P and RPC listeners use UPnP,
  256. // except of course if the rpc is only bound to localhost
  257. nodeInfo.ListenAddr = Fmt("%v:%v", p2pHost, p2pPort)
  258. nodeInfo.Other = append(nodeInfo.Other, Fmt("rpc_addr=%v", rpcListenAddr))
  259. return nodeInfo
  260. }
  261. //------------------------------------------------------------------------------
  262. // Users wishing to:
  263. // * use an external signer for their validators
  264. // * supply an in-proc tmsp app
  265. // should fork tendermint/tendermint and implement RunNode to
  266. // call NewNode with their custom priv validator and/or custom
  267. // proxy.ClientCreator interface
  268. func RunNode(config cfg.Config) {
  269. // Wait until the genesis doc becomes available
  270. genDocFile := config.GetString("genesis_file")
  271. if !FileExists(genDocFile) {
  272. log.Notice(Fmt("Waiting for genesis file %v...", genDocFile))
  273. for {
  274. time.Sleep(time.Second)
  275. if !FileExists(genDocFile) {
  276. continue
  277. }
  278. jsonBlob, err := ioutil.ReadFile(genDocFile)
  279. if err != nil {
  280. Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
  281. }
  282. genDoc := types.GenesisDocFromJSON(jsonBlob)
  283. if genDoc.ChainID == "" {
  284. PanicSanity(Fmt("Genesis doc %v must include non-empty chain_id", genDocFile))
  285. }
  286. config.Set("chain_id", genDoc.ChainID)
  287. }
  288. }
  289. // Create & start node
  290. n := NewNodeDefault(config)
  291. protocol, address := ProtocolAndAddress(config.GetString("node_laddr"))
  292. l := p2p.NewDefaultListener(protocol, address, config.GetBool("skip_upnp"))
  293. n.AddListener(l)
  294. err := n.Start()
  295. if err != nil {
  296. Exit(Fmt("Failed to start node: %v", err))
  297. }
  298. log.Notice("Started node", "nodeInfo", n.sw.NodeInfo())
  299. // If seedNode is provided by config, dial out.
  300. if config.GetString("seeds") != "" {
  301. seeds := strings.Split(config.GetString("seeds"), ",")
  302. n.sw.DialSeeds(seeds)
  303. }
  304. // Run the RPC server.
  305. if config.GetString("rpc_laddr") != "" {
  306. _, err := n.StartRPC()
  307. if err != nil {
  308. PanicCrisis(err)
  309. }
  310. }
  311. // Sleep forever and then...
  312. TrapSignal(func() {
  313. n.Stop()
  314. })
  315. }
  316. func (n *Node) NodeInfo() *p2p.NodeInfo {
  317. return n.sw.NodeInfo()
  318. }
  319. func (n *Node) DialSeeds(seeds []string) {
  320. n.sw.DialSeeds(seeds)
  321. }
  322. //------------------------------------------------------------------------------
  323. // replay
  324. // convenience for replay mode
  325. func newConsensusState(config cfg.Config) *consensus.ConsensusState {
  326. // Get BlockStore
  327. blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir"))
  328. blockStore := bc.NewBlockStore(blockStoreDB)
  329. // Get State
  330. stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir"))
  331. state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  332. // Create proxyAppConn connection (consensus, mempool, query)
  333. proxyApp := proxy.NewAppConns(config, proxy.DefaultClientCreator(config), sm.NewHandshaker(config, state, blockStore))
  334. _, err := proxyApp.Start()
  335. if err != nil {
  336. Exit(Fmt("Error starting proxy app conns: %v", err))
  337. }
  338. // add the chainid to the global config
  339. config.Set("chain_id", state.ChainID)
  340. // Make event switch
  341. eventSwitch := types.NewEventSwitch()
  342. if _, err := eventSwitch.Start(); err != nil {
  343. Exit(Fmt("Failed to start event switch: %v", err))
  344. }
  345. mempool := mempl.NewMempool(config, proxyApp.Mempool())
  346. consensusState := consensus.NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  347. consensusState.SetEventSwitch(eventSwitch)
  348. return consensusState
  349. }
  350. func RunReplayConsole(config cfg.Config, walFile string) {
  351. consensusState := newConsensusState(config)
  352. if err := consensusState.ReplayConsole(walFile); err != nil {
  353. Exit(Fmt("Error during consensus replay: %v", err))
  354. }
  355. }
  356. func RunReplay(config cfg.Config, walFile string) {
  357. consensusState := newConsensusState(config)
  358. if err := consensusState.ReplayMessages(walFile); err != nil {
  359. Exit(Fmt("Error during consensus replay: %v", err))
  360. }
  361. log.Notice("Replay run successfully")
  362. }
  363. // Defaults to tcp
  364. func ProtocolAndAddress(listenAddr string) (string, string) {
  365. protocol, address := "tcp", listenAddr
  366. parts := strings.SplitN(address, "://", 2)
  367. if len(parts) == 2 {
  368. protocol, address = parts[0], parts[1]
  369. }
  370. return protocol, address
  371. }