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.

461 lines
13 KiB

10 years ago
10 years ago
10 years ago
11 years ago
8 years ago
11 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
9 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. sm "github.com/tendermint/tendermint/state"
  23. "github.com/tendermint/tendermint/types"
  24. "github.com/tendermint/tendermint/version"
  25. )
  26. import _ "net/http/pprof"
  27. type Node struct {
  28. config cfg.Config
  29. sw *p2p.Switch
  30. evsw types.EventSwitch
  31. blockStore *bc.BlockStore
  32. bcReactor *bc.BlockchainReactor
  33. mempoolReactor *mempl.MempoolReactor
  34. consensusState *consensus.ConsensusState
  35. consensusReactor *consensus.ConsensusReactor
  36. privValidator *types.PrivValidator
  37. genesisDoc *types.GenesisDoc
  38. privKey crypto.PrivKeyEd25519
  39. proxyApp proxy.AppConns
  40. }
  41. func NewNodeDefault(config cfg.Config) *Node {
  42. // Get PrivValidator
  43. privValidatorFile := config.GetString("priv_validator_file")
  44. privValidator := types.LoadOrGenPrivValidator(privValidatorFile)
  45. return NewNode(config, privValidator, proxy.DefaultClientCreator(config))
  46. }
  47. func NewNode(config cfg.Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node {
  48. EnsureDir(config.GetString("db_dir"), 0700) // incase we use memdb, cswal still gets written here
  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 := getState(config, stateDB)
  56. // Create the proxyApp, which houses three connections:
  57. // query, consensus, and mempool
  58. proxyApp := proxy.NewAppConns(config, clientCreator, state, blockStore)
  59. if _, err := proxyApp.Start(); err != nil {
  60. Exit(Fmt("Error starting proxy app connections: %v", err))
  61. }
  62. // add the chainid and number of validators to the global config
  63. config.Set("chain_id", state.ChainID)
  64. config.Set("num_vals", state.Validators.Size())
  65. // Generate node PrivKey
  66. privKey := crypto.GenPrivKeyEd25519()
  67. // Make event switch
  68. eventSwitch := types.NewEventSwitch()
  69. _, err := eventSwitch.Start()
  70. if err != nil {
  71. Exit(Fmt("Failed to start switch: %v", err))
  72. }
  73. // Decide whether to fast-sync or not
  74. // We don't fast-sync when the only validator is us.
  75. fastSync := config.GetBool("fast_sync")
  76. if state.Validators.Size() == 1 {
  77. addr, _ := state.Validators.GetByIndex(0)
  78. if bytes.Equal(privValidator.Address, addr) {
  79. fastSync = false
  80. }
  81. }
  82. // Make BlockchainReactor
  83. bcReactor := bc.NewBlockchainReactor(state.Copy(), proxyApp.Consensus(), blockStore, fastSync)
  84. // Make MempoolReactor
  85. mempool := mempl.NewMempool(config, proxyApp.Mempool())
  86. mempoolReactor := mempl.NewMempoolReactor(config, mempool)
  87. // Make ConsensusReactor
  88. consensusState := consensus.NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  89. consensusReactor := consensus.NewConsensusReactor(consensusState, blockStore, fastSync)
  90. if privValidator != nil {
  91. consensusReactor.SetPrivValidator(privValidator)
  92. }
  93. // Make p2p network switch
  94. sw := p2p.NewSwitch(config.GetConfig("p2p"))
  95. sw.AddReactor("MEMPOOL", mempoolReactor)
  96. sw.AddReactor("BLOCKCHAIN", bcReactor)
  97. sw.AddReactor("CONSENSUS", consensusReactor)
  98. // Optionally, start the pex reactor
  99. // TODO: this is a dev feature, it needs some love
  100. if config.GetBool("pex_reactor") {
  101. addrBook := p2p.NewAddrBook(config.GetString("addrbook_file"), config.GetBool("addrbook_strict"))
  102. addrBook.Start()
  103. pexReactor := p2p.NewPEXReactor(addrBook)
  104. sw.AddReactor("PEX", pexReactor)
  105. }
  106. // filter peers by addr or pubkey with a tmsp query.
  107. // if the query return code is OK, add peer
  108. // XXX: query format subject to change
  109. if config.GetBool("filter_peers") {
  110. // NOTE: addr is ip:port
  111. sw.SetAddrFilter(func(addr net.Addr) error {
  112. res := proxyApp.Query().QuerySync([]byte(Fmt("p2p/filter/addr/%s", addr.String())))
  113. if res.IsOK() {
  114. return nil
  115. }
  116. return res
  117. })
  118. sw.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
  119. res := proxyApp.Query().QuerySync([]byte(Fmt("p2p/filter/pubkey/%X", pubkey.Bytes())))
  120. if res.IsOK() {
  121. return nil
  122. }
  123. return res
  124. })
  125. }
  126. // add the event switch to all services
  127. // they should all satisfy events.Eventable
  128. SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor)
  129. // run the profile server
  130. profileHost := config.GetString("prof_laddr")
  131. if profileHost != "" {
  132. go func() {
  133. log.Warn("Profile server", "error", http.ListenAndServe(profileHost, nil))
  134. }()
  135. }
  136. return &Node{
  137. config: config,
  138. sw: sw,
  139. evsw: eventSwitch,
  140. blockStore: blockStore,
  141. bcReactor: bcReactor,
  142. mempoolReactor: mempoolReactor,
  143. consensusState: consensusState,
  144. consensusReactor: consensusReactor,
  145. privValidator: privValidator,
  146. genesisDoc: state.GenesisDoc,
  147. privKey: privKey,
  148. proxyApp: proxyApp,
  149. }
  150. }
  151. // Call Start() after adding the listeners.
  152. func (n *Node) Start() error {
  153. n.sw.SetNodeInfo(makeNodeInfo(n.config, n.sw, n.privKey))
  154. n.sw.SetNodePrivKey(n.privKey)
  155. _, err := n.sw.Start()
  156. return err
  157. }
  158. func (n *Node) Stop() {
  159. log.Notice("Stopping Node")
  160. // TODO: gracefully disconnect from peers.
  161. n.sw.Stop()
  162. }
  163. // Add the event switch to reactors, mempool, etc.
  164. func SetEventSwitch(evsw types.EventSwitch, eventables ...types.Eventable) {
  165. for _, e := range eventables {
  166. e.SetEventSwitch(evsw)
  167. }
  168. }
  169. // Add a Listener to accept inbound peer connections.
  170. // Add listeners before starting the Node.
  171. // The first listener is the primary listener (in NodeInfo)
  172. func (n *Node) AddListener(l p2p.Listener) {
  173. log.Notice(Fmt("Added %v", l))
  174. n.sw.AddListener(l)
  175. }
  176. func (n *Node) StartRPC() ([]net.Listener, error) {
  177. rpccore.SetConfig(n.config)
  178. rpccore.SetEventSwitch(n.evsw)
  179. rpccore.SetBlockStore(n.blockStore)
  180. rpccore.SetConsensusState(n.consensusState)
  181. rpccore.SetMempool(n.mempoolReactor.Mempool)
  182. rpccore.SetSwitch(n.sw)
  183. rpccore.SetPubKey(n.privValidator.PubKey)
  184. rpccore.SetGenesisDoc(n.genesisDoc)
  185. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  186. listenAddrs := strings.Split(n.config.GetString("rpc_laddr"), ",")
  187. // we may expose the rpc over both a unix and tcp socket
  188. listeners := make([]net.Listener, len(listenAddrs))
  189. for i, listenAddr := range listenAddrs {
  190. mux := http.NewServeMux()
  191. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  192. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  193. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  194. listener, err := rpcserver.StartHTTPServer(listenAddr, mux)
  195. if err != nil {
  196. return nil, err
  197. }
  198. listeners[i] = 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. // Load the most recent state from "state" db,
  262. // or create a new one (and save) from genesis.
  263. func getState(config cfg.Config, stateDB dbm.DB) *sm.State {
  264. state := sm.LoadState(stateDB)
  265. if state == nil {
  266. state = sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  267. state.Save()
  268. }
  269. return state
  270. }
  271. //------------------------------------------------------------------------------
  272. // Users wishing to:
  273. // * use an external signer for their validators
  274. // * supply an in-proc tmsp app
  275. // should fork tendermint/tendermint and implement RunNode to
  276. // call NewNode with their custom priv validator and/or custom
  277. // proxy.ClientCreator interface
  278. func RunNode(config cfg.Config) {
  279. // Wait until the genesis doc becomes available
  280. genDocFile := config.GetString("genesis_file")
  281. if !FileExists(genDocFile) {
  282. log.Notice(Fmt("Waiting for genesis file %v...", genDocFile))
  283. for {
  284. time.Sleep(time.Second)
  285. if !FileExists(genDocFile) {
  286. continue
  287. }
  288. jsonBlob, err := ioutil.ReadFile(genDocFile)
  289. if err != nil {
  290. Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
  291. }
  292. genDoc := types.GenesisDocFromJSON(jsonBlob)
  293. if genDoc.ChainID == "" {
  294. PanicSanity(Fmt("Genesis doc %v must include non-empty chain_id", genDocFile))
  295. }
  296. config.Set("chain_id", genDoc.ChainID)
  297. }
  298. }
  299. // Create & start node
  300. n := NewNodeDefault(config)
  301. protocol, address := ProtocolAndAddress(config.GetString("node_laddr"))
  302. l := p2p.NewDefaultListener(protocol, address, config.GetBool("skip_upnp"))
  303. n.AddListener(l)
  304. err := n.Start()
  305. if err != nil {
  306. Exit(Fmt("Failed to start node: %v", err))
  307. }
  308. log.Notice("Started node", "nodeInfo", n.sw.NodeInfo())
  309. // If seedNode is provided by config, dial out.
  310. if config.GetString("seeds") != "" {
  311. seeds := strings.Split(config.GetString("seeds"), ",")
  312. n.sw.DialSeeds(seeds)
  313. }
  314. // Run the RPC server.
  315. if config.GetString("rpc_laddr") != "" {
  316. _, err := n.StartRPC()
  317. if err != nil {
  318. PanicCrisis(err)
  319. }
  320. }
  321. // Sleep forever and then...
  322. TrapSignal(func() {
  323. n.Stop()
  324. })
  325. }
  326. func (n *Node) NodeInfo() *p2p.NodeInfo {
  327. return n.sw.NodeInfo()
  328. }
  329. func (n *Node) DialSeeds(seeds []string) {
  330. n.sw.DialSeeds(seeds)
  331. }
  332. //------------------------------------------------------------------------------
  333. // replay
  334. // convenience for replay mode
  335. func newConsensusState(config cfg.Config) *consensus.ConsensusState {
  336. // Get BlockStore
  337. blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir"))
  338. blockStore := bc.NewBlockStore(blockStoreDB)
  339. // Get State
  340. stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir"))
  341. state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  342. // Create two proxyAppConn connections,
  343. // one for the consensus and one for the mempool.
  344. proxyApp := proxy.NewAppConns(config, proxy.DefaultClientCreator(config), state, blockStore)
  345. // add the chainid to the global config
  346. config.Set("chain_id", state.ChainID)
  347. // Make event switch
  348. eventSwitch := types.NewEventSwitch()
  349. _, err := eventSwitch.Start()
  350. if 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) {
  359. walFile := config.GetString("cswal")
  360. if walFile == "" {
  361. Exit("cswal file name not set in tendermint config")
  362. }
  363. consensusState := newConsensusState(config)
  364. if err := consensusState.ReplayConsole(walFile); err != nil {
  365. Exit(Fmt("Error during consensus replay: %v", err))
  366. }
  367. }
  368. func RunReplay(config cfg.Config) {
  369. walFile := config.GetString("cswal")
  370. if walFile == "" {
  371. Exit("cswal file name not set in tendermint config")
  372. }
  373. consensusState := newConsensusState(config)
  374. if err := consensusState.ReplayMessages(walFile); err != nil {
  375. Exit(Fmt("Error during consensus replay: %v", err))
  376. }
  377. log.Notice("Replay run successfully")
  378. }
  379. // Defaults to tcp
  380. func ProtocolAndAddress(listenAddr string) (string, string) {
  381. protocol, address := "tcp", listenAddr
  382. parts := strings.SplitN(address, "://", 2)
  383. if len(parts) == 2 {
  384. protocol, address = parts[0], parts[1]
  385. }
  386. return protocol, address
  387. }