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
9.9 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/eventlog"
  17. "github.com/tendermint/tendermint/internal/mempool"
  18. "github.com/tendermint/tendermint/internal/p2p"
  19. "github.com/tendermint/tendermint/internal/proxy"
  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 transport interface {
  52. Listeners() []string
  53. IsListening() bool
  54. NodeInfo() types.NodeInfo
  55. }
  56. type peerManager interface {
  57. Peers() []types.NodeID
  58. Addresses(types.NodeID) []p2p.NodeAddress
  59. }
  60. //----------------------------------------------
  61. // Environment contains objects and interfaces used by the RPC. It is expected
  62. // to be setup once during startup.
  63. type Environment struct {
  64. // external, thread safe interfaces
  65. ProxyAppQuery proxy.AppConnQuery
  66. ProxyAppMempool proxy.AppConnMempool
  67. // interfaces defined in types and above
  68. StateStore sm.Store
  69. BlockStore sm.BlockStore
  70. EvidencePool sm.EvidencePool
  71. ConsensusState consensusState
  72. ConsensusReactor *consensus.Reactor
  73. BlockSyncReactor *blocksync.Reactor
  74. // Legacy p2p stack
  75. P2PTransport transport
  76. // interfaces for new p2p interfaces
  77. PeerManager peerManager
  78. // objects
  79. PubKey crypto.PubKey
  80. GenDoc *types.GenesisDoc // cache the genesis structure
  81. EventSinks []indexer.EventSink
  82. EventBus *eventbus.EventBus // thread safe
  83. EventLog *eventlog.Log
  84. Mempool mempool.Mempool
  85. StateSyncMetricer statesync.Metricer
  86. Logger log.Logger
  87. Config config.RPCConfig
  88. // cache of chunked genesis data.
  89. genChunks []string
  90. }
  91. //----------------------------------------------
  92. func validatePage(pagePtr *int, perPage, totalCount int) (int, error) {
  93. // this can only happen if we haven't first run validatePerPage
  94. if perPage < 1 {
  95. panic(fmt.Errorf("%w (%d)", coretypes.ErrZeroOrNegativePerPage, perPage))
  96. }
  97. if pagePtr == nil { // no page parameter
  98. return 1, nil
  99. }
  100. pages := ((totalCount - 1) / perPage) + 1
  101. if pages == 0 {
  102. pages = 1 // one page (even if it's empty)
  103. }
  104. page := *pagePtr
  105. if page <= 0 || page > pages {
  106. return 1, fmt.Errorf("%w expected range: [1, %d], given %d", coretypes.ErrPageOutOfRange, pages, page)
  107. }
  108. return page, nil
  109. }
  110. func (env *Environment) validatePerPage(perPagePtr *int) int {
  111. if perPagePtr == nil { // no per_page parameter
  112. return defaultPerPage
  113. }
  114. perPage := *perPagePtr
  115. if perPage < 1 {
  116. return defaultPerPage
  117. // in unsafe mode there is no max on the page size but in safe mode
  118. // we cap it to maxPerPage
  119. } else if perPage > maxPerPage && !env.Config.Unsafe {
  120. return maxPerPage
  121. }
  122. return perPage
  123. }
  124. // InitGenesisChunks configures the environment and should be called on service
  125. // startup.
  126. func (env *Environment) InitGenesisChunks() error {
  127. if env.genChunks != nil {
  128. return nil
  129. }
  130. if env.GenDoc == nil {
  131. return nil
  132. }
  133. data, err := json.Marshal(env.GenDoc)
  134. if err != nil {
  135. return err
  136. }
  137. for i := 0; i < len(data); i += genesisChunkSize {
  138. end := i + genesisChunkSize
  139. if end > len(data) {
  140. end = len(data)
  141. }
  142. env.genChunks = append(env.genChunks, base64.StdEncoding.EncodeToString(data[i:end]))
  143. }
  144. return nil
  145. }
  146. func validateSkipCount(page, perPage int) int {
  147. skipCount := (page - 1) * perPage
  148. if skipCount < 0 {
  149. return 0
  150. }
  151. return skipCount
  152. }
  153. // latestHeight can be either latest committed or uncommitted (+1) height.
  154. func (env *Environment) getHeight(latestHeight int64, heightPtr *int64) (int64, error) {
  155. if heightPtr != nil {
  156. height := *heightPtr
  157. if height <= 0 {
  158. return 0, fmt.Errorf("%w (requested height: %d)", coretypes.ErrZeroOrNegativeHeight, height)
  159. }
  160. if height > latestHeight {
  161. return 0, fmt.Errorf("%w (requested height: %d, blockchain height: %d)",
  162. coretypes.ErrHeightExceedsChainHead, height, latestHeight)
  163. }
  164. base := env.BlockStore.Base()
  165. if height < base {
  166. return 0, fmt.Errorf("%w (requested height: %d, base height: %d)", coretypes.ErrHeightNotAvailable, height, base)
  167. }
  168. return height, nil
  169. }
  170. return latestHeight, nil
  171. }
  172. func (env *Environment) latestUncommittedHeight() int64 {
  173. if env.ConsensusReactor != nil {
  174. // consensus reactor can be nil in inspect mode.
  175. nodeIsSyncing := env.ConsensusReactor.WaitSync()
  176. if nodeIsSyncing {
  177. return env.BlockStore.Height()
  178. }
  179. }
  180. return env.BlockStore.Height() + 1
  181. }
  182. // StartService constructs and starts listeners for the RPC service
  183. // according to the config object, returning an error if the service
  184. // cannot be constructed or started. The listeners, which provide
  185. // access to the service, run until the context is canceled.
  186. func (env *Environment) StartService(ctx context.Context, conf *config.Config) ([]net.Listener, error) {
  187. if err := env.InitGenesisChunks(); err != nil {
  188. return nil, err
  189. }
  190. listenAddrs := strings.SplitAndTrimEmpty(conf.RPC.ListenAddress, ",", " ")
  191. routes := NewRoutesMap(env, &RouteOptions{
  192. Unsafe: conf.RPC.Unsafe,
  193. })
  194. cfg := rpcserver.DefaultConfig()
  195. cfg.MaxBodyBytes = conf.RPC.MaxBodyBytes
  196. cfg.MaxHeaderBytes = conf.RPC.MaxHeaderBytes
  197. cfg.MaxOpenConnections = conf.RPC.MaxOpenConnections
  198. // If necessary adjust global WriteTimeout to ensure it's greater than
  199. // TimeoutBroadcastTxCommit.
  200. // See https://github.com/tendermint/tendermint/issues/3435
  201. if cfg.WriteTimeout <= conf.RPC.TimeoutBroadcastTxCommit {
  202. cfg.WriteTimeout = conf.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  203. }
  204. // If the event log is enabled, subscribe to all events published to the
  205. // event bus, and forward them to the event log.
  206. if lg := env.EventLog; lg != nil {
  207. // TODO(creachadair): This is kind of a hack, ideally we'd share the
  208. // observer with the indexer, but it's tricky to plumb them together.
  209. // For now, use a "normal" subscription with a big buffer allowance.
  210. // The event log should always be able to keep up.
  211. const subscriberID = "event-log-subscriber"
  212. sub, err := env.EventBus.SubscribeWithArgs(ctx, tmpubsub.SubscribeArgs{
  213. ClientID: subscriberID,
  214. Query: query.All,
  215. Limit: 1 << 16, // essentially "no limit"
  216. })
  217. if err != nil {
  218. return nil, fmt.Errorf("event log subscribe: %w", err)
  219. }
  220. go func() {
  221. // N.B. Use background for unsubscribe, ctx is already terminated.
  222. defer env.EventBus.UnsubscribeAll(context.Background(), subscriberID) // nolint:errcheck
  223. for {
  224. msg, err := sub.Next(ctx)
  225. if err != nil {
  226. env.Logger.Error("Subscription terminated", "err", err)
  227. return
  228. }
  229. etype, ok := eventlog.FindType(msg.Events())
  230. if ok {
  231. _ = lg.Add(etype, msg.Data())
  232. }
  233. }
  234. }()
  235. env.Logger.Info("Event log subscription enabled")
  236. }
  237. // We may expose the RPC over both TCP and a Unix-domain socket.
  238. listeners := make([]net.Listener, len(listenAddrs))
  239. for i, listenAddr := range listenAddrs {
  240. mux := http.NewServeMux()
  241. rpcLogger := env.Logger.With("module", "rpc-server")
  242. rpcserver.RegisterRPCFuncs(mux, routes, rpcLogger)
  243. if conf.RPC.ExperimentalDisableWebsocket {
  244. rpcLogger.Info("Disabling websocket endpoints (experimental-disable-websocket=true)")
  245. } else {
  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. }