|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/ethereum/go-ethereum/common/hexutil" |
| 10 | + "github.com/jackc/pgx/v4" |
| 11 | +) |
| 12 | + |
| 13 | +func proofURLToDBQuery(param string) string { |
| 14 | + type proofLookup struct { |
| 15 | + Proof []string `json:"proof"` |
| 16 | + } |
| 17 | + |
| 18 | + lookup := proofLookup{ |
| 19 | + Proof: strings.Split(param, ","), |
| 20 | + } |
| 21 | + |
| 22 | + q, err := json.Marshal([]proofLookup{lookup}) |
| 23 | + if err != nil { |
| 24 | + return "" |
| 25 | + } |
| 26 | + |
| 27 | + return string(q) |
| 28 | +} |
| 29 | + |
| 30 | +func (s *Server) GetRoot(w http.ResponseWriter, r *http.Request) { |
| 31 | + type rootResp struct { |
| 32 | + Root hexutil.Bytes `json:"root"` |
| 33 | + } |
| 34 | + |
| 35 | + var ( |
| 36 | + ctx = r.Context() |
| 37 | + proof = r.URL.Query().Get("proof") |
| 38 | + dbQuery = proofURLToDBQuery(proof) |
| 39 | + ) |
| 40 | + if proof == "" || dbQuery == "" { |
| 41 | + s.sendJSONError(r, w, nil, http.StatusBadRequest, "missing list of proofs") |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + const q = ` |
| 46 | + SELECT root |
| 47 | + FROM trees |
| 48 | + WHERE proofs @> $1 |
| 49 | + LIMIT 1 |
| 50 | + ` |
| 51 | + |
| 52 | + rr := rootResp{} |
| 53 | + err := s.db.QueryRow(ctx, q, dbQuery).Scan( |
| 54 | + &rr.Root, |
| 55 | + ) |
| 56 | + if errors.Is(err, pgx.ErrNoRows) { |
| 57 | + s.sendJSONError(r, w, err, http.StatusNotFound, "root not found for proofs") |
| 58 | + return |
| 59 | + } else if err != nil { |
| 60 | + s.sendJSONError(r, w, err, http.StatusInternalServerError, "selecting root") |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + w.Header().Set("Cache-Control", "public, max-age=3600") |
| 65 | + s.sendJSON(r, w, rr) |
| 66 | +} |
0 commit comments