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.

460 lines
13 KiB

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