diff --git a/README.md b/README.md index cf126bf..7f04bb1 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,6 @@ - `GET /api/v0/event_indexer/address_events`: Retrieves the eventes associated to an EA - query params: - `address`: Address to get events. -- Proxy API: a proxy API that redirect requests to the [Lico API keys](https://github.com/lidofinance/lido-keys-api). Its main functionality is to avoid the cors issues when the Lido CSM UI tries to fetch the API. ## Environment Variables @@ -60,7 +59,6 @@ To configure the app, set the following environment variables: |------------------|------------------------------------------------------------------------------------------------------| | `NETWORK` | Ethereum network (e.g., `mainnet`, `holesky`). Default holesky | | `API_PORT` | Port on which the API will be exposed. Default 8080 | -| `PROXY_API_PORT` | Proxy port on which the Proxy API will be exposed. Default 8081 | | `BEACONCHAIN_URL`| URL of the Ethereum beacon chain client. Default http://beacon-chain.,dncore.dappnode:3500 | | `WS_URL` | URL of the Ethereum WebSocket client. Default ws://execution..dncore.dappnode:8546 | | `RPC_URL` | URL of the Ethereum RPC client. Default http://execution..dncore.dappnode:8545 | diff --git a/cmd/main.go b/cmd/main.go index 3eef4b1..8fcc703 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -90,11 +90,9 @@ func main() { // Initialize API services apiService := services.NewAPIServerService(ctx, networkConfig.ApiPort, storageAdapter, notifierAdapter, relaysUsedAdapter, relaysAllowedAdapter, csModuleEventsScannerService, networkConfig.CORS) - proxyService := services.NewProxyAPIServerService(networkConfig.ProxyApiPort, networkConfig.LidoKeysApiUrl, networkConfig.CORS) // Start API services apiService.Start(&wg) - proxyService.Start(&wg) // Wait for and validate initial configuration if err := waitForConfig(ctx, storageAdapter); err != nil { @@ -123,7 +121,7 @@ func main() { go eventsWatcherService.WatchAllEvents(ctx, &wg) // Handle OS signals for shutdown - handleShutdown(cancel, apiService, proxyService) + handleShutdown(cancel, apiService) // Wait for all goroutines to finish wg.Wait() @@ -153,7 +151,7 @@ func waitForConfig(ctx context.Context, storageAdapter *storage.Storage) error { } // handleShutdown manages graceful shutdown for services -func handleShutdown(cancel context.CancelFunc, apiService *services.APIServerService, proxyService *services.ProxyAPIServerService) { +func handleShutdown(cancel context.CancelFunc, apiService *services.APIServerService) { signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) @@ -167,6 +165,5 @@ func handleShutdown(cancel context.CancelFunc, apiService *services.APIServerSer defer shutdownCancel() apiService.Shutdown(shutdownCtx) - proxyService.Shutdown(shutdownCtx) }() } diff --git a/internal/application/services/proxy_api_server.go b/internal/application/services/proxy_api_server.go deleted file mode 100644 index be80096..0000000 --- a/internal/application/services/proxy_api_server.go +++ /dev/null @@ -1,149 +0,0 @@ -package services - -import ( - "bytes" - "context" - "io" - "net/http" - "net/url" - "strconv" - "sync" - - "lido-events/internal/logger" - - "github.com/gorilla/handlers" - "github.com/gorilla/mux" -) - -type ProxyAPIServerService struct { - server *http.Server - servicePrefix string - proxyApiURL string - router *mux.Router -} - -// NewProxyAPIServerService initializes the Proxy API server -func NewProxyAPIServerService(port uint64, proxyApiURL string, allowedOrigins []string) *ProxyAPIServerService { - router := mux.NewRouter() - - service := &ProxyAPIServerService{ - server: &http.Server{ - Addr: ":" + strconv.FormatUint(port, 10), - }, - servicePrefix: "Proxy API", - proxyApiURL: proxyApiURL, - router: router, - } - - service.setupRoutes() - - // Configure CORS middleware - corsAllowedOrigins := handlers.AllowedOrigins(allowedOrigins) - corsAllowedMethods := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"}) - corsAllowedHeaders := handlers.AllowedHeaders([]string{"Content-Type", "Authorization"}) - - router.Use(handlers.CORS( - corsAllowedOrigins, - corsAllowedMethods, - corsAllowedHeaders, - )) - - service.server.Handler = router - - return service -} - -// Start starts the Proxy API server -func (s *ProxyAPIServerService) Start(wg *sync.WaitGroup) { - wg.Add(1) - go func() { - defer wg.Done() - logger.InfoWithPrefix(s.servicePrefix, "server started on %s", s.server.Addr) - if err := s.server.ListenAndServe(); err != http.ErrServerClosed { - logger.FatalWithPrefix(s.servicePrefix, "server ListenAndServe: %v", err) - } - }() -} - -// Shutdown gracefully shuts down the Proxy API server -func (s *ProxyAPIServerService) Shutdown(ctx context.Context) { - if err := s.server.Shutdown(ctx); err != nil { - logger.WarnWithPrefix(s.servicePrefix, "server Shutdown: %v", err) - } -} - -// setupRoutes sets up all the routes for the Proxy API -func (s *ProxyAPIServerService) setupRoutes() { - s.router.PathPrefix("/v1/").HandlerFunc(s.proxyHandler).Methods("GET", "POST", "OPTIONS") - - // Add a generic OPTIONS handler to ensure preflight requests are handled - s.router.Methods("OPTIONS").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) // Respond to OPTIONS requests with 200 OK - }) -} - -// proxyHandler handles all requests and proxies them to the target API -func (s *ProxyAPIServerService) proxyHandler(w http.ResponseWriter, r *http.Request) { - // Construct the target URL - targetURL, err := url.Parse(s.proxyApiURL) - if err != nil { - http.Error(w, "Invalid proxy URL", http.StatusInternalServerError) - return - } - - // Append the incoming request's path and query parameters to the target URL - targetURL.Path = r.URL.Path - targetURL.RawQuery = r.URL.RawQuery - - // Create the proxy request - proxyReq, err := http.NewRequest(r.Method, targetURL.String(), r.Body) - if err != nil { - http.Error(w, "Failed to create proxy request", http.StatusInternalServerError) - return - } - - // Copy headers from the original request, excluding the Origin header - for key, values := range r.Header { - if key == "Origin" { - continue // Skip the Origin header - } - for _, value := range values { - proxyReq.Header.Add(key, value) - } - } - - // Execute the proxy request - client := &http.Client{} - resp, err := client.Do(proxyReq) - if err != nil { - http.Error(w, "Failed to execute proxy request", http.StatusInternalServerError) - return - } - defer resp.Body.Close() - - // Add CORS headers to the response - w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin")) // Reflect the origin for allowed requests - w.Header().Set("Access-Control-Allow-Credentials", "true") // Allow credentials if needed - w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") - - // Copy other response headers, excluding CORS-related headers - for key, values := range resp.Header { - if key == "Access-Control-Allow-Origin" || key == "Origin" { - continue - } - for _, value := range values { - w.Header().Add(key, value) - } - } - w.WriteHeader(resp.StatusCode) - - // Copy response body - body, err := io.ReadAll(resp.Body) - if err != nil { - http.Error(w, "Failed to read response body", http.StatusInternalServerError) - return - } - - _, _ = io.Copy(w, bytes.NewReader(body)) -} diff --git a/internal/config/config_loader.go b/internal/config/config_loader.go index e7d2fd0..96235ab 100644 --- a/internal/config/config_loader.go +++ b/internal/config/config_loader.go @@ -43,10 +43,6 @@ type Config struct { // tx receipts CSModuleTxReceipt common.Hash - // Lido specifics - LidoKeysApiUrl string - ProxyApiPort uint64 - // Blockchain MinGenesisTime uint64 BlockChunkSize uint64 @@ -98,17 +94,6 @@ func LoadNetworkConfig() (Config, error) { } } - proxyApiPortStr := os.Getenv("PROXY_API_PORT") - proxyApiPort := uint64(8081) - if proxyApiPortStr != "" { - // Try to parse the port as uint64 - if port, err := strconv.ParseUint(proxyApiPortStr, 10, 64); err == nil { - proxyApiPort = port - } else { - logger.Fatal("Invalid PROXY_API_PORT value: %s", proxyApiPortStr) - } - } - network := os.Getenv("NETWORK") // Default to holesky if network == "" { @@ -180,8 +165,6 @@ func LoadNetworkConfig() (Config, error) { CsFeeDistributorBlockDeployment: uint64(1774650), CSModuleAddress: common.HexToAddress("0x4562c3e63c2e586cD1651B958C22F88135aCAd4f"), CSModuleTxReceipt: common.HexToHash("0x1475719ecbb73b28bc531bb54b37695df1bf6b71c6d2bf1d28b4efa404867e26"), - LidoKeysApiUrl: "https://keys-api-holesky.testnet.fi", - ProxyApiPort: proxyApiPort, MinGenesisTime: uint64(1695902400), BlockChunkSize: blockChunkSize, } @@ -221,8 +204,6 @@ func LoadNetworkConfig() (Config, error) { CsFeeDistributorBlockDeployment: uint64(20935463), CSModuleAddress: common.HexToAddress("0xdA7dE2ECdDfccC6c3AF10108Db212ACBBf9EA83F"), CSModuleTxReceipt: common.HexToHash("0xf5330dbcf09885ed145c4435e356b5d8a10054751bb8009d3a2605d476ac173f"), - LidoKeysApiUrl: "https://keys-api.lido.fi", - ProxyApiPort: proxyApiPort, MinGenesisTime: uint64(1606824023), BlockChunkSize: blockChunkSize, }