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.

352 lines
9.7 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "math/rand"
  6. "net"
  7. "net/http"
  8. "strings"
  9. "sync"
  10. "time"
  11. . "github.com/tendermint/go-common"
  12. "github.com/tendermint/go-crypto"
  13. dbm "github.com/tendermint/go-db"
  14. "github.com/tendermint/go-events"
  15. "github.com/tendermint/go-p2p"
  16. "github.com/tendermint/go-rpc"
  17. "github.com/tendermint/go-rpc/server"
  18. "github.com/tendermint/go-wire"
  19. bc "github.com/tendermint/tendermint/blockchain"
  20. "github.com/tendermint/tendermint/consensus"
  21. mempl "github.com/tendermint/tendermint/mempool"
  22. "github.com/tendermint/tendermint/proxy"
  23. "github.com/tendermint/tendermint/rpc/core"
  24. sm "github.com/tendermint/tendermint/state"
  25. "github.com/tendermint/tendermint/types"
  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. // Dial a list of seeds in random order
  127. // Spawns a go routine for each dial
  128. func (n *Node) DialSeed() {
  129. // permute the list, dial them in random order.
  130. seeds := strings.Split(config.GetString("seeds"), ",")
  131. perm := rand.Perm(len(seeds))
  132. for i := 0; i < len(perm); i++ {
  133. go func(i int) {
  134. time.Sleep(time.Duration(rand.Int63n(3000)) * time.Millisecond)
  135. j := perm[i]
  136. addr := p2p.NewNetAddressString(seeds[j])
  137. n.dialSeed(addr)
  138. }(i)
  139. }
  140. }
  141. func (n *Node) dialSeed(addr *p2p.NetAddress) {
  142. peer, err := n.sw.DialPeerWithAddress(addr)
  143. if err != nil {
  144. log.Error("Error dialing seed", "error", err)
  145. return
  146. } else {
  147. log.Notice("Connected to seed", "peer", peer)
  148. }
  149. }
  150. func (n *Node) StartRPC() (net.Listener, error) {
  151. core.SetBlockStore(n.blockStore)
  152. core.SetConsensusState(n.consensusState)
  153. core.SetConsensusReactor(n.consensusReactor)
  154. core.SetMempoolReactor(n.mempoolReactor)
  155. core.SetSwitch(n.sw)
  156. core.SetPrivValidator(n.privValidator)
  157. core.SetGenesisDoc(n.genesisDoc)
  158. listenAddr := config.GetString("rpc_laddr")
  159. mux := http.NewServeMux()
  160. wm := rpcserver.NewWebsocketManager(core.Routes, n.evsw)
  161. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  162. rpcserver.RegisterRPCFuncs(mux, core.Routes)
  163. return rpcserver.StartHTTPServer(listenAddr, mux)
  164. }
  165. func (n *Node) Switch() *p2p.Switch {
  166. return n.sw
  167. }
  168. func (n *Node) BlockStore() *bc.BlockStore {
  169. return n.blockStore
  170. }
  171. func (n *Node) ConsensusState() *consensus.ConsensusState {
  172. return n.consensusState
  173. }
  174. func (n *Node) MempoolReactor() *mempl.MempoolReactor {
  175. return n.mempoolReactor
  176. }
  177. func (n *Node) EventSwitch() *events.EventSwitch {
  178. return n.evsw
  179. }
  180. func makeNodeInfo(sw *p2p.Switch, privKey crypto.PrivKeyEd25519) *p2p.NodeInfo {
  181. nodeInfo := &p2p.NodeInfo{
  182. PubKey: privKey.PubKey().(crypto.PubKeyEd25519),
  183. Moniker: config.GetString("moniker"),
  184. Network: config.GetString("chain_id"),
  185. Version: Version,
  186. Other: []string{
  187. Fmt("p2p_version=%v", p2p.Version),
  188. Fmt("rpc_version=%v", rpc.Version),
  189. Fmt("wire_version=%v", wire.Version),
  190. },
  191. }
  192. // include git hash in the nodeInfo if available
  193. if rev, err := ReadFile(config.GetString("revision_file")); err == nil {
  194. nodeInfo.Other = append(nodeInfo.Other, Fmt("revision=%v", string(rev)))
  195. }
  196. if !sw.IsListening() {
  197. return nodeInfo
  198. }
  199. p2pListener := sw.Listeners()[0]
  200. p2pHost := p2pListener.ExternalAddress().IP.String()
  201. p2pPort := p2pListener.ExternalAddress().Port
  202. rpcListenAddr := config.GetString("rpc_laddr")
  203. // We assume that the rpcListener has the same ExternalAddress.
  204. // This is probably true because both P2P and RPC listeners use UPnP,
  205. // except of course if the rpc is only bound to localhost
  206. nodeInfo.ListenAddr = Fmt("%v:%v", p2pHost, p2pPort)
  207. nodeInfo.Other = append(nodeInfo.Other, Fmt("rpc_addr=%v", rpcListenAddr))
  208. return nodeInfo
  209. }
  210. //------------------------------------------------------------------------------
  211. // Users wishing to use an external signer for their validators
  212. // should fork tendermint/tendermint and implement RunNode to
  213. // load their custom priv validator and call NewNode(privVal)
  214. func RunNode() {
  215. // Wait until the genesis doc becomes available
  216. genDocFile := config.GetString("genesis_file")
  217. if !FileExists(genDocFile) {
  218. log.Notice(Fmt("Waiting for genesis file %v...", genDocFile))
  219. for {
  220. time.Sleep(time.Second)
  221. if !FileExists(genDocFile) {
  222. continue
  223. }
  224. jsonBlob, err := ioutil.ReadFile(genDocFile)
  225. if err != nil {
  226. Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
  227. }
  228. genDoc := types.GenesisDocFromJSON(jsonBlob)
  229. if genDoc.ChainID == "" {
  230. PanicSanity(Fmt("Genesis doc %v must include non-empty chain_id", genDocFile))
  231. }
  232. config.Set("chain_id", genDoc.ChainID)
  233. config.Set("genesis_doc", genDoc)
  234. }
  235. }
  236. // Get PrivValidator
  237. privValidatorFile := config.GetString("priv_validator_file")
  238. privValidator := types.LoadOrGenPrivValidator(privValidatorFile)
  239. // Create & start node
  240. n := NewNode(privValidator)
  241. l := p2p.NewDefaultListener("tcp", config.GetString("node_laddr"), config.GetBool("skip_upnp"))
  242. n.AddListener(l)
  243. err := n.Start()
  244. if err != nil {
  245. Exit(Fmt("Failed to start node: %v", err))
  246. }
  247. log.Notice("Started node", "nodeInfo", n.sw.NodeInfo())
  248. // If seedNode is provided by config, dial out.
  249. if config.GetString("seeds") != "" {
  250. n.DialSeed()
  251. }
  252. // Run the RPC server.
  253. if config.GetString("rpc_laddr") != "" {
  254. _, err := n.StartRPC()
  255. if err != nil {
  256. PanicCrisis(err)
  257. }
  258. }
  259. // Sleep forever and then...
  260. TrapSignal(func() {
  261. n.Stop()
  262. })
  263. }
  264. // Load the most recent state from "state" db,
  265. // or create a new one (and save) from genesis.
  266. func getState() *sm.State {
  267. stateDB := dbm.GetDB("state")
  268. state := sm.LoadState(stateDB)
  269. if state == nil {
  270. state = sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  271. state.Save()
  272. }
  273. return state
  274. }
  275. // Get a connection to the proxyAppConn addr.
  276. // Check the current hash, and panic if it doesn't match.
  277. func getProxyApp(addr string, hash []byte) (proxyAppConn proxy.AppConn) {
  278. // use local app (for testing)
  279. if addr == "local" {
  280. app := example.NewCounterApplication(true)
  281. mtx := new(sync.Mutex)
  282. proxyAppConn = proxy.NewLocalAppConn(mtx, app)
  283. } else {
  284. proxyConn, err := Connect(addr)
  285. if err != nil {
  286. Exit(Fmt("Failed to connect to proxy for mempool: %v", err))
  287. }
  288. remoteApp := proxy.NewRemoteAppConn(proxyConn, 1024)
  289. remoteApp.Start()
  290. proxyAppConn = remoteApp
  291. }
  292. // Check the hash
  293. currentHash, err := proxyAppConn.GetHashSync()
  294. if err != nil {
  295. PanicCrisis(Fmt("Error in getting proxyAppConn hash: %v", err))
  296. }
  297. if !bytes.Equal(hash, currentHash) {
  298. PanicCrisis(Fmt("ProxyApp hash does not match. Expected %X, got %X", hash, currentHash))
  299. }
  300. return proxyAppConn
  301. }