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.

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