adapter.go raw
1 package verify
2
3 import (
4 "context"
5 "encoding/hex"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "net/url"
11 "strconv"
12 "strings"
13 )
14
15 // HTTPDoer is the only network primitive the adapters use, so a caller can supply its own client,
16 // its own timeouts, or a recording one in tests.
17 type HTTPDoer interface {
18 Do(*http.Request) (*http.Response, error)
19 }
20
21 // Paths are the URL shapes of one indexer. They default to the Esplora API because that is what
22 // most public indexers speak, and every one of them can be overridden, which is what keeps the
23 // package from having an opinion about who a user should ask.
24 type Paths struct {
25 // TxStatus is a JSON object with the transaction's status.
26 TxStatus string
27 // TxHex is the transaction's raw hex.
28 TxHex string
29 // TipHash and TipHeight answer the chain head.
30 TipHash string
31 TipHeight string
32 // FeeEstimates is a JSON object of target blocks to satoshis per virtual byte.
33 FeeEstimates string
34 }
35
36 // DefaultPaths is the Esplora shape. A caller who configures nothing but a base URL gets a working
37 // indexer; a caller with a different backend overrides what differs.
38 var DefaultPaths = Paths{
39 TxStatus: "/tx/{txid}",
40 TxHex: "/tx/{txid}/hex",
41 TipHash: "/blocks/tip/hash",
42 TipHeight: "/blocks/tip/height",
43 FeeEstimates: "/fee-estimates",
44 }
45
46 // HTTPAdapter is one configured indexer.
47 //
48 // It carries no default base URL on purpose: the package must not decide which indexer a user
49 // trusts, and a venue-operated backend must never be the thing a build quietly defaults to.
50 type HTTPAdapter struct {
51 // Operator is the name shown to the user and used in agreement reports.
52 Operator string
53 // BaseURL is the indexer's root, for example https://indexer.example.
54 BaseURL string
55 // Paths overrides DefaultPaths where a backend differs.
56 Paths Paths
57 // Client performs the requests.
58 Client HTTPDoer
59 }
60
61 // NewHTTPAdapter returns an adapter with the default paths and the given client.
62 func NewHTTPAdapter(name, baseURL string, client HTTPDoer) (*HTTPAdapter, error) {
63 parsed, err := url.Parse(strings.TrimSpace(baseURL))
64
65 if err != nil || parsed.Scheme == "" || parsed.Host == "" {
66 return nil, fmt.Errorf("verify: %q is not an indexer URL", baseURL)
67 }
68
69 if strings.TrimSpace(name) == "" {
70 return nil, fmt.Errorf("verify: an indexer needs a name")
71 }
72
73 if client == nil {
74 return nil, fmt.Errorf("verify: an indexer needs an HTTP client")
75 }
76
77 return &HTTPAdapter{
78 Operator: name,
79 BaseURL: strings.TrimRight(parsed.String(), "/"),
80 Paths: DefaultPaths,
81 Client: client,
82 }, nil
83 }
84
85 // Name identifies the operator.
86 func (a *HTTPAdapter) Name() string { return a.Operator }
87
88 // Tx asks for a transaction's status and its bytes, and refuses a positive answer that came
89 // without bytes: the engine hashes them, and the adapter must not pretend.
90 func (a *HTTPAdapter) Tx(ctx context.Context, txid [32]byte) (TxFact, error) {
91 display := Hash(txid)
92
93 statusBody, err := a.get(ctx, strings.ReplaceAll(a.Paths.TxStatus, "{txid}", display))
94
95 if err != nil {
96 return TxFact{}, err
97 }
98
99 var status struct {
100 Status struct {
101 Confirmed bool `json:"confirmed"`
102 BlockHeight int64 `json:"block_height"`
103 } `json:"status"`
104 }
105
106 if err := json.Unmarshal(statusBody, &status); err != nil {
107 return TxFact{}, fmt.Errorf("verify: %s: status for %s: %w", a.Name(), display, err)
108 }
109
110 if !status.Status.Confirmed {
111 return TxFact{Found: false}, nil
112 }
113
114 hexBody, err := a.get(ctx, strings.ReplaceAll(a.Paths.TxHex, "{txid}", display))
115
116 if err != nil {
117 return TxFact{}, err
118 }
119
120 raw, err := hex.DecodeString(strings.TrimSpace(string(hexBody)))
121
122 if err != nil {
123 return TxFact{}, fmt.Errorf("verify: %s: bytes for %s are not hex: %w", a.Name(), display, err)
124 }
125
126 // The adapter checks nothing about the bytes here: the engine does, once, for every source.
127 return TxFact{Found: true, Raw: raw, Height: status.Status.BlockHeight}, nil
128 }
129
130 // Tip asks for the chain head.
131 func (a *HTTPAdapter) Tip(ctx context.Context) (Tip, error) {
132 hashBody, err := a.get(ctx, a.Paths.TipHash)
133
134 if err != nil {
135 return Tip{}, err
136 }
137
138 hashText := strings.TrimSpace(string(hashBody))
139
140 hash, err := parseDisplayHash(hashText)
141
142 if err != nil {
143 return Tip{}, fmt.Errorf("verify: %s: tip hash: %w", a.Name(), err)
144 }
145
146 heightBody, err := a.get(ctx, a.Paths.TipHeight)
147
148 if err != nil {
149 return Tip{}, err
150 }
151
152 height, err := strconv.ParseInt(strings.TrimSpace(string(heightBody)), 10, 64)
153
154 if err != nil {
155 return Tip{}, fmt.Errorf("verify: %s: tip height: %w", a.Name(), err)
156 }
157
158 return Tip{Height: height, Hash: hash}, nil
159 }
160
161 // FeeEstimate returns the rate for a confirmation target, in satoshis per virtual byte.
162 func (a *HTTPAdapter) FeeEstimate(ctx context.Context) (int64, error) {
163 body, err := a.get(ctx, a.Paths.FeeEstimates)
164
165 if err != nil {
166 return 0, err
167 }
168
169 var estimates map[string]float64
170
171 if err := json.Unmarshal(body, &estimates); err != nil {
172 return 0, fmt.Errorf("verify: %s: fee estimates: %w", a.Name(), err)
173 }
174
175 // Six blocks is the target a swap is priced against here, because that is the depth a
176 // counterparty will wait for.
177 for _, target := range []string{"6", "5", "7", "4", "3"} {
178 if rate, ok := estimates[target]; ok && rate > 0 {
179 return int64(rate + 0.5), nil
180 }
181 }
182
183 return 0, fmt.Errorf("%w: %s gave no fee estimate", ErrUnverifiable, a.Name())
184 }
185
186 func (a *HTTPAdapter) get(ctx context.Context, path string) ([]byte, error) {
187 request, err := http.NewRequestWithContext(ctx, http.MethodGet, a.BaseURL+path, nil)
188
189 if err != nil {
190 return nil, err
191 }
192
193 response, err := a.Client.Do(request)
194
195 if err != nil {
196 return nil, fmt.Errorf("verify: %s: %w", a.Name(), err)
197 }
198
199 defer response.Body.Close()
200
201 if response.StatusCode != http.StatusOK {
202 return nil, fmt.Errorf("verify: %s: %s: HTTP %d", a.Name(), path, response.StatusCode)
203 }
204
205 body, err := io.ReadAll(io.LimitReader(response.Body, 4<<20))
206
207 if err != nil {
208 return nil, fmt.Errorf("verify: %s: %s: %w", a.Name(), path, err)
209 }
210
211 return body, nil
212 }
213
214 // parseDisplayHash parses the display-order hex every explorer prints.
215 func parseDisplayHash(text string) ([32]byte, error) {
216 var out [32]byte
217
218 raw, err := hex.DecodeString(strings.TrimPrefix(strings.TrimSpace(text), "0x"))
219
220 if err != nil {
221 return out, err
222 }
223
224 if len(raw) != 32 {
225 return out, fmt.Errorf("%d bytes", len(raw))
226 }
227
228 for i := 0; i < 32; i++ {
229 out[31-i] = raw[i]
230 }
231
232 return out, nil
233 }
234