clients.go raw
1 package sales
2
3 import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/base64"
8 "encoding/json"
9 "fmt"
10 "io"
11 "net/http"
12 "net/url"
13 "strings"
14 "sync"
15 "time"
16
17 "github.com/gorilla/websocket"
18
19 "git.smesh.lol/orly/pkg/nostr/encoders/bech32encoding"
20 "git.smesh.lol/orly/pkg/nostr/encoders/event"
21 "git.smesh.lol/orly/pkg/nostr/encoders/hex"
22 "git.smesh.lol/orly/pkg/nostr/encoders/kind"
23 "git.smesh.lol/orly/pkg/nostr/encoders/tag"
24 "git.smesh.lol/orly/pkg/nostr/interfaces/signer"
25 "git.smesh.lol/orly/pkg/nostr/interfaces/signer/p8k"
26 )
27
28 // HTTPBlobs uploads blobs to a Blossom server over BUD-02.
29 type HTTPBlobs struct {
30 // BaseURL is the server origin, for example "https://blossom.example".
31 BaseURL string
32 // Sign authorizes the upload. It is the seller key; a host may accept it if
33 // the shop is the seller.
34 Sign signer.I
35 // Client is optional.
36 Client *http.Client
37 // AllowPrivate permits a mirror target on a private address. It exists for
38 // a local lab; a public deployment must leave it false.
39 AllowPrivate bool
40 }
41
42 // Put uploads data and returns its SHA-256 hex.
43 func (b *HTTPBlobs) Put(ctx context.Context, data []byte) (string, error) {
44 sum := sha256.Sum256(data)
45 x := hex.Enc(sum[:])
46 if b.BaseURL == "" {
47 return "", fmt.Errorf("sales: no Blossom base URL")
48 }
49 if b.Sign == nil {
50 return "", fmt.Errorf("sales: no upload key")
51 }
52 auth, err := blobAuth(b.Sign, "upload", x, b.BaseURL)
53 if err != nil {
54 return "", err
55 }
56 req, err := http.NewRequestWithContext(ctx, http.MethodPut,
57 strings.TrimRight(b.BaseURL, "/")+"/upload", bytes.NewReader(data))
58 if err != nil {
59 return "", err
60 }
61 req.Header.Set("Authorization", "Nostr "+auth)
62 req.Header.Set("Content-Type", "application/octet-stream")
63 req.Header.Set("X-SHA-256", x)
64 client := b.Client
65 if client == nil {
66 client = &http.Client{Timeout: 60 * time.Second}
67 }
68 resp, err := client.Do(req)
69 if err != nil {
70 return "", fmt.Errorf("sales: upload: %w", err)
71 }
72 defer resp.Body.Close()
73 if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
74 body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
75 return "", fmt.Errorf("sales: upload status %d: %s", resp.StatusCode, string(body))
76 }
77 return x, nil
78 }
79
80 // blobAuth builds a BUD-11 kind 24242 authorization token.
81 func blobAuth(sign signer.I, verb, x, server string) (string, error) {
82 ev := event.New()
83 ev.Kind = 24242
84 ev.CreatedAt = time.Now().Unix()
85 ev.Tags = tag.NewS()
86 ev.Tags.Append(tag.NewFromBytesSlice([]byte("t"), []byte(verb)))
87 ev.Tags.Append(tag.NewFromBytesSlice([]byte("x"), []byte(x)))
88 ev.Tags.Append(tag.NewFromBytesSlice([]byte("expiration"),
89 []byte(fmt.Sprintf("%d", time.Now().Add(5*time.Minute).Unix()))))
90 if server != "" {
91 if u, err := url.Parse(server); err == nil {
92 ev.Tags.Append(tag.NewFromBytesSlice([]byte("server"), []byte(u.Host)))
93 }
94 }
95 if err := ev.Sign(sign); err != nil {
96 return "", err
97 }
98 raw, err := ev.MarshalJSON()
99 if err != nil {
100 return "", err
101 }
102 return base64.RawURLEncoding.EncodeToString(raw), nil
103 }
104
105 // Relay publishes events to one relay over NIP-01.
106 //
107 // It keeps one WebSocket connection for publishing. A new connection per event
108 // is wasteful and trips a relay's per-IP upgrade limit; a single connection is
109 // what a real service uses. A dropped connection is redialled once, which is
110 // safe because an EVENT retry carries the same event id and the relay
111 // deduplicates it.
112 type Relay struct {
113 URL string
114 Timeout time.Duration
115
116 mu sync.Mutex
117 conn *websocket.Conn
118 }
119
120 // NewRelay creates a publisher for one relay URL.
121 func NewRelay(u string) *Relay { return &Relay{URL: u, Timeout: 20 * time.Second} }
122
123 // Publish sends one event and waits for an OK.
124 func (r *Relay) Publish(ctx context.Context, ev *event.E) error {
125 if r == nil || r.URL == "" {
126 return fmt.Errorf("sales: no relay URL")
127 }
128 r.mu.Lock()
129 defer r.mu.Unlock()
130
131 var lastErr error
132 for attempt := 0; attempt < 2; attempt++ {
133 if r.conn == nil {
134 conn, err := r.dial(ctx)
135 if err != nil {
136 lastErr = err
137 continue
138 }
139 r.conn = conn
140 }
141 err := r.send(ctx, ev)
142 if err == nil {
143 return nil
144 }
145 lastErr = err
146 _ = r.conn.Close()
147 r.conn = nil
148 }
149 return lastErr
150 }
151
152 func (r *Relay) dial(ctx context.Context) (*websocket.Conn, error) {
153 timeout := r.Timeout
154 if timeout <= 0 {
155 timeout = 20 * time.Second
156 }
157 dialCtx, cancel := context.WithTimeout(ctx, timeout)
158 defer cancel()
159 dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
160 c, resp, err := dialer.DialContext(dialCtx, r.URL, nil)
161 if resp != nil {
162 resp.Body.Close()
163 }
164 if err != nil {
165 return nil, fmt.Errorf("sales: dial %s: %w", r.URL, err)
166 }
167 return c, nil
168 }
169
170 func (r *Relay) send(ctx context.Context, ev *event.E) error {
171 timeout := r.Timeout
172 if timeout <= 0 {
173 timeout = 20 * time.Second
174 }
175 raw, err := ev.MarshalJSON()
176 if err != nil {
177 return err
178 }
179 msg := []byte(`["EVENT",`)
180 msg = append(msg, raw...)
181 msg = append(msg, ']')
182 _ = r.conn.SetWriteDeadline(time.Now().Add(timeout))
183 if err = r.conn.WriteMessage(websocket.TextMessage, msg); err != nil {
184 return fmt.Errorf("sales: write to %s: %w", r.URL, err)
185 }
186 _ = r.conn.SetReadDeadline(time.Now().Add(timeout))
187 for {
188 _, b, rerr := r.conn.ReadMessage()
189 if rerr != nil {
190 return fmt.Errorf("sales: read from %s: %w", r.URL, rerr)
191 }
192 var resp []json.RawMessage
193 if json.Unmarshal(b, &resp) != nil || len(resp) < 4 {
194 continue
195 }
196 var typ, id string
197 if json.Unmarshal(resp[0], &typ) != nil || typ != "OK" {
198 continue
199 }
200 if json.Unmarshal(resp[1], &id) != nil || id != hex.Enc(ev.ID) {
201 continue
202 }
203 var ok bool
204 var reason string
205 _ = json.Unmarshal(resp[2], &ok)
206 _ = json.Unmarshal(resp[3], &reason)
207 if !ok {
208 return fmt.Errorf("sales: relay %s rejected event: %s", r.URL, reason)
209 }
210 // Clear the read deadline so an idle connection stays usable.
211 _ = r.conn.SetReadDeadline(time.Time{})
212 return nil
213 }
214 }
215
216 // Close closes the publishing connection.
217 func (r *Relay) Close() error {
218 if r == nil {
219 return nil
220 }
221 r.mu.Lock()
222 defer r.mu.Unlock()
223 if r.conn != nil {
224 err := r.conn.Close()
225 r.conn = nil
226 return err
227 }
228 return nil
229 }
230
231 // MultiRelay publishes to every relay and succeeds when the minimum number
232 // accepted. The deed redundancy policy asks for at least three independent
233 // relays.
234 type MultiRelay struct {
235 Relays []*Relay
236 Minimum int
237 }
238
239 // Publish fans out. It returns an error only when fewer than Minimum relays
240 // accepted; the successful count is reported in the error text otherwise.
241 func (m *MultiRelay) Publish(ctx context.Context, ev *event.E) error {
242 min := m.Minimum
243 if min <= 0 {
244 min = 1
245 }
246 type result struct{ err error }
247 ch := make(chan result, len(m.Relays))
248 for _, r := range m.Relays {
249 go func(r *Relay) { ch <- result{err: r.Publish(ctx, ev)} }(r)
250 }
251 ok, lastErr := 0, error(nil)
252 for range m.Relays {
253 res := <-ch
254 if res.err == nil {
255 ok++
256 } else {
257 lastErr = res.err
258 }
259 }
260 if ok < min {
261 return fmt.Errorf("sales: deed published to %d/%d relays (need %d): %v",
262 ok, len(m.Relays), min, lastErr)
263 }
264 return nil
265 }
266
267 // FilterServer normalizes a Blossom host for the filter's server tag.
268 func FilterServer(base string) string {
269 if u, err := url.Parse(base); err == nil && u.Host != "" {
270 return u.Host
271 }
272 return strings.TrimRight(base, "/")
273 }
274
275 // KindTitle is a small helper for logs.
276 func KindTitle(k uint16) string { return kind.New(k).Name() }
277
278 // SignerFromSecret accepts an nsec bech32 string or a 32-byte hex secret and
279 // returns a signer.
280 func SignerFromSecret(sec string) (signer.I, error) {
281 sec = strings.TrimSpace(sec)
282 if sec == "" {
283 return nil, fmt.Errorf("sales: empty secret")
284 }
285 var sk []byte
286 var err error
287 if strings.HasPrefix(sec, "nsec1") {
288 sk, err = bech32encoding.NsecToBytes(sec)
289 if err != nil {
290 return nil, fmt.Errorf("sales: decode nsec: %w", err)
291 }
292 } else {
293 sk, err = hex.Dec(sec)
294 if err != nil || len(sk) != 32 {
295 return nil, fmt.Errorf("sales: secret must be 32-byte hex or nsec bech32")
296 }
297 }
298 s, err := p8k.New()
299 if err != nil {
300 return nil, err
301 }
302 if err = s.InitSec(sk); err != nil {
303 return nil, fmt.Errorf("sales: init signer: %w", err)
304 }
305 return s, nil
306 }
307
308 // FirstNonEmpty returns the first non-empty string.
309 func FirstNonEmpty(v ...string) string {
310 for _, s := range v {
311 if s != "" {
312 return s
313 }
314 }
315 return ""
316 }
317
318 // Mirror asks this Blossom server to fetch a blob from another server, which is
319 // how a host onboards a filter set without the seller re-uploading it (BUD-04).
320 func (b *HTTPBlobs) Mirror(ctx context.Context, remoteURL string) error {
321 if b.BaseURL == "" || b.Sign == nil {
322 return fmt.Errorf("sales: mirror needs a base URL and a key")
323 }
324 if err := checkMirrorURL(remoteURL, b.AllowPrivate); err != nil {
325 return err
326 }
327 auth, err := blobAuth(b.Sign, "upload", "", b.BaseURL)
328 if err != nil {
329 return err
330 }
331 body, err := json.Marshal(map[string]string{"url": remoteURL})
332 if err != nil {
333 return err
334 }
335 req, err := http.NewRequestWithContext(ctx, http.MethodPut,
336 strings.TrimRight(b.BaseURL, "/")+"/mirror", bytes.NewReader(body))
337 if err != nil {
338 return err
339 }
340 req.Header.Set("Authorization", "Nostr "+auth)
341 req.Header.Set("Content-Type", "application/json")
342 resp, err := http.DefaultClient.Do(req)
343 if err != nil {
344 return fmt.Errorf("sales: mirror: %w", err)
345 }
346 defer resp.Body.Close()
347 if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
348 b2, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
349 return fmt.Errorf("sales: mirror status %d: %s", resp.StatusCode, string(b2))
350 }
351 return nil
352 }
353
354 // Delete removes a superseded filter blob (BUD-12). The token is scoped to this
355 // server and to the blob hash, so a captured token cannot delete elsewhere.
356 func (b *HTTPBlobs) Delete(ctx context.Context, x string) error {
357 if b.BaseURL == "" || b.Sign == nil {
358 return fmt.Errorf("sales: delete needs a base URL and a key")
359 }
360 auth, err := blobAuth(b.Sign, "delete", x, b.BaseURL)
361 if err != nil {
362 return err
363 }
364 req, err := http.NewRequestWithContext(ctx, http.MethodDelete,
365 strings.TrimRight(b.BaseURL, "/")+"/"+x, nil)
366 if err != nil {
367 return err
368 }
369 req.Header.Set("Authorization", "Nostr "+auth)
370 resp, err := http.DefaultClient.Do(req)
371 if err != nil {
372 return fmt.Errorf("sales: delete: %w", err)
373 }
374 defer resp.Body.Close()
375 if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent &&
376 resp.StatusCode != http.StatusNotFound {
377 b2, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
378 return fmt.Errorf("sales: delete status %d: %s", resp.StatusCode, string(b2))
379 }
380 return nil
381 }
382