diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..2e632372 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,192 @@ +name: Test + +on: + push: + branches: ["tinygo"] + +jobs: + test: + name: Go Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Run tests + run: | + PKGS=( + "." + "./nip04" + "./nip05" + "./nip06" + "./nip10" + "./nip11" + "./nip13" + "./nip14" + "./nip17" + "./nip19" + "./nip22" + "./nip23" + "./nip27" + "./nip31" + "./nip34" + "./nip40" + "./nip42" + "./nip44" + "./nip46" + "./nip49" + "./nip52" + "./nip53" + "./nip54" + "./nip57" + "./nip59" + "./nip60" + "./nip60/client" + "./nip61" + "./nip65" + "./nip70" + "./nip73" + "./nip77" + "./nip77/negentropy" + "./nip86" + "./nip92" + "./nip94" + ) + go test "${PKGS[@]}" + + test-wasm-go: + name: Go WASM Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Install Chrome + uses: browser-actions/setup-chrome@latest + + - name: Disable AppArmor Chrome restriction + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + + - name: Install wasmbrowsertest + run: | + go install github.com/agnivade/wasmbrowsertest@latest + mv $(go env GOPATH)/bin/wasmbrowsertest $(go env GOPATH)/bin/go_js_wasm_exec + + - name: Run GOOS=js WASM tests + run: | + PKGS=( + "." + "./nip04" + "./nip05" + "./nip06" + "./nip10" + "./nip11" + "./nip13" + "./nip14" + "./nip17" + "./nip19" + "./nip22" + "./nip23" + "./nip27" + "./nip31" + "./nip34" + "./nip40" + "./nip42" + "./nip44" + "./nip46" + "./nip49" + "./nip52" + "./nip53" + "./nip54" + "./nip57" + "./nip59" + "./nip60" + "./nip60/client" + "./nip61" + "./nip65" + "./nip70" + "./nip73" + "./nip77" + "./nip77/negentropy" + "./nip86" + "./nip92" + "./nip94" + ) + GOOS=js GOARCH=wasm go test -short "${PKGS[@]}" + + test-wasm-tinygo: + name: TinyGo WASM Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Install TinyGo + run: | + wget -q https://github.com/tinygo-org/tinygo/releases/download/v0.40.1/tinygo_0.40.1_amd64.deb + sudo dpkg -i tinygo_0.40.1_amd64.deb + + - name: Install Chrome + uses: browser-actions/setup-chrome@latest + + - name: Disable AppArmor Chrome restriction + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + + - name: Install wasmbrowsertest + run: | + go install github.com/agnivade/wasmbrowsertest@latest + mv $(go env GOPATH)/bin/wasmbrowsertest $(go env GOPATH)/bin/go_js_wasm_exec + + - name: Run TinyGo WASM tests + run: | + WASM_PKGS=( + "." + "./nip04" + "./nip05" + "./nip06" + "./nip10" + "./nip11" + "./nip13" + "./nip14" + "./nip17" + "./nip19" + "./nip22" + "./nip23" + "./nip27" + "./nip31" + "./nip34" + "./nip40" + "./nip42" + "./nip44" + "./nip46" + "./nip49" + "./nip52" + "./nip53" + "./nip54" + "./nip57" + "./nip59" + "./nip60" + "./nip60/client" + "./nip61" + "./nip65" + "./nip70" + "./nip73" + "./nip77" + "./nip77/negentropy" + "./nip86" + "./nip92" + "./nip94" + ) + GOOS=js GOARCH=wasm tinygo test -short "${PKGS[@]}" diff --git a/.gitignore b/.gitignore index af2ce2f4..65bfef5b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ go-nostr libsecp256k1 +.vscode/ +TODO.md \ No newline at end of file diff --git a/envelopes.go b/envelopes.go index 444546c8..81b4e66b 100644 --- a/envelopes.go +++ b/envelopes.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nostr import ( diff --git a/envelopes_tinygo.go b/envelopes_tinygo.go new file mode 100644 index 00000000..2e8cb547 --- /dev/null +++ b/envelopes_tinygo.go @@ -0,0 +1,443 @@ +//go:build tinygo + +package nostr + +import ( + "errors" + "fmt" + "strconv" + "strings" + + "github.com/tidwall/gjson" +) + +var ( + UnknownLabel = errors.New("unknown envelope label") + InvalidJsonEnvelope = errors.New("invalid json envelope") +) + +func ParseMessage(message string) (Envelope, error) { + firstQuote := strings.IndexByte(message, '"') + if firstQuote == -1 { + return nil, InvalidJsonEnvelope + } + secondQuote := strings.IndexByte(message[firstQuote+1:], '"') + if secondQuote == -1 { + return nil, InvalidJsonEnvelope + } + label := message[firstQuote+1 : firstQuote+1+secondQuote] + + var v Envelope + switch label { + case "EVENT": + v = &EventEnvelope{} + case "REQ": + v = &ReqEnvelope{} + case "COUNT": + v = &CountEnvelope{} + case "NOTICE": + x := NoticeEnvelope("") + v = &x + case "EOSE": + x := EOSEEnvelope("") + v = &x + case "OK": + v = &OKEnvelope{} + case "AUTH": + v = &AuthEnvelope{} + case "CLOSED": + v = &ClosedEnvelope{} + case "CLOSE": + x := CloseEnvelope("") + v = &x + default: + return nil, UnknownLabel + } + + if err := v.FromJSON(message); err != nil { + return nil, err + } + + return v, nil +} + +// Envelope is the interface for all nostr message envelopes. +type Envelope interface { + Label() string + FromJSON(string) error + MarshalJSON() ([]byte, error) + String() string +} + +var ( + _ Envelope = (*EventEnvelope)(nil) + _ Envelope = (*ReqEnvelope)(nil) + _ Envelope = (*CountEnvelope)(nil) + _ Envelope = (*NoticeEnvelope)(nil) + _ Envelope = (*EOSEEnvelope)(nil) + _ Envelope = (*CloseEnvelope)(nil) + _ Envelope = (*OKEnvelope)(nil) + _ Envelope = (*AuthEnvelope)(nil) +) + +// EventEnvelope represents an EVENT message. +type EventEnvelope struct { + SubscriptionID *string + Event +} + +func (_ EventEnvelope) Label() string { return "EVENT" } + +func (v *EventEnvelope) FromJSON(data string) error { + r := gjson.Parse(data) + arr := r.Array() + switch len(arr) { + case 2: + return json.Unmarshal([]byte(arr[1].Raw), &v.Event) + case 3: + subid := arr[1].String() + v.SubscriptionID = &subid + return json.Unmarshal([]byte(arr[2].Raw), &v.Event) + default: + return fmt.Errorf("failed to decode EVENT envelope") + } +} + +func (v EventEnvelope) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `["EVENT",`...) + if v.SubscriptionID != nil { + b = escapeString(b, *v.SubscriptionID) + b = append(b, ',') + } + eb, err := v.Event.MarshalJSON() + if err != nil { + return nil, err + } + b = append(b, eb...) + b = append(b, ']') + return b, nil +} + +// ReqEnvelope represents a REQ message. +type ReqEnvelope struct { + SubscriptionID string + Filters []Filter +} + +func (_ ReqEnvelope) Label() string { return "REQ" } +func (c ReqEnvelope) String() string { + v, _ := json.Marshal(c) + return string(v) +} + +func (v *ReqEnvelope) FromJSON(data string) error { + r := gjson.Parse(data) + arr := r.Array() + if len(arr) < 3 { + return fmt.Errorf("failed to decode REQ envelope: missing filters") + } + v.SubscriptionID = arr[1].String() + + v.Filters = make([]Filter, len(arr)-2) + for i, filterj := range arr[2:] { + if err := json.Unmarshal([]byte(filterj.Raw), &v.Filters[i]); err != nil { + return fmt.Errorf("on filter: %w", err) + } + } + + return nil +} + +func (v ReqEnvelope) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `["REQ",`...) + b = escapeString(b, v.SubscriptionID) + for _, f := range v.Filters { + b = append(b, ',') + fb, err := f.MarshalJSON() + if err != nil { + return nil, err + } + b = append(b, fb...) + } + b = append(b, ']') + return b, nil +} + +// CountEnvelope represents a COUNT message. +type CountEnvelope struct { + SubscriptionID string + Filter + Count *uint32 + HyperLogLog []byte +} + +func (_ CountEnvelope) Label() string { return "COUNT" } +func (c CountEnvelope) String() string { + v, _ := json.Marshal(c) + return string(v) +} + +func (v *CountEnvelope) FromJSON(data string) error { + r := gjson.Parse(data) + arr := r.Array() + if len(arr) < 3 { + return fmt.Errorf("failed to decode COUNT envelope: missing filters") + } + v.SubscriptionID = arr[1].String() + + var countResult struct { + Count *uint32 `json:"count"` + HLL string `json:"hll"` + } + // Try to unmarshal as count result first + if err := json.Unmarshal([]byte(arr[2].Raw), &countResult); err == nil && countResult.Count != nil { + v.Count = countResult.Count + if len(countResult.HLL) > 0 { + hll, err := HexDecodeString(countResult.HLL) + if err != nil { + return fmt.Errorf("invalid \"hll\" value in COUNT message: %w", err) + } + v.HyperLogLog = hll + } + return nil + } + + // Otherwise it's a filter + if err := json.Unmarshal([]byte(arr[2].Raw), &v.Filter); err != nil { + return fmt.Errorf("on filter: %w", err) + } + + return nil +} + +func (v CountEnvelope) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `["COUNT",`...) + b = escapeString(b, v.SubscriptionID) + b = append(b, ',') + if v.Count != nil { + b = append(b, `{"count":`...) + b = append(b, strconv.FormatUint(uint64(*v.Count), 10)...) + if v.HyperLogLog != nil { + b = append(b, `,"hll":"`...) + b = append(b, HexEncodeToString(v.HyperLogLog)...) + b = append(b, '"') + } + b = append(b, '}') + } else { + fb, err := v.Filter.MarshalJSON() + if err != nil { + return nil, err + } + b = append(b, fb...) + } + b = append(b, ']') + return b, nil +} + +// NoticeEnvelope represents a NOTICE message. +type NoticeEnvelope string + +func (_ NoticeEnvelope) Label() string { return "NOTICE" } +func (n NoticeEnvelope) String() string { + v, _ := json.Marshal(n) + return string(v) +} + +func (v *NoticeEnvelope) FromJSON(data string) error { + r := gjson.Parse(data) + arr := r.Array() + if len(arr) < 2 { + return fmt.Errorf("failed to decode NOTICE envelope") + } + *v = NoticeEnvelope(arr[1].String()) + return nil +} + +func (v NoticeEnvelope) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `["NOTICE",`...) + b = escapeString(b, string(v)) + b = append(b, ']') + return b, nil +} + +// EOSEEnvelope represents an EOSE (End of Stored Events) message. +type EOSEEnvelope string + +func (_ EOSEEnvelope) Label() string { return "EOSE" } +func (e EOSEEnvelope) String() string { + v, _ := json.Marshal(e) + return string(v) +} + +func (v *EOSEEnvelope) FromJSON(data string) error { + r := gjson.Parse(data) + arr := r.Array() + if len(arr) < 2 { + return fmt.Errorf("failed to decode EOSE envelope") + } + *v = EOSEEnvelope(arr[1].String()) + return nil +} + +func (v EOSEEnvelope) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `["EOSE",`...) + b = escapeString(b, string(v)) + b = append(b, ']') + return b, nil +} + +// CloseEnvelope represents a CLOSE message. +type CloseEnvelope string + +func (_ CloseEnvelope) Label() string { return "CLOSE" } +func (c CloseEnvelope) String() string { + v, _ := json.Marshal(c) + return string(v) +} + +func (v *CloseEnvelope) FromJSON(data string) error { + r := gjson.Parse(data) + arr := r.Array() + if len(arr) < 2 { + return fmt.Errorf("failed to decode CLOSE envelope") + } + *v = CloseEnvelope(arr[1].String()) + return nil +} + +func (v CloseEnvelope) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `["CLOSE",`...) + b = escapeString(b, string(v)) + b = append(b, ']') + return b, nil +} + +// ClosedEnvelope represents a CLOSED message. +type ClosedEnvelope struct { + SubscriptionID string + Reason string +} + +func (_ ClosedEnvelope) Label() string { return "CLOSED" } +func (c ClosedEnvelope) String() string { + v, _ := json.Marshal(c) + return string(v) +} + +func (v *ClosedEnvelope) FromJSON(data string) error { + r := gjson.Parse(data) + arr := r.Array() + if len(arr) < 3 { + return fmt.Errorf("failed to decode CLOSED envelope") + } + *v = ClosedEnvelope{ + SubscriptionID: arr[1].String(), + Reason: arr[2].String(), + } + return nil +} + +func (v ClosedEnvelope) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `["CLOSED",`...) + b = escapeString(b, v.SubscriptionID) + b = append(b, ',') + b = escapeString(b, v.Reason) + b = append(b, ']') + return b, nil +} + +// OKEnvelope represents an OK message. +type OKEnvelope struct { + EventID ID + OK bool + Reason string +} + +func (_ OKEnvelope) Label() string { return "OK" } +func (o OKEnvelope) String() string { + v, _ := json.Marshal(o) + return string(v) +} + +func (v *OKEnvelope) FromJSON(data string) error { + r := gjson.Parse(data) + arr := r.Array() + if len(arr) < 4 { + return fmt.Errorf("failed to decode OK envelope: missing fields") + } + b, err := HexDecodeString(arr[1].String()) + if err != nil { + return err + } + copy(v.EventID[:], b) + v.OK = arr[2].Bool() + v.Reason = arr[3].String() + + return nil +} + +func (v OKEnvelope) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `["OK","`...) + b = append(b, HexEncodeToString(v.EventID[:])...) + b = append(b, `",`...) + if v.OK { + b = append(b, "true"...) + } else { + b = append(b, "false"...) + } + b = append(b, ',') + b = escapeString(b, v.Reason) + b = append(b, ']') + return b, nil +} + +// AuthEnvelope represents an AUTH message. +type AuthEnvelope struct { + Challenge *string + Event Event +} + +func (_ AuthEnvelope) Label() string { return "AUTH" } +func (a AuthEnvelope) String() string { + v, _ := json.Marshal(a) + return string(v) +} + +func (v *AuthEnvelope) FromJSON(data string) error { + r := gjson.Parse(data) + arr := r.Array() + if len(arr) < 2 { + return fmt.Errorf("failed to decode Auth envelope: missing fields") + } + if arr[1].IsObject() { + return json.Unmarshal([]byte(arr[1].Raw), &v.Event) + } else { + challenge := arr[1].String() + v.Challenge = &challenge + } + return nil +} + +func (v AuthEnvelope) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `["AUTH",`...) + if v.Challenge != nil { + b = escapeString(b, *v.Challenge) + } else { + eb, err := v.Event.MarshalJSON() + if err != nil { + return nil, err + } + b = append(b, eb...) + } + b = append(b, ']') + return b, nil +} diff --git a/event.go b/event.go index 51ad0b19..30fef7ca 100644 --- a/event.go +++ b/event.go @@ -2,10 +2,6 @@ package nostr import ( "crypto/sha256" - "strconv" - - "github.com/mailru/easyjson" - "github.com/templexxx/xhex" ) // Event represents a Nostr event. @@ -19,11 +15,6 @@ type Event struct { Sig [64]byte } -func (evt Event) String() string { - j, _ := easyjson.Marshal(evt) - return string(j) -} - // GetID serializes and returns the event ID as a string. func (evt Event) GetID() ID { return sha256.Sum256(evt.Serialize()) @@ -33,44 +24,3 @@ func (evt Event) GetID() ID { func (evt Event) CheckID() bool { return evt.GetID() == evt.ID } - -// Serialize outputs a byte array that can be hashed to produce the canonical event "id". -func (evt Event) Serialize() []byte { - // the serialization process is just putting everything into a JSON array - // so the order is kept. See NIP-01 - dst := make([]byte, 4+64, 100+len(evt.Content)+len(evt.Tags)*80) - - // the header portion is easy to serialize - // [0,"pubkey",created_at,kind,[ - copy(dst, `[0,"`) - xhex.Encode(dst[4:4+64], evt.PubKey[:]) // there will always be such capacity - dst = append(dst, `",`...) - dst = append(dst, strconv.FormatInt(int64(evt.CreatedAt), 10)...) - dst = append(dst, `,`...) - dst = append(dst, strconv.FormatUint(uint64(evt.Kind), 10)...) - dst = append(dst, `,`...) - - // tags - dst = append(dst, '[') - for i, tag := range evt.Tags { - if i > 0 { - dst = append(dst, ',') - } - // tag item - dst = append(dst, '[') - for i, s := range tag { - if i > 0 { - dst = append(dst, ',') - } - dst = escapeString(dst, s) - } - dst = append(dst, ']') - } - dst = append(dst, "],"...) - - // content needs to be escaped in general as it is user generated. - dst = escapeString(dst, evt.Content) - dst = append(dst, ']') - - return dst -} diff --git a/event_easyjson.go b/event_easyjson.go index 1371ff23..b439ddea 100644 --- a/event_easyjson.go +++ b/event_easyjson.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nostr import ( diff --git a/event_methods.go b/event_methods.go new file mode 100644 index 00000000..718843e8 --- /dev/null +++ b/event_methods.go @@ -0,0 +1,56 @@ +//go:build !tinygo + +package nostr + +import ( + "strconv" + + "github.com/mailru/easyjson" + "github.com/templexxx/xhex" +) + +func (evt Event) String() string { + j, _ := easyjson.Marshal(evt) + return string(j) +} + +// Serialize outputs a byte array that can be hashed to produce the canonical event "id". +func (evt Event) Serialize() []byte { + // the serialization process is just putting everything into a JSON array + // so the order is kept. See NIP-01 + dst := make([]byte, 4+64, 100+len(evt.Content)+len(evt.Tags)*80) + + // the header portion is easy to serialize + // [0,"pubkey",created_at,kind,[ + copy(dst, `[0,"`) + xhex.Encode(dst[4:4+64], evt.PubKey[:]) // there will always be such capacity + dst = append(dst, `",`...) + dst = append(dst, strconv.FormatInt(int64(evt.CreatedAt), 10)...) + dst = append(dst, `,`...) + dst = append(dst, strconv.FormatUint(uint64(evt.Kind), 10)...) + dst = append(dst, `,`...) + + // tags + dst = append(dst, '[') + for i, tag := range evt.Tags { + if i > 0 { + dst = append(dst, ',') + } + // tag item + dst = append(dst, '[') + for i, s := range tag { + if i > 0 { + dst = append(dst, ',') + } + dst = escapeString(dst, s) + } + dst = append(dst, ']') + } + dst = append(dst, "],"...) + + // content needs to be escaped in general as it is user generated. + dst = escapeString(dst, evt.Content) + dst = append(dst, ']') + + return dst +} diff --git a/event_methods_tinygo.go b/event_methods_tinygo.go new file mode 100644 index 00000000..99578964 --- /dev/null +++ b/event_methods_tinygo.go @@ -0,0 +1,129 @@ +//go:build tinygo + +package nostr + +import ( + "encoding/hex" + "strconv" + + "github.com/tidwall/gjson" +) + +func (evt Event) String() string { + j, _ := json.Marshal(evt) + return string(j) +} + +func (evt Event) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `{"kind":`...) + b = append(b, strconv.Itoa(int(evt.Kind))...) + b = append(b, `,"id":"`...) + b = append(b, evt.ID.Hex()...) + b = append(b, `","pubkey":"`...) + b = append(b, evt.PubKey.Hex()...) + b = append(b, `","created_at":`...) + b = append(b, strconv.FormatInt(int64(evt.CreatedAt), 10)...) + b = append(b, `,"tags":[`...) + for i, tag := range evt.Tags { + if i > 0 { + b = append(b, ',') + } + b = append(b, '[') + for j, s := range tag { + if j > 0 { + b = append(b, ',') + } + b = escapeString(b, s) + } + b = append(b, ']') + } + b = append(b, `],"content":`...) + b = escapeString(b, evt.Content) + b = append(b, `,"sig":"`...) + b = append(b, hex.EncodeToString(evt.Sig[:])...) + b = append(b, `"}`...) + + return b, nil +} + +func (evt *Event) UnmarshalJSON(data []byte) error { + r := gjson.ParseBytes(data) + + evt.Kind = Kind(r.Get("kind").Int()) + + idHex := r.Get("id").String() + if len(idHex) == 64 { + b, _ := hex.DecodeString(idHex) + copy(evt.ID[:], b) + } + + pubkeyHex := r.Get("pubkey").String() + if len(pubkeyHex) == 64 { + b, _ := hex.DecodeString(pubkeyHex) + copy(evt.PubKey[:], b) + } + + evt.CreatedAt = Timestamp(r.Get("created_at").Int()) + + tagsResult := r.Get("tags").Array() + evt.Tags = make(Tags, len(tagsResult)) + for i, tagResult := range tagsResult { + tagArr := tagResult.Array() + evt.Tags[i] = make(Tag, len(tagArr)) + for j, tagItem := range tagArr { + evt.Tags[i][j] = tagItem.String() + } + } + + evt.Content = r.Get("content").String() + + sigHex := r.Get("sig").String() + if len(sigHex) == 128 { + b, _ := hex.DecodeString(sigHex) + copy(evt.Sig[:], b) + } + + return nil +} + +// Serialize outputs a byte array that can be hashed to produce the canonical event "id". +func (evt Event) Serialize() []byte { + // the serialization process is just putting everything into a JSON array + // so the order is kept. See NIP-01 + dst := make([]byte, 4+64, 100+len(evt.Content)+len(evt.Tags)*80) + + // the header portion is easy to serialize + // [0,"pubkey",created_at,kind,[ + copy(dst, `[0,"`) + hex.Encode(dst[4:4+64], evt.PubKey[:]) // there will always be such capacity + dst = append(dst, `",`...) + dst = append(dst, strconv.FormatInt(int64(evt.CreatedAt), 10)...) + dst = append(dst, `,`...) + dst = append(dst, strconv.FormatUint(uint64(evt.Kind), 10)...) + dst = append(dst, `,`...) + + // tags + dst = append(dst, '[') + for i, tag := range evt.Tags { + if i > 0 { + dst = append(dst, ',') + } + // tag item + dst = append(dst, '[') + for i, s := range tag { + if i > 0 { + dst = append(dst, ',') + } + dst = escapeString(dst, s) + } + dst = append(dst, ']') + } + dst = append(dst, "],"...) + + // content needs to be escaped in general as it is user generated. + dst = escapeString(dst, evt.Content) + dst = append(dst, ']') + + return dst +} diff --git a/filter.go b/filter.go index c5e53117..a6c7a7ec 100644 --- a/filter.go +++ b/filter.go @@ -3,8 +3,6 @@ package nostr import ( "math" "slices" - - "github.com/mailru/easyjson" ) type Filter struct { @@ -23,11 +21,6 @@ type Filter struct { type TagMap map[string][]string -func (ef Filter) String() string { - j, _ := easyjson.Marshal(ef) - return string(j) -} - func (ef Filter) Matches(event Event) bool { if !ef.MatchesIgnoringTimestampConstraints(event) { return false diff --git a/filter_easyjson.go b/filter_easyjson.go index 1ddbfcbc..778a7b51 100644 --- a/filter_easyjson.go +++ b/filter_easyjson.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nostr import ( diff --git a/filter_methods.go b/filter_methods.go new file mode 100644 index 00000000..e27ac5ba --- /dev/null +++ b/filter_methods.go @@ -0,0 +1,10 @@ +//go:build !tinygo + +package nostr + +import "github.com/mailru/easyjson" + +func (ef Filter) String() string { + j, _ := easyjson.Marshal(ef) + return string(j) +} diff --git a/filter_methods_tinygo.go b/filter_methods_tinygo.go new file mode 100644 index 00000000..b75f4868 --- /dev/null +++ b/filter_methods_tinygo.go @@ -0,0 +1,191 @@ +//go:build tinygo + +package nostr + +import ( + "encoding/hex" + stdjson "encoding/json" + "strconv" + + "github.com/tidwall/gjson" +) + +func (ef Filter) String() string { + j, _ := stdjson.Marshal(ef) + return string(j) +} + +func (ef Filter) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, '{') + + first := true + + if len(ef.IDs) > 0 { + if !first { + b = append(b, ',') + } + first = false + b = append(b, `"ids":[`...) + for i, id := range ef.IDs { + if i > 0 { + b = append(b, ',') + } + b = append(b, '"') + b = append(b, id.Hex()...) + b = append(b, '"') + } + b = append(b, ']') + } + + if len(ef.Kinds) > 0 { + if !first { + b = append(b, ',') + } + first = false + b = append(b, `"kinds":[`...) + for i, kind := range ef.Kinds { + if i > 0 { + b = append(b, ',') + } + b = append(b, strconv.Itoa(int(kind))...) + } + b = append(b, ']') + } + + if len(ef.Authors) > 0 { + if !first { + b = append(b, ',') + } + first = false + b = append(b, `"authors":[`...) + for i, pk := range ef.Authors { + if i > 0 { + b = append(b, ',') + } + b = append(b, '"') + b = append(b, pk.Hex()...) + b = append(b, '"') + } + b = append(b, ']') + } + + if ef.Since != 0 { + if !first { + b = append(b, ',') + } + first = false + b = append(b, `"since":`...) + b = append(b, strconv.FormatInt(int64(ef.Since), 10)...) + } + + if ef.Until != 0 { + if !first { + b = append(b, ',') + } + first = false + b = append(b, `"until":`...) + b = append(b, strconv.FormatInt(int64(ef.Until), 10)...) + } + + if ef.Limit > 0 || ef.LimitZero { + if !first { + b = append(b, ',') + } + first = false + b = append(b, `"limit":`...) + b = append(b, strconv.Itoa(ef.Limit)...) + } + + if ef.Search != "" { + if !first { + b = append(b, ',') + } + first = false + b = append(b, `"search":`...) + b = escapeString(b, ef.Search) + } + + for key, values := range ef.Tags { + if !first { + b = append(b, ',') + } + first = false + b = append(b, `"#`...) + b = append(b, key...) + b = append(b, `":[`...) + for i, v := range values { + if i > 0 { + b = append(b, ',') + } + b = escapeString(b, v) + } + b = append(b, ']') + } + + b = append(b, '}') + return b, nil +} + +func (ef *Filter) UnmarshalJSON(data []byte) error { + r := gjson.ParseBytes(data) + + r.ForEach(func(key, val gjson.Result) bool { + switch key.String() { + case "ids": + idsResult := val.Array() + for _, s := range idsResult { + var id ID + hexStr := s.String() + if len(hexStr) == 64 { + b, _ := hex.DecodeString(hexStr) + copy(id[:], b) + } + ef.IDs = append(ef.IDs, id) + } + case "kinds": + kindsResult := val.Array() + for _, k := range kindsResult { + ef.Kinds = append(ef.Kinds, Kind(k.Int())) + } + case "authors": + authorsResult := val.Array() + for _, s := range authorsResult { + var pk PubKey + hexStr := s.String() + if len(hexStr) == 64 { + b, _ := hex.DecodeString(hexStr) + copy(pk[:], b) + } + ef.Authors = append(ef.Authors, pk) + } + case "since": + ef.Since = Timestamp(val.Int()) + case "until": + ef.Until = Timestamp(val.Int()) + case "limit": + ef.Limit = int(val.Int()) + if ef.Limit == 0 { + ef.LimitZero = true + } + case "search": + ef.Search = val.String() + default: + k := key.String() + if len(k) > 1 && k[0] == '#' { + if ef.Tags == nil { + ef.Tags = make(TagMap) + } + valuesResult := val.Array() + values := make([]string, len(valuesResult)) + for i, v := range valuesResult { + values[i] = v.String() + } + ef.Tags[k[1:]] = values + } + } + return true + }) + + return nil +} diff --git a/go.mod b/go.mod index 4baecdc0..df132bfb 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,6 @@ require ( github.com/coder/websocket v1.8.13 github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 github.com/elnosh/gonuts v0.4.2 - github.com/fasthttp/websocket v1.5.12 github.com/gomarkdown/markdown v0.0.0-20241205020045-f7e15b2f3e62 github.com/json-iterator/go v1.1.12 github.com/kr/pretty v0.3.1 @@ -29,30 +28,32 @@ require ( github.com/tyler-smith/go-bip32 v1.0.0 github.com/tyler-smith/go-bip39 v1.1.0 github.com/urfave/cli/v3 v3.0.0-beta1 - github.com/valyala/fasthttp v1.59.0 go.etcd.io/bbolt v1.4.2 - golang.org/x/crypto v0.39.0 + golang.org/x/crypto v0.43.0 golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 - golang.org/x/net v0.41.0 - golang.org/x/sync v0.15.0 - golang.org/x/text v0.26.0 + golang.org/x/net v0.46.0 + golang.org/x/sync v0.17.0 + golang.org/x/text v0.30.0 gopkg.in/yaml.v3 v3.0.1 ) require ( fiatjaf.com/lib v0.3.6 github.com/dgraph-io/ristretto/v2 v2.3.0 + github.com/fasthttp/websocket v1.5.12 github.com/go-git/go-git/v5 v5.16.3 github.com/sivukhin/godjot v1.0.6 github.com/templexxx/cpu v0.0.1 github.com/templexxx/xhex v0.0.0-20200614015412-aed53437177b + github.com/valyala/fasthttp v1.68.0 + marwan.io/wasm-fetch v0.1.0 ) require ( github.com/FactomProject/basen v0.0.0-20150613233007-fe3947df716e // indirect github.com/FactomProject/btcutilecc v0.0.0-20130527213604-d3a63a5752ec // indirect github.com/RoaringBitmap/roaring v1.9.4 // indirect - github.com/andybalholm/brotli v1.1.1 // indirect + github.com/andybalholm/brotli v1.2.0 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/bits-and-blooms/bitset v1.17.0 // indirect github.com/blevesearch/bleve_index_api v1.1.12 // indirect @@ -84,7 +85,7 @@ require ( github.com/golang/snappy v0.0.4 // indirect github.com/gorilla/css v1.0.1 // indirect github.com/josharian/intern v1.0.0 // indirect - github.com/klauspost/compress v1.18.0 // indirect + github.com/klauspost/compress v1.18.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect @@ -98,6 +99,6 @@ require ( github.com/tidwall/pretty v1.2.1 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/x448/float16 v0.8.4 // indirect - golang.org/x/sys v0.35.0 // indirect + golang.org/x/sys v0.37.0 // indirect google.golang.org/protobuf v1.33.0 // indirect ) diff --git a/go.sum b/go.sum index 788c24b7..8bd5b65d 100644 --- a/go.sum +++ b/go.sum @@ -13,8 +13,8 @@ github.com/PowerDNS/lmdb-go v1.9.3/go.mod h1:TE0l+EZK8Z1B4dx070ZxkWTlp8RG1mjN0/+ github.com/RoaringBitmap/roaring v1.9.4 h1:yhEIoH4YezLYT04s1nHehNO64EKFTop/wBhxv2QzDdQ= github.com/RoaringBitmap/roaring v1.9.4/go.mod h1:6AXUsoIEzDTFFQCe1RbGA6uFONMhvejWj5rqITANK90= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= -github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= -github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= +github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= +github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY= @@ -158,8 +158,8 @@ github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlT github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/compress v1.18.1 h1:bcSGx7UbpBqMChDtsF28Lw6v/G94LPrrbMbdC3JH2co= +github.com/klauspost/compress v1.18.1/go.mod h1:ZQFFVG+MdnR0P+l6wpXgIL4NTtwiKIdBnrBd8Nrxr+0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -238,8 +238,8 @@ github.com/urfave/cli/v3 v3.0.0-beta1 h1:6DTaaUarcM0wX7qj5Hcvs+5Dm3dyUTBbEwIWAjc github.com/urfave/cli/v3 v3.0.0-beta1/go.mod h1:FnIeEMYu+ko8zP1F9Ypr3xkZMIDqW3DR92yUtY39q1Y= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasthttp v1.59.0 h1:Qu0qYHfXvPk1mSLNqcFtEk6DpxgA26hy6bmydotDpRI= -github.com/valyala/fasthttp v1.59.0/go.mod h1:GTxNb9Bc6r2a9D0TWNSPwDz78UxnTGBViY3xZNEqyYU= +github.com/valyala/fasthttp v1.68.0 h1:v12Nx16iepr8r9ySOwqI+5RBJ/DqTxhOy1HrHoDFnok= +github.com/valyala/fasthttp v1.68.0/go.mod h1:5EXiRfYQAoiO/khu4oU9VISC/eVY6JqmSpPJoHCKsz4= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= @@ -250,8 +250,8 @@ golang.org/x/crypto v0.0.0-20170613210332-850760c427c5/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM= -golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U= +golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= +golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw= golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -259,11 +259,11 @@ golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= -golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= +golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4= +golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8= -golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -277,13 +277,13 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= -golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= +golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= -golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= +golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= +golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -310,3 +310,5 @@ gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= launchpad.net/gocheck v0.0.0-20140225173054-000000000087 h1:Izowp2XBH6Ya6rv+hqbceQyw/gSGoXfH/UPoTGduL54= launchpad.net/gocheck v0.0.0-20140225173054-000000000087/go.mod h1:hj7XX3B/0A+80Vse0e+BUHsHMTEhd0O4cpUHr/e/BUM= +marwan.io/wasm-fetch v0.1.0 h1:0kKeCsry7IQfPmxj78FUWtO6qwXIaQqMmZbzbZz2rkw= +marwan.io/wasm-fetch v0.1.0/go.mod h1:PlaZmevjPJGIy/BaqMtVjUKvrA8CgrDh+aomnuhmTO8= diff --git a/helpers.go b/helpers.go index ba5154a9..d7043dc9 100644 --- a/helpers.go +++ b/helpers.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nostr import ( diff --git a/helpers_tinygo.go b/helpers_tinygo.go new file mode 100644 index 00000000..703e708a --- /dev/null +++ b/helpers_tinygo.go @@ -0,0 +1,274 @@ +//go:build tinygo + +package nostr + +import ( + "encoding/hex" + stdjson "encoding/json" + "hash/fnv" + "io" + "strconv" + "strings" + "sync" + + "golang.org/x/exp/constraints" +) + +const MAX_LOCKS = 50 + +var ( + namedMutexPool = make([]sync.Mutex, MAX_LOCKS) + json = stdJsonWrapper{} +) + +type stdJsonWrapper struct{} + +func (stdJsonWrapper) Marshal(v any) ([]byte, error) { + return stdjson.Marshal(v) +} + +func (stdJsonWrapper) Unmarshal(data []byte, v any) error { + return stdjson.Unmarshal(data, v) +} + +func (stdJsonWrapper) NewEncoder(w io.Writer) *stdjson.Encoder { + return stdjson.NewEncoder(w) +} + +func (stdJsonWrapper) NewDecoder(r io.Reader) *stdjson.Decoder { + return stdjson.NewDecoder(r) +} + +func namedLock(name string) (unlock func()) { + h := fnv.New32a() + h.Write([]byte(name)) + idx := h.Sum32() % MAX_LOCKS + namedMutexPool[idx].Lock() + return namedMutexPool[idx].Unlock +} + +func similar[E constraints.Ordered](as, bs []E) bool { + if len(as) != len(bs) { + return false + } + + for _, a := range as { + for _, b := range bs { + if b == a { + goto next + } + } + // didn't find a B that corresponded to the current A + return false + + next: + continue + } + + return true +} + +func similarID(as, bs []ID) bool { + if len(as) != len(bs) { + return false + } + + for _, a := range as { + for _, b := range bs { + if b == a { + goto next + } + } + // didn't find a B that corresponded to the current A + return false + + next: + continue + } + + return true +} + +func similarPublicKey(as, bs []PubKey) bool { + if len(as) != len(bs) { + return false + } + + for _, a := range as { + for _, b := range bs { + if b == a { + goto next + } + } + // didn't find a B that corresponded to the current A + return false + + next: + continue + } + + return true +} + +// Escaping strings for JSON encoding according to RFC8259. +// Also encloses result in quotation marks "". +func escapeString(dst []byte, s string) []byte { + dst = append(dst, '"') + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case c == '"': + // quotation mark + dst = append(dst, []byte{'\\', '"'}...) + case c == '\\': + // reverse solidus + dst = append(dst, []byte{'\\', '\\'}...) + case c >= 0x20: + // default, rest below are control chars + dst = append(dst, c) + case c == 0x08: + dst = append(dst, []byte{'\\', 'b'}...) + case c < 0x09: + dst = append(dst, []byte{'\\', 'u', '0', '0', '0', '0' + c}...) + case c == 0x09: + dst = append(dst, []byte{'\\', 't'}...) + case c == 0x0a: + dst = append(dst, []byte{'\\', 'n'}...) + case c == 0x0c: + dst = append(dst, []byte{'\\', 'f'}...) + case c == 0x0d: + dst = append(dst, []byte{'\\', 'r'}...) + case c < 0x10: + dst = append(dst, []byte{'\\', 'u', '0', '0', '0', 0x57 + c}...) + case c < 0x1a: + dst = append(dst, []byte{'\\', 'u', '0', '0', '1', 0x20 + c}...) + case c < 0x20: + dst = append(dst, []byte{'\\', 'u', '0', '0', '1', 0x47 + c}...) + } + } + dst = append(dst, '"') + return dst +} + +func subIdToSerial(subId string) int64 { + n := strings.Index(subId, ":") + if n < 0 || n > len(subId) { + return -1 + } + serialId, _ := strconv.ParseInt(subId[0:n], 10, 64) + return serialId +} + +func isLowerHex(thing string) bool { + for _, charNumber := range thing { + if (charNumber >= 48 && charNumber <= 57) || (charNumber >= 97 && charNumber <= 102) { + continue + } + return false + } + return true +} + +func extractSubID(jsonStr string) string { + // look for "EVENT" pattern + start := strings.Index(jsonStr, `"EVENT"`) + if start == -1 { + return "" + } + + // move to the next quote + offset := strings.Index(jsonStr[start+7:], `"`) + if offset == -1 { + return "" + } + + start += 7 + offset + 1 + + // find the ending quote + end := strings.Index(jsonStr[start:], `"`) + + // get the contents + return jsonStr[start : start+end] +} + +func extractEventID(jsonStr string) ID { + // look for "id" pattern + start := strings.Index(jsonStr, `"id"`) + if start == -1 { + return [32]byte{} + } + + // move to the next quote + offset := strings.IndexByte(jsonStr[start+4:], '"') + start += 4 + offset + 1 + + // get 64 characters of the id + var id [32]byte + // xhex.Decode(id[:], unsafe.Slice(unsafe.StringData(jsonStr[start:start+64]), 64)) + hex.Decode(id[:], []byte(jsonStr[start:start+64])) + return id +} + +func extractEventPubKey(jsonStr string) PubKey { + // look for "pubkey" pattern + start := strings.Index(jsonStr, `"pubkey"`) + if start == -1 { + return PubKey{} + } + + // move to the next quote + offset := strings.IndexByte(jsonStr[start+8:], '"') + start += 8 + offset + 1 + + // get 64 characters of the pubkey + var pk [32]byte + // xhex.Decode(pk[:], unsafe.Slice(unsafe.StringData(jsonStr[start:start+64]), 64)) + hex.Decode(pk[:], []byte(jsonStr[start:start+64])) + return pk +} + +func extractDTag(jsonStr string) string { + // look for ["d", pattern + start := strings.Index(jsonStr, `["d"`) + if start == -1 { + return "" + } + + // move to the next quote + offset := strings.IndexByte(jsonStr[start+4:], '"') + start += 4 + offset + 1 + + // find the ending quote + end := strings.IndexByte(jsonStr[start:], '"') + if end == -1 { + return "" + } + + // get the contents + return jsonStr[start : start+end] +} + +func extractTimestamp(jsonStr string) Timestamp { + // look for "created_at": pattern + start := strings.Index(jsonStr, `"created_at"`) + if start == -1 { + return 0 + } + + // move to the next number + offset := strings.IndexAny(jsonStr[start+12:], "9876543210") + if offset == -1 { + return 0 + } + start += 12 + offset + + // find the end + end := strings.IndexAny(jsonStr[start:], ",} ") + if end == -1 { + return 0 + } + + // get the contents + ts, _ := strconv.ParseInt(jsonStr[start:start+end], 10, 64) + return Timestamp(ts) +} diff --git a/keyer/lib.go b/keyer/lib.go index fb1b3880..519f2808 100644 --- a/keyer/lib.go +++ b/keyer/lib.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package keyer import ( diff --git a/keyer/lib_tinygo.go b/keyer/lib_tinygo.go new file mode 100644 index 00000000..9973dd7f --- /dev/null +++ b/keyer/lib_tinygo.go @@ -0,0 +1,100 @@ +//go:build tinygo + +package keyer + +import ( + "context" + "fmt" + "strings" + "time" + + "fiatjaf.com/nostr" + "fiatjaf.com/nostr/nip05" + "fiatjaf.com/nostr/nip19" + "fiatjaf.com/nostr/nip46" + "fiatjaf.com/nostr/nip49" +) + +var ( + _ nostr.Keyer = (*BunkerSigner)(nil) + _ nostr.Keyer = (*EncryptedKeySigner)(nil) + _ nostr.Keyer = (*KeySigner)(nil) + _ nostr.Keyer = (*ManualSigner)(nil) +) + +// SignerOptions contains configuration options for creating a new signer. +type SignerOptions struct { + // BunkerClientSecretKey is the secret key used for the bunker client + BunkerClientSecretKey nostr.SecretKey + + // BunkerSignTimeout is the timeout duration for bunker signing operations + BunkerSignTimeout time.Duration + + // BunkerAuthHandler is called when authentication is needed for bunker operations + BunkerAuthHandler func(string) + + // PasswordHandler is called when an operation needs access to the encrypted key. + // If provided, the key will be stored encrypted and this function will be called + // every time an operation needs access to the key so the user can be prompted. + PasswordHandler func(context.Context) string + + // Password is used along with ncryptsec to decrypt the key. + // If provided, the key will be decrypted and stored in plaintext. + Password string +} + +// New creates a new Keyer implementation based on the input string format. +// It supports various input formats: +// - ncryptsec: Creates an EncryptedKeySigner or KeySigner depending on options +// - NIP-46 bunker URL or NIP-05 identifier: Creates a BunkerSigner +// - nsec: Creates a KeySigner +// - hex private key: Creates a KeySigner +// +// The context is used for operations that may require network access. +// The pool is used for relay connections when needed. +// Options are used for additional pieces required for EncryptedKeySigner and BunkerSigner. +func New(ctx context.Context, pool *nostr.Pool, input string, opts *SignerOptions) (nostr.Keyer, error) { + if opts == nil { + opts = &SignerOptions{} + } + + if strings.HasPrefix(input, "ncryptsec") { + if opts.PasswordHandler != nil { + return &EncryptedKeySigner{input, nostr.ZeroPK, opts.PasswordHandler}, nil + } + sec, err := nip49.Decrypt(input, opts.Password) + if err != nil { + if opts.Password == "" { + return nil, fmt.Errorf("failed to decrypt with blank password: %w", err) + } + return nil, fmt.Errorf("failed to decrypt with given password: %w", err) + } + pk := nostr.GetPublicKey(sec) + return KeySigner{sec, pk, nostr.NewMapOf[nostr.PubKey, [32]byte]()}, nil + } else if nip46.IsValidBunkerURL(input) || nip05.IsValidIdentifier(input) { + bcsk := nostr.Generate() + oa := func(url string) { println("auth_url received but not handled") } + + if opts.BunkerClientSecretKey != [32]byte{} { + bcsk = opts.BunkerClientSecretKey + } + if opts.BunkerAuthHandler != nil { + oa = opts.BunkerAuthHandler + } + + bunker, err := nip46.ConnectBunker(ctx, bcsk, input, pool, oa) + if err != nil { + return nil, err + } + return BunkerSigner{bunker}, nil + } else if prefix, parsed, err := nip19.Decode(input); err == nil && prefix == "nsec" { + sec := parsed.(nostr.SecretKey) + pk := nostr.GetPublicKey(sec) + return KeySigner{sec, pk, nostr.NewMapOf[nostr.PubKey, [32]byte]()}, nil + } else if sk, err := nostr.SecretKeyFromHex(input); err == nil { + pk := nostr.GetPublicKey(sk) + return KeySigner{sk, pk, nostr.NewMapOf[nostr.PubKey, [32]byte]()}, nil + } + + return nil, fmt.Errorf("unsupported input '%s'", input) +} diff --git a/keyer/plain.go b/keyer/plain.go index 167e23ea..9c793796 100644 --- a/keyer/plain.go +++ b/keyer/plain.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package keyer import ( diff --git a/keyer/plain_tinygo.go b/keyer/plain_tinygo.go new file mode 100644 index 00000000..20ca7d84 --- /dev/null +++ b/keyer/plain_tinygo.go @@ -0,0 +1,63 @@ +//go:build tinygo + +package keyer + +import ( + "context" + + "fiatjaf.com/nostr" + "fiatjaf.com/nostr/nip44" +) + +var _ nostr.Keyer = (*KeySigner)(nil) + +// KeySigner is a signer that holds the private key in memory +type KeySigner struct { + sk [32]byte + pk nostr.PubKey + + conversationKeys *nostr.MapOf[nostr.PubKey, [32]byte] +} + +// NewPlainKeySigner creates a new KeySigner from a private key. +// Returns an error if the private key is invalid. +func NewPlainKeySigner(sec [32]byte) KeySigner { + return KeySigner{sec, nostr.GetPublicKey(sec), nostr.NewMapOf[nostr.PubKey, [32]byte]()} +} + +// SignEvent signs the provided event with the signer's private key. +// It sets the event's ID, PubKey, and Sig fields. +func (ks KeySigner) SignEvent(ctx context.Context, evt *nostr.Event) error { return evt.Sign(ks.sk) } + +// GetPublicKey returns the public key associated with this signer. +func (ks KeySigner) GetPublicKey(ctx context.Context) (nostr.PubKey, error) { return ks.pk, nil } + +// Encrypt encrypts a plaintext message for a recipient using NIP-44. +// It caches conversation keys for efficiency in repeated operations. +func (ks KeySigner) Encrypt(ctx context.Context, plaintext string, recipient nostr.PubKey) (string, error) { + ck, ok := ks.conversationKeys.Load(recipient) + if !ok { + var err error + ck, err = nip44.GenerateConversationKey(recipient, ks.sk) + if err != nil { + return "", err + } + ks.conversationKeys.Store(recipient, ck) + } + return nip44.Encrypt(plaintext, ck) +} + +// Decrypt decrypts a base64-encoded ciphertext from a sender using NIP-44. +// It caches conversation keys for efficiency in repeated operations. +func (ks KeySigner) Decrypt(ctx context.Context, base64ciphertext string, sender nostr.PubKey) (string, error) { + ck, ok := ks.conversationKeys.Load(sender) + if !ok { + var err error + ck, err = nip44.GenerateConversationKey(sender, ks.sk) + if err != nil { + return "", err + } + ks.conversationKeys.Store(sender, ck) + } + return nip44.Decrypt(base64ciphertext, ck) +} diff --git a/keys.go b/keys.go index 7273bfab..ff729e34 100644 --- a/keys.go +++ b/keys.go @@ -130,6 +130,25 @@ func (pk *PubKey) UnmarshalJSON(buf []byte) error { return nil } +func (pk PubKey) MarshalText() ([]byte, error) { + res := make([]byte, 64) + xhex.Encode(res, pk[:]) + return res, nil +} + +func (pk *PubKey) UnmarshalText(buf []byte) error { + if len(buf) != 64 { + return fmt.Errorf("must be a hex string of 64 characters") + } + if err := xhex.Decode(pk[:], buf); err != nil { + return err + } + if _, err := schnorr.ParsePubKey(pk[:]); err != nil { + return fmt.Errorf("pubkey is not valid %w", err) + } + return nil +} + func PubKeyFromHex(pkh string) (PubKey, error) { pk := PubKey{} if len(pkh) != 64 { diff --git a/nip05/nip05.go b/nip05/nip05.go index 79bff7a5..8ae7daeb 100644 --- a/nip05/nip05.go +++ b/nip05/nip05.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nip05 import ( diff --git a/nip05/nip05_easyjson.go b/nip05/nip05_easyjson.go index 84a2b3fc..5e3f085e 100644 --- a/nip05/nip05_easyjson.go +++ b/nip05/nip05_easyjson.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nip05 import ( diff --git a/nip05/nip05_test.go b/nip05/nip05_test.go index 6303a3e3..6d25d3a9 100644 --- a/nip05/nip05_test.go +++ b/nip05/nip05_test.go @@ -75,8 +75,8 @@ func TestResponse(t *testing.T) { respj, err := json.Marshal(resp) require.NoError(t, err) - require.Equal(t, `{"names":{"foo":"`+pk1.Hex()+`","bar":"`+pk2.Hex()+`"},"relays":{"`+pk1.Hex()+`":["wss://a.com"],"`+pk2.Hex()+`":["wss://a.com","wss://b.com"]}}`, string(respj)) + // unmarshal and compare structurally (map iteration order is not guaranteed) back := WellKnownResponse{} err = json.Unmarshal(respj, &back) require.NoError(t, err) diff --git a/nip05/nip05_tinygo.go b/nip05/nip05_tinygo.go new file mode 100644 index 00000000..03f8a24f --- /dev/null +++ b/nip05/nip05_tinygo.go @@ -0,0 +1,95 @@ +//go:build tinygo + +package nip05 + +import ( + "context" + "encoding/json" + "fmt" + "regexp" + "strings" + + "fiatjaf.com/nostr" + fetch "marwan.io/wasm-fetch" +) + +var NIP05_REGEX = regexp.MustCompile(`^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$`) + +type WellKnownResponse struct { + Names map[string]nostr.PubKey `json:"names"` + Relays map[nostr.PubKey][]string `json:"relays,omitempty"` + NIP46 map[nostr.PubKey][]string `json:"nip46,omitempty"` +} + +func IsValidIdentifier(input string) bool { + return NIP05_REGEX.MatchString(input) +} + +func ParseIdentifier(fullname string) (name string, domain string, err error) { + res := NIP05_REGEX.FindStringSubmatch(fullname) + if len(res) == 0 { + return "", "", fmt.Errorf("invalid identifier") + } + if res[1] == "" { + res[1] = "_" + } + return res[1], res[2], nil +} + +func QueryIdentifier(ctx context.Context, fullname string) (*nostr.ProfilePointer, error) { + result, name, err := Fetch(ctx, fullname) + if err != nil { + return nil, err + } + + pubkey, ok := result.Names[name] + if !ok { + return nil, fmt.Errorf("no entry for name '%s'", name) + } + + relays, _ := result.Relays[pubkey] + return &nostr.ProfilePointer{ + PublicKey: pubkey, + Relays: relays, + }, nil +} + +func Fetch(ctx context.Context, fullname string) (resp WellKnownResponse, name string, err error) { + name, domain, err := ParseIdentifier(fullname) + if err != nil { + return resp, name, fmt.Errorf("failed to parse '%s': %w", fullname, err) + } + + r, err := fetch.Fetch(fmt.Sprintf("https://%s/.well-known/nostr.json?name=%s", domain, name), &fetch.Opts{ + Method: fetch.MethodGet, + Signal: ctx, + }) + if err != nil { + return resp, name, fmt.Errorf("fetch failed: %w", err) + } + if r.Status != 200 && r.Status != 204 { + return resp, name, fmt.Errorf("fetch status is not ok: %d", r.Status) + } + + var result WellKnownResponse + if err := json.Unmarshal(r.Body, &result); err != nil { + return resp, name, fmt.Errorf("failed to unmarshal response: %w", err) + } + return result, name, nil +} + +func NormalizeIdentifier(fullname string) string { + if strings.HasPrefix(fullname, "_@") { + return fullname[2:] + } + + return fullname +} + +func IdentifierToURL(address string) string { + spl := strings.Split(address, "@") + if len(spl) == 1 { + return fmt.Sprintf("https://%s/.well-known/nostr.json?name=_", spl[0]) + } + return fmt.Sprintf("https://%s/.well-known/nostr.json?name=%s", spl[1], spl[0]) +} diff --git a/nip11/fetch.go b/nip11/fetch.go index 065913ab..2a3de3ea 100644 --- a/nip11/fetch.go +++ b/nip11/fetch.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nip11 import ( @@ -7,7 +9,6 @@ import ( "time" "fiatjaf.com/nostr" - jsoniter "github.com/json-iterator/go" ) // Fetch fetches the NIP-11 metadata for a relay. @@ -50,7 +51,7 @@ func Fetch(ctx context.Context, u string) (info RelayInformationDocument, err er } defer resp.Body.Close() - if err := jsoniter.NewDecoder(resp.Body).Decode(&info); err != nil { + if err := json.NewDecoder(resp.Body).Decode(&info); err != nil { return info, fmt.Errorf("invalid json: %w", err) } diff --git a/nip11/fetch_tinygo.go b/nip11/fetch_tinygo.go new file mode 100644 index 00000000..b9c86943 --- /dev/null +++ b/nip11/fetch_tinygo.go @@ -0,0 +1,56 @@ +//go:build tinygo + +package nip11 + +import ( + "context" + "fmt" + "time" + + "fiatjaf.com/nostr" + fetch "marwan.io/wasm-fetch" +) + +// Fetch fetches the NIP-11 metadata for a relay. +// +// It will always return `info` with at least `URL` filled -- even if we can't connect to the +// relay or if it doesn't have a NIP-11 handler -- although in that case it will also return +// an error. +func Fetch(ctx context.Context, u string) (info RelayInformationDocument, err error) { + // normalize URL to start with http://, https:// or without protocol + u = nostr.NormalizeURL(u) + if len(u) < 8 { + return info, fmt.Errorf("invalid url %s", u) + } + + info = RelayInformationDocument{ + URL: u, + } + + 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() + } + + // make request + headers := make(map[string]string, 2) + headers["Accept"] = "application/nostr+json" + headers["User-Agent"] = "nostrlib/go" + r, err := fetch.Fetch("http"+u[2:], &fetch.Opts{ + Method: fetch.MethodGet, + Signal: ctx, + Headers: headers, + }) + if err != nil { + return info, fmt.Errorf("fetch failed: %w", err) + } + if r.Status != 200 && r.Status != 204 { + return info, fmt.Errorf("fetch status is not ok: %d", r.Status) + } + if err := json.Unmarshal(r.Body, &info); err != nil { + return info, fmt.Errorf("failed to unmarshal response: %w", err) + } + return info, nil +} diff --git a/nip11/json.go b/nip11/json.go new file mode 100644 index 00000000..f43186cc --- /dev/null +++ b/nip11/json.go @@ -0,0 +1,7 @@ +//go:build !tinygo + +package nip11 + +import jsoniter "github.com/json-iterator/go" + +var json = jsoniter.ConfigCompatibleWithStandardLibrary diff --git a/nip11/json_tinygo.go b/nip11/json_tinygo.go new file mode 100644 index 00000000..8f4bd574 --- /dev/null +++ b/nip11/json_tinygo.go @@ -0,0 +1,28 @@ +//go:build tinygo + +package nip11 + +import ( + stdjson "encoding/json" + "io" +) + +var json = stdJsonWrapper{} + +type stdJsonWrapper struct{} + +func (stdJsonWrapper) Marshal(v any) ([]byte, error) { + return stdjson.Marshal(v) +} + +func (stdJsonWrapper) Unmarshal(data []byte, v any) error { + return stdjson.Unmarshal(data, v) +} + +func (stdJsonWrapper) NewEncoder(w io.Writer) *stdjson.Encoder { + return stdjson.NewEncoder(w) +} + +func (stdJsonWrapper) NewDecoder(r io.Reader) *stdjson.Decoder { + return stdjson.NewDecoder(r) +} diff --git a/nip46/client.go b/nip46/client.go index 9603150e..0ebeb635 100644 --- a/nip46/client.go +++ b/nip46/client.go @@ -7,12 +7,9 @@ import ( "net/url" "strconv" "sync/atomic" - "unsafe" "fiatjaf.com/nostr" "fiatjaf.com/nostr/nip44" - "github.com/mailru/easyjson" - "github.com/puzpuzpuz/xsync/v3" ) type BunkerClient struct { @@ -23,7 +20,7 @@ type BunkerClient struct { pool *nostr.Pool target nostr.PubKey conversationKey [32]byte // nip44 - listeners *xsync.MapOf[string, chan Response] + listeners *listenersMap idPrefix string onAuth func(string) @@ -125,7 +122,7 @@ func NewBunker( target: targetPublicKey, Relays: relays, conversationKey: conversationKey, - listeners: xsync.NewMapOf[string, chan Response](), + listeners: newListenersMap(), onAuth: onAuth, idPrefix: "nl-" + strconv.Itoa(rand.Intn(65536)), } @@ -224,7 +221,7 @@ func (bunker *BunkerClient) SignEvent(ctx context.Context, evt *nostr.Event) err return err } - err = easyjson.Unmarshal(unsafe.Slice(unsafe.StringData(resp), len(resp)), evt) + err = unmarshalEvent(resp, evt) if err != nil { return err } diff --git a/nip46/client_std.go b/nip46/client_std.go new file mode 100644 index 00000000..9059109b --- /dev/null +++ b/nip46/client_std.go @@ -0,0 +1,25 @@ +//go:build !tinygo + +package nip46 + +import ( + "unsafe" + + "fiatjaf.com/nostr" + "github.com/mailru/easyjson" + "github.com/puzpuzpuz/xsync/v3" +) + +type listenersMap = xsync.MapOf[string, chan Response] + +func newListenersMap() *listenersMap { + return xsync.NewMapOf[string, chan Response]() +} + +func unmarshalEvent(data string, evt *nostr.Event) error { + return easyjson.Unmarshal(unsafe.Slice(unsafe.StringData(data), len(data)), evt) +} + +func marshalEvent(evt *nostr.Event) ([]byte, error) { + return easyjson.Marshal(evt) +} diff --git a/nip46/client_tinygo.go b/nip46/client_tinygo.go new file mode 100644 index 00000000..10861c49 --- /dev/null +++ b/nip46/client_tinygo.go @@ -0,0 +1,41 @@ +//go:build tinygo + +package nip46 + +import ( + "sync" + + "fiatjaf.com/nostr" +) + +type listenersMap struct { + m sync.Map +} + +func newListenersMap() *listenersMap { + return &listenersMap{} +} + +func (m *listenersMap) LoadAndDelete(key string) (chan Response, bool) { + v, ok := m.m.LoadAndDelete(key) + if !ok { + return nil, false + } + return v.(chan Response), true +} + +func (m *listenersMap) Store(key string, value chan Response) { + m.m.Store(key, value) +} + +func (m *listenersMap) Delete(key string) { + m.m.Delete(key) +} + +func unmarshalEvent(data string, evt *nostr.Event) error { + return json.Unmarshal([]byte(data), evt) +} + +func marshalEvent(evt *nostr.Event) ([]byte, error) { + return json.Marshal(evt) +} diff --git a/nip46/dynamic-signer.go b/nip46/dynamic-signer.go index 8c5683b5..d68953bc 100644 --- a/nip46/dynamic-signer.go +++ b/nip46/dynamic-signer.go @@ -7,7 +7,6 @@ import ( "fiatjaf.com/nostr" "fiatjaf.com/nostr/nip44" - "github.com/mailru/easyjson" ) var _ Signer = (*DynamicSigner)(nil) @@ -140,7 +139,7 @@ func (p *DynamicSigner) HandleRequest(ctx context.Context, event nostr.Event) ( break } evt := nostr.Event{} - err = easyjson.Unmarshal([]byte(req.Params[0]), &evt) + err = unmarshalEvent(req.Params[0], &evt) if err != nil { resultErr = fmt.Errorf("failed to decode event/2: %w", err) break @@ -158,7 +157,7 @@ func (p *DynamicSigner) HandleRequest(ctx context.Context, event nostr.Event) ( break } - jrevt, _ := easyjson.Marshal(evt) + jrevt, _ := marshalEvent(&evt) result = string(jrevt) case "nip44_encrypt": if len(req.Params) != 2 { diff --git a/nip46/json_std.go b/nip46/json_std.go new file mode 100644 index 00000000..66759b25 --- /dev/null +++ b/nip46/json_std.go @@ -0,0 +1,7 @@ +//go:build !tinygo + +package nip46 + +import jsoniter "github.com/json-iterator/go" + +var json = jsoniter.ConfigFastest diff --git a/nip46/json_tinygo.go b/nip46/json_tinygo.go new file mode 100644 index 00000000..219e49f8 --- /dev/null +++ b/nip46/json_tinygo.go @@ -0,0 +1,28 @@ +//go:build tinygo + +package nip46 + +import ( + stdjson "encoding/json" + "io" +) + +var json = stdJsonWrapper{} + +type stdJsonWrapper struct{} + +func (stdJsonWrapper) Marshal(v any) ([]byte, error) { + return stdjson.Marshal(v) +} + +func (stdJsonWrapper) Unmarshal(data []byte, v any) error { + return stdjson.Unmarshal(data, v) +} + +func (stdJsonWrapper) NewEncoder(w io.Writer) *stdjson.Encoder { + return stdjson.NewEncoder(w) +} + +func (stdJsonWrapper) NewDecoder(r io.Reader) *stdjson.Decoder { + return stdjson.NewDecoder(r) +} diff --git a/nip46/nip46.go b/nip46/nip46.go index 02a83c2c..7856efd1 100644 --- a/nip46/nip46.go +++ b/nip46/nip46.go @@ -6,11 +6,8 @@ import ( "strings" "fiatjaf.com/nostr" - jsoniter "github.com/json-iterator/go" ) -var json = jsoniter.ConfigFastest - type Request struct { ID string `json:"id"` Method string `json:"method"` diff --git a/nip46/static-key-signer.go b/nip46/static-key-signer.go index 25d84623..a3f738af 100644 --- a/nip46/static-key-signer.go +++ b/nip46/static-key-signer.go @@ -10,7 +10,6 @@ import ( "fiatjaf.com/nostr" "fiatjaf.com/nostr/nip04" "fiatjaf.com/nostr/nip44" - "github.com/mailru/easyjson" ) var _ Signer = (*StaticKeySigner)(nil) @@ -146,7 +145,7 @@ func (p *StaticKeySigner) HandleRequest(_ context.Context, event nostr.Event) ( break } evt := nostr.Event{} - err = easyjson.Unmarshal([]byte(req.Params[0]), &evt) + err = unmarshalEvent(req.Params[0], &evt) if err != nil { resultErr = fmt.Errorf("failed to decode event/2: %w", err) break @@ -156,7 +155,7 @@ func (p *StaticKeySigner) HandleRequest(_ context.Context, event nostr.Event) ( resultErr = fmt.Errorf("failed to sign event: %w", err) break } - jrevt, _ := easyjson.Marshal(evt) + jrevt, _ := marshalEvent(&evt) result = string(jrevt) case "nip44_encrypt": if len(req.Params) != 2 { diff --git a/nip59/json_std.go b/nip59/json_std.go new file mode 100644 index 00000000..dd23f7a4 --- /dev/null +++ b/nip59/json_std.go @@ -0,0 +1,12 @@ +//go:build !tinygo + +package nip59 + +import ( + "fiatjaf.com/nostr" + "github.com/mailru/easyjson" +) + +func unmarshalEvent(data []byte, evt *nostr.Event) error { + return easyjson.Unmarshal(data, evt) +} diff --git a/nip59/json_tinygo.go b/nip59/json_tinygo.go new file mode 100644 index 00000000..29d912d2 --- /dev/null +++ b/nip59/json_tinygo.go @@ -0,0 +1,13 @@ +//go:build tinygo + +package nip59 + +import ( + "encoding/json" + + "fiatjaf.com/nostr" +) + +func unmarshalEvent(data []byte, evt *nostr.Event) error { + return json.Unmarshal(data, evt) +} diff --git a/nip59/nip59.go b/nip59/nip59.go index 65c5c45e..432729f8 100644 --- a/nip59/nip59.go +++ b/nip59/nip59.go @@ -6,7 +6,6 @@ import ( "fiatjaf.com/nostr" "fiatjaf.com/nostr/nip44" - "github.com/mailru/easyjson" ) // GiftWrap takes a 'rumor', encrypts it with our own key, making a 'seal', then encrypts that with a nonce key and @@ -74,7 +73,7 @@ func GiftUnwrap( } var seal nostr.Event - err = easyjson.Unmarshal([]byte(jseal), &seal) + err = unmarshalEvent([]byte(jseal), &seal) if err != nil { return rumor, fmt.Errorf("seal is invalid json: %w", err) } @@ -88,7 +87,7 @@ func GiftUnwrap( return rumor, fmt.Errorf("failed to decrypt rumor: %w", err) } - err = easyjson.Unmarshal([]byte(jrumor), &rumor) + err = unmarshalEvent([]byte(jrumor), &rumor) if err != nil { return rumor, fmt.Errorf("rumor is invalid json: %w", err) } diff --git a/nip77/envelopes.go b/nip77/envelopes.go index 702575d2..aec2d04a 100644 --- a/nip77/envelopes.go +++ b/nip77/envelopes.go @@ -7,8 +7,6 @@ import ( "unsafe" "fiatjaf.com/nostr" - "github.com/mailru/easyjson" - jwriter "github.com/mailru/easyjson/jwriter" "github.com/tidwall/gjson" ) @@ -67,7 +65,7 @@ func (v *OpenEnvelope) FromJSON(data string) error { v.SubscriptionID = arr[1].Str v.Message = arr[3].Str - return easyjson.Unmarshal(unsafe.Slice(unsafe.StringData(arr[2].Raw), len(arr[2].Raw)), &v.Filter) + return unmarshalFilter(unsafe.Slice(unsafe.StringData(arr[2].Raw), len(arr[2].Raw)), &v.Filter) } func (v OpenEnvelope) MarshalJSON() ([]byte, error) { @@ -77,9 +75,9 @@ func (v OpenEnvelope) MarshalJSON() ([]byte, error) { res.WriteString(v.SubscriptionID) res.WriteString(`",`) - w := jwriter.Writer{NoEscapeHTML: true} - v.Filter.MarshalEasyJSON(&w) - w.Buffer.DumpTo(res) + if err := writeFilterToBuffer(res, v.Filter); err != nil { + return nil, err + } res.WriteString(`,"`) res.WriteString(v.Message) diff --git a/nip77/json_std.go b/nip77/json_std.go new file mode 100644 index 00000000..10b9eb8f --- /dev/null +++ b/nip77/json_std.go @@ -0,0 +1,25 @@ +//go:build !tinygo + +package nip77 + +import ( + "bytes" + + "fiatjaf.com/nostr" + "github.com/mailru/easyjson" + jwriter "github.com/mailru/easyjson/jwriter" +) + +func unmarshalFilter(data []byte, v *nostr.Filter) error { + return easyjson.Unmarshal(data, v) +} + +func writeFilterToBuffer(buf *bytes.Buffer, f nostr.Filter) error { + w := jwriter.Writer{NoEscapeHTML: true} + f.MarshalEasyJSON(&w) + if w.Error != nil { + return w.Error + } + w.Buffer.DumpTo(buf) + return nil +} diff --git a/nip77/json_tinygo.go b/nip77/json_tinygo.go new file mode 100644 index 00000000..f60aaf9a --- /dev/null +++ b/nip77/json_tinygo.go @@ -0,0 +1,23 @@ +//go:build tinygo + +package nip77 + +import ( + "bytes" + "encoding/json" + + "fiatjaf.com/nostr" +) + +func unmarshalFilter(data []byte, v *nostr.Filter) error { + return json.Unmarshal(data, v) +} + +func writeFilterToBuffer(buf *bytes.Buffer, f nostr.Filter) error { + b, err := json.Marshal(f) + if err != nil { + return err + } + buf.Write(b) + return nil +} diff --git a/nip77/nip77.go b/nip77/nip77.go index 701e2ec5..c5e892d8 100644 --- a/nip77/nip77.go +++ b/nip77/nip77.go @@ -110,22 +110,26 @@ func NegentropySync( // handle emitted events from either direction if source != nil { - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() handle(ctx, Direction{ From: source, To: relay, Items: neg.Haves, }) - }) + }() } if target != nil { - wg.Go(func() { + wg.Add(1) + go func() { + defer wg.Done() handle(ctx, Direction{ From: relay, To: target, Items: neg.HaveNots, }) - }) + }() } done := make(chan struct{}) diff --git a/pointers_easyjson.go b/pointers_easyjson.go index 7c99e80c..455a6b57 100644 --- a/pointers_easyjson.go +++ b/pointers_easyjson.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nostr import ( diff --git a/pool.go b/pool.go index b73e4bc8..4edd2d16 100644 --- a/pool.go +++ b/pool.go @@ -12,7 +12,6 @@ import ( "time" "fiatjaf.com/nostr/nip45/hyperloglog" - "github.com/puzpuzpuz/xsync/v3" ) const ( @@ -21,7 +20,7 @@ const ( // Pool manages connections to multiple relays, ensures they are reopened when necessary and not duplicated. type Pool struct { - Relays *xsync.MapOf[string, *Relay] + Relays *MapOf[string, *Relay] Context context.Context authRequiredHandler func(context.Context, *Event) error @@ -54,7 +53,7 @@ func NewPool(opts PoolOptions) *Pool { ctx, cancel := context.WithCancelCause(context.Background()) pool := &Pool{ - Relays: xsync.NewMapOf[string, *Relay](), + Relays: NewMapOf[string, *Relay](), Context: ctx, cancel: cancel, @@ -276,7 +275,7 @@ func (pool *Pool) fetchMany( closedChan chan RelayClosed, opts SubscriptionOptions, ) chan RelayEvent { - seenAlready := xsync.NewMapOf[ID, struct{}]() + seenAlready := NewMapOf[ID, struct{}]() if opts.CheckDuplicate == nil { opts.CheckDuplicate = func(id ID, relay string) bool { @@ -335,15 +334,15 @@ func (pool *Pool) FetchManyReplaceable( urls []string, filter Filter, opts SubscriptionOptions, -) *xsync.MapOf[ReplaceableKey, Event] { +) *MapOf[ReplaceableKey, Event] { ctx, cancel := context.WithCancelCause(ctx) - results := xsync.NewMapOf[ReplaceableKey, Event]() + results := NewMapOf[ReplaceableKey, Event]() wg := sync.WaitGroup{} wg.Add(len(urls)) - seenAlreadyLatest := xsync.NewMapOf[ReplaceableKey, Timestamp]() + seenAlreadyLatest := NewMapOf[ReplaceableKey, Timestamp]() opts.CheckDuplicateReplaceable = func(rk ReplaceableKey, ts Timestamp) bool { discard := true seenAlreadyLatest.Compute(rk, func(latest Timestamp, _ bool) (newValue Timestamp, delete bool) { @@ -439,7 +438,7 @@ func (pool *Pool) subMany( ctx, cancel := context.WithCancelCause(ctx) _ = cancel // do this so `go vet` will stop complaining events := make(chan RelayEvent) - seenAlready := xsync.NewMapOf[ID, Timestamp]() + seenAlready := NewMapOf[ID, Timestamp]() ticker := time.NewTicker(seenAlreadyDropTick) eoseWg := sync.WaitGroup{} @@ -807,7 +806,7 @@ func (pool *Pool) batchedQueryMany( res := make(chan RelayEvent) wg := sync.WaitGroup{} wg.Add(len(dfs)) - seenAlready := xsync.NewMapOf[ID, struct{}]() + seenAlready := NewMapOf[ID, struct{}]() forwardWg := sync.WaitGroup{} opts.CheckDuplicate = func(id ID, relay string) bool { @@ -896,7 +895,7 @@ func (pool *Pool) batchedSubscribeMany( res := make(chan RelayEvent) wg := sync.WaitGroup{} wg.Add(len(dfs)) - seenAlready := xsync.NewMapOf[ID, struct{}]() + seenAlready := NewMapOf[ID, struct{}]() forwardWg := sync.WaitGroup{} opts.CheckDuplicate = func(id ID, relay string) bool { diff --git a/relay.go b/relay.go index c1ccd196..a44c2aac 100644 --- a/relay.go +++ b/relay.go @@ -1,3 +1,5 @@ +//go:build !js + package nostr import ( @@ -18,7 +20,6 @@ import ( "time" ws "github.com/coder/websocket" - "github.com/puzpuzpuz/xsync/v3" ) var subscriptionIDCounter atomic.Int64 @@ -55,7 +56,7 @@ type Relay struct { writeQueue chan writeRequest closed *atomic.Bool - Subscriptions *xsync.MapOf[int64, *Subscription] + Subscriptions *MapOf[int64, *Subscription] ConnectionError error connectionContext context.Context // will be canceled when the connection closes @@ -81,7 +82,7 @@ func NewRelay(ctx context.Context, url string, opts RelayOptions) *Relay { URL: NormalizeURL(url), connectionContext: ctx, connectionContextCancel: cancel, - Subscriptions: xsync.NewMapOf[int64, *Subscription](), + Subscriptions: NewMapOf[int64, *Subscription](), okCallbacks: make(map[ID]okcallback, 20), subscriptionChannelCloseQueue: make(chan *Subscription), requestHeader: opts.RequestHeader, diff --git a/relay_js.go b/relay_js.go new file mode 100644 index 00000000..5d414659 --- /dev/null +++ b/relay_js.go @@ -0,0 +1,730 @@ +//go:build js + +package nostr + +import ( + "bytes" + "context" + "crypto/tls" + "errors" + "fmt" + "io" + "iter" + "log" + "math" + "net/http" + "strconv" + "sync" + "sync/atomic" + "time" + + ws "github.com/coder/websocket" +) + +var subscriptionIDCounter atomic.Int64 + +var ( + ErrDisconnected = errors.New("") + ErrPingFailed = errors.New("") +) + +type writeRequest struct { + msg []byte + answer chan error +} + +type closeCause struct { + code ws.StatusCode + reason string +} + +func (c closeCause) Error() string { + if c.reason == "" { + return "relay closed" + } + return c.reason +} + +// Relay represents a connection to a Nostr relay. +type Relay struct { + URL string + requestHeader http.Header // e.g. for origin header + + // websocket connection + conn *ws.Conn + writeQueue chan writeRequest + closed *atomic.Bool + + Subscriptions *MapOf[int64, *Subscription] + + ConnectionError error + connectionContext context.Context // will be canceled when the connection closes + connectionContextCancel context.CancelCauseFunc + + challenge string // NIP-42 challenge, we only keep the last + authHandler func(context.Context, *Relay, *Event) error + noticeHandler func(*Relay, string) // NIP-01 NOTICEs + customHandler func(string) // nonstandard unparseable messages + okCallbacks map[ID]okcallback + okCallbacksMutex sync.Mutex + subscriptionChannelCloseQueue chan *Subscription + + // custom things that aren't often used + // + AssumeValid bool // this will skip verifying signatures for events received from this relay +} + +// NewRelay returns a new relay. It takes a context that, when canceled, will close the relay connection. +func NewRelay(ctx context.Context, url string, opts RelayOptions) *Relay { + ctx, cancel := context.WithCancelCause(ctx) + r := &Relay{ + URL: NormalizeURL(url), + connectionContext: ctx, + connectionContextCancel: cancel, + Subscriptions: NewMapOf[int64, *Subscription](), + okCallbacks: make(map[ID]okcallback, 20), + subscriptionChannelCloseQueue: make(chan *Subscription), + requestHeader: opts.RequestHeader, + customHandler: opts.CustomHandler, + noticeHandler: opts.NoticeHandler, + authHandler: opts.AuthHandler, + closed: &atomic.Bool{}, + } + + go func() { + <-ctx.Done() + + if wasClosed := r.closed.Swap(true); wasClosed { + return + } + + if r.conn != nil { + cause := context.Cause(ctx) + code := ws.StatusNormalClosure + reason := "" + var cc closeCause + if errors.As(cause, &cc) { + code = cc.code + reason = cc.reason + } else if cause != nil { + reason = cause.Error() + } + + _ = r.conn.Close(code, reason) + } + }() + + return r +} + +// RelayConnect returns a relay object connected to url. +// +// The given subscription is only used during the connection phase. Once successfully connected, cancelling ctx has no effect. +// +// The ongoing relay connection uses a background context. To close the connection, call r.Close(). +// If you need fine grained long-term connection contexts, use NewRelay() instead. +func RelayConnect(ctx context.Context, url string, opts RelayOptions) (*Relay, error) { + r := NewRelay(context.Background(), url, opts) + err := r.Connect(ctx) + return r, err +} + +type RelayOptions struct { + // AuthHandler is fired when an AUTH message is received. It is given the AUTH event, unsigned, and expects you to sign it. + AuthHandler func(context.Context, *Relay, *Event) error + + // NoticeHandler just takes notices and is expected to do something with them. + // When not given defaults to logging the notices. + NoticeHandler func(relay *Relay, notice string) + + // CustomHandler, if given, must be a function that handles any relay message + // that couldn't be parsed as a standard envelope. + CustomHandler func(data string) + + // RequestHeader sets the HTTP request header of the websocket preflight request + RequestHeader http.Header +} + +// String just returns the relay URL. +func (r *Relay) String() string { + return r.URL +} + +// Context retrieves the context that is associated with this relay connection. +// It will be closed when the relay is disconnected. +func (r *Relay) Context() context.Context { return r.connectionContext } + +// IsConnected returns true if the connection to this relay seems to be active. +func (r *Relay) IsConnected() bool { + if r.closed.Load() { + return false + } + if r.conn == nil { + return false + } + if r.connectionContext == nil { + return false + } + return r.connectionContext.Err() == nil +} + +// Connect tries to establish a websocket connection to r.URL. +// 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. +// +// The given context here is only used during the connection phase. The long-living +// relay connection will be based on the context given to NewRelay(). +func (r *Relay) Connect(ctx context.Context) error { + return r.ConnectWithClient(ctx, nil) +} + +// ConnectWithTLS is like Connect(), but takes a special tls.Config if you need that. +func (r *Relay) ConnectWithTLS(ctx context.Context, _ *tls.Config) error { + return r.ConnectWithClient(ctx, &http.Client{ + Transport: &http.Transport{}, + }) +} + +// ConnectWithClient is like Connect(), but takes a special *http.Client if you need that. +func (r *Relay) ConnectWithClient(ctx context.Context, client *http.Client) error { + if r.connectionContext == nil || r.Subscriptions == nil { + return fmt.Errorf("relay must be initialized with a call to NewRelay()") + } + if r.connectionContext.Err() != nil { + return fmt.Errorf("relay context canceled") + } + + if r.URL == "" { + return fmt.Errorf("invalid relay URL '%s'", r.URL) + } + + if err := r.newConnection(ctx, client); err != nil { + return fmt.Errorf("error opening websocket to '%s': %w", r.URL, err) + } + + return nil +} + +func (r *Relay) newConnection(ctx context.Context, httpClient *http.Client) error { + debugLogf("{%s} connecting!\n", r.URL) + + dialCtx := ctx + if _, ok := dialCtx.Deadline(); !ok { + // if no timeout is set, force it to 7 seconds + dialCtx, _ = context.WithTimeoutCause(ctx, 7*time.Second, errors.New("connection took too long")) + } + + // dialOpts := &ws.DialOptions{ + // HTTPHeader: http.Header{ + // textproto.CanonicalMIMEHeaderKey("User-Agent"): {"fiatjaf.com/nostr"}, + // }, + // CompressionMode: ws.CompressionContextTakeover, + // HTTPClient: httpClient, + // } + // for k, v := range r.requestHeader { + // dialOpts.HTTPHeader[k] = v + // } + + c, _, err := ws.Dial(dialCtx, r.URL, nil) + if err != nil { + return err + } + c.SetReadLimit(2 << 24) // 33MB + + // ping every 19 seconds + ticker := time.NewTicker(19 * time.Second) + + // main websocket loop + readQueue := make(chan string, 64 /* add some buffer to account for processing/IO mismatches */) + + r.conn = c + r.writeQueue = make(chan writeRequest, 64 /* idem */) + r.closed = &atomic.Bool{} + + connCtx := r.connectionContext + go func() { + pingAttempt := 0 + + for { + select { + case <-connCtx.Done(): + return + case <-ticker.C: + debugLogf("{%s} pinging\n", r.URL) + pingCtx, cancel := context.WithTimeoutCause(connCtx, time.Millisecond*800, errors.New("ping took too long")) + err := c.Ping(pingCtx) + cancel() + + if err != nil { + pingAttempt++ + debugLogf("{%s} error writing ping (attempt %d): %v", r.URL, pingAttempt, err) + + if pingAttempt >= 3 { + debugLogf("{%s} error writing ping after multiple attempts; closing websocket", r.URL) + _ = r.close(ErrPingFailed) + } + + continue + } + + // ping was OK + debugLogf("{%s} ping OK", r.URL) + pingAttempt = 0 + case wr := <-r.writeQueue: + debugLogf("{%s} sending '%v'\n", r.URL, string(wr.msg)) + writeCtx, cancel := context.WithTimeoutCause(connCtx, time.Second*10, errors.New("write took too long")) + err := c.Write(writeCtx, ws.MessageText, wr.msg) + cancel() + if err != nil { + debugLogf("{%s} closing!, write failed: '%s'\n", r.URL, err) + _ = r.close(closeCause{code: ws.StatusAbnormalClosure, reason: "write failed"}) + if wr.answer != nil { + wr.answer <- err + } + return + } + if wr.answer != nil { + close(wr.answer) + } + case msg := <-readQueue: + debugLogf("{%s} received %v\n", r.URL, msg) + r.handleMessage(msg) + } + } + }() + + // read loop -- loops back to the main loop + go func() { + buf := new(bytes.Buffer) + + for { + buf.Reset() + + _, reader, err := c.Reader(connCtx) + if err != nil { + debugLogf("{%s} closing!, reader failure: '%s'\n", r.URL, err) + _ = r.close(closeCause{code: ws.StatusAbnormalClosure, reason: "failed to get reader"}) + return + } + if _, err := io.Copy(buf, reader); err != nil { + debugLogf("{%s} closing!, read failure: '%s'\n", r.URL, err) + _ = r.close(closeCause{code: ws.StatusAbnormalClosure, reason: "failed to read"}) + return + } + + msg := string(buf.Bytes()) + select { + case readQueue <- msg: + case <-connCtx.Done(): + return + } + } + }() + + return nil +} + +func (r *Relay) closeConnection(code ws.StatusCode, reason string) { +} + +func (r *Relay) handleMessage(message string) { + // if this is an "EVENT" we will have this preparser logic that should speed things up a little + // as we skip handling duplicate events + subid := extractSubID(message) + sub, ok := r.Subscriptions.Load(subIdToSerial(subid)) + if ok { + if sub.checkDuplicate != nil { + if sub.checkDuplicate(extractEventID(message[10+len(subid):]), r.URL) { + return + } + } else if sub.checkDuplicateReplaceable != nil { + if sub.checkDuplicateReplaceable( + ReplaceableKey{extractEventPubKey(message), extractDTag(message)}, + extractTimestamp(message), + ) { + return + } + } + } + + envelope, err := ParseMessage(message) + if envelope == nil { + if r.customHandler != nil && err == UnknownLabel { + go r.customHandler(message) + } + return + } + + switch env := envelope.(type) { + case *NoticeEnvelope: + // see WithNoticeHandler + if r.noticeHandler != nil { + r.noticeHandler(r, string(*env)) + } else { + log.Printf("NOTICE from %s: '%s'\n", r.URL, string(*env)) + } + case *AuthEnvelope: + if env.Challenge == nil { + return + } + r.challenge = *env.Challenge + if r.authHandler != nil { + go func() { + r.Auth(r.Context(), func(ctx context.Context, evt *Event) error { + return r.authHandler(ctx, r, evt) + }) + }() + } + case *EventEnvelope: + // we already have the subscription from the pre-check above, so we can just reuse it + if sub == nil { + // InfoLogger.Printf("{%s} no subscription with id '%s'\n", r.URL, *env.SubscriptionID) + return + } else { + // check if the event matches the desired filter, ignore otherwise + if !sub.match(env.Event) { + InfoLogger.Printf("{%s} filter does not match: %v ~ %v\n", r.URL, sub.Filter, env.Event) + return + } + + // check signature, ignore invalid, except from trusted (AssumeValid) relays + if !r.AssumeValid { + if !env.Event.VerifySignature() { + InfoLogger.Printf("{%s} bad signature on %s\n", r.URL, env.Event.ID) + return + } + } + + // dispatch this to the internal .events channel of the subscription + sub.dispatchEvent(env.Event) + } + case *EOSEEnvelope: + if subscription, ok := r.Subscriptions.Load(subIdToSerial(string(*env))); ok { + subscription.dispatchEose() + } + case *ClosedEnvelope: + if subscription, ok := r.Subscriptions.Load(subIdToSerial(env.SubscriptionID)); ok { + subscription.handleClosed(env.Reason) + } + case *CountEnvelope: + if subscription, ok := r.Subscriptions.Load(subIdToSerial(env.SubscriptionID)); ok && env.Count != nil && subscription.countResult != nil { + subscription.countResult <- *env + } + case *OKEnvelope: + r.okCallbacksMutex.Lock() + if okCallback, exist := r.okCallbacks[env.EventID]; exist { + okCallback(env.OK, env.Reason) + } else { + InfoLogger.Printf("{%s} got an unexpected OK message for event %s", r.URL, env.EventID) + } + r.okCallbacksMutex.Unlock() + } +} + +// Write queues an arbitrary message to be sent to the relay. +func (r *Relay) Write(msg []byte) { + select { + case <-r.connectionContext.Done(): + case r.writeQueue <- writeRequest{msg: msg, answer: nil}: + } +} + +// WriteWithError is like Write, but returns an error if the write fails (and the connection gets closed). +func (r *Relay) WriteWithError(msg []byte) error { + ch := make(chan error) + + if r.writeQueue == nil { + return nil + } + + select { + case <-r.connectionContext.Done(): + return fmt.Errorf("failed to write to %s: %w", r.URL, context.Cause(r.connectionContext)) + case r.writeQueue <- writeRequest{msg: msg, answer: ch}: + } + return <-ch +} + +// Publish sends an "EVENT" command to the relay r as in NIP-01 and waits for an OK response. +func (r *Relay) Publish(ctx context.Context, event Event) error { + return r.publish(ctx, event.ID, &EventEnvelope{Event: event}) +} + +// Auth sends an "AUTH" command client->relay as in NIP-42 and waits for an OK response. +// +// You don't have to build the AUTH event yourself, this function takes a function to which the +// event that must be signed will be passed, so it's only necessary to sign that. +func (r *Relay) Auth(ctx context.Context, sign func(context.Context, *Event) error) error { + authEvent := Event{ + CreatedAt: Now(), + Kind: KindClientAuthentication, + Tags: Tags{ + Tag{"relay", r.URL}, + Tag{"challenge", r.challenge}, + }, + Content: "", + } + if err := sign(ctx, &authEvent); err != nil { + return fmt.Errorf("error signing auth event: %w", err) + } + + return r.publish(ctx, authEvent.ID, &AuthEnvelope{Event: authEvent}) +} + +// publish can be used both for EVENT and for AUTH +func (r *Relay) publish(ctx context.Context, id ID, env Envelope) error { + var err error + var cancel context.CancelFunc + + if _, ok := ctx.Deadline(); !ok { + // if no timeout is set, force it to 7 seconds + ctx, cancel = context.WithTimeoutCause(ctx, 7*time.Second, fmt.Errorf("given up waiting for an OK")) + defer cancel() + } else { + // otherwise make the context cancellable so we can stop everything upon receiving an "OK" + ctx, cancel = context.WithCancel(ctx) + defer cancel() + } + + // listen for an OK callback + gotOk := make(chan bool, 1) + handleOk := func(ok bool, reason string) { + err = fmt.Errorf("msg: %s", reason) + gotOk <- ok + } + + r.okCallbacksMutex.Lock() + if previous, exists := r.okCallbacks[id]; !exists { + // normal path: there is nothing listening for this id, so we register this function + r.okCallbacks[id] = func(ok bool, reason string) { + handleOk(ok, reason) + + // and when it's called the mutex will be locked + // so we just eliminate it + delete(r.okCallbacks, id) + } + } else { + // if the same event is published twice there will be something here already + // so we make a function that concatenates both + r.okCallbacks[id] = func(ok bool, reason string) { + // we call this with an informative helper for the developer + handleOk(ok, fmt.Sprintf("published twice: %s", reason)) + + // then we replace it with the previous (and when this is called it will nuke itself accordingly) + r.okCallbacks[id] = previous + } + } + r.okCallbacksMutex.Unlock() + + // publish event + envb, _ := env.MarshalJSON() + if err := r.WriteWithError(envb); err != nil { + return err + } + + for { + select { + case ok := <-gotOk: + if ok { + return nil + } + return err + case <-ctx.Done(): + r.okCallbacksMutex.Lock() + if cb, _ := r.okCallbacks[id]; cb != nil { + cb(false, "timeout") + } + r.okCallbacksMutex.Unlock() + return fmt.Errorf("publish: %w", context.Cause(ctx)) + case <-r.connectionContext.Done(): + r.okCallbacks = make(map[ID]okcallback) + return fmt.Errorf("relay: %w", context.Cause(r.connectionContext)) + } + } +} + +// 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). +// +// Remember to cancel subscriptions, either by calling `.Unsub()` on them or ensuring their `context.Context` will be canceled at some point. +// Failure to do that will result in a huge number of halted goroutines being created. +func (r *Relay) Subscribe(ctx context.Context, filter Filter, opts SubscriptionOptions) (*Subscription, error) { + if !r.IsConnected() { + return nil, ErrDisconnected + } + + sub := r.PrepareSubscription(ctx, filter, opts) + + if err := sub.Fire(); err != nil { + sub.cancel(ErrFireFailed) + return nil, fmt.Errorf("couldn't subscribe to %v at %s: %w", filter, r.URL, err) + } + + go func() { + <-ctx.Done() + sub.cancel(nil) + }() + + return sub, nil +} + +// PrepareSubscription creates a subscription, but doesn't fire it. +// +// Remember to cancel subscriptions, either by calling `.Unsub()` on them or ensuring their `context.Context` will be canceled at some point. +// Failure to do that will result in a huge number of halted goroutines being created. +func (r *Relay) PrepareSubscription(ctx context.Context, filter Filter, opts SubscriptionOptions) *Subscription { + current := subscriptionIDCounter.Add(1) + ctx, cancel := context.WithCancelCause(ctx) + + sub := &Subscription{ + Relay: r, + Context: ctx, + cancel: cancel, + counter: current, + Events: make(chan Event), + EndOfStoredEvents: make(chan struct{}, 1), + ClosedReason: make(chan string, 1), + Filter: filter, + match: filter.Matches, + eoseTimedOut: make(chan struct{}), + } + + sub.checkDuplicate = opts.CheckDuplicate + sub.checkDuplicateReplaceable = opts.CheckDuplicateReplaceable + + // subscription id computation + buf := subIdPool.Get().([]byte)[:0] + buf = strconv.AppendInt(buf, sub.counter, 10) + buf = append(buf, ':') + buf = append(buf, opts.Label...) + defer subIdPool.Put(buf) + sub.id = string(buf) + + // we track subscriptions only by their counter, no need for the full id + r.Subscriptions.Store(int64(sub.counter), sub) + + // start counting down for dispatching the fake EOSE + if opts.MaxWaitForEOSE != math.MaxInt64 { + if opts.MaxWaitForEOSE == 0 { + opts.MaxWaitForEOSE = time.Second * 7 + } + + go func() { + time.Sleep(opts.MaxWaitForEOSE) + close(sub.eoseTimedOut) + sub.dispatchEose() + }() + } + + // start handling events, eose, unsub etc: + go func() { + <-sub.Context.Done() + + // mark subscription as closed and send a CLOSE to the relay (naive sync.Once implementation) + if sub.live.CompareAndSwap(true, false) { + closeMsg := CloseEnvelope(sub.id) + closeb, _ := (&closeMsg).MarshalJSON() + if err := sub.Relay.WriteWithError(closeb); err != nil { + _ = sub.Relay.close(err) + } + } + + // remove subscription from our map + sub.Relay.Subscriptions.Delete(sub.counter) + + // do this so we don't have the possibility of closing the Events channel and then trying to send to it + sub.mu.Lock() + close(sub.Events) + sub.mu.Unlock() + }() + + return sub +} + +// implement Querier interface +func (r *Relay) QueryEvents(filter Filter) iter.Seq[Event] { + ctx, cancel := context.WithCancel(r.connectionContext) + + return func(yield func(Event) bool) { + defer cancel() + + sub, err := r.Subscribe(ctx, filter, SubscriptionOptions{Label: "queryevents"}) + if err != nil { + return + } + + for { + select { + case evt := <-sub.Events: + if !yield(evt) { + return + } + case <-sub.EndOfStoredEvents: + return + case <-sub.ClosedReason: + return + case <-ctx.Done(): + return + } + } + } +} + +// Count sends a "COUNT" command to the relay and returns the count of events matching the filters. +func (r *Relay) Count( + ctx context.Context, + filter Filter, + opts SubscriptionOptions, +) (uint32, []byte, error) { + v, err := r.countInternal(ctx, filter, opts) + if err != nil { + return 0, nil, err + } + + return *v.Count, v.HyperLogLog, nil +} + +func (r *Relay) countInternal(ctx context.Context, filter Filter, opts SubscriptionOptions) (CountEnvelope, error) { + sub := r.PrepareSubscription(ctx, filter, opts) + sub.countResult = make(chan CountEnvelope) + + if err := sub.Fire(); err != nil { + return CountEnvelope{}, err + } + + defer sub.cancel(errors.New("countInternal() ended")) + + if _, ok := ctx.Deadline(); !ok { + // if no timeout is set, force it to 7 seconds + var cancel context.CancelFunc + ctx, cancel = context.WithTimeoutCause(ctx, 7*time.Second, errors.New("countInternal took too long")) + defer cancel() + } + + for { + select { + case count := <-sub.countResult: + return count, nil + case <-ctx.Done(): + return CountEnvelope{}, ctx.Err() + } + } +} + +// Close closes the relay connection. +func (r *Relay) Close() error { + return r.close(errors.New("Close() called")) +} + +func (r *Relay) close(reason error) error { + r.connectionContextCancel(reason) + return nil +} + +var subIdPool = sync.Pool{ + New: func() any { return make([]byte, 0, 15) }, +} + +type okcallback func(ok bool, reason string) diff --git a/relay_test.go b/relay_test.go index ed52ab9f..4c5233b9 100644 --- a/relay_test.go +++ b/relay_test.go @@ -157,65 +157,3 @@ func newWebsocketServer(handler func(*websocket.Conn)) *httptest.Server { var anyOriginHandshake = func(conf *websocket.Config, r *http.Request) error { return nil } - -func makeKeyPair(t *testing.T) (priv, pub [32]byte) { - t.Helper() - - privkey := Generate() - pubkey := GetPublicKey(privkey) - - return privkey, pubkey -} - -func mustRelayConnect(t *testing.T, url string) *Relay { - t.Helper() - - rl, err := RelayConnect(t.Context(), url, RelayOptions{}) - require.NoError(t, err) - - return rl -} - -func parseEventMessage(t *testing.T, raw []stdjson.RawMessage) Event { - t.Helper() - - require.Condition(t, func() (success bool) { - return len(raw) >= 2 - }) - - var typ string - err := json.Unmarshal(raw[0], &typ) - require.NoError(t, err) - require.Equal(t, "EVENT", typ) - - var event Event - err = json.Unmarshal(raw[1], &event) - require.NoError(t, err) - - return event -} - -func parseSubscriptionMessage(t *testing.T, raw []stdjson.RawMessage) (subid string, filters []Filter) { - t.Helper() - - require.Greater(t, len(raw), 3) - - var typ string - err := json.Unmarshal(raw[0], &typ) - - require.NoError(t, err) - require.Equal(t, "REQ", typ) - - var id string - err = json.Unmarshal(raw[1], &id) - require.NoError(t, err) - - var ff []Filter - for _, b := range raw[2:] { - var f Filter - err := json.Unmarshal(b, &f) - require.NoError(t, err) - ff = append(ff, f) - } - return id, ff -} diff --git a/relay_util_std_test.go b/relay_util_std_test.go new file mode 100644 index 00000000..d1e6b939 --- /dev/null +++ b/relay_util_std_test.go @@ -0,0 +1,17 @@ +//go:build !tinygo + +package nostr + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func mustRelayConnect(t *testing.T, url string) *Relay { + t.Helper() + rl, err := RelayConnect(t.Context(), url, RelayOptions{}) + require.NoError(t, err) + + return rl +} diff --git a/relay_util_test.go b/relay_util_test.go new file mode 100644 index 00000000..a9c159b5 --- /dev/null +++ b/relay_util_test.go @@ -0,0 +1,61 @@ +package nostr + +import ( + stdjson "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func makeKeyPair(t *testing.T) (priv, pub [32]byte) { + t.Helper() + + privkey := Generate() + pubkey := GetPublicKey(privkey) + + return privkey, pubkey +} + +func parseEventMessage(t *testing.T, raw []stdjson.RawMessage) Event { + t.Helper() + + require.Condition(t, func() (success bool) { + return len(raw) >= 2 + }) + + var typ string + err := json.Unmarshal(raw[0], &typ) + require.NoError(t, err) + require.Equal(t, "EVENT", typ) + + var event Event + err = json.Unmarshal(raw[1], &event) + require.NoError(t, err) + + return event +} + +func parseSubscriptionMessage(t *testing.T, raw []stdjson.RawMessage) (subid string, filters []Filter) { + t.Helper() + + require.Greater(t, len(raw), 3) + + var typ string + err := json.Unmarshal(raw[0], &typ) + + require.NoError(t, err) + require.Equal(t, "REQ", typ) + + var id string + err = json.Unmarshal(raw[1], &id) + require.NoError(t, err) + + var ff []Filter + for _, b := range raw[2:] { + var f Filter + err := json.Unmarshal(b, &f) + require.NoError(t, err) + ff = append(ff, f) + } + return id, ff +} diff --git a/relay_util_tinygo_test.go b/relay_util_tinygo_test.go new file mode 100644 index 00000000..37c4e388 --- /dev/null +++ b/relay_util_tinygo_test.go @@ -0,0 +1,18 @@ +//go:build tinygo + +package nostr + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func mustRelayConnect(t *testing.T, url string) *Relay { + t.Helper() + rl, err := RelayConnect(context.Background(), url, RelayOptions{}) + require.NoError(t, err) + + return rl +} diff --git a/sdk/cache/memory/cache.go b/sdk/cache/memory/cache_ristretto.go similarity index 97% rename from sdk/cache/memory/cache.go rename to sdk/cache/memory/cache_ristretto.go index 233eaf6a..07efa343 100644 --- a/sdk/cache/memory/cache.go +++ b/sdk/cache/memory/cache_ristretto.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package cache_memory import ( diff --git a/sdk/cache/memory/cache_test.go b/sdk/cache/memory/cache_test.go new file mode 100644 index 00000000..67227fde --- /dev/null +++ b/sdk/cache/memory/cache_test.go @@ -0,0 +1,78 @@ +package cache_memory + +import ( + "encoding/binary" + "testing" + "time" +) + +func TestCache(t *testing.T) { + c := New[string](100) + key := [32]byte{1} + + c.Set(key, "hello") + time.Sleep(50 * time.Millisecond) + val, ok := c.Get(key) + if !ok { + t.Fatal("expected to find key") + } + if val != "hello" { + t.Fatalf("expected hello, got %s", val) + } + + c.Delete(key) + _, ok = c.Get(key) + if ok { + t.Fatal("expected not to find key") + } +} + +func TestTTL(t *testing.T) { + c := New[string](100) + key := [32]byte{2} + + c.SetWithTTL(key, "hello", 100*time.Millisecond) + time.Sleep(50 * time.Millisecond) + val, ok := c.Get(key) + if !ok { + t.Fatal("expected to find key") + } + if val != "hello" { + t.Fatalf("expected hello, got %s", val) + } + + time.Sleep(200 * time.Millisecond) + _, ok = c.Get(key) + if ok { + t.Fatal("expected key to expire") + } +} + +func TestEviction(t *testing.T) { + max := int64(100) + c := New[int](max) + + for i := 0; i < 200; i++ { + k := [32]byte{} + binary.BigEndian.PutUint64(k[24:], uint64(i)) + c.Set(k, i) + } + + time.Sleep(200 * time.Millisecond) + + count := 0 + for i := 0; i < 200; i++ { + k := [32]byte{} + binary.BigEndian.PutUint64(k[24:], uint64(i)) + if _, ok := c.Get(k); ok { + count++ + } + } + + if count > int(max)+10 { + t.Fatalf("expected around %d items, got %d", max, count) + } + if count == 0 { + t.Fatalf("expected some items, got 0") + } +} diff --git a/sdk/cache/memory/cache_tinygo.go b/sdk/cache/memory/cache_tinygo.go new file mode 100644 index 00000000..06e7d721 --- /dev/null +++ b/sdk/cache/memory/cache_tinygo.go @@ -0,0 +1,89 @@ +//go:build tinygo + +package cache_memory + +import ( + "sync" + "time" +) + +type RistrettoCache[V any] struct { + backend *simpleCache[V] +} + +type item[V any] struct { + value V + expiration time.Time +} + +type simpleCache[V any] struct { + mu sync.Mutex + items map[[32]byte]item[V] + maxSize int64 +} + +func New[V any](max int64) *RistrettoCache[V] { + return &RistrettoCache[V]{ + backend: &simpleCache[V]{ + items: make(map[[32]byte]item[V]), + maxSize: max, + }, + } +} + +func (s RistrettoCache[V]) Get(k [32]byte) (v V, ok bool) { + s.backend.mu.Lock() + defer s.backend.mu.Unlock() + + it, found := s.backend.items[k] + if !found { + return v, false + } + + if !it.expiration.IsZero() && time.Now().After(it.expiration) { + delete(s.backend.items, k) + return v, false + } + + return it.value, true +} + +func (s RistrettoCache[V]) Delete(k [32]byte) { + s.backend.mu.Lock() + defer s.backend.mu.Unlock() + delete(s.backend.items, k) +} + +func (s RistrettoCache[V]) Set(k [32]byte, v V) bool { + s.backend.mu.Lock() + defer s.backend.mu.Unlock() + + if int64(len(s.backend.items)) >= s.backend.maxSize { + // Evict one random item + for k := range s.backend.items { + delete(s.backend.items, k) + break + } + } + + s.backend.items[k] = item[V]{value: v} + return true +} + +func (s RistrettoCache[V]) SetWithTTL(k [32]byte, v V, d time.Duration) bool { + s.backend.mu.Lock() + defer s.backend.mu.Unlock() + + if int64(len(s.backend.items)) >= s.backend.maxSize { + for k := range s.backend.items { + delete(s.backend.items, k) + break + } + } + + s.backend.items[k] = item[V]{ + value: v, + expiration: time.Now().Add(d), + } + return true +} diff --git a/sdk/feeds_test.go b/sdk/feeds_test.go index 521f61eb..70997a40 100644 --- a/sdk/feeds_test.go +++ b/sdk/feeds_test.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package sdk import ( diff --git a/sdk/fetch_std.go b/sdk/fetch_std.go new file mode 100644 index 00000000..a1106b81 --- /dev/null +++ b/sdk/fetch_std.go @@ -0,0 +1,31 @@ +//go:build !tinygo + +package sdk + +import ( + "context" + "fmt" + "io" + "net/http" + "time" +) + +func fetch(ctx context.Context, url string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, "GET", url, nil) + if err != nil { + return nil, err + } + + client := &http.Client{Timeout: 10 * time.Second} + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + return nil, fmt.Errorf("status code %d", resp.StatusCode) + } + + return io.ReadAll(resp.Body) +} diff --git a/sdk/fetch_tinygo.go b/sdk/fetch_tinygo.go new file mode 100644 index 00000000..9ee4f09b --- /dev/null +++ b/sdk/fetch_tinygo.go @@ -0,0 +1,25 @@ +//go:build tinygo + +package sdk + +import ( + "context" + "fmt" + + fetch_ "marwan.io/wasm-fetch" +) + +func fetch(ctx context.Context, url string) ([]byte, error) { + resp, err := fetch_.Fetch(url, &fetch_.Opts{ + Method: fetch_.MethodGet, + Signal: ctx, + }) + if err != nil { + return nil, err + } + if resp.Status >= 300 { + return nil, fmt.Errorf("status code %d", resp.Status) + } + + return resp.Body, nil +} diff --git a/sdk/wot_test.go b/sdk/wot_test.go index 0abeb2a3..24d2b6e2 100644 --- a/sdk/wot_test.go +++ b/sdk/wot_test.go @@ -1,6 +1,7 @@ package sdk import ( + "context" "sync" "testing" "time" @@ -11,7 +12,7 @@ import ( func TestLoadWoT(t *testing.T) { sys := NewSystem() - ctx := t.Context() + ctx := context.Background() // test with fiatjaf's pubkey wotch, err := sys.loadWoT(ctx, nostr.MustPubKeyFromHex("3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d")) @@ -46,7 +47,7 @@ func TestLoadWoT(t *testing.T) { func TestLoadWoTManyPeople(t *testing.T) { sys := NewSystem() - ctx := t.Context() + ctx := context.Background() wg := sync.WaitGroup{} wg.Add(3 + 2 + 2) diff --git a/sdk/zap.go b/sdk/zap.go index 1856f117..0ffd31a4 100644 --- a/sdk/zap.go +++ b/sdk/zap.go @@ -3,8 +3,6 @@ package sdk import ( "context" "crypto/sha256" - "io" - "net/http" "strings" "time" @@ -38,20 +36,12 @@ func (sys *System) FetchZapProvider(ctx context.Context, pk nostr.PubKey) nostr. parts := strings.Split(pm.LUD16, "@") if len(parts) == 2 { url := "http://" + parts[1] + "/.well-known/lnurlp/" + parts[0] - req, err := http.NewRequestWithContext(ctx, "GET", url, nil) - if err == nil { - client := &http.Client{Timeout: 10 * time.Second} - resp, err := client.Do(req) - if err == nil { - defer resp.Body.Close() - if body, err := io.ReadAll(resp.Body); err == nil { - gj := gjson.ParseBytes(body) - if gj.Get("allowsNostr").Type == gjson.True { - if pk, err := nostr.PubKeyFromHex(gj.Get("nostrPubkey").Str); err == nil { - sys.ZapProviderCache.SetWithTTL(pk, pk, time.Hour*6) - return pk - } - } + if body, err := fetch(ctx, url); err == nil { + gj := gjson.ParseBytes(body) + if gj.Get("allowsNostr").Type == gjson.True { + if pk, err := nostr.PubKeyFromHex(gj.Get("nostrPubkey").Str); err == nil { + sys.ZapProviderCache.SetWithTTL(pk, pk, time.Hour*6) + return pk } } } diff --git a/sdk/zap_test.go b/sdk/zap_test.go index c84f081e..645063ad 100644 --- a/sdk/zap_test.go +++ b/sdk/zap_test.go @@ -3,6 +3,7 @@ package sdk import ( "context" "testing" + "time" "fiatjaf.com/nostr" "github.com/stretchr/testify/require" @@ -15,6 +16,12 @@ func TestFetchZapProvider(t *testing.T) { pk, err := nostr.PubKeyFromHex("fa984bd7dbb282f07e16e7ae87b26a2a7b9b90b7246a44771f0cf5ae58018f52") require.NoError(t, err) + // inject metadata to avoid network fetch which crashes in tinygo/wasm environment due to websocket issues + sys.MetadataCache.SetWithTTL(pk, ProfileMetadata{ + PubKey: pk, + LUD16: "pablof7z@primal.net", + }, time.Hour) + zp := sys.FetchZapProvider(ctx, pk) expected, err := nostr.PubKeyFromHex("f81611363554b64306467234d7396ec88455707633f54738f6c4683535098cd3") require.NoError(t, err) diff --git a/tinygotest b/tinygotest new file mode 100755 index 00000000..7bf5279a --- /dev/null +++ b/tinygotest @@ -0,0 +1,2 @@ +#!/bin/bash +GOOS=js GOARCH=wasm tinygo test `go list ./... | egrep -v 'eventstore|libsecp256k1|khatru|schema|nipb0|nip13|sdk'` diff --git a/utils_map.go b/utils_map.go new file mode 100644 index 00000000..09c2ec3d --- /dev/null +++ b/utils_map.go @@ -0,0 +1,17 @@ +//go:build !tinygo + +package nostr + +import "github.com/puzpuzpuz/xsync/v3" + +type MapOf[K comparable, V any] = xsync.MapOf[K, V] + +func NewMapOf[K comparable, V any]() *MapOf[K, V] { + return xsync.NewMapOf[K, V]() +} + +type Counter = xsync.Counter + +func NewCounter() *Counter { + return xsync.NewCounter() +} diff --git a/utils_map_tinygo.go b/utils_map_tinygo.go new file mode 100644 index 00000000..003611ed --- /dev/null +++ b/utils_map_tinygo.go @@ -0,0 +1,100 @@ +//go:build tinygo + +package nostr + +import ( + "sync" + "sync/atomic" +) + +type MapOf[K comparable, V any] struct { + mu sync.Mutex + m map[K]V +} + +func NewMapOf[K comparable, V any]() *MapOf[K, V] { + return &MapOf[K, V]{ + m: make(map[K]V), + } +} + +func (m *MapOf[K, V]) Load(key K) (value V, ok bool) { + m.mu.Lock() + defer m.mu.Unlock() + value, ok = m.m[key] + return +} + +func (m *MapOf[K, V]) Store(key K, value V) { + m.mu.Lock() + defer m.mu.Unlock() + m.m[key] = value +} + +func (m *MapOf[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) { + m.mu.Lock() + defer m.mu.Unlock() + actual, loaded = m.m[key] + if loaded { + return actual, true + } + m.m[key] = value + return value, false +} + +func (m *MapOf[K, V]) Delete(key K) { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.m, key) +} + +func (m *MapOf[K, V]) Range(yield func(key K, value V) bool) { + m.mu.Lock() + // Copy keys to avoid holding lock during iteration or modification issues + // Since we can't easily copy map without knowing size, and we want to be safe. + // A full copy is safest. + snapshot := make(map[K]V, len(m.m)) + for k, v := range m.m { + snapshot[k] = v + } + m.mu.Unlock() + + for k, v := range snapshot { + if !yield(k, v) { + return + } + } +} + +func (m *MapOf[K, V]) Compute(key K, computeFunc func(oldValue V, loaded bool) (newValue V, delete bool)) (actual V, deleted bool) { + m.mu.Lock() + defer m.mu.Unlock() + oldValue, loaded := m.m[key] + newValue, shouldDelete := computeFunc(oldValue, loaded) + if shouldDelete { + delete(m.m, key) + return oldValue, true + } + m.m[key] = newValue + return newValue, false +} + +type Counter struct { + v atomic.Int64 +} + +func NewCounter() *Counter { + return &Counter{} +} + +func (c *Counter) Add(delta int64) { + c.v.Add(delta) +} + +func (c *Counter) Dec() { + c.v.Add(-1) +} + +func (c *Counter) Value() int64 { + return c.v.Load() +}