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.

451 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. // deterministic accountability
  94. err = consensusState.OpenWAL(config.GetString("cswal"))
  95. if err != nil {
  96. log.Error("Failed to open cswal", "error", err.Error())
  97. }
  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.SetConsensusReactor(n.consensusReactor)
  179. rpccore.SetMempoolReactor(n.mempoolReactor)
  180. rpccore.SetSwitch(n.sw)
  181. rpccore.SetPrivValidator(n.privValidator)
  182. rpccore.SetGenesisDoc(n.genesisDoc)
  183. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  184. listenAddrs := strings.Split(n.config.GetString("rpc_laddr"), ",")
  185. // we may expose the rpc over both a unix and tcp socket
  186. listeners := make([]net.Listener, len(listenAddrs))
  187. for i, listenAddr := range listenAddrs {
  188. mux := http.NewServeMux()
  189. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  190. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  191. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  192. listener, err := rpcserver.StartHTTPServer(listenAddr, mux)
  193. if err != nil {
  194. return nil, err
  195. }
  196. listeners[i] = listener
  197. }
  198. return listeners, nil
  199. }
  200. func (n *Node) Switch() *p2p.Switch {
  201. return n.sw
  202. }
  203. func (n *Node) BlockStore() *bc.BlockStore {
  204. return n.blockStore
  205. }
  206. func (n *Node) ConsensusState() *consensus.ConsensusState {
  207. return n.consensusState
  208. }
  209. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  210. return n.consensusReactor
  211. }
  212. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  213. return n.mempoolReactor
  214. }
  215. func (n *Node) EventSwitch() types.EventSwitch {
  216. return n.evsw
  217. }
  218. // XXX: for convenience
  219. func (n *Node) PrivValidator() *types.PrivValidator {
  220. return n.privValidator
  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. }