http.go raw

   1  package relay
   2  
   3  import (
   4  	"encoding/hex"
   5  	"encoding/json"
   6  	"errors"
   7  	"fmt"
   8  	"io"
   9  	"net/http"
  10  	"sort"
  11  	"strconv"
  12  	"strings"
  13  
  14  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  15  
  16  	"git.smesh.lol/btcd-lite/internal/wire"
  17  )
  18  
  19  // SpentLookup answers what the instance's UTXO data says about an outpoint at
  20  // the tip: spent, and at which height. An instance that holds no UTXO data
  21  // answers nothing and the relay reports `unknown` instead of guessing.
  22  type SpentLookup func(op wire.OutPoint) (height uint32, known bool, spent bool)
  23  
  24  // Handler is the relay's HTTP face for one chain.
  25  //
  26  //	POST /v1/chains/{chain}/tx   {"tx": "<hex>", "depends_on": ["<txid>:<vout>"]}
  27  //	GET  /v1/chains/{chain}/tx/{txid}
  28  //
  29  // A transaction is admitted, filed in the window and announced to whatever
  30  // peers are connected. The answer is the window's state, `announced`, which is
  31  // exactly what the instance did: it checked what a non-node can check and the
  32  // txid went to `peers` connections. It is not acceptance, and no answer from
  33  // this endpoint claims to be.
  34  type Handler struct {
  35  	Chain  string
  36  	Relay  *Relay
  37  	Window *Window
  38  	// Spent is the instance's UTXO answer, nil when it has none.
  39  	Spent SpentLookup
  40  	// MaxBody bounds a request body.
  41  	MaxBody int64
  42  }
  43  
  44  // SubmitRequest is the POST body.
  45  type SubmitRequest struct {
  46  	Tx        string   `json:"tx"`
  47  	DependsOn []string `json:"depends_on,omitempty"`
  48  }
  49  
  50  // SubmitResponse is a relayed transaction.
  51  type SubmitResponse struct {
  52  	TxID  string `json:"txid"`
  53  	State string `json:"state"`
  54  	Peers int    `json:"peers"`
  55  }
  56  
  57  // ErrorResponse is a refusal.
  58  type ErrorResponse struct {
  59  	Error    string `json:"error"`
  60  	TxID     string `json:"txid,omitempty"`
  61  	OutPoint string `json:"outpoint,omitempty"`
  62  }
  63  
  64  // Routes registers the relay's endpoints on a mux.
  65  func (h *Handler) Routes(mux *http.ServeMux) {
  66  	Multi(mux, map[string]*Handler{h.Chain: h})
  67  }
  68  
  69  // Multi registers the relay's endpoints once for several chains, dispatching on
  70  // the chain segment. One process that relays for two chains cannot register the
  71  // same pattern twice, and a second mux would put the two chains on different
  72  // addresses: the pattern is the chain's name, so the name is the dispatch.
  73  func Multi(mux *http.ServeMux, handlers map[string]*Handler) {
  74  	mux.HandleFunc("POST /v1/chains/{chain}/tx", func(w http.ResponseWriter, r *http.Request) {
  75  		h, ok := handlers[r.PathValue("chain")]
  76  		if !ok {
  77  			writeErr(w, http.StatusNotFound, ErrorResponse{Error: fmt.Sprintf("this instance relays for %s, not %q", chainsOf(handlers), r.PathValue("chain"))})
  78  			return
  79  		}
  80  		h.submit(w, r)
  81  	})
  82  	mux.HandleFunc("GET /v1/chains/{chain}/tx/{txid}", func(w http.ResponseWriter, r *http.Request) {
  83  		h, ok := handlers[r.PathValue("chain")]
  84  		if !ok {
  85  			writeErr(w, http.StatusNotFound, ErrorResponse{Error: fmt.Sprintf("this instance relays for %s, not %q", chainsOf(handlers), r.PathValue("chain"))})
  86  			return
  87  		}
  88  		h.status(w, r)
  89  	})
  90  }
  91  
  92  // chainsOf names the chains a set of handlers holds, sorted.
  93  func chainsOf(handlers map[string]*Handler) string {
  94  	names := make([]string, 0, len(handlers))
  95  	for name := range handlers {
  96  		names = append(names, name)
  97  	}
  98  	sort.Strings(names)
  99  	return strings.Join(names, ",")
 100  }
 101  
 102  func (h *Handler) submit(w http.ResponseWriter, r *http.Request) {
 103  	if chain := r.PathValue("chain"); chain != h.Chain {
 104  		writeErr(w, http.StatusNotFound, ErrorResponse{Error: fmt.Sprintf("this instance relays for %q, not %q", h.Chain, chain)})
 105  		return
 106  	}
 107  	max := h.MaxBody
 108  	if max <= 0 {
 109  		max = MaxTxSize*2 + 1024
 110  	}
 111  	body, err := io.ReadAll(io.LimitReader(r.Body, max))
 112  	if err != nil {
 113  		writeErr(w, http.StatusBadRequest, ErrorResponse{Error: err.Error()})
 114  		return
 115  	}
 116  	var req SubmitRequest
 117  	if err := json.Unmarshal(body, &req); err != nil {
 118  		writeErr(w, http.StatusBadRequest, ErrorResponse{Error: "the body is not the JSON this endpoint takes"})
 119  		return
 120  	}
 121  	raw, err := hex.DecodeString(req.Tx)
 122  	if err != nil {
 123  		writeErr(w, http.StatusBadRequest, ErrorResponse{Error: "tx is not hex"})
 124  		return
 125  	}
 126  	tx, txid, err := ParseAndCheck(raw)
 127  	if err != nil {
 128  		writeErr(w, http.StatusBadRequest, ErrorResponse{Error: err.Error()})
 129  		return
 130  	}
 131  	// The dependencies are what the client says it relies on. A spending set
 132  	// that already has one of them is the failure the instance can see before
 133  	// the client finds out the expensive way.
 134  	if h.Spent != nil {
 135  		for _, dep := range req.DependsOn {
 136  			op, err := parseOutpoint(dep)
 137  			if err != nil {
 138  				writeErr(w, http.StatusBadRequest, ErrorResponse{Error: err.Error(), TxID: txid.String()})
 139  				return
 140  			}
 141  			if at, known, spent := h.Spent(op); known && spent {
 142  				writeErr(w, http.StatusUnprocessableEntity, ErrorResponse{
 143  					Error:    "the instance's set records this outpoint as spent",
 144  					TxID:     txid.String(),
 145  					OutPoint: fmt.Sprintf("%s (spent at %d)", dep, at),
 146  				})
 147  				return
 148  			}
 149  		}
 150  	}
 151  	entry, already := h.Window.Add(&Entry{
 152  		TxID: txid, Raw: raw, Scripts: ScriptsOf(tx), Inputs: InputsOf(tx), Size: len(raw),
 153  	})
 154  	sent := 0
 155  	if !already || entry.State == Announced {
 156  		sent, _ = h.Relay.Announce(r.Context(), []chainhash.Hash{txid})
 157  	}
 158  	writeJSON(w, http.StatusOK, SubmitResponse{TxID: txid.String(), State: entry.State.String(), Peers: sent})
 159  }
 160  
 161  func (h *Handler) status(w http.ResponseWriter, r *http.Request) {
 162  	if chain := r.PathValue("chain"); chain != h.Chain {
 163  		writeErr(w, http.StatusNotFound, ErrorResponse{Error: fmt.Sprintf("this instance relays for %q", h.Chain)})
 164  		return
 165  	}
 166  	id, err := chainhash.NewHashFromStr(r.PathValue("txid"))
 167  	if err != nil {
 168  		writeErr(w, http.StatusBadRequest, ErrorResponse{Error: "txid is not a 32-byte hash"})
 169  		return
 170  	}
 171  	e, ok := h.Window.Get(*id)
 172  	if !ok {
 173  		writeErr(w, http.StatusNotFound, ErrorResponse{Error: "this instance never relayed that txid, or it has aged out of the window", TxID: id.String()})
 174  		return
 175  	}
 176  	writeJSON(w, http.StatusOK, map[string]any{
 177  		"txid":      id.String(),
 178  		"state":     e.State.String(),
 179  		"height":    e.Height,
 180  		"announced": e.Announced.Format(announcedLayout),
 181  		"size":      e.Size,
 182  	})
 183  }
 184  
 185  const announcedLayout = "2006-01-02T15:04:05Z07:00"
 186  
 187  // parseOutpoint reads "txid:vout".
 188  func parseOutpoint(s string) (wire.OutPoint, error) {
 189  	var hashPart string
 190  	var vout int64
 191  	if n, err := fmt.Sscanf(s, "%64s", &hashPart); err != nil || n != 1 {
 192  		return wire.OutPoint{}, errors.New("an outpoint is txid:vout")
 193  	}
 194  	// Sscanf cannot split on the colon with %64s, so the split is explicit.
 195  	for i := len(s) - 1; i > 0; i-- {
 196  		if s[i] != ':' {
 197  			continue
 198  		}
 199  		hashPart = s[:i]
 200  		v, err := strconv.ParseInt(s[i+1:], 10, 64)
 201  		if err != nil || v < 0 || v > 0xffffffff {
 202  			return wire.OutPoint{}, fmt.Errorf("%q is not txid:vout", s)
 203  		}
 204  		vout = v
 205  		break
 206  	}
 207  	h, err := chainhash.NewHashFromStr(hashPart)
 208  	if err != nil {
 209  		return wire.OutPoint{}, fmt.Errorf("%q is not txid:vout", s)
 210  	}
 211  	return wire.OutPoint{Hash: *h, Index: uint32(vout)}, nil
 212  }
 213  
 214  func writeJSON(w http.ResponseWriter, code int, v any) {
 215  	w.Header().Set("Content-Type", "application/json")
 216  	w.WriteHeader(code)
 217  	_ = json.NewEncoder(w).Encode(v)
 218  }
 219  
 220  func writeErr(w http.ResponseWriter, code int, e ErrorResponse) { writeJSON(w, code, e) }
 221