package verify import ( "context" "encoding/hex" "encoding/json" "fmt" "io" "net/http" "net/url" "strconv" "strings" ) // HTTPDoer is the only network primitive the adapters use, so a caller can supply its own client, // its own timeouts, or a recording one in tests. type HTTPDoer interface { Do(*http.Request) (*http.Response, error) } // Paths are the URL shapes of one indexer. They default to the Esplora API because that is what // most public indexers speak, and every one of them can be overridden, which is what keeps the // package from having an opinion about who a user should ask. type Paths struct { // TxStatus is a JSON object with the transaction's status. TxStatus string // TxHex is the transaction's raw hex. TxHex string // TipHash and TipHeight answer the chain head. TipHash string TipHeight string // FeeEstimates is a JSON object of target blocks to satoshis per virtual byte. FeeEstimates string } // DefaultPaths is the Esplora shape. A caller who configures nothing but a base URL gets a working // indexer; a caller with a different backend overrides what differs. var DefaultPaths = Paths{ TxStatus: "/tx/{txid}", TxHex: "/tx/{txid}/hex", TipHash: "/blocks/tip/hash", TipHeight: "/blocks/tip/height", FeeEstimates: "/fee-estimates", } // HTTPAdapter is one configured indexer. // // It carries no default base URL on purpose: the package must not decide which indexer a user // trusts, and a venue-operated backend must never be the thing a build quietly defaults to. type HTTPAdapter struct { // Operator is the name shown to the user and used in agreement reports. Operator string // BaseURL is the indexer's root, for example https://indexer.example. BaseURL string // Paths overrides DefaultPaths where a backend differs. Paths Paths // Client performs the requests. Client HTTPDoer } // NewHTTPAdapter returns an adapter with the default paths and the given client. func NewHTTPAdapter(name, baseURL string, client HTTPDoer) (*HTTPAdapter, error) { parsed, err := url.Parse(strings.TrimSpace(baseURL)) if err != nil || parsed.Scheme == "" || parsed.Host == "" { return nil, fmt.Errorf("verify: %q is not an indexer URL", baseURL) } if strings.TrimSpace(name) == "" { return nil, fmt.Errorf("verify: an indexer needs a name") } if client == nil { return nil, fmt.Errorf("verify: an indexer needs an HTTP client") } return &HTTPAdapter{ Operator: name, BaseURL: strings.TrimRight(parsed.String(), "/"), Paths: DefaultPaths, Client: client, }, nil } // Name identifies the operator. func (a *HTTPAdapter) Name() string { return a.Operator } // Tx asks for a transaction's status and its bytes, and refuses a positive answer that came // without bytes: the engine hashes them, and the adapter must not pretend. func (a *HTTPAdapter) Tx(ctx context.Context, txid [32]byte) (TxFact, error) { display := Hash(txid) statusBody, err := a.get(ctx, strings.ReplaceAll(a.Paths.TxStatus, "{txid}", display)) if err != nil { return TxFact{}, err } var status struct { Status struct { Confirmed bool `json:"confirmed"` BlockHeight int64 `json:"block_height"` } `json:"status"` } if err := json.Unmarshal(statusBody, &status); err != nil { return TxFact{}, fmt.Errorf("verify: %s: status for %s: %w", a.Name(), display, err) } if !status.Status.Confirmed { return TxFact{Found: false}, nil } hexBody, err := a.get(ctx, strings.ReplaceAll(a.Paths.TxHex, "{txid}", display)) if err != nil { return TxFact{}, err } raw, err := hex.DecodeString(strings.TrimSpace(string(hexBody))) if err != nil { return TxFact{}, fmt.Errorf("verify: %s: bytes for %s are not hex: %w", a.Name(), display, err) } // The adapter checks nothing about the bytes here: the engine does, once, for every source. return TxFact{Found: true, Raw: raw, Height: status.Status.BlockHeight}, nil } // Tip asks for the chain head. func (a *HTTPAdapter) Tip(ctx context.Context) (Tip, error) { hashBody, err := a.get(ctx, a.Paths.TipHash) if err != nil { return Tip{}, err } hashText := strings.TrimSpace(string(hashBody)) hash, err := parseDisplayHash(hashText) if err != nil { return Tip{}, fmt.Errorf("verify: %s: tip hash: %w", a.Name(), err) } heightBody, err := a.get(ctx, a.Paths.TipHeight) if err != nil { return Tip{}, err } height, err := strconv.ParseInt(strings.TrimSpace(string(heightBody)), 10, 64) if err != nil { return Tip{}, fmt.Errorf("verify: %s: tip height: %w", a.Name(), err) } return Tip{Height: height, Hash: hash}, nil } // FeeEstimate returns the rate for a confirmation target, in satoshis per virtual byte. func (a *HTTPAdapter) FeeEstimate(ctx context.Context) (int64, error) { body, err := a.get(ctx, a.Paths.FeeEstimates) if err != nil { return 0, err } var estimates map[string]float64 if err := json.Unmarshal(body, &estimates); err != nil { return 0, fmt.Errorf("verify: %s: fee estimates: %w", a.Name(), err) } // Six blocks is the target a swap is priced against here, because that is the depth a // counterparty will wait for. for _, target := range []string{"6", "5", "7", "4", "3"} { if rate, ok := estimates[target]; ok && rate > 0 { return int64(rate + 0.5), nil } } return 0, fmt.Errorf("%w: %s gave no fee estimate", ErrUnverifiable, a.Name()) } func (a *HTTPAdapter) get(ctx context.Context, path string) ([]byte, error) { request, err := http.NewRequestWithContext(ctx, http.MethodGet, a.BaseURL+path, nil) if err != nil { return nil, err } response, err := a.Client.Do(request) if err != nil { return nil, fmt.Errorf("verify: %s: %w", a.Name(), err) } defer response.Body.Close() if response.StatusCode != http.StatusOK { return nil, fmt.Errorf("verify: %s: %s: HTTP %d", a.Name(), path, response.StatusCode) } body, err := io.ReadAll(io.LimitReader(response.Body, 4<<20)) if err != nil { return nil, fmt.Errorf("verify: %s: %s: %w", a.Name(), path, err) } return body, nil } // parseDisplayHash parses the display-order hex every explorer prints. func parseDisplayHash(text string) ([32]byte, error) { var out [32]byte raw, err := hex.DecodeString(strings.TrimPrefix(strings.TrimSpace(text), "0x")) if err != nil { return out, err } if len(raw) != 32 { return out, fmt.Errorf("%d bytes", len(raw)) } for i := 0; i < 32; i++ { out[31-i] = raw[i] } return out, nil }