mirror of
https://github.com/luxfi/explorer.git
synced 2026-09-24 00:25:12 +00:00
One binary answers explore.lux.network, explore.hanzo.network and
explore.zoo.network. Only /envs.js and the slug-prefixed /v1/indexer/{slug}
routes knew that. Everything else read whichever chain the config called
default, so Hanzo's home page printed 1,107,383 total blocks above its own
Latest blocks list topping out at 29,805 — Lux's number, on Hanzo's page,
overstating Hanzo's chain 37x and Zoo's 49x. Measured on all three brands.
Config.Serves(host) is now the one thing that answers "which chain is this
request about", and the three surfaces that were guessing ask it:
* StatsService keeps a read handle per chain instead of one pinned at
startup, so /v1/counters, /v1/lines, /v1/pages/* and /v1/stats report the
host's chain: 1107259 / 29805 / 22728 on the three brand hosts, where all
three read 1107259 before.
* The realtime stream carries the host's chain. It carried all of them: a
45s read of /v1/base/realtime returned the same 6 cchain + 14 hanzo + 5 zoo
events on every brand host, and the SPA appends what it is sent, so a
50-block page rendered 63 rows with 2 Lux on top and 8 Zoo at the bottom.
?chain= still overrides; an empty filter no longer means "all chains",
because no brand host wants another brand's blocks.
* A slug-less /v1/indexer/* request follows the host, falling back to the
default only when the host names no chain (api-explore.lux.network) or
names one that is not up.
Also here, because they were all the same mistake about the same column: the
timestamp in evm_blocks is a Go time.Time bound into a column declared
TIMESTAMP, so SQLite stores a datetime STRING, and everything that read it as
a unix epoch got nothing and said nothing.
* /stats' daily charts were empty on all three brands. strftime with the
'unixepoch' modifier returns NULL on a datetime string, the scan failed,
and handlePagesMain discarded the error into `daily, _ :=` — a nil slice
marshals to `null`, which the page renders as "No data". Now 22 points.
* Average block time read 0.0s on a chain producing a block every 10s: the
three-value Scan failed and its error was never checked, so the zero went
out as the answer. Now 60.0 on a one-block-per-minute fixture.
* /v1/blocks reported `"timestamp": 2026` for every block — CAST of a
datetime string takes its leading digits, and 2026 looks like a number
rather than a failure. Now a real epoch.
* Transactions (24h) was the lifetime total. SQLite orders every INTEGER
below every TEXT, so `timestamp > <epoch>` was true for all 1.1M rows.
blockEpoch and blockDay are the only two spellings allowed to touch that
column now. The fixtures were the reason none of this failed a test: they
declared the column TIMESTAMP and then inserted integers into it, so the suite
exercised a database the indexer never writes. They bind a time.Time now, and
on the old queries they fail with exactly what production showed —
average_block_time "0.0", empty charts, timestamp 2026.
Deleted: the eight per-channel SSE routes at bare /blocks, /transactions,
/tokens, /gas-tracker, /stats, /validators, /token-transfers and /internal-txs.
Every one of those is also an SPA page path, and one mux cannot serve both; the
SPA opens only the multiplexed stream, so they had no subscriber to lose. With
them goes the second envelope, the per-channel framing built on every
broadcast, and the client's channel field — SSE has one endpoint and one shape.
indexer v1.5.3 for the block transaction-count name.
Co-authored-by: Hanzo Dev <[email protected]>
233 lines
7.3 KiB
Go
233 lines
7.3 KiB
Go
// Package main is the unified Lux explorer: a single Go binary that embeds
|
|
// the SPA, indexes one or more chains via github.com/luxfi/indexer, runs a
|
|
// per-chain GraphQL engine via github.com/luxfi/graph, and exposes the
|
|
// admin/realtime API and frontend assets on one HTTP listener.
|
|
//
|
|
// Build: go build -o explorer .
|
|
// Run: explorer --config /etc/explorer/chains.yaml
|
|
//
|
|
// Routes:
|
|
//
|
|
// / SPA (embedded; SPA-routing fallback)
|
|
// /envs.js runtime config window.ENV = {...}
|
|
// /icon.svg, /logo.svg per-host brand assets (disk override)
|
|
// /health service health
|
|
// /v1/indexer/* default chain explorer API
|
|
// /v1/indexer/{slug}/* per-chain explorer API
|
|
// /v1/explorer/{slug}/* legacy alias for /v1/indexer/{slug}
|
|
// /v1/graph/{slug}/{subgraph}/graphql per-chain, per-subgraph GraphQL
|
|
// /v1/explorer/admin/chains[/{slug}] runtime registry CRUD
|
|
// /v1/explorer/realtime WebSocket realtime hub
|
|
// /v1/explorer/realtime/stats realtime stats
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
var version = "dev"
|
|
|
|
func main() {
|
|
var (
|
|
httpAddr = flag.String("http", "", "HTTP listen address (default :8090 / $HTTP_ADDR)")
|
|
dataDir = flag.String("data", "", "Data directory (default $DATA_DIR or ~/.explorer/data)")
|
|
configPath = flag.String("config", "", "Path to chains.yaml ($EXPLORER_CONFIG)")
|
|
enableMDNS = flag.Bool("mdns", envBool("EXPLORER_MDNS", false), "Auto-discover chains via mDNS")
|
|
showVer = flag.Bool("version", false, "Show version and exit")
|
|
)
|
|
flag.Parse()
|
|
|
|
if *showVer {
|
|
fmt.Printf("explorer %s (%s)\n", version, fingerprint())
|
|
os.Exit(0)
|
|
}
|
|
|
|
if *httpAddr == "" {
|
|
*httpAddr = env("HTTP_ADDR", ":8090")
|
|
if p := os.Getenv("PORT"); p != "" && *httpAddr == ":8090" {
|
|
*httpAddr = ":" + p
|
|
}
|
|
}
|
|
if *dataDir == "" {
|
|
home, _ := os.UserHomeDir()
|
|
*dataDir = env("DATA_DIR", filepath.Join(home, ".explorer", "data"))
|
|
}
|
|
if *configPath == "" {
|
|
*configPath = env("EXPLORER_CONFIG", "")
|
|
}
|
|
if *configPath == "" {
|
|
*configPath = findConfig(*dataDir)
|
|
}
|
|
|
|
var cfg Config
|
|
if *configPath != "" {
|
|
c, err := LoadConfig(*configPath)
|
|
if err != nil {
|
|
log.Fatalf("[explorer] config: %v", err)
|
|
}
|
|
cfg = c
|
|
}
|
|
if cfg.DataDir == "" {
|
|
cfg.DataDir = *dataDir
|
|
}
|
|
if cfg.HTTPAddr == "" {
|
|
cfg.HTTPAddr = *httpAddr
|
|
}
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
|
|
sigCh := make(chan os.Signal, 1)
|
|
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
|
|
go func() { <-sigCh; log.Println("[explorer] shutdown"); cancel() }()
|
|
|
|
registry := NewChainRegistry()
|
|
supervisor := NewChainSupervisor(cfg)
|
|
registry.AttachSupervisor(supervisor)
|
|
// Bridge indexer block events into the realtime hub so WebSocket +
|
|
// SSE subscribers see new blocks as they're ingested. Must happen
|
|
// before any chain starts indexing — runChain installs the
|
|
// Subscriber.OnBroadcast callback off the hub set here.
|
|
supervisor.AttachRealtime(registry.hub)
|
|
|
|
for _, c := range cfg.Chains {
|
|
c.Source = "config"
|
|
if err := registry.Add(c); err != nil {
|
|
log.Printf("[explorer] skip %s from config: %v", c.Slug, err)
|
|
}
|
|
}
|
|
|
|
if chains := os.Getenv("CHAINS"); chains != "" {
|
|
registry.LoadFromEnv(chains)
|
|
}
|
|
|
|
if *enableMDNS {
|
|
go registry.StartMDNSDiscovery()
|
|
}
|
|
|
|
go registry.hub.Run(ctx)
|
|
go supervisor.Wait(ctx)
|
|
|
|
frontend, err := NewFrontend(cfg, registry)
|
|
if err != nil {
|
|
log.Fatalf("[explorer] frontend: %v", err)
|
|
}
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]any{
|
|
"status": "ok",
|
|
"version": version,
|
|
"chains": registry.Count(),
|
|
})
|
|
})
|
|
|
|
// Blockscout stats-microservice surface (/v1/counters, /v1/lines,
|
|
// /v1/lines/{id}, /v1/pages/*). The Next.js /stats page enables these when
|
|
// NEXT_PUBLIC_STATS_API_HOST is set and shows error banners without them;
|
|
// each answer is read from the live indexer SQLite DB of the chain the
|
|
// request host is served.
|
|
NewStatsService(cfg.DataDir, cfg).Mount(mux)
|
|
|
|
mux.HandleFunc("GET /v1/explorer/admin/chains", registry.HandleList)
|
|
mux.HandleFunc("POST /v1/explorer/admin/chains", registry.HandleAdd)
|
|
mux.HandleFunc("PUT /v1/explorer/admin/chains/{slug}", registry.HandleUpdate)
|
|
mux.HandleFunc("DELETE /v1/explorer/admin/chains/{slug}", registry.HandleRemove)
|
|
|
|
mux.HandleFunc("/v1/explorer/realtime", registry.hub.HandleRealtime)
|
|
mux.HandleFunc("GET /v1/explorer/realtime/stats", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(registry.hub.Stats())
|
|
})
|
|
|
|
// /v1/base/realtime — the multiplexed SSE channel, and the only one the SPA
|
|
// opens. One stream carries every broadcast for the host's chain in a JSON
|
|
// envelope `{event, chain, data}` that the SPA routes off via its handler
|
|
// map. HEAD is registered explicitly so the SPA's pre-flight
|
|
// (HEAD-then-EventSource) reaches the same handler; net/http's ServeMux
|
|
// answers 405 for HEAD on a GET-only route, which the SPA's `r.ok` check
|
|
// reads as a dead channel. See realtime_sse.go.
|
|
realtime := registry.hub.HandleMultiplexedSSE(cfg)
|
|
mux.HandleFunc("GET /v1/base/realtime", realtime)
|
|
mux.HandleFunc("HEAD /v1/base/realtime", realtime)
|
|
|
|
supervisor.MountRoutes(mux)
|
|
frontend.Mount(mux)
|
|
|
|
log.Printf("[explorer] %s listening %s data=%s chains=%d mdns=%v %s",
|
|
version, cfg.HTTPAddr, cfg.DataDir, registry.Count(), *enableMDNS, fingerprint())
|
|
|
|
server := &http.Server{Addr: cfg.HTTPAddr, Handler: withSecurity(mux)}
|
|
go func() {
|
|
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
log.Fatalf("[explorer] server: %v", err)
|
|
}
|
|
}()
|
|
<-ctx.Done()
|
|
shutCtx, shutCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer shutCancel()
|
|
server.Shutdown(shutCtx)
|
|
log.Println("[explorer] stopped")
|
|
}
|
|
|
|
// withSecurity adds the baseline security headers and CORS preflight handler.
|
|
func withSecurity(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.Header().Set("X-Frame-Options", "DENY")
|
|
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
|
if r.Method == http.MethodOptions {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func env(key, fallback string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return fallback
|
|
}
|
|
|
|
func envBool(key string, fallback bool) bool {
|
|
switch strings.ToLower(os.Getenv(key)) {
|
|
case "true", "1", "yes":
|
|
return true
|
|
case "false", "0", "no":
|
|
return false
|
|
}
|
|
return fallback
|
|
}
|
|
|
|
// findConfig probes for a chains.yaml in the standard locations.
|
|
func findConfig(dataDir string) string {
|
|
for _, p := range []string{
|
|
filepath.Join(dataDir, "chains.yaml"),
|
|
"chains.yaml",
|
|
"/etc/explorer/chains.yaml",
|
|
} {
|
|
if _, err := os.Stat(p); err == nil {
|
|
return p
|
|
}
|
|
}
|
|
return ""
|
|
}
|