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.

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