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.

440 lines
13 KiB

10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 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
10 years ago
10 years ago
10 years ago
10 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. // Get BlockStore
  49. blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir"))
  50. blockStore := bc.NewBlockStore(blockStoreDB)
  51. // Get State db
  52. stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir"))
  53. // Get State
  54. state := getState(config, stateDB)
  55. // Create the proxyApp, which houses three connections:
  56. // query, consensus, and mempool
  57. proxyApp := proxy.NewAppConns(config, clientCreator, 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. consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync)
  89. if privValidator != nil {
  90. consensusReactor.SetPrivValidator(privValidator)
  91. }
  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. return listeners, nil
  192. }
  193. func (n *Node) Switch() *p2p.Switch {
  194. return n.sw
  195. }
  196. func (n *Node) BlockStore() *bc.BlockStore {
  197. return n.blockStore
  198. }
  199. func (n *Node) ConsensusState() *consensus.ConsensusState {
  200. return n.consensusState
  201. }
  202. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  203. return n.consensusReactor
  204. }
  205. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  206. return n.mempoolReactor
  207. }
  208. func (n *Node) EventSwitch() types.EventSwitch {
  209. return n.evsw
  210. }
  211. // XXX: for convenience
  212. func (n *Node) PrivValidator() *types.PrivValidator {
  213. return n.privValidator
  214. }
  215. func (n *Node) GenesisDoc() *types.GenesisDoc {
  216. return n.genesisDoc
  217. }
  218. func (n *Node) ProxyApp() proxy.AppConns {
  219. return n.proxyApp
  220. }
  221. func makeNodeInfo(config cfg.Config, sw *p2p.Switch, privKey crypto.PrivKeyEd25519) *p2p.NodeInfo {
  222. nodeInfo := &p2p.NodeInfo{
  223. PubKey: privKey.PubKey().(crypto.PubKeyEd25519),
  224. Moniker: config.GetString("moniker"),
  225. Network: config.GetString("chain_id"),
  226. Version: version.Version,
  227. Other: []string{
  228. Fmt("wire_version=%v", wire.Version),
  229. Fmt("p2p_version=%v", p2p.Version),
  230. Fmt("consensus_version=%v", consensus.Version),
  231. Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  232. },
  233. }
  234. // include git hash in the nodeInfo if available
  235. if rev, err := ReadFile(config.GetString("revision_file")); err == nil {
  236. nodeInfo.Other = append(nodeInfo.Other, Fmt("revision=%v", string(rev)))
  237. }
  238. if !sw.IsListening() {
  239. return nodeInfo
  240. }
  241. p2pListener := sw.Listeners()[0]
  242. p2pHost := p2pListener.ExternalAddress().IP.String()
  243. p2pPort := p2pListener.ExternalAddress().Port
  244. rpcListenAddr := config.GetString("rpc_laddr")
  245. // We assume that the rpcListener has the same ExternalAddress.
  246. // This is probably true because both P2P and RPC listeners use UPnP,
  247. // except of course if the rpc is only bound to localhost
  248. nodeInfo.ListenAddr = Fmt("%v:%v", p2pHost, p2pPort)
  249. nodeInfo.Other = append(nodeInfo.Other, Fmt("rpc_addr=%v", rpcListenAddr))
  250. return nodeInfo
  251. }
  252. // Load the most recent state from "state" db,
  253. // or create a new one (and save) from genesis.
  254. func getState(config cfg.Config, stateDB dbm.DB) *sm.State {
  255. state := sm.LoadState(stateDB)
  256. if state == nil {
  257. state = sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  258. state.Save()
  259. }
  260. return state
  261. }
  262. //------------------------------------------------------------------------------
  263. // Users wishing to:
  264. // * use an external signer for their validators
  265. // * supply an in-proc tmsp app
  266. // should fork tendermint/tendermint and implement RunNode to
  267. // call NewNode with their custom priv validator and/or custom
  268. // proxy.ClientCreator interface
  269. func RunNode(config cfg.Config) {
  270. // Wait until the genesis doc becomes available
  271. genDocFile := config.GetString("genesis_file")
  272. if !FileExists(genDocFile) {
  273. log.Notice(Fmt("Waiting for genesis file %v...", genDocFile))
  274. for {
  275. time.Sleep(time.Second)
  276. if !FileExists(genDocFile) {
  277. continue
  278. }
  279. jsonBlob, err := ioutil.ReadFile(genDocFile)
  280. if err != nil {
  281. Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
  282. }
  283. genDoc := types.GenesisDocFromJSON(jsonBlob)
  284. if genDoc.ChainID == "" {
  285. PanicSanity(Fmt("Genesis doc %v must include non-empty chain_id", genDocFile))
  286. }
  287. config.Set("chain_id", genDoc.ChainID)
  288. }
  289. }
  290. // Create & start node
  291. n := NewNodeDefault(config)
  292. protocol, address := ProtocolAndAddress(config.GetString("node_laddr"))
  293. l := p2p.NewDefaultListener(protocol, address, config.GetBool("skip_upnp"))
  294. n.AddListener(l)
  295. err := n.Start()
  296. if err != nil {
  297. Exit(Fmt("Failed to start node: %v", err))
  298. }
  299. log.Notice("Started node", "nodeInfo", n.sw.NodeInfo())
  300. // If seedNode is provided by config, dial out.
  301. if config.GetString("seeds") != "" {
  302. seeds := strings.Split(config.GetString("seeds"), ",")
  303. n.sw.DialSeeds(seeds)
  304. }
  305. // Run the RPC server.
  306. if config.GetString("rpc_laddr") != "" {
  307. _, err := n.StartRPC()
  308. if err != nil {
  309. PanicCrisis(err)
  310. }
  311. }
  312. // Sleep forever and then...
  313. TrapSignal(func() {
  314. n.Stop()
  315. })
  316. }
  317. func (n *Node) NodeInfo() *p2p.NodeInfo {
  318. return n.sw.NodeInfo()
  319. }
  320. func (n *Node) DialSeeds(seeds []string) {
  321. n.sw.DialSeeds(seeds)
  322. }
  323. //------------------------------------------------------------------------------
  324. // replay
  325. // convenience for replay mode
  326. func newConsensusState(config cfg.Config) *consensus.ConsensusState {
  327. // Get BlockStore
  328. blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir"))
  329. blockStore := bc.NewBlockStore(blockStoreDB)
  330. // Get State
  331. stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir"))
  332. state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  333. // Create two proxyAppConn connections,
  334. // one for the consensus and one for the mempool.
  335. proxyApp := proxy.NewAppConns(config, proxy.DefaultClientCreator(config), state, blockStore)
  336. // add the chainid to the global config
  337. config.Set("chain_id", state.ChainID)
  338. // Make event switch
  339. eventSwitch := types.NewEventSwitch()
  340. _, err := eventSwitch.Start()
  341. if err != nil {
  342. Exit(Fmt("Failed to start event switch: %v", err))
  343. }
  344. mempool := mempl.NewMempool(config, proxyApp.Mempool())
  345. consensusState := consensus.NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  346. consensusState.SetEventSwitch(eventSwitch)
  347. return consensusState
  348. }
  349. func RunReplayConsole(config cfg.Config, walFile string) {
  350. consensusState := newConsensusState(config)
  351. if err := consensusState.ReplayConsole(walFile); err != nil {
  352. Exit(Fmt("Error during consensus replay: %v", err))
  353. }
  354. }
  355. func RunReplay(config cfg.Config, walFile string) {
  356. consensusState := newConsensusState(config)
  357. if err := consensusState.ReplayMessages(walFile); err != nil {
  358. Exit(Fmt("Error during consensus replay: %v", err))
  359. }
  360. log.Notice("Replay run successfully")
  361. }
  362. // Defaults to tcp
  363. func ProtocolAndAddress(listenAddr string) (string, string) {
  364. protocol, address := "tcp", listenAddr
  365. parts := strings.SplitN(address, "://", 2)
  366. if len(parts) == 2 {
  367. protocol, address = parts[0], parts[1]
  368. }
  369. return protocol, address
  370. }