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.

327 lines
9.2 KiB

10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
9 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net"
  6. "net/http"
  7. "strings"
  8. "sync"
  9. "time"
  10. . "github.com/tendermint/go-common"
  11. "github.com/tendermint/go-crypto"
  12. dbm "github.com/tendermint/go-db"
  13. "github.com/tendermint/go-events"
  14. "github.com/tendermint/go-p2p"
  15. "github.com/tendermint/go-rpc"
  16. "github.com/tendermint/go-rpc/server"
  17. "github.com/tendermint/go-wire"
  18. bc "github.com/tendermint/tendermint/blockchain"
  19. "github.com/tendermint/tendermint/consensus"
  20. mempl "github.com/tendermint/tendermint/mempool"
  21. "github.com/tendermint/tendermint/proxy"
  22. rpccore "github.com/tendermint/tendermint/rpc/core"
  23. sm "github.com/tendermint/tendermint/state"
  24. "github.com/tendermint/tendermint/types"
  25. "github.com/tendermint/tendermint/version"
  26. "github.com/tendermint/tmsp/example/golang"
  27. )
  28. import _ "net/http/pprof"
  29. type Node struct {
  30. sw *p2p.Switch
  31. evsw *events.EventSwitch
  32. blockStore *bc.BlockStore
  33. bcReactor *bc.BlockchainReactor
  34. mempoolReactor *mempl.MempoolReactor
  35. consensusState *consensus.ConsensusState
  36. consensusReactor *consensus.ConsensusReactor
  37. privValidator *types.PrivValidator
  38. genesisDoc *types.GenesisDoc
  39. privKey crypto.PrivKeyEd25519
  40. }
  41. func NewNode(privValidator *types.PrivValidator) *Node {
  42. // Get BlockStore
  43. blockStoreDB := dbm.GetDB("blockstore")
  44. blockStore := bc.NewBlockStore(blockStoreDB)
  45. // Get State
  46. state := getState()
  47. // Create two proxyAppConn connections,
  48. // one for the consensus and one for the mempool.
  49. proxyAddr := config.GetString("proxy_app")
  50. proxyAppConnMempool := getProxyApp(proxyAddr, state.AppHash)
  51. proxyAppConnConsensus := getProxyApp(proxyAddr, state.AppHash)
  52. // add the chainid to the global config
  53. config.Set("chain_id", state.ChainID)
  54. // Generate node PrivKey
  55. privKey := crypto.GenPrivKeyEd25519()
  56. // Make event switch
  57. eventSwitch := events.NewEventSwitch()
  58. _, err := eventSwitch.Start()
  59. if err != nil {
  60. Exit(Fmt("Failed to start switch: %v", err))
  61. }
  62. // Make BlockchainReactor
  63. bcReactor := bc.NewBlockchainReactor(state.Copy(), proxyAppConnConsensus, blockStore, config.GetBool("fast_sync"))
  64. // Make MempoolReactor
  65. mempool := mempl.NewMempool(proxyAppConnMempool)
  66. mempoolReactor := mempl.NewMempoolReactor(mempool)
  67. // Make ConsensusReactor
  68. consensusState := consensus.NewConsensusState(state.Copy(), proxyAppConnConsensus, blockStore, mempool)
  69. consensusReactor := consensus.NewConsensusReactor(consensusState, blockStore, config.GetBool("fast_sync"))
  70. if privValidator != nil {
  71. consensusReactor.SetPrivValidator(privValidator)
  72. }
  73. // Make p2p network switch
  74. sw := p2p.NewSwitch()
  75. sw.AddReactor("MEMPOOL", mempoolReactor)
  76. sw.AddReactor("BLOCKCHAIN", bcReactor)
  77. sw.AddReactor("CONSENSUS", consensusReactor)
  78. // add the event switch to all services
  79. // they should all satisfy events.Eventable
  80. SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor)
  81. // run the profile server
  82. profileHost := config.GetString("prof_laddr")
  83. if profileHost != "" {
  84. go func() {
  85. log.Warn("Profile server", "error", http.ListenAndServe(profileHost, nil))
  86. }()
  87. }
  88. return &Node{
  89. sw: sw,
  90. evsw: eventSwitch,
  91. blockStore: blockStore,
  92. bcReactor: bcReactor,
  93. mempoolReactor: mempoolReactor,
  94. consensusState: consensusState,
  95. consensusReactor: consensusReactor,
  96. privValidator: privValidator,
  97. genesisDoc: state.GenesisDoc,
  98. privKey: privKey,
  99. }
  100. }
  101. // Call Start() after adding the listeners.
  102. func (n *Node) Start() error {
  103. n.sw.SetNodeInfo(makeNodeInfo(n.sw, n.privKey))
  104. n.sw.SetNodePrivKey(n.privKey)
  105. _, err := n.sw.Start()
  106. return err
  107. }
  108. func (n *Node) Stop() {
  109. log.Notice("Stopping Node")
  110. // TODO: gracefully disconnect from peers.
  111. n.sw.Stop()
  112. }
  113. // Add the event switch to reactors, mempool, etc.
  114. func SetEventSwitch(evsw *events.EventSwitch, eventables ...events.Eventable) {
  115. for _, e := range eventables {
  116. e.SetEventSwitch(evsw)
  117. }
  118. }
  119. // Add a Listener to accept inbound peer connections.
  120. // Add listeners before starting the Node.
  121. // The first listener is the primary listener (in NodeInfo)
  122. func (n *Node) AddListener(l p2p.Listener) {
  123. log.Notice(Fmt("Added %v", l))
  124. n.sw.AddListener(l)
  125. }
  126. func (n *Node) StartRPC() (net.Listener, error) {
  127. rpccore.SetBlockStore(n.blockStore)
  128. rpccore.SetConsensusState(n.consensusState)
  129. rpccore.SetConsensusReactor(n.consensusReactor)
  130. rpccore.SetMempoolReactor(n.mempoolReactor)
  131. rpccore.SetSwitch(n.sw)
  132. rpccore.SetPrivValidator(n.privValidator)
  133. rpccore.SetGenesisDoc(n.genesisDoc)
  134. listenAddr := config.GetString("rpc_laddr")
  135. mux := http.NewServeMux()
  136. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  137. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  138. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  139. return rpcserver.StartHTTPServer(listenAddr, mux)
  140. }
  141. func (n *Node) Switch() *p2p.Switch {
  142. return n.sw
  143. }
  144. func (n *Node) BlockStore() *bc.BlockStore {
  145. return n.blockStore
  146. }
  147. func (n *Node) ConsensusState() *consensus.ConsensusState {
  148. return n.consensusState
  149. }
  150. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  151. return n.mempoolReactor
  152. }
  153. func (n *Node) EventSwitch() *events.EventSwitch {
  154. return n.evsw
  155. }
  156. func makeNodeInfo(sw *p2p.Switch, privKey crypto.PrivKeyEd25519) *p2p.NodeInfo {
  157. nodeInfo := &p2p.NodeInfo{
  158. PubKey: privKey.PubKey().(crypto.PubKeyEd25519),
  159. Moniker: config.GetString("moniker"),
  160. Network: config.GetString("chain_id"),
  161. Version: version.Version,
  162. Other: []string{
  163. Fmt("wire_version=%v", wire.Version),
  164. Fmt("p2p_version=%v", p2p.Version),
  165. Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  166. },
  167. }
  168. // include git hash in the nodeInfo if available
  169. if rev, err := ReadFile(config.GetString("revision_file")); err == nil {
  170. nodeInfo.Other = append(nodeInfo.Other, Fmt("revision=%v", string(rev)))
  171. }
  172. if !sw.IsListening() {
  173. return nodeInfo
  174. }
  175. p2pListener := sw.Listeners()[0]
  176. p2pHost := p2pListener.ExternalAddress().IP.String()
  177. p2pPort := p2pListener.ExternalAddress().Port
  178. rpcListenAddr := config.GetString("rpc_laddr")
  179. // We assume that the rpcListener has the same ExternalAddress.
  180. // This is probably true because both P2P and RPC listeners use UPnP,
  181. // except of course if the rpc is only bound to localhost
  182. nodeInfo.ListenAddr = Fmt("%v:%v", p2pHost, p2pPort)
  183. nodeInfo.Other = append(nodeInfo.Other, Fmt("rpc_addr=%v", rpcListenAddr))
  184. return nodeInfo
  185. }
  186. //------------------------------------------------------------------------------
  187. // Users wishing to use an external signer for their validators
  188. // should fork tendermint/tendermint and implement RunNode to
  189. // load their custom priv validator and call NewNode(privVal)
  190. func RunNode() {
  191. // Wait until the genesis doc becomes available
  192. genDocFile := config.GetString("genesis_file")
  193. if !FileExists(genDocFile) {
  194. log.Notice(Fmt("Waiting for genesis file %v...", genDocFile))
  195. for {
  196. time.Sleep(time.Second)
  197. if !FileExists(genDocFile) {
  198. continue
  199. }
  200. jsonBlob, err := ioutil.ReadFile(genDocFile)
  201. if err != nil {
  202. Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
  203. }
  204. genDoc := types.GenesisDocFromJSON(jsonBlob)
  205. if genDoc.ChainID == "" {
  206. PanicSanity(Fmt("Genesis doc %v must include non-empty chain_id", genDocFile))
  207. }
  208. config.Set("chain_id", genDoc.ChainID)
  209. config.Set("genesis_doc", genDoc)
  210. }
  211. }
  212. // Get PrivValidator
  213. privValidatorFile := config.GetString("priv_validator_file")
  214. privValidator := types.LoadOrGenPrivValidator(privValidatorFile)
  215. // Create & start node
  216. n := NewNode(privValidator)
  217. l := p2p.NewDefaultListener("tcp", config.GetString("node_laddr"), config.GetBool("skip_upnp"))
  218. n.AddListener(l)
  219. err := n.Start()
  220. if err != nil {
  221. Exit(Fmt("Failed to start node: %v", err))
  222. }
  223. log.Notice("Started node", "nodeInfo", n.sw.NodeInfo())
  224. // If seedNode is provided by config, dial out.
  225. if config.GetString("seeds") != "" {
  226. seeds := strings.Split(config.GetString("seeds"), ",")
  227. n.sw.DialSeeds(seeds)
  228. }
  229. // Run the RPC server.
  230. if config.GetString("rpc_laddr") != "" {
  231. _, err := n.StartRPC()
  232. if err != nil {
  233. PanicCrisis(err)
  234. }
  235. }
  236. // Sleep forever and then...
  237. TrapSignal(func() {
  238. n.Stop()
  239. })
  240. }
  241. // Load the most recent state from "state" db,
  242. // or create a new one (and save) from genesis.
  243. func getState() *sm.State {
  244. stateDB := dbm.GetDB("state")
  245. state := sm.LoadState(stateDB)
  246. if state == nil {
  247. state = sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  248. state.Save()
  249. }
  250. return state
  251. }
  252. // Get a connection to the proxyAppConn addr.
  253. // Check the current hash, and panic if it doesn't match.
  254. func getProxyApp(addr string, hash []byte) (proxyAppConn proxy.AppConn) {
  255. // use local app (for testing)
  256. if addr == "local" {
  257. app := example.NewCounterApplication(true)
  258. mtx := new(sync.Mutex)
  259. proxyAppConn = proxy.NewLocalAppConn(mtx, app)
  260. } else {
  261. proxyConn, err := Connect(addr)
  262. if err != nil {
  263. Exit(Fmt("Failed to connect to proxy for mempool: %v", err))
  264. }
  265. remoteApp := proxy.NewRemoteAppConn(proxyConn, 1024)
  266. remoteApp.Start()
  267. proxyAppConn = remoteApp
  268. }
  269. // Check the hash
  270. currentHash, err := proxyAppConn.GetHashSync()
  271. if err != nil {
  272. PanicCrisis(Fmt("Error in getting proxyAppConn hash: %v", err))
  273. }
  274. if !bytes.Equal(hash, currentHash) {
  275. PanicCrisis(Fmt("ProxyApp hash does not match. Expected %X, got %X", hash, currentHash))
  276. }
  277. return proxyAppConn
  278. }