2022-11-06 21:15:42 -03:00
|
|
|
package nostr
|
|
|
|
|
|
|
|
import (
|
2022-12-17 19:39:10 +01:00
|
|
|
"context"
|
2022-12-19 22:40:24 -06:00
|
|
|
"crypto/rand"
|
2022-11-06 21:15:42 -03:00
|
|
|
"encoding/hex"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
s "github.com/SaveTheRbtz/generic-sync-map-go"
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Status int
|
|
|
|
|
|
|
|
const (
|
|
|
|
PublishStatusSent Status = 0
|
|
|
|
PublishStatusFailed Status = -1
|
|
|
|
PublishStatusSucceeded Status = 1
|
|
|
|
)
|
|
|
|
|
|
|
|
func (s Status) String() string {
|
|
|
|
switch s {
|
|
|
|
case PublishStatusSent:
|
|
|
|
return "sent"
|
|
|
|
case PublishStatusFailed:
|
|
|
|
return "failed"
|
|
|
|
case PublishStatusSucceeded:
|
|
|
|
return "success"
|
|
|
|
}
|
|
|
|
|
|
|
|
return "unknown"
|
|
|
|
}
|
|
|
|
|
|
|
|
type Relay struct {
|
|
|
|
URL string
|
|
|
|
|
|
|
|
Connection *Connection
|
|
|
|
subscriptions s.MapOf[string, *Subscription]
|
|
|
|
|
2022-11-15 07:53:50 -03:00
|
|
|
Notices chan string
|
|
|
|
ConnectionError chan error
|
|
|
|
|
2023-01-01 20:22:40 -03:00
|
|
|
okCallbacks s.MapOf[string, func(bool)]
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
|
|
|
|
2023-01-15 07:19:00 -05:00
|
|
|
// RelayConnect returns a relay object connected to url
|
|
|
|
// Once successfully connected, cancelling ctx has no effect
|
|
|
|
// To close the connection, call r.Close()
|
2023-01-01 20:22:40 -03:00
|
|
|
func RelayConnect(ctx context.Context, url string) (*Relay, error) {
|
2022-11-15 07:53:50 -03:00
|
|
|
r := &Relay{URL: NormalizeURL(url)}
|
2023-01-01 20:22:40 -03:00
|
|
|
err := r.Connect(ctx)
|
2022-11-15 07:53:50 -03:00
|
|
|
return r, err
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
|
|
|
|
2022-11-26 09:25:31 -03:00
|
|
|
func (r *Relay) String() string {
|
|
|
|
return r.URL
|
|
|
|
}
|
|
|
|
|
2023-01-01 20:22:40 -03:00
|
|
|
// Connect tries to establish a websocket connection to r.URL.
|
2022-12-17 19:39:10 +01:00
|
|
|
// If the context expires before the connection is complete, an error is returned.
|
|
|
|
// Once successfully connected, context expiration has no effect: call r.Close
|
|
|
|
// to close the connection.
|
2023-01-01 20:22:40 -03:00
|
|
|
func (r *Relay) Connect(ctx context.Context) error {
|
2022-11-06 21:15:42 -03:00
|
|
|
if r.URL == "" {
|
|
|
|
return fmt.Errorf("invalid relay URL '%s'", r.URL)
|
|
|
|
}
|
|
|
|
|
2023-01-03 14:47:21 -03:00
|
|
|
if _, ok := ctx.Deadline(); !ok {
|
|
|
|
// if no timeout is set, force it to 7 seconds
|
|
|
|
var cancel context.CancelFunc
|
|
|
|
ctx, cancel = context.WithTimeout(ctx, 7*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
}
|
|
|
|
|
2022-12-17 19:39:10 +01:00
|
|
|
socket, _, err := websocket.DefaultDialer.DialContext(ctx, r.URL, nil)
|
2022-11-06 21:15:42 -03:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error opening websocket to '%s': %w", r.URL, err)
|
|
|
|
}
|
|
|
|
|
2022-11-15 07:53:50 -03:00
|
|
|
r.Notices = make(chan string)
|
|
|
|
r.ConnectionError = make(chan error)
|
|
|
|
|
2022-11-06 21:15:42 -03:00
|
|
|
conn := NewConnection(socket)
|
2022-11-14 19:48:02 -03:00
|
|
|
r.Connection = conn
|
2022-11-06 21:15:42 -03:00
|
|
|
|
2022-11-14 19:48:02 -03:00
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
typ, message, err := conn.socket.ReadMessage()
|
|
|
|
if err != nil {
|
2022-11-15 07:53:50 -03:00
|
|
|
r.ConnectionError <- err
|
|
|
|
break
|
2022-11-14 19:48:02 -03:00
|
|
|
}
|
2022-11-15 07:53:50 -03:00
|
|
|
|
2022-11-14 19:48:02 -03:00
|
|
|
if typ == websocket.PingMessage {
|
|
|
|
conn.WriteMessage(websocket.PongMessage, nil)
|
|
|
|
continue
|
|
|
|
}
|
2022-11-06 21:15:42 -03:00
|
|
|
|
2022-11-14 19:48:02 -03:00
|
|
|
if typ != websocket.TextMessage || len(message) == 0 || message[0] != '[' {
|
|
|
|
continue
|
|
|
|
}
|
2022-11-06 21:15:42 -03:00
|
|
|
|
2022-11-14 19:48:02 -03:00
|
|
|
var jsonMessage []json.RawMessage
|
|
|
|
err = json.Unmarshal(message, &jsonMessage)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2022-11-06 21:15:42 -03:00
|
|
|
|
2022-11-14 19:48:02 -03:00
|
|
|
if len(jsonMessage) < 2 {
|
2022-11-06 21:15:42 -03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-11-14 19:48:02 -03:00
|
|
|
var label string
|
|
|
|
json.Unmarshal(jsonMessage[0], &label)
|
|
|
|
|
|
|
|
switch label {
|
|
|
|
case "NOTICE":
|
|
|
|
var content string
|
|
|
|
json.Unmarshal(jsonMessage[1], &content)
|
|
|
|
r.Notices <- content
|
|
|
|
case "EVENT":
|
|
|
|
if len(jsonMessage) < 3 {
|
2022-11-06 21:15:42 -03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-11-14 19:48:02 -03:00
|
|
|
var channel string
|
|
|
|
json.Unmarshal(jsonMessage[1], &channel)
|
|
|
|
if subscription, ok := r.subscriptions.Load(channel); ok {
|
|
|
|
var event Event
|
|
|
|
json.Unmarshal(jsonMessage[2], &event)
|
|
|
|
|
|
|
|
// check signature of all received events, ignore invalid
|
|
|
|
ok, err := event.CheckSignature()
|
|
|
|
if !ok {
|
|
|
|
errmsg := ""
|
|
|
|
if err != nil {
|
|
|
|
errmsg = err.Error()
|
|
|
|
}
|
|
|
|
log.Printf("bad signature: %s", errmsg)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// check if the event matches the desired filter, ignore otherwise
|
2023-01-15 07:19:00 -05:00
|
|
|
func() {
|
|
|
|
subscription.mutex.Lock()
|
|
|
|
defer subscription.mutex.Unlock()
|
|
|
|
if !subscription.Filters.Match(&event) || subscription.stopped {
|
|
|
|
return
|
|
|
|
}
|
2022-11-14 19:48:02 -03:00
|
|
|
subscription.Events <- event
|
2023-01-15 07:19:00 -05:00
|
|
|
}()
|
2022-11-14 19:48:02 -03:00
|
|
|
}
|
|
|
|
case "EOSE":
|
|
|
|
if len(jsonMessage) < 2 {
|
2022-11-06 21:15:42 -03:00
|
|
|
continue
|
|
|
|
}
|
2022-11-14 19:48:02 -03:00
|
|
|
var channel string
|
|
|
|
json.Unmarshal(jsonMessage[1], &channel)
|
|
|
|
if subscription, ok := r.subscriptions.Load(channel); ok {
|
2022-11-16 10:07:15 -03:00
|
|
|
subscription.emitEose.Do(func() {
|
|
|
|
subscription.EndOfStoredEvents <- struct{}{}
|
|
|
|
})
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
2022-11-14 19:48:02 -03:00
|
|
|
case "OK":
|
|
|
|
if len(jsonMessage) < 3 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
var (
|
|
|
|
eventId string
|
|
|
|
ok bool
|
|
|
|
)
|
|
|
|
json.Unmarshal(jsonMessage[1], &eventId)
|
|
|
|
json.Unmarshal(jsonMessage[2], &ok)
|
|
|
|
|
2023-01-01 20:22:40 -03:00
|
|
|
if okCallback, exist := r.okCallbacks.Load(eventId); exist {
|
|
|
|
okCallback(ok)
|
2022-11-12 21:49:57 -03:00
|
|
|
}
|
|
|
|
}
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
2022-11-14 19:48:02 -03:00
|
|
|
}()
|
|
|
|
|
|
|
|
return nil
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
|
|
|
|
2023-01-15 07:19:00 -05:00
|
|
|
// Publish sends an "EVENT" command to the relay r as in NIP-01
|
|
|
|
// status can be: success, failed, or sent (no response from relay before ctx times out)
|
2023-01-01 20:22:40 -03:00
|
|
|
func (r *Relay) Publish(ctx context.Context, event Event) Status {
|
|
|
|
status := PublishStatusFailed
|
2022-11-06 21:15:42 -03:00
|
|
|
|
2023-01-01 20:22:40 -03:00
|
|
|
if _, ok := ctx.Deadline(); !ok {
|
|
|
|
// if no timeout is set, force it to 3 seconds
|
|
|
|
var cancel context.CancelFunc
|
|
|
|
ctx, cancel = context.WithTimeout(ctx, 3*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
}
|
|
|
|
|
|
|
|
// make it cancellable so we can stop everything upon receiving an "OK"
|
|
|
|
var cancel context.CancelFunc
|
|
|
|
ctx, cancel = context.WithCancel(ctx)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
// listen for an OK callback
|
|
|
|
okCallback := func(ok bool) {
|
|
|
|
if ok {
|
|
|
|
status = PublishStatusSucceeded
|
|
|
|
} else {
|
|
|
|
status = PublishStatusFailed
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
2023-01-01 20:22:40 -03:00
|
|
|
cancel()
|
|
|
|
}
|
|
|
|
r.okCallbacks.Store(event.ID, okCallback)
|
|
|
|
defer r.okCallbacks.Delete(event.ID)
|
2022-11-06 21:15:42 -03:00
|
|
|
|
2023-01-01 20:22:40 -03:00
|
|
|
// publish event
|
|
|
|
err := r.Connection.WriteJSON([]interface{}{"EVENT", event})
|
|
|
|
if err != nil {
|
|
|
|
return status
|
|
|
|
}
|
|
|
|
|
|
|
|
// update status (this will be returned later)
|
|
|
|
status = PublishStatusSent
|
|
|
|
|
|
|
|
sub := r.Subscribe(ctx, Filters{Filter{IDs: []string{event.ID}}})
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case receivedEvent := <-sub.Events:
|
|
|
|
if receivedEvent.ID == event.ID {
|
|
|
|
// we got a success, so update our status and proceed to return
|
|
|
|
status = PublishStatusSucceeded
|
|
|
|
return status
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
2023-01-01 20:22:40 -03:00
|
|
|
case <-ctx.Done():
|
|
|
|
// return status as it was
|
|
|
|
// will proceed to return status as it is
|
|
|
|
// e.g. if this happens because of the timeout then status will probably be "failed"
|
|
|
|
// but if it happens because okCallback was called then it might be "succeeded"
|
|
|
|
return status
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
2023-01-01 20:22:40 -03:00
|
|
|
}
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
|
|
|
|
2023-01-15 07:19:00 -05:00
|
|
|
// Subscribe sends a "REQ" command to the relay r as in NIP-01
|
|
|
|
// Events are returned through the channel sub.Events
|
|
|
|
// the subscription is closed when context ctx is cancelled ("CLOSE" in NIP-01)
|
2023-01-01 20:22:40 -03:00
|
|
|
func (r *Relay) Subscribe(ctx context.Context, filters Filters) *Subscription {
|
2022-11-14 19:48:02 -03:00
|
|
|
if r.Connection == nil {
|
|
|
|
panic(fmt.Errorf("must call .Connect() first before calling .Subscribe()"))
|
|
|
|
}
|
|
|
|
|
2022-11-19 14:00:29 -03:00
|
|
|
sub := r.PrepareSubscription()
|
|
|
|
sub.Filters = filters
|
2023-01-01 20:22:40 -03:00
|
|
|
sub.Fire(ctx)
|
|
|
|
|
2022-11-19 14:00:29 -03:00
|
|
|
return sub
|
|
|
|
}
|
|
|
|
|
2023-01-01 20:22:40 -03:00
|
|
|
func (r *Relay) QuerySync(ctx context.Context, filter Filter) []Event {
|
|
|
|
sub := r.Subscribe(ctx, Filters{filter})
|
|
|
|
defer sub.Unsub()
|
|
|
|
|
|
|
|
if _, ok := ctx.Deadline(); !ok {
|
|
|
|
// if no timeout is set, force it to 3 seconds
|
|
|
|
var cancel context.CancelFunc
|
|
|
|
ctx, cancel = context.WithTimeout(ctx, 3*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
}
|
|
|
|
|
2022-11-26 19:32:03 -03:00
|
|
|
var events []Event
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case evt := <-sub.Events:
|
|
|
|
events = append(events, evt)
|
|
|
|
case <-sub.EndOfStoredEvents:
|
|
|
|
return events
|
2023-01-01 20:22:40 -03:00
|
|
|
case <-ctx.Done():
|
2022-11-26 19:32:03 -03:00
|
|
|
return events
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-19 14:00:29 -03:00
|
|
|
func (r *Relay) PrepareSubscription() *Subscription {
|
2022-11-06 21:15:42 -03:00
|
|
|
random := make([]byte, 7)
|
|
|
|
rand.Read(random)
|
|
|
|
id := hex.EncodeToString(random)
|
2022-11-19 14:00:29 -03:00
|
|
|
|
|
|
|
return r.prepareSubscription(id)
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
|
|
|
|
2022-11-19 14:00:29 -03:00
|
|
|
func (r *Relay) prepareSubscription(id string) *Subscription {
|
|
|
|
sub := &Subscription{
|
2022-11-26 09:25:51 -03:00
|
|
|
Relay: r,
|
2022-11-14 19:48:02 -03:00
|
|
|
conn: r.Connection,
|
|
|
|
id: id,
|
|
|
|
Events: make(chan Event),
|
2022-11-16 10:05:28 -03:00
|
|
|
EndOfStoredEvents: make(chan struct{}, 1),
|
2022-11-14 19:48:02 -03:00
|
|
|
}
|
2022-11-06 21:15:42 -03:00
|
|
|
|
2022-11-19 14:00:29 -03:00
|
|
|
r.subscriptions.Store(sub.id, sub)
|
|
|
|
return sub
|
2022-11-06 21:15:42 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Relay) Close() error {
|
|
|
|
return r.Connection.Close()
|
|
|
|
}
|