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.

396 lines
11 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
9 years ago
9 years ago
9 years ago
9 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. // deterministic accountability
  74. err = consensusState.OpenWAL(config.GetString("cswal"))
  75. if err != nil {
  76. log.Error("Failed to open cswal", "error", err.Error())
  77. }
  78. // Make p2p network switch
  79. sw := p2p.NewSwitch()
  80. sw.AddReactor("MEMPOOL", mempoolReactor)
  81. sw.AddReactor("BLOCKCHAIN", bcReactor)
  82. sw.AddReactor("CONSENSUS", consensusReactor)
  83. // add the event switch to all services
  84. // they should all satisfy events.Eventable
  85. SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor)
  86. // run the profile server
  87. profileHost := config.GetString("prof_laddr")
  88. if profileHost != "" {
  89. go func() {
  90. log.Warn("Profile server", "error", http.ListenAndServe(profileHost, nil))
  91. }()
  92. }
  93. return &Node{
  94. sw: sw,
  95. evsw: eventSwitch,
  96. blockStore: blockStore,
  97. bcReactor: bcReactor,
  98. mempoolReactor: mempoolReactor,
  99. consensusState: consensusState,
  100. consensusReactor: consensusReactor,
  101. privValidator: privValidator,
  102. genesisDoc: state.GenesisDoc,
  103. privKey: privKey,
  104. }
  105. }
  106. // Call Start() after adding the listeners.
  107. func (n *Node) Start() error {
  108. n.sw.SetNodeInfo(makeNodeInfo(n.sw, n.privKey))
  109. n.sw.SetNodePrivKey(n.privKey)
  110. _, err := n.sw.Start()
  111. return err
  112. }
  113. func (n *Node) Stop() {
  114. log.Notice("Stopping Node")
  115. // TODO: gracefully disconnect from peers.
  116. n.sw.Stop()
  117. }
  118. // Add the event switch to reactors, mempool, etc.
  119. func SetEventSwitch(evsw *events.EventSwitch, eventables ...events.Eventable) {
  120. for _, e := range eventables {
  121. e.SetEventSwitch(evsw)
  122. }
  123. }
  124. // Add a Listener to accept inbound peer connections.
  125. // Add listeners before starting the Node.
  126. // The first listener is the primary listener (in NodeInfo)
  127. func (n *Node) AddListener(l p2p.Listener) {
  128. log.Notice(Fmt("Added %v", l))
  129. n.sw.AddListener(l)
  130. }
  131. func (n *Node) StartRPC() (net.Listener, error) {
  132. rpccore.SetBlockStore(n.blockStore)
  133. rpccore.SetConsensusState(n.consensusState)
  134. rpccore.SetConsensusReactor(n.consensusReactor)
  135. rpccore.SetMempoolReactor(n.mempoolReactor)
  136. rpccore.SetSwitch(n.sw)
  137. rpccore.SetPrivValidator(n.privValidator)
  138. rpccore.SetGenesisDoc(n.genesisDoc)
  139. listenAddr := config.GetString("rpc_laddr")
  140. mux := http.NewServeMux()
  141. wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw)
  142. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  143. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes)
  144. return rpcserver.StartHTTPServer(listenAddr, mux)
  145. }
  146. func (n *Node) Switch() *p2p.Switch {
  147. return n.sw
  148. }
  149. func (n *Node) BlockStore() *bc.BlockStore {
  150. return n.blockStore
  151. }
  152. func (n *Node) ConsensusState() *consensus.ConsensusState {
  153. return n.consensusState
  154. }
  155. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  156. return n.mempoolReactor
  157. }
  158. func (n *Node) EventSwitch() *events.EventSwitch {
  159. return n.evsw
  160. }
  161. func makeNodeInfo(sw *p2p.Switch, privKey crypto.PrivKeyEd25519) *p2p.NodeInfo {
  162. nodeInfo := &p2p.NodeInfo{
  163. PubKey: privKey.PubKey().(crypto.PubKeyEd25519),
  164. Moniker: config.GetString("moniker"),
  165. Network: config.GetString("chain_id"),
  166. Version: version.Version,
  167. Other: []string{
  168. Fmt("wire_version=%v", wire.Version),
  169. Fmt("p2p_version=%v", p2p.Version),
  170. Fmt("rpc_version=%v/%v", rpc.Version, rpccore.Version),
  171. },
  172. }
  173. // include git hash in the nodeInfo if available
  174. if rev, err := ReadFile(config.GetString("revision_file")); err == nil {
  175. nodeInfo.Other = append(nodeInfo.Other, Fmt("revision=%v", string(rev)))
  176. }
  177. if !sw.IsListening() {
  178. return nodeInfo
  179. }
  180. p2pListener := sw.Listeners()[0]
  181. p2pHost := p2pListener.ExternalAddress().IP.String()
  182. p2pPort := p2pListener.ExternalAddress().Port
  183. rpcListenAddr := config.GetString("rpc_laddr")
  184. // We assume that the rpcListener has the same ExternalAddress.
  185. // This is probably true because both P2P and RPC listeners use UPnP,
  186. // except of course if the rpc is only bound to localhost
  187. nodeInfo.ListenAddr = Fmt("%v:%v", p2pHost, p2pPort)
  188. nodeInfo.Other = append(nodeInfo.Other, Fmt("rpc_addr=%v", rpcListenAddr))
  189. return nodeInfo
  190. }
  191. // Get a connection to the proxyAppConn addr.
  192. // Check the current hash, and panic if it doesn't match.
  193. func getProxyApp(addr string, hash []byte) (proxyAppConn proxy.AppConn) {
  194. // use local app (for testing)
  195. if addr == "local" {
  196. app := example.NewCounterApplication(true)
  197. mtx := new(sync.Mutex)
  198. proxyAppConn = proxy.NewLocalAppConn(mtx, app)
  199. } else {
  200. proxyConn, err := Connect(addr)
  201. if err != nil {
  202. Exit(Fmt("Failed to connect to proxy for mempool: %v", err))
  203. }
  204. remoteApp := proxy.NewRemoteAppConn(proxyConn, 1024)
  205. remoteApp.Start()
  206. proxyAppConn = remoteApp
  207. }
  208. // Check the hash
  209. currentHash, _, err := proxyAppConn.GetHashSync()
  210. if err != nil {
  211. PanicCrisis(Fmt("Error in getting proxyAppConn hash: %v", err))
  212. }
  213. if !bytes.Equal(hash, currentHash) {
  214. PanicCrisis(Fmt("ProxyApp hash does not match. Expected %X, got %X", hash, currentHash))
  215. }
  216. return proxyAppConn
  217. }
  218. // Load the most recent state from "state" db,
  219. // or create a new one (and save) from genesis.
  220. func getState() *sm.State {
  221. stateDB := dbm.GetDB("state")
  222. state := sm.LoadState(stateDB)
  223. if state == nil {
  224. state = sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  225. state.Save()
  226. }
  227. return state
  228. }
  229. //------------------------------------------------------------------------------
  230. // Users wishing to use an external signer for their validators
  231. // should fork tendermint/tendermint and implement RunNode to
  232. // load their custom priv validator and call NewNode(privVal)
  233. func RunNode() {
  234. // Wait until the genesis doc becomes available
  235. genDocFile := config.GetString("genesis_file")
  236. if !FileExists(genDocFile) {
  237. log.Notice(Fmt("Waiting for genesis file %v...", genDocFile))
  238. for {
  239. time.Sleep(time.Second)
  240. if !FileExists(genDocFile) {
  241. continue
  242. }
  243. jsonBlob, err := ioutil.ReadFile(genDocFile)
  244. if err != nil {
  245. Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
  246. }
  247. genDoc := types.GenesisDocFromJSON(jsonBlob)
  248. if genDoc.ChainID == "" {
  249. PanicSanity(Fmt("Genesis doc %v must include non-empty chain_id", genDocFile))
  250. }
  251. config.Set("chain_id", genDoc.ChainID)
  252. config.Set("genesis_doc", genDoc)
  253. }
  254. }
  255. // Get PrivValidator
  256. privValidatorFile := config.GetString("priv_validator_file")
  257. privValidator := types.LoadOrGenPrivValidator(privValidatorFile)
  258. // Create & start node
  259. n := NewNode(privValidator)
  260. l := p2p.NewDefaultListener("tcp", config.GetString("node_laddr"), config.GetBool("skip_upnp"))
  261. n.AddListener(l)
  262. err := n.Start()
  263. if err != nil {
  264. Exit(Fmt("Failed to start node: %v", err))
  265. }
  266. log.Notice("Started node", "nodeInfo", n.sw.NodeInfo())
  267. // If seedNode is provided by config, dial out.
  268. if config.GetString("seeds") != "" {
  269. seeds := strings.Split(config.GetString("seeds"), ",")
  270. n.sw.DialSeeds(seeds)
  271. }
  272. // Run the RPC server.
  273. if config.GetString("rpc_laddr") != "" {
  274. _, err := n.StartRPC()
  275. if err != nil {
  276. PanicCrisis(err)
  277. }
  278. }
  279. // Sleep forever and then...
  280. TrapSignal(func() {
  281. n.Stop()
  282. })
  283. }
  284. //------------------------------------------------------------------------------
  285. // replay
  286. // convenience for replay mode
  287. func newConsensusState() *consensus.ConsensusState {
  288. // Get BlockStore
  289. blockStoreDB := dbm.GetDB("blockstore")
  290. blockStore := bc.NewBlockStore(blockStoreDB)
  291. // Get State
  292. stateDB := dbm.GetDB("state")
  293. state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  294. // Create two proxyAppConn connections,
  295. // one for the consensus and one for the mempool.
  296. proxyAddr := config.GetString("proxy_app")
  297. proxyAppConnMempool := getProxyApp(proxyAddr, state.AppHash)
  298. proxyAppConnConsensus := getProxyApp(proxyAddr, state.AppHash)
  299. // add the chainid to the global config
  300. config.Set("chain_id", state.ChainID)
  301. // Make event switch
  302. eventSwitch := events.NewEventSwitch()
  303. _, err := eventSwitch.Start()
  304. if err != nil {
  305. Exit(Fmt("Failed to start event switch: %v", err))
  306. }
  307. mempool := mempl.NewMempool(proxyAppConnMempool)
  308. consensusState := consensus.NewConsensusState(state.Copy(), proxyAppConnConsensus, blockStore, mempool)
  309. consensusState.SetEventSwitch(eventSwitch)
  310. return consensusState
  311. }
  312. func RunReplayConsole() {
  313. walFile := config.GetString("cswal")
  314. if walFile == "" {
  315. Exit("cswal file name not set in tendermint config")
  316. }
  317. consensusState := newConsensusState()
  318. if err := consensusState.ReplayConsole(walFile); err != nil {
  319. Exit(Fmt("Error during consensus replay: %v", err))
  320. }
  321. }
  322. func RunReplay() {
  323. walFile := config.GetString("cswal")
  324. if walFile == "" {
  325. Exit("cswal file name not set in tendermint config")
  326. }
  327. consensusState := newConsensusState()
  328. if err := consensusState.ReplayMessages(walFile); err != nil {
  329. Exit(Fmt("Error during consensus replay: %v", err))
  330. }
  331. log.Notice("Replay run successfully")
  332. }