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.

353 lines
10 KiB

cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
  1. package core
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "time"
  10. "github.com/rs/cors"
  11. abciclient "github.com/tendermint/tendermint/abci/client"
  12. "github.com/tendermint/tendermint/config"
  13. "github.com/tendermint/tendermint/crypto"
  14. "github.com/tendermint/tendermint/internal/blocksync"
  15. "github.com/tendermint/tendermint/internal/consensus"
  16. "github.com/tendermint/tendermint/internal/eventbus"
  17. "github.com/tendermint/tendermint/internal/eventlog"
  18. "github.com/tendermint/tendermint/internal/mempool"
  19. "github.com/tendermint/tendermint/internal/p2p"
  20. tmpubsub "github.com/tendermint/tendermint/internal/pubsub"
  21. "github.com/tendermint/tendermint/internal/pubsub/query"
  22. sm "github.com/tendermint/tendermint/internal/state"
  23. "github.com/tendermint/tendermint/internal/state/indexer"
  24. "github.com/tendermint/tendermint/internal/statesync"
  25. "github.com/tendermint/tendermint/libs/log"
  26. "github.com/tendermint/tendermint/libs/strings"
  27. "github.com/tendermint/tendermint/rpc/coretypes"
  28. rpcserver "github.com/tendermint/tendermint/rpc/jsonrpc/server"
  29. "github.com/tendermint/tendermint/types"
  30. )
  31. const (
  32. // see README
  33. defaultPerPage = 30
  34. maxPerPage = 100
  35. // SubscribeTimeout is the maximum time we wait to subscribe for an event.
  36. // must be less than the server's write timeout (see rpcserver.DefaultConfig)
  37. SubscribeTimeout = 5 * time.Second
  38. // genesisChunkSize is the maximum size, in bytes, of each
  39. // chunk in the genesis structure for the chunked API
  40. genesisChunkSize = 16 * 1024 * 1024 // 16
  41. )
  42. //----------------------------------------------
  43. // These interfaces are used by RPC and must be thread safe
  44. type consensusState interface {
  45. GetState() sm.State
  46. GetValidators() (int64, []*types.Validator)
  47. GetLastHeight() int64
  48. GetRoundStateJSON() ([]byte, error)
  49. GetRoundStateSimpleJSON() ([]byte, error)
  50. }
  51. type peerManager interface {
  52. Peers() []types.NodeID
  53. Addresses(types.NodeID) []p2p.NodeAddress
  54. }
  55. //----------------------------------------------
  56. // Environment contains objects and interfaces used by the RPC. It is expected
  57. // to be setup once during startup.
  58. type Environment struct {
  59. // external, thread safe interfaces
  60. ProxyApp abciclient.Client
  61. // interfaces defined in types and above
  62. StateStore sm.Store
  63. BlockStore sm.BlockStore
  64. EvidencePool sm.EvidencePool
  65. ConsensusState consensusState
  66. ConsensusReactor *consensus.Reactor
  67. BlockSyncReactor *blocksync.Reactor
  68. IsListening bool
  69. Listeners []string
  70. NodeInfo types.NodeInfo
  71. // interfaces for new p2p interfaces
  72. PeerManager peerManager
  73. // objects
  74. PubKey crypto.PubKey
  75. GenDoc *types.GenesisDoc // cache the genesis structure
  76. EventSinks []indexer.EventSink
  77. EventBus *eventbus.EventBus // thread safe
  78. EventLog *eventlog.Log
  79. Mempool mempool.Mempool
  80. StateSyncMetricer statesync.Metricer
  81. Logger log.Logger
  82. Config config.RPCConfig
  83. // cache of chunked genesis data.
  84. genChunks []string
  85. }
  86. //----------------------------------------------
  87. func validatePage(pagePtr *int, perPage, totalCount int) (int, error) {
  88. // this can only happen if we haven't first run validatePerPage
  89. if perPage < 1 {
  90. panic(fmt.Errorf("%w (%d)", coretypes.ErrZeroOrNegativePerPage, perPage))
  91. }
  92. if pagePtr == nil { // no page parameter
  93. return 1, nil
  94. }
  95. pages := ((totalCount - 1) / perPage) + 1
  96. if pages == 0 {
  97. pages = 1 // one page (even if it's empty)
  98. }
  99. page := *pagePtr
  100. if page <= 0 || page > pages {
  101. return 1, fmt.Errorf("%w expected range: [1, %d], given %d", coretypes.ErrPageOutOfRange, pages, page)
  102. }
  103. return page, nil
  104. }
  105. func (env *Environment) validatePerPage(perPagePtr *int) int {
  106. if perPagePtr == nil { // no per_page parameter
  107. return defaultPerPage
  108. }
  109. perPage := *perPagePtr
  110. if perPage < 1 {
  111. return defaultPerPage
  112. // in unsafe mode there is no max on the page size but in safe mode
  113. // we cap it to maxPerPage
  114. } else if perPage > maxPerPage && !env.Config.Unsafe {
  115. return maxPerPage
  116. }
  117. return perPage
  118. }
  119. // InitGenesisChunks configures the environment and should be called on service
  120. // startup.
  121. func (env *Environment) InitGenesisChunks() error {
  122. if env.genChunks != nil {
  123. return nil
  124. }
  125. if env.GenDoc == nil {
  126. return nil
  127. }
  128. data, err := json.Marshal(env.GenDoc)
  129. if err != nil {
  130. return err
  131. }
  132. for i := 0; i < len(data); i += genesisChunkSize {
  133. end := i + genesisChunkSize
  134. if end > len(data) {
  135. end = len(data)
  136. }
  137. env.genChunks = append(env.genChunks, base64.StdEncoding.EncodeToString(data[i:end]))
  138. }
  139. return nil
  140. }
  141. func validateSkipCount(page, perPage int) int {
  142. skipCount := (page - 1) * perPage
  143. if skipCount < 0 {
  144. return 0
  145. }
  146. return skipCount
  147. }
  148. // latestHeight can be either latest committed or uncommitted (+1) height.
  149. func (env *Environment) getHeight(latestHeight int64, heightPtr *int64) (int64, error) {
  150. if heightPtr != nil {
  151. height := *heightPtr
  152. if height <= 0 {
  153. return 0, fmt.Errorf("%w (requested height: %d)", coretypes.ErrZeroOrNegativeHeight, height)
  154. }
  155. if height > latestHeight {
  156. return 0, fmt.Errorf("%w (requested height: %d, blockchain height: %d)",
  157. coretypes.ErrHeightExceedsChainHead, height, latestHeight)
  158. }
  159. base := env.BlockStore.Base()
  160. if height < base {
  161. return 0, fmt.Errorf("%w (requested height: %d, base height: %d)", coretypes.ErrHeightNotAvailable, height, base)
  162. }
  163. return height, nil
  164. }
  165. return latestHeight, nil
  166. }
  167. func (env *Environment) latestUncommittedHeight() int64 {
  168. if env.ConsensusReactor != nil {
  169. // consensus reactor can be nil in inspect mode.
  170. nodeIsSyncing := env.ConsensusReactor.WaitSync()
  171. if nodeIsSyncing {
  172. return env.BlockStore.Height()
  173. }
  174. }
  175. return env.BlockStore.Height() + 1
  176. }
  177. // StartService constructs and starts listeners for the RPC service
  178. // according to the config object, returning an error if the service
  179. // cannot be constructed or started. The listeners, which provide
  180. // access to the service, run until the context is canceled.
  181. func (env *Environment) StartService(ctx context.Context, conf *config.Config) ([]net.Listener, error) {
  182. if err := env.InitGenesisChunks(); err != nil {
  183. return nil, err
  184. }
  185. env.Listeners = []string{
  186. fmt.Sprintf("Listener(@%v)", conf.P2P.ExternalAddress),
  187. }
  188. listenAddrs := strings.SplitAndTrimEmpty(conf.RPC.ListenAddress, ",", " ")
  189. routes := NewRoutesMap(env, &RouteOptions{
  190. Unsafe: conf.RPC.Unsafe,
  191. })
  192. cfg := rpcserver.DefaultConfig()
  193. cfg.MaxBodyBytes = conf.RPC.MaxBodyBytes
  194. cfg.MaxHeaderBytes = conf.RPC.MaxHeaderBytes
  195. cfg.MaxOpenConnections = conf.RPC.MaxOpenConnections
  196. // If necessary adjust global WriteTimeout to ensure it's greater than
  197. // TimeoutBroadcastTxCommit.
  198. // See https://github.com/tendermint/tendermint/issues/3435
  199. if cfg.WriteTimeout <= conf.RPC.TimeoutBroadcastTxCommit {
  200. cfg.WriteTimeout = conf.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  201. }
  202. // If the event log is enabled, subscribe to all events published to the
  203. // event bus, and forward them to the event log.
  204. if lg := env.EventLog; lg != nil {
  205. // TODO(creachadair): This is kind of a hack, ideally we'd share the
  206. // observer with the indexer, but it's tricky to plumb them together.
  207. // For now, use a "normal" subscription with a big buffer allowance.
  208. // The event log should always be able to keep up.
  209. const subscriberID = "event-log-subscriber"
  210. sub, err := env.EventBus.SubscribeWithArgs(ctx, tmpubsub.SubscribeArgs{
  211. ClientID: subscriberID,
  212. Query: query.All,
  213. Limit: 1 << 16, // essentially "no limit"
  214. })
  215. if err != nil {
  216. return nil, fmt.Errorf("event log subscribe: %w", err)
  217. }
  218. go func() {
  219. // N.B. Use background for unsubscribe, ctx is already terminated.
  220. defer env.EventBus.UnsubscribeAll(context.Background(), subscriberID) // nolint:errcheck
  221. for {
  222. msg, err := sub.Next(ctx)
  223. if err != nil {
  224. env.Logger.Error("Subscription terminated", "err", err)
  225. return
  226. }
  227. etype, ok := eventlog.FindType(msg.Events())
  228. if ok {
  229. _ = lg.Add(etype, msg.Data())
  230. }
  231. }
  232. }()
  233. env.Logger.Info("Event log subscription enabled")
  234. }
  235. // We may expose the RPC over both TCP and a Unix-domain socket.
  236. listeners := make([]net.Listener, len(listenAddrs))
  237. for i, listenAddr := range listenAddrs {
  238. mux := http.NewServeMux()
  239. rpcLogger := env.Logger.With("module", "rpc-server")
  240. rpcserver.RegisterRPCFuncs(mux, routes, rpcLogger)
  241. if conf.RPC.ExperimentalDisableWebsocket {
  242. rpcLogger.Info("Disabling websocket endpoints (experimental-disable-websocket=true)")
  243. } else {
  244. rpcLogger.Info("WARNING: Websocket RPC access is deprecated and will be removed " +
  245. "in Tendermint v0.37. See https://tinyurl.com/adr075 for more information.")
  246. wmLogger := rpcLogger.With("protocol", "websocket")
  247. wm := rpcserver.NewWebsocketManager(wmLogger, routes,
  248. rpcserver.OnDisconnect(func(remoteAddr string) {
  249. err := env.EventBus.UnsubscribeAll(context.Background(), remoteAddr)
  250. if err != nil && err != tmpubsub.ErrSubscriptionNotFound {
  251. wmLogger.Error("Failed to unsubscribe addr from events", "addr", remoteAddr, "err", err)
  252. }
  253. }),
  254. rpcserver.ReadLimit(cfg.MaxBodyBytes),
  255. )
  256. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  257. }
  258. listener, err := rpcserver.Listen(
  259. listenAddr,
  260. cfg.MaxOpenConnections,
  261. )
  262. if err != nil {
  263. return nil, err
  264. }
  265. var rootHandler http.Handler = mux
  266. if conf.RPC.IsCorsEnabled() {
  267. corsMiddleware := cors.New(cors.Options{
  268. AllowedOrigins: conf.RPC.CORSAllowedOrigins,
  269. AllowedMethods: conf.RPC.CORSAllowedMethods,
  270. AllowedHeaders: conf.RPC.CORSAllowedHeaders,
  271. })
  272. rootHandler = corsMiddleware.Handler(mux)
  273. }
  274. if conf.RPC.IsTLSEnabled() {
  275. go func() {
  276. if err := rpcserver.ServeTLS(
  277. ctx,
  278. listener,
  279. rootHandler,
  280. conf.RPC.CertFile(),
  281. conf.RPC.KeyFile(),
  282. rpcLogger,
  283. cfg,
  284. ); err != nil {
  285. env.Logger.Error("error serving server with TLS", "err", err)
  286. }
  287. }()
  288. } else {
  289. go func() {
  290. if err := rpcserver.Serve(
  291. ctx,
  292. listener,
  293. rootHandler,
  294. rpcLogger,
  295. cfg,
  296. ); err != nil {
  297. env.Logger.Error("error serving server", "err", err)
  298. }
  299. }()
  300. }
  301. listeners[i] = listener
  302. }
  303. return listeners, nil
  304. }