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.

425 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
10 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. n.BaseService.OnStart()
  168. // Create & add listener
  169. protocol, address := ProtocolAndAddress(n.config.GetString("node_laddr"))
  170. l := p2p.NewDefaultListener(protocol, address, n.config.GetBool("skip_upnp"))
  171. n.sw.AddListener(l)
  172. // Start the switch
  173. n.sw.SetNodeInfo(makeNodeInfo(n.config, n.sw, n.privKey))
  174. n.sw.SetNodePrivKey(n.privKey)
  175. _, err := n.sw.Start()
  176. if err != nil {
  177. return err
  178. }
  179. // If seeds exist, add them to the address book and dial out
  180. if n.config.GetString("seeds") != "" {
  181. seeds := strings.Split(n.config.GetString("seeds"), ",")
  182. if n.config.GetBool("pex_reactor") {
  183. // add seeds to `addrBook` to avoid losing
  184. ourAddrS := n.NodeInfo().ListenAddr
  185. ourAddr, _ := p2p.NewNetAddressString(ourAddrS)
  186. for _, s := range seeds {
  187. // do not add ourselves
  188. if s == ourAddrS {
  189. continue
  190. }
  191. addr, err := p2p.NewNetAddressString(s)
  192. if err != nil {
  193. n.addrBook.AddAddress(addr, ourAddr)
  194. }
  195. }
  196. n.addrBook.Save()
  197. }
  198. // dial out
  199. if err := n.sw.DialSeeds(seeds); err != nil {
  200. return err
  201. }
  202. }
  203. // Run the RPC server
  204. if n.config.GetString("rpc_laddr") != "" {
  205. listeners, err := n.startRPC()
  206. if err != nil {
  207. return err
  208. }
  209. n.rpcListeners = listeners
  210. }
  211. return nil
  212. }
  213. func (n *Node) RunForever() {
  214. // Sleep forever and then...
  215. cmn.TrapSignal(func() {
  216. n.Stop()
  217. })
  218. }
  219. func (n *Node) OnStop() {
  220. n.BaseService.OnStop()
  221. log.Notice("Stopping Node")
  222. // TODO: gracefully disconnect from peers.
  223. n.sw.Stop()
  224. for _, l := range n.rpcListeners {
  225. log.Info("Closing rpc listener", "listener", l)
  226. if err := l.Close(); err != nil {
  227. log.Error("Error closing listener", "listener", l, "error", err)
  228. }
  229. }
  230. }
  231. // Add the event switch to reactors, mempool, etc.
  232. func SetEventSwitch(evsw types.EventSwitch, eventables ...types.Eventable) {
  233. for _, e := range eventables {
  234. e.SetEventSwitch(evsw)
  235. }
  236. }
  237. // Add a Listener to accept inbound peer connections.
  238. // Add listeners before starting the Node.
  239. // The first listener is the primary listener (in NodeInfo)
  240. func (n *Node) AddListener(l p2p.Listener) {
  241. n.sw.AddListener(l)
  242. }
  243. // ConfigureRPC sets all variables in rpccore so they will serve
  244. // rpc calls from this node
  245. func (n *Node) ConfigureRPC() {
  246. rpccore.SetConfig(n.config)
  247. rpccore.SetEventSwitch(n.evsw)
  248. rpccore.SetBlockStore(n.blockStore)
  249. rpccore.SetConsensusState(n.consensusState)
  250. rpccore.SetMempool(n.mempoolReactor.Mempool)
  251. rpccore.SetSwitch(n.sw)
  252. rpccore.SetPubKey(n.privValidator.PubKey)
  253. rpccore.SetGenesisDoc(n.genesisDoc)
  254. rpccore.SetProxyAppQuery(n.proxyApp.Query())
  255. }
  256. func (n *Node) startRPC() ([]net.Listener, error) {
  257. n.ConfigureRPC()
  258. listenAddrs := strings.Split(n.config.GetString("rpc_laddr"), ",")
  259. // we may expose the rpc over both a unix and tcp socket
  260. listeners := make([]net.Listener, len(listenAddrs))
  261. for i, listenAddr := range listenAddrs {
  262. mux := http.NewServeMux()
  263. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  264. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  265. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  266. listener, err := rpcserver.StartHTTPServer(listenAddr, mux)
  267. if err != nil {
  268. return nil, err
  269. }
  270. listeners[i] = listener
  271. }
  272. // we expose a simplified api over grpc for convenience to app devs
  273. grpcListenAddr := n.config.GetString("grpc_laddr")
  274. if grpcListenAddr != "" {
  275. listener, err := grpccore.StartGRPCServer(grpcListenAddr)
  276. if err != nil {
  277. return nil, err
  278. }
  279. listeners = append(listeners, listener)
  280. }
  281. return listeners, nil
  282. }
  283. func (n *Node) Switch() *p2p.Switch {
  284. return n.sw
  285. }
  286. func (n *Node) BlockStore() *bc.BlockStore {
  287. return n.blockStore
  288. }
  289. func (n *Node) ConsensusState() *consensus.ConsensusState {
  290. return n.consensusState
  291. }
  292. func (n *Node) ConsensusReactor() *consensus.ConsensusReactor {
  293. return n.consensusReactor
  294. }
  295. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  296. return n.mempoolReactor
  297. }
  298. func (n *Node) EventSwitch() types.EventSwitch {
  299. return n.evsw
  300. }
  301. // XXX: for convenience
  302. func (n *Node) PrivValidator() *types.PrivValidator {
  303. return n.privValidator
  304. }
  305. func (n *Node) GenesisDoc() *types.GenesisDoc {
  306. return n.genesisDoc
  307. }
  308. func (n *Node) ProxyApp() proxy.AppConns {
  309. return n.proxyApp
  310. }
  311. func makeNodeInfo(config cfg.Config, sw *p2p.Switch, privKey crypto.PrivKeyEd25519) *p2p.NodeInfo {
  312. nodeInfo := &p2p.NodeInfo{
  313. PubKey: privKey.PubKey().(crypto.PubKeyEd25519),
  314. Moniker: config.GetString("moniker"),
  315. Network: config.GetString("chain_id"),
  316. Version: version.Version,
  317. Other: []string{
  318. cmn.Fmt("wire_version=%v", wire.Version),
  319. cmn.Fmt("p2p_version=%v", p2p.Version),
  320. cmn.Fmt("consensus_version=%v", consensus.Version),
  321. cmn.Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  322. },
  323. }
  324. // include git hash in the nodeInfo if available
  325. if rev, err := cmn.ReadFile(config.GetString("revision_file")); err == nil {
  326. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("revision=%v", string(rev)))
  327. }
  328. if !sw.IsListening() {
  329. return nodeInfo
  330. }
  331. p2pListener := sw.Listeners()[0]
  332. p2pHost := p2pListener.ExternalAddress().IP.String()
  333. p2pPort := p2pListener.ExternalAddress().Port
  334. rpcListenAddr := config.GetString("rpc_laddr")
  335. // We assume that the rpcListener has the same ExternalAddress.
  336. // This is probably true because both P2P and RPC listeners use UPnP,
  337. // except of course if the rpc is only bound to localhost
  338. nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort)
  339. nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("rpc_addr=%v", rpcListenAddr))
  340. return nodeInfo
  341. }
  342. //------------------------------------------------------------------------------
  343. func (n *Node) NodeInfo() *p2p.NodeInfo {
  344. return n.sw.NodeInfo()
  345. }
  346. func (n *Node) DialSeeds(seeds []string) {
  347. n.sw.DialSeeds(seeds)
  348. }
  349. // Defaults to tcp
  350. func ProtocolAndAddress(listenAddr string) (string, string) {
  351. protocol, address := "tcp", listenAddr
  352. parts := strings.SplitN(address, "://", 2)
  353. if len(parts) == 2 {
  354. protocol, address = parts[0], parts[1]
  355. }
  356. return protocol, address
  357. }