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.

430 lines
12 KiB

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