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.

406 lines
12 KiB

10 years ago
10 years ago
11 years ago
11 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
9 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "errors"
  5. "net"
  6. "net/http"
  7. "strings"
  8. abci "github.com/tendermint/abci/types"
  9. cmn "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. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  23. sm "github.com/tendermint/tendermint/state"
  24. "github.com/tendermint/tendermint/types"
  25. "github.com/tendermint/tendermint/version"
  26. _ "net/http/pprof"
  27. )
  28. type Node struct {
  29. cmn.BaseService
  30. // config
  31. config cfg.Config // user config
  32. genesisDoc *types.GenesisDoc // initial validator set
  33. privValidator *types.PrivValidator // local node's validator key
  34. // network
  35. privKey crypto.PrivKeyEd25519 // local node's p2p key
  36. sw *p2p.Switch // p2p connections
  37. addrBook *p2p.AddrBook // known peers
  38. // services
  39. evsw types.EventSwitch // pub/sub for services
  40. blockStore *bc.BlockStore // store the blockchain to disk
  41. bcReactor *bc.BlockchainReactor // for fast-syncing
  42. mempoolReactor *mempl.MempoolReactor // for gossipping transactions
  43. consensusState *consensus.ConsensusState // latest consensus state
  44. consensusReactor *consensus.ConsensusReactor // for participating in the consensus
  45. proxyApp proxy.AppConns // connection to the application
  46. rpcListeners []net.Listener // rpc servers
  47. }
  48. func NewNodeDefault(config cfg.Config) *Node {
  49. // Get PrivValidator
  50. privValidatorFile := config.GetString("priv_validator_file")
  51. privValidator := types.LoadOrGenPrivValidator(privValidatorFile)
  52. return NewNode(config, privValidator, proxy.DefaultClientCreator(config))
  53. }
  54. func NewNode(config cfg.Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node {
  55. // Get BlockStore
  56. blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir"))
  57. blockStore := bc.NewBlockStore(blockStoreDB)
  58. // Get State
  59. stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir"))
  60. state := sm.GetState(config, stateDB)
  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. // Create the proxyApp, which manages connections (consensus, mempool, query)
  65. // and sync tendermint and the app by replaying any necessary blocks
  66. proxyApp := proxy.NewAppConns(config, clientCreator, consensus.NewHandshaker(config, state, blockStore))
  67. if _, err := proxyApp.Start(); err != nil {
  68. cmn.Exit(cmn.Fmt("Error starting proxy app connections: %v", err))
  69. }
  70. // reload the state (it may have been updated by the handshake)
  71. state = sm.LoadState(stateDB)
  72. // Generate node PrivKey
  73. privKey := crypto.GenPrivKeyEd25519()
  74. // Make event switch
  75. eventSwitch := types.NewEventSwitch()
  76. _, err := eventSwitch.Start()
  77. if err != nil {
  78. cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
  79. }
  80. // Decide whether to fast-sync or not
  81. // We don't fast-sync when the only validator is us.
  82. fastSync := config.GetBool("fast_sync")
  83. if state.Validators.Size() == 1 {
  84. addr, _ := state.Validators.GetByIndex(0)
  85. if bytes.Equal(privValidator.Address, addr) {
  86. fastSync = false
  87. }
  88. }
  89. // Make BlockchainReactor
  90. bcReactor := bc.NewBlockchainReactor(config, state.Copy(), proxyApp.Consensus(), blockStore, fastSync)
  91. // Make MempoolReactor
  92. mempool := mempl.NewMempool(config, proxyApp.Mempool())
  93. mempoolReactor := mempl.NewMempoolReactor(config, mempool)
  94. // Make ConsensusReactor
  95. consensusState := consensus.NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  96. if privValidator != nil {
  97. consensusState.SetPrivValidator(privValidator)
  98. }
  99. consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync)
  100. // Make p2p network switch
  101. sw := p2p.NewSwitch(config.GetConfig("p2p"))
  102. sw.AddReactor("MEMPOOL", mempoolReactor)
  103. sw.AddReactor("BLOCKCHAIN", bcReactor)
  104. sw.AddReactor("CONSENSUS", consensusReactor)
  105. // Optionally, start the pex reactor
  106. var addrBook *p2p.AddrBook
  107. if config.GetBool("pex_reactor") {
  108. addrBook = p2p.NewAddrBook(config.GetString("addrbook_file"), config.GetBool("addrbook_strict"))
  109. pexReactor := p2p.NewPEXReactor(addrBook)
  110. sw.AddReactor("PEX", pexReactor)
  111. }
  112. // Filter peers by addr or pubkey with an ABCI query.
  113. // If the query return code is OK, add peer.
  114. // XXX: Query format subject to change
  115. if config.GetBool("filter_peers") {
  116. // NOTE: addr is ip:port
  117. sw.SetAddrFilter(func(addr net.Addr) error {
  118. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())})
  119. if err != nil {
  120. return err
  121. }
  122. if resQuery.Code.IsOK() {
  123. return nil
  124. }
  125. return errors.New(resQuery.Code.String())
  126. })
  127. sw.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
  128. resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/pubkey/%X", pubkey.Bytes())})
  129. if err != nil {
  130. return err
  131. }
  132. if resQuery.Code.IsOK() {
  133. return nil
  134. }
  135. return errors.New(resQuery.Code.String())
  136. })
  137. }
  138. // add the event switch to all services
  139. // they should all satisfy events.Eventable
  140. SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor)
  141. // run the profile server
  142. profileHost := config.GetString("prof_laddr")
  143. if profileHost != "" {
  144. go func() {
  145. log.Warn("Profile server", "error", http.ListenAndServe(profileHost, nil))
  146. }()
  147. }
  148. node := &Node{
  149. config: config,
  150. genesisDoc: state.GenesisDoc,
  151. privValidator: privValidator,
  152. privKey: privKey,
  153. sw: sw,
  154. addrBook: addrBook,
  155. evsw: eventSwitch,
  156. blockStore: blockStore,
  157. bcReactor: bcReactor,
  158. mempoolReactor: mempoolReactor,
  159. consensusState: consensusState,
  160. consensusReactor: consensusReactor,
  161. proxyApp: proxyApp,
  162. }
  163. node.BaseService = *cmn.NewBaseService(log, "Node", node)
  164. return node
  165. }
  166. func (n *Node) OnStart() error {
  167. // Create & add listener
  168. protocol, address := ProtocolAndAddress(n.config.GetString("node_laddr"))
  169. l := p2p.NewDefaultListener(protocol, address, n.config.GetBool("skip_upnp"))
  170. n.sw.AddListener(l)
  171. // Start the switch
  172. n.sw.SetNodeInfo(makeNodeInfo(n.config, n.sw, n.privKey))
  173. n.sw.SetNodePrivKey(n.privKey)
  174. _, err := n.sw.Start()
  175. if err != nil {
  176. return err
  177. }
  178. // If seeds exist, add them to the address book and dial out
  179. if n.config.GetString("seeds") != "" {
  180. // dial out
  181. seeds := strings.Split(n.config.GetString("seeds"), ",")
  182. if err := n.DialSeeds(seeds); err != nil {
  183. return err
  184. }
  185. }
  186. // Run the RPC server
  187. if n.config.GetString("rpc_laddr") != "" {
  188. listeners, err := n.startRPC()
  189. if err != nil {
  190. return err
  191. }
  192. n.rpcListeners = listeners
  193. }
  194. return nil
  195. }
  196. func (n *Node) OnStop() {
  197. n.BaseService.OnStop()
  198. log.Notice("Stopping Node")
  199. // TODO: gracefully disconnect from peers.
  200. n.sw.Stop()
  201. for _, l := range n.rpcListeners {
  202. log.Info("Closing rpc listener", "listener", l)
  203. if err := l.Close(); err != nil {
  204. log.Error("Error closing listener", "listener", l, "error", err)
  205. }
  206. }
  207. }
  208. func (n *Node) RunForever() {
  209. // Sleep forever and then...
  210. cmn.TrapSignal(func() {
  211. n.Stop()
  212. })
  213. }
  214. // Add the event switch to reactors, mempool, etc.
  215. func SetEventSwitch(evsw types.EventSwitch, eventables ...types.Eventable) {
  216. for _, e := range eventables {
  217. e.SetEventSwitch(evsw)
  218. }
  219. }
  220. // Add a Listener to accept inbound peer connections.
  221. // Add listeners before starting the Node.
  222. // The first listener is the primary listener (in NodeInfo)
  223. func (n *Node) AddListener(l p2p.Listener) {
  224. n.sw.AddListener(l)
  225. }
  226. // ConfigureRPC sets all variables in rpccore so they will serve
  227. // rpc calls from this node
  228. func (n *Node) ConfigureRPC() {
  229. rpccore.SetConfig(n.config)
  230. rpccore.SetEventSwitch(n.evsw)
  231. rpccore.SetBlockStore(n.blockStore)
  232. rpccore.SetConsensusState(n.consensusState)
  233. rpccore.SetMempool(n.mempoolReactor.Mempool)
  234. rpccore.SetSwitch(n.sw)
  235. rpccore.SetPubKey(n.privValidator.PubKey)
  236. rpccore.SetGenesisDoc(n.genesisDoc)
  237. rpccore.SetAddrBook(n.addrBook)
  238. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  239. }
  240. func (n *Node) startRPC() ([]net.Listener, error) {
  241. n.ConfigureRPC()
  242. listenAddrs := strings.Split(n.config.GetString("rpc_laddr"), ",")
  243. // we may expose the rpc over both a unix and tcp socket
  244. listeners := make([]net.Listener, len(listenAddrs))
  245. for i, listenAddr := range listenAddrs {
  246. mux := http.NewServeMux()
  247. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  248. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  249. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  250. listener, err := rpcserver.StartHTTPServer(listenAddr, mux)
  251. if err != nil {
  252. return nil, err
  253. }
  254. listeners[i] = listener
  255. }
  256. // we expose a simplified api over grpc for convenience to app devs
  257. grpcListenAddr := n.config.GetString("grpc_laddr")
  258. if grpcListenAddr != "" {
  259. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  260. if err != nil {
  261. return nil, err
  262. }
  263. listeners = append(listeners, listener)
  264. }
  265. return listeners, nil
  266. }
  267. func (n *Node) Switch() *p2p.Switch {
  268. return n.sw
  269. }
  270. func (n *Node) BlockStore() *bc.BlockStore {
  271. return n.blockStore
  272. }
  273. func (n *Node) ConsensusState() *consensus.ConsensusState {
  274. return n.consensusState
  275. }
  276. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  277. return n.consensusReactor
  278. }
  279. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  280. return n.mempoolReactor
  281. }
  282. func (n *Node) EventSwitch() types.EventSwitch {
  283. return n.evsw
  284. }
  285. // XXX: for convenience
  286. func (n *Node) PrivValidator() *types.PrivValidator {
  287. return n.privValidator
  288. }
  289. func (n *Node) GenesisDoc() *types.GenesisDoc {
  290. return n.genesisDoc
  291. }
  292. func (n *Node) ProxyApp() proxy.AppConns {
  293. return n.proxyApp
  294. }
  295. func makeNodeInfo(config cfg.Config, sw *p2p.Switch, privKey crypto.PrivKeyEd25519) *p2p.NodeInfo {
  296. nodeInfo := &p2p.NodeInfo{
  297. PubKey: privKey.PubKey().(crypto.PubKeyEd25519),
  298. Moniker: config.GetString("moniker"),
  299. Network: config.GetString("chain_id"),
  300. Version: version.Version,
  301. Other: []string{
  302. cmn.Fmt("wire_version=%v", wire.Version),
  303. cmn.Fmt("p2p_version=%v", p2p.Version),
  304. cmn.Fmt("consensus_version=%v", consensus.Version),
  305. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  306. },
  307. }
  308. // include git hash in the nodeInfo if available
  309. if rev, err := cmn.ReadFile(config.GetString("revision_file")); err == nil {
  310. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("revision=%v", string(rev)))
  311. }
  312. if !sw.IsListening() {
  313. return nodeInfo
  314. }
  315. p2pListener := sw.Listeners()[0]
  316. p2pHost := p2pListener.ExternalAddress().IP.String()
  317. p2pPort := p2pListener.ExternalAddress().Port
  318. rpcListenAddr := config.GetString("rpc_laddr")
  319. // We assume that the rpcListener has the same ExternalAddress.
  320. // This is probably true because both P2P and RPC listeners use UPnP,
  321. // except of course if the rpc is only bound to localhost
  322. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  323. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  324. return nodeInfo
  325. }
  326. //------------------------------------------------------------------------------
  327. func (n *Node) NodeInfo() *p2p.NodeInfo {
  328. return n.sw.NodeInfo()
  329. }
  330. func (n *Node) DialSeeds(seeds []string) error {
  331. return n.sw.DialSeeds(n.addrBook, seeds)
  332. }
  333. // Defaults to tcp
  334. func ProtocolAndAddress(listenAddr string) (string, string) {
  335. protocol, address := "tcp", listenAddr
  336. parts := strings.SplitN(address, "://", 2)
  337. if len(parts) == 2 {
  338. protocol, address = parts[0], parts[1]
  339. }
  340. return protocol, address
  341. }