package relay import ( "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/http" "sort" "strconv" "strings" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/wire" ) // SpentLookup answers what the instance's UTXO data says about an outpoint at // the tip: spent, and at which height. An instance that holds no UTXO data // answers nothing and the relay reports `unknown` instead of guessing. type SpentLookup func(op wire.OutPoint) (height uint32, known bool, spent bool) // Handler is the relay's HTTP face for one chain. // // POST /v1/chains/{chain}/tx {"tx": "", "depends_on": [":"]} // GET /v1/chains/{chain}/tx/{txid} // // A transaction is admitted, filed in the window and announced to whatever // peers are connected. The answer is the window's state, `announced`, which is // exactly what the instance did: it checked what a non-node can check and the // txid went to `peers` connections. It is not acceptance, and no answer from // this endpoint claims to be. type Handler struct { Chain string Relay *Relay Window *Window // Spent is the instance's UTXO answer, nil when it has none. Spent SpentLookup // MaxBody bounds a request body. MaxBody int64 } // SubmitRequest is the POST body. type SubmitRequest struct { Tx string `json:"tx"` DependsOn []string `json:"depends_on,omitempty"` } // SubmitResponse is a relayed transaction. type SubmitResponse struct { TxID string `json:"txid"` State string `json:"state"` Peers int `json:"peers"` } // ErrorResponse is a refusal. type ErrorResponse struct { Error string `json:"error"` TxID string `json:"txid,omitempty"` OutPoint string `json:"outpoint,omitempty"` } // Routes registers the relay's endpoints on a mux. func (h *Handler) Routes(mux *http.ServeMux) { Multi(mux, map[string]*Handler{h.Chain: h}) } // Multi registers the relay's endpoints once for several chains, dispatching on // the chain segment. One process that relays for two chains cannot register the // same pattern twice, and a second mux would put the two chains on different // addresses: the pattern is the chain's name, so the name is the dispatch. func Multi(mux *http.ServeMux, handlers map[string]*Handler) { mux.HandleFunc("POST /v1/chains/{chain}/tx", func(w http.ResponseWriter, r *http.Request) { h, ok := handlers[r.PathValue("chain")] if !ok { writeErr(w, http.StatusNotFound, ErrorResponse{Error: fmt.Sprintf("this instance relays for %s, not %q", chainsOf(handlers), r.PathValue("chain"))}) return } h.submit(w, r) }) mux.HandleFunc("GET /v1/chains/{chain}/tx/{txid}", func(w http.ResponseWriter, r *http.Request) { h, ok := handlers[r.PathValue("chain")] if !ok { writeErr(w, http.StatusNotFound, ErrorResponse{Error: fmt.Sprintf("this instance relays for %s, not %q", chainsOf(handlers), r.PathValue("chain"))}) return } h.status(w, r) }) } // chainsOf names the chains a set of handlers holds, sorted. func chainsOf(handlers map[string]*Handler) string { names := make([]string, 0, len(handlers)) for name := range handlers { names = append(names, name) } sort.Strings(names) return strings.Join(names, ",") } func (h *Handler) submit(w http.ResponseWriter, r *http.Request) { if chain := r.PathValue("chain"); chain != h.Chain { writeErr(w, http.StatusNotFound, ErrorResponse{Error: fmt.Sprintf("this instance relays for %q, not %q", h.Chain, chain)}) return } max := h.MaxBody if max <= 0 { max = MaxTxSize*2 + 1024 } body, err := io.ReadAll(io.LimitReader(r.Body, max)) if err != nil { writeErr(w, http.StatusBadRequest, ErrorResponse{Error: err.Error()}) return } var req SubmitRequest if err := json.Unmarshal(body, &req); err != nil { writeErr(w, http.StatusBadRequest, ErrorResponse{Error: "the body is not the JSON this endpoint takes"}) return } raw, err := hex.DecodeString(req.Tx) if err != nil { writeErr(w, http.StatusBadRequest, ErrorResponse{Error: "tx is not hex"}) return } tx, txid, err := ParseAndCheck(raw) if err != nil { writeErr(w, http.StatusBadRequest, ErrorResponse{Error: err.Error()}) return } // The dependencies are what the client says it relies on. A spending set // that already has one of them is the failure the instance can see before // the client finds out the expensive way. if h.Spent != nil { for _, dep := range req.DependsOn { op, err := parseOutpoint(dep) if err != nil { writeErr(w, http.StatusBadRequest, ErrorResponse{Error: err.Error(), TxID: txid.String()}) return } if at, known, spent := h.Spent(op); known && spent { writeErr(w, http.StatusUnprocessableEntity, ErrorResponse{ Error: "the instance's set records this outpoint as spent", TxID: txid.String(), OutPoint: fmt.Sprintf("%s (spent at %d)", dep, at), }) return } } } entry, already := h.Window.Add(&Entry{ TxID: txid, Raw: raw, Scripts: ScriptsOf(tx), Inputs: InputsOf(tx), Size: len(raw), }) sent := 0 if !already || entry.State == Announced { sent, _ = h.Relay.Announce(r.Context(), []chainhash.Hash{txid}) } writeJSON(w, http.StatusOK, SubmitResponse{TxID: txid.String(), State: entry.State.String(), Peers: sent}) } func (h *Handler) status(w http.ResponseWriter, r *http.Request) { if chain := r.PathValue("chain"); chain != h.Chain { writeErr(w, http.StatusNotFound, ErrorResponse{Error: fmt.Sprintf("this instance relays for %q", h.Chain)}) return } id, err := chainhash.NewHashFromStr(r.PathValue("txid")) if err != nil { writeErr(w, http.StatusBadRequest, ErrorResponse{Error: "txid is not a 32-byte hash"}) return } e, ok := h.Window.Get(*id) if !ok { writeErr(w, http.StatusNotFound, ErrorResponse{Error: "this instance never relayed that txid, or it has aged out of the window", TxID: id.String()}) return } writeJSON(w, http.StatusOK, map[string]any{ "txid": id.String(), "state": e.State.String(), "height": e.Height, "announced": e.Announced.Format(announcedLayout), "size": e.Size, }) } const announcedLayout = "2006-01-02T15:04:05Z07:00" // parseOutpoint reads "txid:vout". func parseOutpoint(s string) (wire.OutPoint, error) { var hashPart string var vout int64 if n, err := fmt.Sscanf(s, "%64s", &hashPart); err != nil || n != 1 { return wire.OutPoint{}, errors.New("an outpoint is txid:vout") } // Sscanf cannot split on the colon with %64s, so the split is explicit. for i := len(s) - 1; i > 0; i-- { if s[i] != ':' { continue } hashPart = s[:i] v, err := strconv.ParseInt(s[i+1:], 10, 64) if err != nil || v < 0 || v > 0xffffffff { return wire.OutPoint{}, fmt.Errorf("%q is not txid:vout", s) } vout = v break } h, err := chainhash.NewHashFromStr(hashPart) if err != nil { return wire.OutPoint{}, fmt.Errorf("%q is not txid:vout", s) } return wire.OutPoint{Hash: *h, Index: uint32(vout)}, nil } func writeJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) _ = json.NewEncoder(w).Encode(v) } func writeErr(w http.ResponseWriter, code int, e ErrorResponse) { writeJSON(w, code, e) }