package sales import ( "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" "sync" "time" "github.com/gorilla/websocket" "git.smesh.lol/orly/pkg/nostr/encoders/bech32encoding" "git.smesh.lol/orly/pkg/nostr/encoders/event" "git.smesh.lol/orly/pkg/nostr/encoders/hex" "git.smesh.lol/orly/pkg/nostr/encoders/kind" "git.smesh.lol/orly/pkg/nostr/encoders/tag" "git.smesh.lol/orly/pkg/nostr/interfaces/signer" "git.smesh.lol/orly/pkg/nostr/interfaces/signer/p8k" ) // HTTPBlobs uploads blobs to a Blossom server over BUD-02. type HTTPBlobs struct { // BaseURL is the server origin, for example "https://blossom.example". BaseURL string // Sign authorizes the upload. It is the seller key; a host may accept it if // the shop is the seller. Sign signer.I // Client is optional. Client *http.Client // AllowPrivate permits a mirror target on a private address. It exists for // a local lab; a public deployment must leave it false. AllowPrivate bool } // Put uploads data and returns its SHA-256 hex. func (b *HTTPBlobs) Put(ctx context.Context, data []byte) (string, error) { sum := sha256.Sum256(data) x := hex.Enc(sum[:]) if b.BaseURL == "" { return "", fmt.Errorf("sales: no Blossom base URL") } if b.Sign == nil { return "", fmt.Errorf("sales: no upload key") } auth, err := blobAuth(b.Sign, "upload", x, b.BaseURL) if err != nil { return "", err } req, err := http.NewRequestWithContext(ctx, http.MethodPut, strings.TrimRight(b.BaseURL, "/")+"/upload", bytes.NewReader(data)) if err != nil { return "", err } req.Header.Set("Authorization", "Nostr "+auth) req.Header.Set("Content-Type", "application/octet-stream") req.Header.Set("X-SHA-256", x) client := b.Client if client == nil { client = &http.Client{Timeout: 60 * time.Second} } resp, err := client.Do(req) if err != nil { return "", fmt.Errorf("sales: upload: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { body, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) return "", fmt.Errorf("sales: upload status %d: %s", resp.StatusCode, string(body)) } return x, nil } // blobAuth builds a BUD-11 kind 24242 authorization token. func blobAuth(sign signer.I, verb, x, server string) (string, error) { ev := event.New() ev.Kind = 24242 ev.CreatedAt = time.Now().Unix() ev.Tags = tag.NewS() ev.Tags.Append(tag.NewFromBytesSlice([]byte("t"), []byte(verb))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("x"), []byte(x))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("expiration"), []byte(fmt.Sprintf("%d", time.Now().Add(5*time.Minute).Unix())))) if server != "" { if u, err := url.Parse(server); err == nil { ev.Tags.Append(tag.NewFromBytesSlice([]byte("server"), []byte(u.Host))) } } if err := ev.Sign(sign); err != nil { return "", err } raw, err := ev.MarshalJSON() if err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(raw), nil } // Relay publishes events to one relay over NIP-01. // // It keeps one WebSocket connection for publishing. A new connection per event // is wasteful and trips a relay's per-IP upgrade limit; a single connection is // what a real service uses. A dropped connection is redialled once, which is // safe because an EVENT retry carries the same event id and the relay // deduplicates it. type Relay struct { URL string Timeout time.Duration mu sync.Mutex conn *websocket.Conn } // NewRelay creates a publisher for one relay URL. func NewRelay(u string) *Relay { return &Relay{URL: u, Timeout: 20 * time.Second} } // Publish sends one event and waits for an OK. func (r *Relay) Publish(ctx context.Context, ev *event.E) error { if r == nil || r.URL == "" { return fmt.Errorf("sales: no relay URL") } r.mu.Lock() defer r.mu.Unlock() var lastErr error for attempt := 0; attempt < 2; attempt++ { if r.conn == nil { conn, err := r.dial(ctx) if err != nil { lastErr = err continue } r.conn = conn } err := r.send(ctx, ev) if err == nil { return nil } lastErr = err _ = r.conn.Close() r.conn = nil } return lastErr } func (r *Relay) dial(ctx context.Context) (*websocket.Conn, error) { timeout := r.Timeout if timeout <= 0 { timeout = 20 * time.Second } dialCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second} c, resp, err := dialer.DialContext(dialCtx, r.URL, nil) if resp != nil { resp.Body.Close() } if err != nil { return nil, fmt.Errorf("sales: dial %s: %w", r.URL, err) } return c, nil } func (r *Relay) send(ctx context.Context, ev *event.E) error { timeout := r.Timeout if timeout <= 0 { timeout = 20 * time.Second } raw, err := ev.MarshalJSON() if err != nil { return err } msg := []byte(`["EVENT",`) msg = append(msg, raw...) msg = append(msg, ']') _ = r.conn.SetWriteDeadline(time.Now().Add(timeout)) if err = r.conn.WriteMessage(websocket.TextMessage, msg); err != nil { return fmt.Errorf("sales: write to %s: %w", r.URL, err) } _ = r.conn.SetReadDeadline(time.Now().Add(timeout)) for { _, b, rerr := r.conn.ReadMessage() if rerr != nil { return fmt.Errorf("sales: read from %s: %w", r.URL, rerr) } var resp []json.RawMessage if json.Unmarshal(b, &resp) != nil || len(resp) < 4 { continue } var typ, id string if json.Unmarshal(resp[0], &typ) != nil || typ != "OK" { continue } if json.Unmarshal(resp[1], &id) != nil || id != hex.Enc(ev.ID) { continue } var ok bool var reason string _ = json.Unmarshal(resp[2], &ok) _ = json.Unmarshal(resp[3], &reason) if !ok { return fmt.Errorf("sales: relay %s rejected event: %s", r.URL, reason) } // Clear the read deadline so an idle connection stays usable. _ = r.conn.SetReadDeadline(time.Time{}) return nil } } // Close closes the publishing connection. func (r *Relay) Close() error { if r == nil { return nil } r.mu.Lock() defer r.mu.Unlock() if r.conn != nil { err := r.conn.Close() r.conn = nil return err } return nil } // MultiRelay publishes to every relay and succeeds when the minimum number // accepted. The deed redundancy policy asks for at least three independent // relays. type MultiRelay struct { Relays []*Relay Minimum int } // Publish fans out. It returns an error only when fewer than Minimum relays // accepted; the successful count is reported in the error text otherwise. func (m *MultiRelay) Publish(ctx context.Context, ev *event.E) error { min := m.Minimum if min <= 0 { min = 1 } type result struct{ err error } ch := make(chan result, len(m.Relays)) for _, r := range m.Relays { go func(r *Relay) { ch <- result{err: r.Publish(ctx, ev)} }(r) } ok, lastErr := 0, error(nil) for range m.Relays { res := <-ch if res.err == nil { ok++ } else { lastErr = res.err } } if ok < min { return fmt.Errorf("sales: deed published to %d/%d relays (need %d): %v", ok, len(m.Relays), min, lastErr) } return nil } // FilterServer normalizes a Blossom host for the filter's server tag. func FilterServer(base string) string { if u, err := url.Parse(base); err == nil && u.Host != "" { return u.Host } return strings.TrimRight(base, "/") } // KindTitle is a small helper for logs. func KindTitle(k uint16) string { return kind.New(k).Name() } // SignerFromSecret accepts an nsec bech32 string or a 32-byte hex secret and // returns a signer. func SignerFromSecret(sec string) (signer.I, error) { sec = strings.TrimSpace(sec) if sec == "" { return nil, fmt.Errorf("sales: empty secret") } var sk []byte var err error if strings.HasPrefix(sec, "nsec1") { sk, err = bech32encoding.NsecToBytes(sec) if err != nil { return nil, fmt.Errorf("sales: decode nsec: %w", err) } } else { sk, err = hex.Dec(sec) if err != nil || len(sk) != 32 { return nil, fmt.Errorf("sales: secret must be 32-byte hex or nsec bech32") } } s, err := p8k.New() if err != nil { return nil, err } if err = s.InitSec(sk); err != nil { return nil, fmt.Errorf("sales: init signer: %w", err) } return s, nil } // FirstNonEmpty returns the first non-empty string. func FirstNonEmpty(v ...string) string { for _, s := range v { if s != "" { return s } } return "" } // Mirror asks this Blossom server to fetch a blob from another server, which is // how a host onboards a filter set without the seller re-uploading it (BUD-04). func (b *HTTPBlobs) Mirror(ctx context.Context, remoteURL string) error { if b.BaseURL == "" || b.Sign == nil { return fmt.Errorf("sales: mirror needs a base URL and a key") } if err := checkMirrorURL(remoteURL, b.AllowPrivate); err != nil { return err } auth, err := blobAuth(b.Sign, "upload", "", b.BaseURL) if err != nil { return err } body, err := json.Marshal(map[string]string{"url": remoteURL}) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPut, strings.TrimRight(b.BaseURL, "/")+"/mirror", bytes.NewReader(body)) if err != nil { return err } req.Header.Set("Authorization", "Nostr "+auth) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return fmt.Errorf("sales: mirror: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { b2, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) return fmt.Errorf("sales: mirror status %d: %s", resp.StatusCode, string(b2)) } return nil } // Delete removes a superseded filter blob (BUD-12). The token is scoped to this // server and to the blob hash, so a captured token cannot delete elsewhere. func (b *HTTPBlobs) Delete(ctx context.Context, x string) error { if b.BaseURL == "" || b.Sign == nil { return fmt.Errorf("sales: delete needs a base URL and a key") } auth, err := blobAuth(b.Sign, "delete", x, b.BaseURL) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodDelete, strings.TrimRight(b.BaseURL, "/")+"/"+x, nil) if err != nil { return err } req.Header.Set("Authorization", "Nostr "+auth) resp, err := http.DefaultClient.Do(req) if err != nil { return fmt.Errorf("sales: delete: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound { b2, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) return fmt.Errorf("sales: delete status %d: %s", resp.StatusCode, string(b2)) } return nil }