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.

315 lines
8.6 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. "github.com/tendermint/tendermint/config"
  12. "github.com/tendermint/tendermint/crypto"
  13. "github.com/tendermint/tendermint/internal/blocksync"
  14. "github.com/tendermint/tendermint/internal/consensus"
  15. "github.com/tendermint/tendermint/internal/eventbus"
  16. "github.com/tendermint/tendermint/internal/mempool"
  17. "github.com/tendermint/tendermint/internal/p2p"
  18. "github.com/tendermint/tendermint/internal/proxy"
  19. tmpubsub "github.com/tendermint/tendermint/internal/pubsub"
  20. sm "github.com/tendermint/tendermint/internal/state"
  21. "github.com/tendermint/tendermint/internal/state/indexer"
  22. "github.com/tendermint/tendermint/internal/statesync"
  23. "github.com/tendermint/tendermint/libs/log"
  24. "github.com/tendermint/tendermint/libs/strings"
  25. "github.com/tendermint/tendermint/rpc/coretypes"
  26. rpcserver "github.com/tendermint/tendermint/rpc/jsonrpc/server"
  27. "github.com/tendermint/tendermint/types"
  28. )
  29. const (
  30. // see README
  31. defaultPerPage = 30
  32. maxPerPage = 100
  33. // SubscribeTimeout is the maximum time we wait to subscribe for an event.
  34. // must be less than the server's write timeout (see rpcserver.DefaultConfig)
  35. SubscribeTimeout = 5 * time.Second
  36. // genesisChunkSize is the maximum size, in bytes, of each
  37. // chunk in the genesis structure for the chunked API
  38. genesisChunkSize = 16 * 1024 * 1024 // 16
  39. )
  40. //----------------------------------------------
  41. // These interfaces are used by RPC and must be thread safe
  42. type consensusState interface {
  43. GetState() sm.State
  44. GetValidators() (int64, []*types.Validator)
  45. GetLastHeight() int64
  46. GetRoundStateJSON() ([]byte, error)
  47. GetRoundStateSimpleJSON() ([]byte, error)
  48. }
  49. type transport interface {
  50. Listeners() []string
  51. IsListening() bool
  52. NodeInfo() types.NodeInfo
  53. }
  54. type peerManager interface {
  55. Peers() []types.NodeID
  56. Addresses(types.NodeID) []p2p.NodeAddress
  57. }
  58. //----------------------------------------------
  59. // Environment contains objects and interfaces used by the RPC. It is expected
  60. // to be setup once during startup.
  61. type Environment struct {
  62. // external, thread safe interfaces
  63. ProxyAppQuery proxy.AppConnQuery
  64. ProxyAppMempool proxy.AppConnMempool
  65. // interfaces defined in types and above
  66. StateStore sm.Store
  67. BlockStore sm.BlockStore
  68. EvidencePool sm.EvidencePool
  69. ConsensusState consensusState
  70. ConsensusReactor *consensus.Reactor
  71. BlockSyncReactor *blocksync.Reactor
  72. // Legacy p2p stack
  73. P2PTransport transport
  74. // interfaces for new p2p interfaces
  75. PeerManager peerManager
  76. // objects
  77. PubKey crypto.PubKey
  78. GenDoc *types.GenesisDoc // cache the genesis structure
  79. EventSinks []indexer.EventSink
  80. EventBus *eventbus.EventBus // thread safe
  81. Mempool mempool.Mempool
  82. StateSyncMetricer statesync.Metricer
  83. Logger log.Logger
  84. Config config.RPCConfig
  85. // cache of chunked genesis data.
  86. genChunks []string
  87. }
  88. //----------------------------------------------
  89. func validatePage(pagePtr *int, perPage, totalCount int) (int, error) {
  90. // this can only happen if we haven't first run validatePerPage
  91. if perPage < 1 {
  92. panic(fmt.Errorf("%w (%d)", coretypes.ErrZeroOrNegativePerPage, perPage))
  93. }
  94. if pagePtr == nil { // no page parameter
  95. return 1, nil
  96. }
  97. pages := ((totalCount - 1) / perPage) + 1
  98. if pages == 0 {
  99. pages = 1 // one page (even if it's empty)
  100. }
  101. page := *pagePtr
  102. if page <= 0 || page > pages {
  103. return 1, fmt.Errorf("%w expected range: [1, %d], given %d", coretypes.ErrPageOutOfRange, pages, page)
  104. }
  105. return page, nil
  106. }
  107. func (env *Environment) validatePerPage(perPagePtr *int) int {
  108. if perPagePtr == nil { // no per_page parameter
  109. return defaultPerPage
  110. }
  111. perPage := *perPagePtr
  112. if perPage < 1 {
  113. return defaultPerPage
  114. // in unsafe mode there is no max on the page size but in safe mode
  115. // we cap it to maxPerPage
  116. } else if perPage > maxPerPage && !env.Config.Unsafe {
  117. return maxPerPage
  118. }
  119. return perPage
  120. }
  121. // InitGenesisChunks configures the environment and should be called on service
  122. // startup.
  123. func (env *Environment) InitGenesisChunks() error {
  124. if env.genChunks != nil {
  125. return nil
  126. }
  127. if env.GenDoc == nil {
  128. return nil
  129. }
  130. data, err := json.Marshal(env.GenDoc)
  131. if err != nil {
  132. return err
  133. }
  134. for i := 0; i < len(data); i += genesisChunkSize {
  135. end := i + genesisChunkSize
  136. if end > len(data) {
  137. end = len(data)
  138. }
  139. env.genChunks = append(env.genChunks, base64.StdEncoding.EncodeToString(data[i:end]))
  140. }
  141. return nil
  142. }
  143. func validateSkipCount(page, perPage int) int {
  144. skipCount := (page - 1) * perPage
  145. if skipCount < 0 {
  146. return 0
  147. }
  148. return skipCount
  149. }
  150. // latestHeight can be either latest committed or uncommitted (+1) height.
  151. func (env *Environment) getHeight(latestHeight int64, heightPtr *int64) (int64, error) {
  152. if heightPtr != nil {
  153. height := *heightPtr
  154. if height <= 0 {
  155. return 0, fmt.Errorf("%w (requested height: %d)", coretypes.ErrZeroOrNegativeHeight, height)
  156. }
  157. if height > latestHeight {
  158. return 0, fmt.Errorf("%w (requested height: %d, blockchain height: %d)",
  159. coretypes.ErrHeightExceedsChainHead, height, latestHeight)
  160. }
  161. base := env.BlockStore.Base()
  162. if height < base {
  163. return 0, fmt.Errorf("%w (requested height: %d, base height: %d)", coretypes.ErrHeightNotAvailable, height, base)
  164. }
  165. return height, nil
  166. }
  167. return latestHeight, nil
  168. }
  169. func (env *Environment) latestUncommittedHeight() int64 {
  170. if env.ConsensusReactor != nil {
  171. // consensus reactor can be nil in inspect mode.
  172. nodeIsSyncing := env.ConsensusReactor.WaitSync()
  173. if nodeIsSyncing {
  174. return env.BlockStore.Height()
  175. }
  176. }
  177. return env.BlockStore.Height() + 1
  178. }
  179. // StartService constructs and starts listeners for the RPC service
  180. // according to the config object, returning an error if the service
  181. // cannot be constructed or started. The listeners, which provide
  182. // access to the service, run until the context is canceled.
  183. func (env *Environment) StartService(ctx context.Context, conf *config.Config) ([]net.Listener, error) {
  184. if err := env.InitGenesisChunks(); err != nil {
  185. return nil, err
  186. }
  187. listenAddrs := strings.SplitAndTrimEmpty(conf.RPC.ListenAddress, ",", " ")
  188. routes := NewRoutesMap(env, &RouteOptions{
  189. Unsafe: conf.RPC.Unsafe,
  190. })
  191. cfg := rpcserver.DefaultConfig()
  192. cfg.MaxBodyBytes = conf.RPC.MaxBodyBytes
  193. cfg.MaxHeaderBytes = conf.RPC.MaxHeaderBytes
  194. cfg.MaxOpenConnections = conf.RPC.MaxOpenConnections
  195. // If necessary adjust global WriteTimeout to ensure it's greater than
  196. // TimeoutBroadcastTxCommit.
  197. // See https://github.com/tendermint/tendermint/issues/3435
  198. if cfg.WriteTimeout <= conf.RPC.TimeoutBroadcastTxCommit {
  199. cfg.WriteTimeout = conf.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  200. }
  201. // We may expose the RPC over both TCP and a Unix-domain socket.
  202. listeners := make([]net.Listener, len(listenAddrs))
  203. for i, listenAddr := range listenAddrs {
  204. mux := http.NewServeMux()
  205. rpcLogger := env.Logger.With("module", "rpc-server")
  206. rpcserver.RegisterRPCFuncs(mux, routes, rpcLogger)
  207. if conf.RPC.ExperimentalDisableWebsocket {
  208. rpcLogger.Info("Disabling websocket endpoints (experimental-disable-websocket=true)")
  209. } else {
  210. wmLogger := rpcLogger.With("protocol", "websocket")
  211. wm := rpcserver.NewWebsocketManager(wmLogger, routes,
  212. rpcserver.OnDisconnect(func(remoteAddr string) {
  213. err := env.EventBus.UnsubscribeAll(context.Background(), remoteAddr)
  214. if err != nil && err != tmpubsub.ErrSubscriptionNotFound {
  215. wmLogger.Error("Failed to unsubscribe addr from events", "addr", remoteAddr, "err", err)
  216. }
  217. }),
  218. rpcserver.ReadLimit(cfg.MaxBodyBytes),
  219. )
  220. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  221. }
  222. listener, err := rpcserver.Listen(
  223. listenAddr,
  224. cfg.MaxOpenConnections,
  225. )
  226. if err != nil {
  227. return nil, err
  228. }
  229. var rootHandler http.Handler = mux
  230. if conf.RPC.IsCorsEnabled() {
  231. corsMiddleware := cors.New(cors.Options{
  232. AllowedOrigins: conf.RPC.CORSAllowedOrigins,
  233. AllowedMethods: conf.RPC.CORSAllowedMethods,
  234. AllowedHeaders: conf.RPC.CORSAllowedHeaders,
  235. })
  236. rootHandler = corsMiddleware.Handler(mux)
  237. }
  238. if conf.RPC.IsTLSEnabled() {
  239. go func() {
  240. if err := rpcserver.ServeTLS(
  241. ctx,
  242. listener,
  243. rootHandler,
  244. conf.RPC.CertFile(),
  245. conf.RPC.KeyFile(),
  246. rpcLogger,
  247. cfg,
  248. ); err != nil {
  249. env.Logger.Error("error serving server with TLS", "err", err)
  250. }
  251. }()
  252. } else {
  253. go func() {
  254. if err := rpcserver.Serve(
  255. ctx,
  256. listener,
  257. rootHandler,
  258. rpcLogger,
  259. cfg,
  260. ); err != nil {
  261. env.Logger.Error("error serving server", "err", err)
  262. }
  263. }()
  264. }
  265. listeners[i] = listener
  266. }
  267. return listeners, nil
  268. }