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.

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