From fc0c9fdbea23d5582981e06bf102243beedbcf63 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Tue, 2 Dec 2025 22:52:55 +0900 Subject: [PATCH 01/24] phase 1 --- count_test.go | 2 + envelopes.go | 2 + envelopes_test.go | 2 + envelopes_tinygo.go | 382 +++++++++++++++++++++++++++++++++++++++ eose_test.go | 2 + event.go | 50 ----- event_easyjson.go | 2 + event_methods.go | 56 ++++++ event_methods_tinygo.go | 112 ++++++++++++ event_test.go | 2 + event_tinygo_test.go | 91 ++++++++++ filter.go | 7 - filter_easyjson.go | 2 + filter_methods.go | 10 + filter_methods_tinygo.go | 195 ++++++++++++++++++++ helpers.go | 2 + helpers_tinygo.go | 274 ++++++++++++++++++++++++++++ keys.go | 2 + keys_tinygo.go | 186 +++++++++++++++++++ pointers_easyjson.go | 2 + pool.go | 21 +-- relay.go | 5 +- subscription_test.go | 2 + types.go | 2 + types_tinygo.go | 80 ++++++++ utils.go | 2 + utils_map.go | 17 ++ utils_map_tinygo.go | 100 ++++++++++ utils_tinygo.go | 73 ++++++++ 29 files changed, 1614 insertions(+), 71 deletions(-) create mode 100644 envelopes_tinygo.go create mode 100644 event_methods.go create mode 100644 event_methods_tinygo.go create mode 100644 event_tinygo_test.go create mode 100644 filter_methods.go create mode 100644 filter_methods_tinygo.go create mode 100644 helpers_tinygo.go create mode 100644 keys_tinygo.go create mode 100644 types_tinygo.go create mode 100644 utils_map.go create mode 100644 utils_map_tinygo.go create mode 100644 utils_tinygo.go diff --git a/count_test.go b/count_test.go index 9e27543e..e7a0c0e6 100644 --- a/count_test.go +++ b/count_test.go @@ -1,3 +1,5 @@ +//go:build !js + package nostr import ( 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_test.go b/envelopes_test.go index 08c19b83..cf9144f2 100644 --- a/envelopes_test.go +++ b/envelopes_test.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..0be10a4d --- /dev/null +++ b/envelopes_tinygo.go @@ -0,0 +1,382 @@ +//go:build tinygo + +package nostr + +import ( + "errors" + "fmt" + "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) { + // Manual marshaling to match the array structure ["EVENT", ...] + // We can use a temporary struct or build it manually. + // Building manually is safer to avoid reflection overhead if possible, but json.Marshal is fine. + if v.SubscriptionID != nil { + return json.Marshal([]interface{}{"EVENT", *v.SubscriptionID, v.Event}) + } + return json.Marshal([]interface{}{"EVENT", v.Event}) +} + +// 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) { + data := make([]interface{}, 2+len(v.Filters)) + data[0] = "REQ" + data[1] = v.SubscriptionID + for i, f := range v.Filters { + data[2+i] = f + } + return json.Marshal(data) +} + +// 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) { + if v.Count != nil { + res := struct { + Count *uint32 `json:"count"` + HLL string `json:"hll,omitempty"` + }{ + Count: v.Count, + } + if v.HyperLogLog != nil { + res.HLL = HexEncodeToString(v.HyperLogLog) + } + return json.Marshal([]interface{}{"COUNT", v.SubscriptionID, res}) + } + return json.Marshal([]interface{}{"COUNT", v.SubscriptionID, v.Filter}) +} + +// 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) { + return json.Marshal([]interface{}{"NOTICE", string(v)}) +} + +// 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) { + return json.Marshal([]interface{}{"EOSE", string(v)}) +} + +// 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) { + return json.Marshal([]interface{}{"CLOSE", string(v)}) +} + +// 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) { + return json.Marshal([]interface{}{"CLOSED", v.SubscriptionID, v.Reason}) +} + +// 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) { + return json.Marshal([]interface{}{"OK", HexEncodeToString(v.EventID[:]), v.OK, v.Reason}) +} + +// 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) { + if v.Challenge != nil { + return json.Marshal([]interface{}{"AUTH", *v.Challenge}) + } + return json.Marshal([]interface{}{"AUTH", v.Event}) +} diff --git a/eose_test.go b/eose_test.go index 71305a23..6ed6a090 100644 --- a/eose_test.go +++ b/eose_test.go @@ -1,3 +1,5 @@ +//go:build !js + package nostr import ( 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..9ed03b0a --- /dev/null +++ b/event_methods_tinygo.go @@ -0,0 +1,112 @@ +//go:build tinygo + +package nostr + +import ( + "encoding/hex" + "strconv" +) + +func (evt Event) String() string { + j, _ := json.Marshal(evt) + return string(j) +} + +func (evt Event) MarshalJSON() ([]byte, error) { + type EventJSON struct { + ID ID `json:"id"` + PubKey PubKey `json:"pubkey"` + CreatedAt Timestamp `json:"created_at"` + Kind Kind `json:"kind"` + Tags Tags `json:"tags"` + Content string `json:"content"` + Sig string `json:"sig"` + } + + ej := EventJSON{ + ID: evt.ID, + PubKey: evt.PubKey, + CreatedAt: evt.CreatedAt, + Kind: evt.Kind, + Tags: evt.Tags, + Content: evt.Content, + Sig: hex.EncodeToString(evt.Sig[:]), + } + + return json.Marshal(ej) +} + +func (evt *Event) UnmarshalJSON(data []byte) error { + type EventJSON struct { + ID ID `json:"id"` + PubKey PubKey `json:"pubkey"` + CreatedAt Timestamp `json:"created_at"` + Kind Kind `json:"kind"` + Tags Tags `json:"tags"` + Content string `json:"content"` + Sig string `json:"sig"` + } + + var ej EventJSON + if err := json.Unmarshal(data, &ej); err != nil { + return err + } + + evt.ID = ej.ID + evt.PubKey = ej.PubKey + evt.CreatedAt = ej.CreatedAt + evt.Kind = ej.Kind + evt.Tags = ej.Tags + evt.Content = ej.Content + + if len(ej.Sig) == 128 { + b, err := hex.DecodeString(ej.Sig) + if err != nil { + return err + } + 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/event_test.go b/event_test.go index 93d643de..8b27cdf6 100644 --- a/event_test.go +++ b/event_test.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nostr import ( diff --git a/event_tinygo_test.go b/event_tinygo_test.go new file mode 100644 index 00000000..781a355d --- /dev/null +++ b/event_tinygo_test.go @@ -0,0 +1,91 @@ +//go:build tinygo + +package nostr + +import ( + "encoding/hex" + "testing" +) + +func TestEventParsingAndVerifying(t *testing.T) { + rawEvents := []string{ + `{"kind":1,"id":"dc90c95f09947507c1044e8f48bcf6350aa6bff1507dd4acfc755b9239b5c962","pubkey":"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","created_at":1644271588,"tags":[],"content":"now that https://blueskyweb.org/blog/2-7-2022-overview was announced we can stop working on nostr?","sig":"230e9d8f0ddaf7eb70b5f7741ccfa37e87a455c9a469282e3464e2052d3192cd63a167e196e381ef9d7e69e9ea43af2443b839974dc85d8aaab9efe1d9296524"}`, + `{"kind":1,"id":"dc90c95f09947507c1044e8f48bcf6350aa6bff1507dd4acfc755b9239b5c962","pubkey":"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","created_at":1644271588,"tags":[],"content":"now that https://blueskyweb.org/blog/2-7-2022-overview was announced we can stop working on nostr?","sig":"230e9d8f0ddaf7eb70b5f7741ccfa37e87a455c9a469282e3464e2052d3192cd63a167e196e381ef9d7e69e9ea43af2443b839974dc85d8aaab9efe1d9296524"}`, + `{"kind":1,"id":"dc90c95f09947507c1044e8f48bcf6350aa6bff1507dd4acfc755b9239b5c962","pubkey":"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","created_at":1644271588,"tags":[],"content":"now that https://blueskyweb.org/blog/2-7-2022-overview was announced we can stop working on nostr?","sig":"230e9d8f0ddaf7eb70b5f7741ccfa37e87a455c9a469282e3464e2052d3192cd63a167e196e381ef9d7e69e9ea43af2443b839974dc85d8aaab9efe1d9296524"}`, + `{"kind":3,"id":"9e662bdd7d8abc40b5b15ee1ff5e9320efc87e9274d8d440c58e6eed2dddfbe2","pubkey":"373ebe3d45ec91977296a178d9f19f326c70631d2a1b0bbba5c5ecc2eb53b9e7","created_at":1644844224,"tags":[["p","3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d"],["p","75fc5ac2487363293bd27fb0d14fb966477d0f1dbc6361d37806a6a740eda91e"],["p","46d0dfd3a724a302ca9175163bdf788f3606b3fd1bb12d5fe055d1e418cb60ea"]],"content":"{\"wss://nostr-pub.wellorder.net\":{\"read\":true,\"write\":true},\"wss://nostr.bitcoiner.social\":{\"read\":false,\"write\":true},\"wss://expensive-relay.fiatjaf.com\":{\"read\":true,\"write\":true},\"wss://relayer.fiatjaf.com\":{\"read\":true,\"write\":true},\"wss://relay.bitid.nz\":{\"read\":true,\"write\":true},\"wss://nostr.rocks\":{\"read\":true,\"write\":true}}","sig":"811355d3484d375df47581cb5d66bed05002c2978894098304f20b595e571b7e01b2efd906c5650080ffe49cf1c62b36715698e9d88b9e8be43029a2f3fa66be"}`, + } + + for _, raw := range rawEvents { + var ev Event + err := json.Unmarshal([]byte(raw), &ev) + if err != nil { + t.Errorf("failed to unmarshal event: %v", err) + } + + if ev.ID != ev.GetID() { + t.Errorf("ID mismatch: expected %s, got %s", ev.ID, ev.GetID()) + } + + ok := ev.VerifySignature() + if !ok { + t.Errorf("signature verification failed when it should have succeeded") + } + + asJSON, err := json.Marshal(ev) + if err != nil { + t.Errorf("failed to marshal event: %v", err) + } + if string(asJSON) != raw { + t.Errorf("marshaled JSON differs from original: expected %s, got %s", raw, string(asJSON)) + } + } +} + +func TestEventSerialization(t *testing.T) { + sigBytes, _ := hex.DecodeString("ed08d2dd5b0f7b6a3cdc74643d4adee3158ddede9cc848e8cd97630c097001acc2d052d2d3ec2b7ac4708b2314b797106d1b3c107322e61b5e5cc2116e099b79") + var sig [64]byte + copy(sig[:], sigBytes) + + events := []Event{ + { + ID: MustIDFromHex("92570b321da503eac8014b23447301eb3d0bbdfbace0d11a4e4072e72bb7205d"), + PubKey: MustPubKeyFromHex("e9142f724955c5854de36324dab0434f97b15ec6b33464d56ebe491e3f559d1b"), + Kind: KindEncryptedDirectMessage, + CreatedAt: Timestamp(1671028682), + Tags: Tags{Tag{"p", "f8340b2bde651576b75af61aa26c80e13c65029f00f7f64004eece679bf7059f"}}, + Content: "you say yes, I say no", + Sig: sig, + }, + } + + for _, evt := range events { + b, err := json.Marshal(evt) + if err != nil { + t.Errorf("failed to marshal event: %v", err) + } + + var re Event + err = json.Unmarshal(b, &re) + if err != nil { + t.Errorf("failed to unmarshal event: %v", err) + } + + if evt.ID != re.ID || evt.PubKey != re.PubKey || evt.Content != re.Content || + evt.CreatedAt != re.CreatedAt || evt.Sig != re.Sig || + len(evt.Tags) != len(re.Tags) { + t.Errorf("re-parsed event differs from original") + } + + for i := range evt.Tags { + if len(evt.Tags[i]) != len(re.Tags[i]) { + t.Errorf("re-parsed tags %d length differ from original", i) + } + + for j := range evt.Tags[i] { + if re.Tags[i][j] != evt.Tags[i][j] { + t.Errorf("re-parsed tag content %d %d length differ from original", i, j) + } + } + } + } +} diff --git a/filter.go b/filter.go index fa9c8ac0..4a08ed2b 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 afc8429a..e65ff8fb 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..12cc205c --- /dev/null +++ b/filter_methods_tinygo.go @@ -0,0 +1,195 @@ +//go:build tinygo + +package nostr + +import ( + "encoding/hex" + stdjson "encoding/json" + "strconv" +) + +func (ef Filter) String() string { + j, _ := json.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":`...) + sb, _ := json.Marshal(ef.Search) + b = append(b, sb...) + } + + for key, values := range ef.Tags { + if !first { + b = append(b, ',') + } + first = false + b = append(b, `"#`...) + b = append(b, key...) + b = append(b, `":`...) + vb, _ := json.Marshal(values) + b = append(b, vb...) + } + + b = append(b, '}') + return b, nil +} + +func (ef *Filter) UnmarshalJSON(data []byte) error { + var raw map[string]stdjson.RawMessage + if err := stdjson.Unmarshal(data, &raw); err != nil { + return err + } + + for key, val := range raw { + switch key { + case "ids": + var ids []string + if err := stdjson.Unmarshal(val, &ids); err != nil { + return err + } + for _, s := range ids { + var id ID + if len(s) == 64 { + b, _ := hex.DecodeString(s) + copy(id[:], b) + } + ef.IDs = append(ef.IDs, id) + } + case "kinds": + if err := stdjson.Unmarshal(val, &ef.Kinds); err != nil { + return err + } + case "authors": + var authors []string + if err := stdjson.Unmarshal(val, &authors); err != nil { + return err + } + for _, s := range authors { + var pk PubKey + if len(s) == 64 { + b, _ := hex.DecodeString(s) + copy(pk[:], b) + } + ef.Authors = append(ef.Authors, pk) + } + case "since": + if err := stdjson.Unmarshal(val, &ef.Since); err != nil { + return err + } + case "until": + if err := stdjson.Unmarshal(val, &ef.Until); err != nil { + return err + } + case "limit": + if err := stdjson.Unmarshal(val, &ef.Limit); err != nil { + return err + } + if ef.Limit == 0 { + ef.LimitZero = true + } + case "search": + if err := stdjson.Unmarshal(val, &ef.Search); err != nil { + return err + } + default: + if len(key) > 1 && key[0] == '#' { + if ef.Tags == nil { + ef.Tags = make(TagMap) + } + var values []string + if err := stdjson.Unmarshal(val, &values); err != nil { + return err + } + ef.Tags[key[1:]] = values + } + } + } + return nil +} 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/keys.go b/keys.go index c8505268..4ab7ef57 100644 --- a/keys.go +++ b/keys.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nostr import ( diff --git a/keys_tinygo.go b/keys_tinygo.go new file mode 100644 index 00000000..2e29f3a1 --- /dev/null +++ b/keys_tinygo.go @@ -0,0 +1,186 @@ +//go:build tinygo + +package nostr + +import ( + "crypto/rand" + "encoding/hex" + stdjson "encoding/json" + "fmt" + "io" + "strings" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" +) + +var KeyOne = SecretKey{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} + +func Generate() SecretKey { + var sk SecretKey + + for { + if _, err := io.ReadFull(rand.Reader, sk[:]); err != nil { + panic(fmt.Errorf("failed to read random bytes when generating private key")) + } + + // there is a ridiculously small probabily of the secret key not yield a valid public key, so iterate here + pk := sk.Public() + if _, err := schnorr.ParsePubKey(pk[:]); err != nil { + continue + } + + return sk + } +} + +type SecretKey [32]byte + +func (sk SecretKey) String() string { return "sk::" + sk.Hex() } +func (sk SecretKey) Hex() string { return hex.EncodeToString(sk[:]) } +func (sk SecretKey) Public() PubKey { return GetPublicKey(sk) } +func (pk SecretKey) MarshalJSON() ([]byte, error) { + return stdjson.Marshal(pk.Hex()) +} + +func (pk *SecretKey) UnmarshalJSON(buf []byte) error { + var s string + if err := stdjson.Unmarshal(buf, &s); err != nil { + return err + } + if len(s) != 64 { + return fmt.Errorf("must be a hex string of 64 characters") + } + b, err := hex.DecodeString(s) + if err != nil { + return err + } + copy(pk[:], b) + return nil +} + +func SecretKeyFromHex(skh string) (SecretKey, error) { + sk := SecretKey{} + + if len(skh) < 64 { + skh = strings.Repeat("0", 64-len(skh)) + skh + } else if len(skh) > 64 { + return sk, fmt.Errorf("secret key should be at most 64-char hex, got '%s'", skh) + } + + b, err := hex.DecodeString(skh) + if err != nil { + return sk, fmt.Errorf("'%s' is not valid hex: %w", skh, err) + } + copy(sk[:], b) + + if sk.Public() != ZeroPK { + return sk, nil + } + + return sk, fmt.Errorf("invalid secret key") +} + +func MustSecretKeyFromHex(idh string) SecretKey { + sk, err := SecretKeyFromHex(idh) + if err != nil { + panic(err) + } + return sk +} + +func GetPublicKey(sk [32]byte) PubKey { + _, pk := btcec.PrivKeyFromBytes(sk[:]) + return [32]byte(pk.SerializeCompressed()[1:]) +} + +var ( + ZeroPK = PubKey{} + + // this special public key doesn't have a secret key known to anyone, + // it corresponds to the hash of the block #3 of bitcoin (the first 3 block hashes are not valid public keys) + NUMS = MustPubKeyFromHex("0000000082b5015589a3fdf2d4baff403e6f0be035a5d9742c1cae6295464449") +) + +type PubKey [32]byte + +var ( + _ stdjson.Marshaler = PubKey{} + _ stdjson.Unmarshaler = (*PubKey)(nil) + _ stdjson.Marshaler = SecretKey{} + _ stdjson.Unmarshaler = (*SecretKey)(nil) +) + +func (pk PubKey) String() string { return "pk::" + pk.Hex() } +func (pk PubKey) Hex() string { return hex.EncodeToString(pk[:]) } +func (pk PubKey) MarshalJSON() ([]byte, error) { + return stdjson.Marshal(pk.Hex()) +} + +func (pk *PubKey) UnmarshalJSON(buf []byte) error { + var s string + if err := stdjson.Unmarshal(buf, &s); err != nil { + return err + } + if len(s) != 64 { + return fmt.Errorf("must be a hex string of 64 characters") + } + b, err := hex.DecodeString(s) + if err != nil { + return err + } + copy(pk[:], b) + + 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 { + return pk, fmt.Errorf("pubkey should be 64-char hex, got '%s'", pkh) + } + b, err := hex.DecodeString(pkh) + if err != nil { + return pk, fmt.Errorf("'%s' is not valid hex: %w", pkh, err) + } + copy(pk[:], b) + + if _, err := schnorr.ParsePubKey(pk[:]); err != nil { + return pk, fmt.Errorf("'%s' is not a valid pubkey", pkh) + } + return pk, nil +} + +func PubKeyFromHexCheap(pkh string) (PubKey, error) { + pk := PubKey{} + if len(pkh) != 64 { + return pk, fmt.Errorf("pubkey should be 64-char hex, got '%s'", pkh) + } + b, err := hex.DecodeString(pkh) + if err != nil { + return pk, fmt.Errorf("'%s' is not valid hex: %w", pkh, err) + } + copy(pk[:], b) + + return pk, nil +} + +func MustPubKeyFromHex(pkh string) PubKey { + pk, err := PubKeyFromHexCheap(pkh) + if err != nil { + panic(err) + } + return pk +} + +func ContainsPubKey(haystack []PubKey, needle PubKey) bool { + for _, cand := range haystack { + if cand == needle { + return true + } + } + return false +} 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 9a343204..8bb616e1 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 authHandler func(context.Context, *Event) error @@ -50,7 +49,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, @@ -245,7 +244,7 @@ func (pool *Pool) FetchMany( filter Filter, 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 { @@ -284,15 +283,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) { @@ -387,7 +386,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{} @@ -409,7 +408,7 @@ func (pool *Pool) subMany( } } - pending := xsync.NewCounter() + pending := NewCounter() pending.Add(int64(len(urls))) for i, url := range urls { url = NormalizeURL(url) @@ -691,7 +690,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{}]() opts.CheckDuplicate = func(id ID, relay string) bool { _, exists := seenAlready.LoadOrStore(id, struct{}{}) @@ -736,7 +735,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{}]() opts.CheckDuplicate = func(id ID, relay string) bool { _, exists := seenAlready.LoadOrStore(id, struct{}{}) diff --git a/relay.go b/relay.go index d81c2791..e2b52505 100644 --- a/relay.go +++ b/relay.go @@ -15,7 +15,6 @@ import ( "time" ws "github.com/coder/websocket" - "github.com/puzpuzpuz/xsync/v3" ) var subscriptionIDCounter atomic.Int64 @@ -33,7 +32,7 @@ type Relay struct { closed *atomic.Bool closedNotify chan struct{} - Subscriptions *xsync.MapOf[int64, *Subscription] + Subscriptions *MapOf[int64, *Subscription] ConnectionError error connectionContext context.Context // will be canceled when the connection closes @@ -58,7 +57,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/subscription_test.go b/subscription_test.go index ca333212..e162cc6f 100644 --- a/subscription_test.go +++ b/subscription_test.go @@ -1,3 +1,5 @@ +//go:build !js + package nostr import ( diff --git a/types.go b/types.go index 2a4111f6..54d37d07 100644 --- a/types.go +++ b/types.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nostr import ( diff --git a/types_tinygo.go b/types_tinygo.go new file mode 100644 index 00000000..44adcf91 --- /dev/null +++ b/types_tinygo.go @@ -0,0 +1,80 @@ +//go:build tinygo + +package nostr + +import ( + "encoding/hex" + stdjson "encoding/json" + "fmt" +) + +// RelayEvent represents an event received from a specific relay. +type RelayEvent struct { + Event + Relay *Relay +} + +var ZeroID = ID{} + +// ID represents an event id +type ID [32]byte + +var ( + _ stdjson.Marshaler = ID{} + _ stdjson.Unmarshaler = (*ID)(nil) +) + +func (id ID) String() string { return "id::" + id.Hex() } +func (id ID) Hex() string { return hex.EncodeToString(id[:]) } + +func (id ID) MarshalJSON() ([]byte, error) { + return stdjson.Marshal(id.Hex()) +} + +func (id *ID) UnmarshalJSON(buf []byte) error { + var s string + if err := stdjson.Unmarshal(buf, &s); err != nil { + return err + } + if len(s) != 64 { + return fmt.Errorf("must be a hex string of 64 characters") + } + b, err := hex.DecodeString(s) + if err != nil { + return err + } + copy(id[:], b) + return nil +} + +func IDFromHex(idh string) (ID, error) { + id := ID{} + + if len(idh) != 64 { + return id, fmt.Errorf("pubkey should be 64-char hex, got '%s'", idh) + } + b, err := hex.DecodeString(idh) + if err != nil { + return id, fmt.Errorf("'%s' is not valid hex: %w", idh, err) + } + copy(id[:], b) + + return id, nil +} + +func MustIDFromHex(idh string) ID { + id, err := IDFromHex(idh) + if err != nil { + panic(err) + } + return id +} + +func ContainsID(haystack []ID, needle ID) bool { + for _, cand := range haystack { + if cand == needle { + return true + } + } + return false +} diff --git a/utils.go b/utils.go index e8bea0a7..638d44ed 100644 --- a/utils.go +++ b/utils.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nostr import ( 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() +} diff --git a/utils_tinygo.go b/utils_tinygo.go new file mode 100644 index 00000000..975539df --- /dev/null +++ b/utils_tinygo.go @@ -0,0 +1,73 @@ +//go:build tinygo + +package nostr + +import ( + "bytes" + "cmp" + "encoding/hex" + "net/url" + "slices" +) + +// IsValidRelayURL checks if a URL is a valid relay URL (ws:// or wss://). +func IsValidRelayURL(u string) bool { + parsed, err := url.Parse(u) + if err != nil { + return false + } + if parsed.Scheme != "wss" && parsed.Scheme != "ws" { + return false + } + return true +} + +// HexEncodeToString encodes src into a hex string. +func HexEncodeToString(src []byte) string { + return hex.EncodeToString(src) +} + +// HexDecodeString decodes a hex string into bytes. +func HexDecodeString(s string) ([]byte, error) { + return hex.DecodeString(s) +} + +// IsValid32ByteHex checks if a string is a valid 32-byte hex string. +func IsValid32ByteHex(thing string) bool { + if !isLowerHex(thing) { + return false + } + if len(thing) != 64 { + return false + } + _, err := HexDecodeString(thing) + return err == nil +} + +// CompareEvent is meant to to be used with slices.Sort +func CompareEvent(a, b Event) int { + if a.CreatedAt == b.CreatedAt { + return bytes.Compare(a.ID[:], b.ID[:]) + } + return cmp.Compare(a.CreatedAt, b.CreatedAt) +} + +// CompareEventReverse is meant to to be used with slices.Sort +func CompareEventReverse(b, a Event) int { + if a.CreatedAt == b.CreatedAt { + return bytes.Compare(a.ID[:], b.ID[:]) + } + return cmp.Compare(a.CreatedAt, b.CreatedAt) +} + +// AppendUnique adds items to an array only if they don't already exist in the array. +// Returns the modified array. +func AppendUnique[I comparable](arr []I, item ...I) []I { + for _, item := range item { + if slices.Contains(arr, item) { + return arr + } + arr = append(arr, item) + } + return arr +} From 0697f3a42968b3b01a90313f977db25d54f55f56 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Tue, 2 Dec 2025 23:17:23 +0900 Subject: [PATCH 02/24] phase 2: root test passes --- event_methods_tinygo.go | 8 ++-- event_test.go | 2 - event_tinygo_test.go | 91 ----------------------------------------- 3 files changed, 4 insertions(+), 97 deletions(-) delete mode 100644 event_tinygo_test.go diff --git a/event_methods_tinygo.go b/event_methods_tinygo.go index 9ed03b0a..1949fa8e 100644 --- a/event_methods_tinygo.go +++ b/event_methods_tinygo.go @@ -14,20 +14,20 @@ func (evt Event) String() string { func (evt Event) MarshalJSON() ([]byte, error) { type EventJSON struct { + Kind Kind `json:"kind"` ID ID `json:"id"` PubKey PubKey `json:"pubkey"` CreatedAt Timestamp `json:"created_at"` - Kind Kind `json:"kind"` Tags Tags `json:"tags"` Content string `json:"content"` Sig string `json:"sig"` } ej := EventJSON{ + Kind: evt.Kind, ID: evt.ID, PubKey: evt.PubKey, CreatedAt: evt.CreatedAt, - Kind: evt.Kind, Tags: evt.Tags, Content: evt.Content, Sig: hex.EncodeToString(evt.Sig[:]), @@ -38,10 +38,10 @@ func (evt Event) MarshalJSON() ([]byte, error) { func (evt *Event) UnmarshalJSON(data []byte) error { type EventJSON struct { + Kind Kind `json:"kind"` ID ID `json:"id"` PubKey PubKey `json:"pubkey"` CreatedAt Timestamp `json:"created_at"` - Kind Kind `json:"kind"` Tags Tags `json:"tags"` Content string `json:"content"` Sig string `json:"sig"` @@ -52,10 +52,10 @@ func (evt *Event) UnmarshalJSON(data []byte) error { return err } + evt.Kind = ej.Kind evt.ID = ej.ID evt.PubKey = ej.PubKey evt.CreatedAt = ej.CreatedAt - evt.Kind = ej.Kind evt.Tags = ej.Tags evt.Content = ej.Content diff --git a/event_test.go b/event_test.go index 8b27cdf6..93d643de 100644 --- a/event_test.go +++ b/event_test.go @@ -1,5 +1,3 @@ -//go:build !tinygo - package nostr import ( diff --git a/event_tinygo_test.go b/event_tinygo_test.go deleted file mode 100644 index 781a355d..00000000 --- a/event_tinygo_test.go +++ /dev/null @@ -1,91 +0,0 @@ -//go:build tinygo - -package nostr - -import ( - "encoding/hex" - "testing" -) - -func TestEventParsingAndVerifying(t *testing.T) { - rawEvents := []string{ - `{"kind":1,"id":"dc90c95f09947507c1044e8f48bcf6350aa6bff1507dd4acfc755b9239b5c962","pubkey":"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","created_at":1644271588,"tags":[],"content":"now that https://blueskyweb.org/blog/2-7-2022-overview was announced we can stop working on nostr?","sig":"230e9d8f0ddaf7eb70b5f7741ccfa37e87a455c9a469282e3464e2052d3192cd63a167e196e381ef9d7e69e9ea43af2443b839974dc85d8aaab9efe1d9296524"}`, - `{"kind":1,"id":"dc90c95f09947507c1044e8f48bcf6350aa6bff1507dd4acfc755b9239b5c962","pubkey":"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","created_at":1644271588,"tags":[],"content":"now that https://blueskyweb.org/blog/2-7-2022-overview was announced we can stop working on nostr?","sig":"230e9d8f0ddaf7eb70b5f7741ccfa37e87a455c9a469282e3464e2052d3192cd63a167e196e381ef9d7e69e9ea43af2443b839974dc85d8aaab9efe1d9296524"}`, - `{"kind":1,"id":"dc90c95f09947507c1044e8f48bcf6350aa6bff1507dd4acfc755b9239b5c962","pubkey":"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","created_at":1644271588,"tags":[],"content":"now that https://blueskyweb.org/blog/2-7-2022-overview was announced we can stop working on nostr?","sig":"230e9d8f0ddaf7eb70b5f7741ccfa37e87a455c9a469282e3464e2052d3192cd63a167e196e381ef9d7e69e9ea43af2443b839974dc85d8aaab9efe1d9296524"}`, - `{"kind":3,"id":"9e662bdd7d8abc40b5b15ee1ff5e9320efc87e9274d8d440c58e6eed2dddfbe2","pubkey":"373ebe3d45ec91977296a178d9f19f326c70631d2a1b0bbba5c5ecc2eb53b9e7","created_at":1644844224,"tags":[["p","3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d"],["p","75fc5ac2487363293bd27fb0d14fb966477d0f1dbc6361d37806a6a740eda91e"],["p","46d0dfd3a724a302ca9175163bdf788f3606b3fd1bb12d5fe055d1e418cb60ea"]],"content":"{\"wss://nostr-pub.wellorder.net\":{\"read\":true,\"write\":true},\"wss://nostr.bitcoiner.social\":{\"read\":false,\"write\":true},\"wss://expensive-relay.fiatjaf.com\":{\"read\":true,\"write\":true},\"wss://relayer.fiatjaf.com\":{\"read\":true,\"write\":true},\"wss://relay.bitid.nz\":{\"read\":true,\"write\":true},\"wss://nostr.rocks\":{\"read\":true,\"write\":true}}","sig":"811355d3484d375df47581cb5d66bed05002c2978894098304f20b595e571b7e01b2efd906c5650080ffe49cf1c62b36715698e9d88b9e8be43029a2f3fa66be"}`, - } - - for _, raw := range rawEvents { - var ev Event - err := json.Unmarshal([]byte(raw), &ev) - if err != nil { - t.Errorf("failed to unmarshal event: %v", err) - } - - if ev.ID != ev.GetID() { - t.Errorf("ID mismatch: expected %s, got %s", ev.ID, ev.GetID()) - } - - ok := ev.VerifySignature() - if !ok { - t.Errorf("signature verification failed when it should have succeeded") - } - - asJSON, err := json.Marshal(ev) - if err != nil { - t.Errorf("failed to marshal event: %v", err) - } - if string(asJSON) != raw { - t.Errorf("marshaled JSON differs from original: expected %s, got %s", raw, string(asJSON)) - } - } -} - -func TestEventSerialization(t *testing.T) { - sigBytes, _ := hex.DecodeString("ed08d2dd5b0f7b6a3cdc74643d4adee3158ddede9cc848e8cd97630c097001acc2d052d2d3ec2b7ac4708b2314b797106d1b3c107322e61b5e5cc2116e099b79") - var sig [64]byte - copy(sig[:], sigBytes) - - events := []Event{ - { - ID: MustIDFromHex("92570b321da503eac8014b23447301eb3d0bbdfbace0d11a4e4072e72bb7205d"), - PubKey: MustPubKeyFromHex("e9142f724955c5854de36324dab0434f97b15ec6b33464d56ebe491e3f559d1b"), - Kind: KindEncryptedDirectMessage, - CreatedAt: Timestamp(1671028682), - Tags: Tags{Tag{"p", "f8340b2bde651576b75af61aa26c80e13c65029f00f7f64004eece679bf7059f"}}, - Content: "you say yes, I say no", - Sig: sig, - }, - } - - for _, evt := range events { - b, err := json.Marshal(evt) - if err != nil { - t.Errorf("failed to marshal event: %v", err) - } - - var re Event - err = json.Unmarshal(b, &re) - if err != nil { - t.Errorf("failed to unmarshal event: %v", err) - } - - if evt.ID != re.ID || evt.PubKey != re.PubKey || evt.Content != re.Content || - evt.CreatedAt != re.CreatedAt || evt.Sig != re.Sig || - len(evt.Tags) != len(re.Tags) { - t.Errorf("re-parsed event differs from original") - } - - for i := range evt.Tags { - if len(evt.Tags[i]) != len(re.Tags[i]) { - t.Errorf("re-parsed tags %d length differ from original", i) - } - - for j := range evt.Tags[i] { - if re.Tags[i][j] != evt.Tags[i][j] { - t.Errorf("re-parsed tag content %d %d length differ from original", i, j) - } - } - } - } -} From 9843827cfd19da9fa4937cc261e1ab8594c54617 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Tue, 2 Dec 2025 23:27:59 +0900 Subject: [PATCH 03/24] phase 3: go passes, tinygo not --- count_test.go | 2 -- envelopes_test.go | 2 -- eose_test.go | 2 -- relay_test.go | 62 --------------------------------------- relay_test_util.go | 70 ++++++++++++++++++++++++++++++++++++++++++++ subscription_test.go | 2 -- 6 files changed, 70 insertions(+), 70 deletions(-) create mode 100644 relay_test_util.go diff --git a/count_test.go b/count_test.go index e7a0c0e6..9e27543e 100644 --- a/count_test.go +++ b/count_test.go @@ -1,5 +1,3 @@ -//go:build !js - package nostr import ( diff --git a/envelopes_test.go b/envelopes_test.go index cf9144f2..08c19b83 100644 --- a/envelopes_test.go +++ b/envelopes_test.go @@ -1,5 +1,3 @@ -//go:build !tinygo - package nostr import ( diff --git a/eose_test.go b/eose_test.go index 6ed6a090..71305a23 100644 --- a/eose_test.go +++ b/eose_test.go @@ -1,5 +1,3 @@ -//go:build !js - package nostr import ( 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_test_util.go b/relay_test_util.go new file mode 100644 index 00000000..43e1aaba --- /dev/null +++ b/relay_test_util.go @@ -0,0 +1,70 @@ +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 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/subscription_test.go b/subscription_test.go index e162cc6f..ca333212 100644 --- a/subscription_test.go +++ b/subscription_test.go @@ -1,5 +1,3 @@ -//go:build !js - package nostr import ( From 42ea4a3d2deecb0775078a97c4c390f856b2e18d Mon Sep 17 00:00:00 2001 From: 1l0 Date: Tue, 2 Dec 2025 23:49:16 +0900 Subject: [PATCH 04/24] phase 4: tinygo passes --- relay_util_std_test.go | 17 +++++++++++++++++ relay_test_util.go => relay_util_test.go | 9 --------- relay_util_tinygo_test.go | 18 ++++++++++++++++++ 3 files changed, 35 insertions(+), 9 deletions(-) create mode 100644 relay_util_std_test.go rename relay_test_util.go => relay_util_test.go (86%) create mode 100644 relay_util_tinygo_test.go 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_test_util.go b/relay_util_test.go similarity index 86% rename from relay_test_util.go rename to relay_util_test.go index 43e1aaba..a9c159b5 100644 --- a/relay_test_util.go +++ b/relay_util_test.go @@ -16,15 +16,6 @@ func makeKeyPair(t *testing.T) (priv, pub [32]byte) { 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() 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 +} From 835e9c18d4a2a44771f2476fcc38f9acd5c20ee1 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Wed, 3 Dec 2025 00:29:32 +0900 Subject: [PATCH 05/24] phase 5: tidy --- keyer/lib.go | 2 + keyer/lib_tinygo.go | 100 +++++++++++++++++++++++ keyer/plain.go | 2 + keyer/plain_tinygo.go | 63 ++++++++++++++ keys.go | 2 - keys_tinygo.go | 186 ------------------------------------------ nip05/nip05.go | 6 -- nip05/util.go | 11 +++ nip05/util_tinygo.go | 7 ++ types.go | 2 - types_tinygo.go | 80 ------------------ utils.go | 2 - utils_tinygo.go | 73 ----------------- 13 files changed, 185 insertions(+), 351 deletions(-) create mode 100644 keyer/lib_tinygo.go create mode 100644 keyer/plain_tinygo.go delete mode 100644 keys_tinygo.go create mode 100644 nip05/util.go create mode 100644 nip05/util_tinygo.go delete mode 100644 types_tinygo.go delete mode 100644 utils_tinygo.go 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 4ab7ef57..c8505268 100644 --- a/keys.go +++ b/keys.go @@ -1,5 +1,3 @@ -//go:build !tinygo - package nostr import ( diff --git a/keys_tinygo.go b/keys_tinygo.go deleted file mode 100644 index 2e29f3a1..00000000 --- a/keys_tinygo.go +++ /dev/null @@ -1,186 +0,0 @@ -//go:build tinygo - -package nostr - -import ( - "crypto/rand" - "encoding/hex" - stdjson "encoding/json" - "fmt" - "io" - "strings" - - "github.com/btcsuite/btcd/btcec/v2" - "github.com/btcsuite/btcd/btcec/v2/schnorr" -) - -var KeyOne = SecretKey{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} - -func Generate() SecretKey { - var sk SecretKey - - for { - if _, err := io.ReadFull(rand.Reader, sk[:]); err != nil { - panic(fmt.Errorf("failed to read random bytes when generating private key")) - } - - // there is a ridiculously small probabily of the secret key not yield a valid public key, so iterate here - pk := sk.Public() - if _, err := schnorr.ParsePubKey(pk[:]); err != nil { - continue - } - - return sk - } -} - -type SecretKey [32]byte - -func (sk SecretKey) String() string { return "sk::" + sk.Hex() } -func (sk SecretKey) Hex() string { return hex.EncodeToString(sk[:]) } -func (sk SecretKey) Public() PubKey { return GetPublicKey(sk) } -func (pk SecretKey) MarshalJSON() ([]byte, error) { - return stdjson.Marshal(pk.Hex()) -} - -func (pk *SecretKey) UnmarshalJSON(buf []byte) error { - var s string - if err := stdjson.Unmarshal(buf, &s); err != nil { - return err - } - if len(s) != 64 { - return fmt.Errorf("must be a hex string of 64 characters") - } - b, err := hex.DecodeString(s) - if err != nil { - return err - } - copy(pk[:], b) - return nil -} - -func SecretKeyFromHex(skh string) (SecretKey, error) { - sk := SecretKey{} - - if len(skh) < 64 { - skh = strings.Repeat("0", 64-len(skh)) + skh - } else if len(skh) > 64 { - return sk, fmt.Errorf("secret key should be at most 64-char hex, got '%s'", skh) - } - - b, err := hex.DecodeString(skh) - if err != nil { - return sk, fmt.Errorf("'%s' is not valid hex: %w", skh, err) - } - copy(sk[:], b) - - if sk.Public() != ZeroPK { - return sk, nil - } - - return sk, fmt.Errorf("invalid secret key") -} - -func MustSecretKeyFromHex(idh string) SecretKey { - sk, err := SecretKeyFromHex(idh) - if err != nil { - panic(err) - } - return sk -} - -func GetPublicKey(sk [32]byte) PubKey { - _, pk := btcec.PrivKeyFromBytes(sk[:]) - return [32]byte(pk.SerializeCompressed()[1:]) -} - -var ( - ZeroPK = PubKey{} - - // this special public key doesn't have a secret key known to anyone, - // it corresponds to the hash of the block #3 of bitcoin (the first 3 block hashes are not valid public keys) - NUMS = MustPubKeyFromHex("0000000082b5015589a3fdf2d4baff403e6f0be035a5d9742c1cae6295464449") -) - -type PubKey [32]byte - -var ( - _ stdjson.Marshaler = PubKey{} - _ stdjson.Unmarshaler = (*PubKey)(nil) - _ stdjson.Marshaler = SecretKey{} - _ stdjson.Unmarshaler = (*SecretKey)(nil) -) - -func (pk PubKey) String() string { return "pk::" + pk.Hex() } -func (pk PubKey) Hex() string { return hex.EncodeToString(pk[:]) } -func (pk PubKey) MarshalJSON() ([]byte, error) { - return stdjson.Marshal(pk.Hex()) -} - -func (pk *PubKey) UnmarshalJSON(buf []byte) error { - var s string - if err := stdjson.Unmarshal(buf, &s); err != nil { - return err - } - if len(s) != 64 { - return fmt.Errorf("must be a hex string of 64 characters") - } - b, err := hex.DecodeString(s) - if err != nil { - return err - } - copy(pk[:], b) - - 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 { - return pk, fmt.Errorf("pubkey should be 64-char hex, got '%s'", pkh) - } - b, err := hex.DecodeString(pkh) - if err != nil { - return pk, fmt.Errorf("'%s' is not valid hex: %w", pkh, err) - } - copy(pk[:], b) - - if _, err := schnorr.ParsePubKey(pk[:]); err != nil { - return pk, fmt.Errorf("'%s' is not a valid pubkey", pkh) - } - return pk, nil -} - -func PubKeyFromHexCheap(pkh string) (PubKey, error) { - pk := PubKey{} - if len(pkh) != 64 { - return pk, fmt.Errorf("pubkey should be 64-char hex, got '%s'", pkh) - } - b, err := hex.DecodeString(pkh) - if err != nil { - return pk, fmt.Errorf("'%s' is not valid hex: %w", pkh, err) - } - copy(pk[:], b) - - return pk, nil -} - -func MustPubKeyFromHex(pkh string) PubKey { - pk, err := PubKeyFromHexCheap(pkh) - if err != nil { - panic(err) - } - return pk -} - -func ContainsPubKey(haystack []PubKey, needle PubKey) bool { - for _, cand := range haystack { - if cand == needle { - return true - } - } - return false -} diff --git a/nip05/nip05.go b/nip05/nip05.go index a4e1f998..5316efe1 100644 --- a/nip05/nip05.go +++ b/nip05/nip05.go @@ -57,12 +57,6 @@ func QueryIdentifier(ctx context.Context, fullname string) (*nostr.ProfilePointe }, nil } -var httpClient = &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - }, -} - func Fetch(ctx context.Context, fullname string) (resp WellKnownResponse, name string, err error) { name, domain, err := ParseIdentifier(fullname) if err != nil { diff --git a/nip05/util.go b/nip05/util.go new file mode 100644 index 00000000..0fc2aebb --- /dev/null +++ b/nip05/util.go @@ -0,0 +1,11 @@ +//go:build !tinygo + +package nip05 + +import "net/http" + +var httpClient = &http.Client{ + CheckRedirect: func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + }, +} diff --git a/nip05/util_tinygo.go b/nip05/util_tinygo.go new file mode 100644 index 00000000..9d8a9483 --- /dev/null +++ b/nip05/util_tinygo.go @@ -0,0 +1,7 @@ +//go:build tinygo + +package nip05 + +import "net/http" + +var httpClient = &http.Client{} diff --git a/types.go b/types.go index 54d37d07..2a4111f6 100644 --- a/types.go +++ b/types.go @@ -1,5 +1,3 @@ -//go:build !tinygo - package nostr import ( diff --git a/types_tinygo.go b/types_tinygo.go deleted file mode 100644 index 44adcf91..00000000 --- a/types_tinygo.go +++ /dev/null @@ -1,80 +0,0 @@ -//go:build tinygo - -package nostr - -import ( - "encoding/hex" - stdjson "encoding/json" - "fmt" -) - -// RelayEvent represents an event received from a specific relay. -type RelayEvent struct { - Event - Relay *Relay -} - -var ZeroID = ID{} - -// ID represents an event id -type ID [32]byte - -var ( - _ stdjson.Marshaler = ID{} - _ stdjson.Unmarshaler = (*ID)(nil) -) - -func (id ID) String() string { return "id::" + id.Hex() } -func (id ID) Hex() string { return hex.EncodeToString(id[:]) } - -func (id ID) MarshalJSON() ([]byte, error) { - return stdjson.Marshal(id.Hex()) -} - -func (id *ID) UnmarshalJSON(buf []byte) error { - var s string - if err := stdjson.Unmarshal(buf, &s); err != nil { - return err - } - if len(s) != 64 { - return fmt.Errorf("must be a hex string of 64 characters") - } - b, err := hex.DecodeString(s) - if err != nil { - return err - } - copy(id[:], b) - return nil -} - -func IDFromHex(idh string) (ID, error) { - id := ID{} - - if len(idh) != 64 { - return id, fmt.Errorf("pubkey should be 64-char hex, got '%s'", idh) - } - b, err := hex.DecodeString(idh) - if err != nil { - return id, fmt.Errorf("'%s' is not valid hex: %w", idh, err) - } - copy(id[:], b) - - return id, nil -} - -func MustIDFromHex(idh string) ID { - id, err := IDFromHex(idh) - if err != nil { - panic(err) - } - return id -} - -func ContainsID(haystack []ID, needle ID) bool { - for _, cand := range haystack { - if cand == needle { - return true - } - } - return false -} diff --git a/utils.go b/utils.go index 638d44ed..e8bea0a7 100644 --- a/utils.go +++ b/utils.go @@ -1,5 +1,3 @@ -//go:build !tinygo - package nostr import ( diff --git a/utils_tinygo.go b/utils_tinygo.go deleted file mode 100644 index 975539df..00000000 --- a/utils_tinygo.go +++ /dev/null @@ -1,73 +0,0 @@ -//go:build tinygo - -package nostr - -import ( - "bytes" - "cmp" - "encoding/hex" - "net/url" - "slices" -) - -// IsValidRelayURL checks if a URL is a valid relay URL (ws:// or wss://). -func IsValidRelayURL(u string) bool { - parsed, err := url.Parse(u) - if err != nil { - return false - } - if parsed.Scheme != "wss" && parsed.Scheme != "ws" { - return false - } - return true -} - -// HexEncodeToString encodes src into a hex string. -func HexEncodeToString(src []byte) string { - return hex.EncodeToString(src) -} - -// HexDecodeString decodes a hex string into bytes. -func HexDecodeString(s string) ([]byte, error) { - return hex.DecodeString(s) -} - -// IsValid32ByteHex checks if a string is a valid 32-byte hex string. -func IsValid32ByteHex(thing string) bool { - if !isLowerHex(thing) { - return false - } - if len(thing) != 64 { - return false - } - _, err := HexDecodeString(thing) - return err == nil -} - -// CompareEvent is meant to to be used with slices.Sort -func CompareEvent(a, b Event) int { - if a.CreatedAt == b.CreatedAt { - return bytes.Compare(a.ID[:], b.ID[:]) - } - return cmp.Compare(a.CreatedAt, b.CreatedAt) -} - -// CompareEventReverse is meant to to be used with slices.Sort -func CompareEventReverse(b, a Event) int { - if a.CreatedAt == b.CreatedAt { - return bytes.Compare(a.ID[:], b.ID[:]) - } - return cmp.Compare(a.CreatedAt, b.CreatedAt) -} - -// AppendUnique adds items to an array only if they don't already exist in the array. -// Returns the modified array. -func AppendUnique[I comparable](arr []I, item ...I) []I { - for _, item := range item { - if slices.Contains(arr, item) { - return arr - } - arr = append(arr, item) - } - return arr -} From 78b51ec144db03cd88c69c8641c2dd6854b5ea06 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Wed, 3 Dec 2025 00:52:44 +0900 Subject: [PATCH 06/24] phase 5: support sdk/cache/memory --- nip05/nip05.go | 6 ++ nip05/util.go | 11 --- nip05/util_tinygo.go | 7 -- .../memory/{cache.go => cache_ristretto.go} | 2 + sdk/cache/memory/cache_test.go | 78 ++++++++++++++++ sdk/cache/memory/cache_tinygo.go | 89 +++++++++++++++++++ 6 files changed, 175 insertions(+), 18 deletions(-) delete mode 100644 nip05/util.go delete mode 100644 nip05/util_tinygo.go rename sdk/cache/memory/{cache.go => cache_ristretto.go} (97%) create mode 100644 sdk/cache/memory/cache_test.go create mode 100644 sdk/cache/memory/cache_tinygo.go diff --git a/nip05/nip05.go b/nip05/nip05.go index 5316efe1..a4e1f998 100644 --- a/nip05/nip05.go +++ b/nip05/nip05.go @@ -57,6 +57,12 @@ func QueryIdentifier(ctx context.Context, fullname string) (*nostr.ProfilePointe }, nil } +var httpClient = &http.Client{ + CheckRedirect: func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + }, +} + func Fetch(ctx context.Context, fullname string) (resp WellKnownResponse, name string, err error) { name, domain, err := ParseIdentifier(fullname) if err != nil { diff --git a/nip05/util.go b/nip05/util.go deleted file mode 100644 index 0fc2aebb..00000000 --- a/nip05/util.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !tinygo - -package nip05 - -import "net/http" - -var httpClient = &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - }, -} diff --git a/nip05/util_tinygo.go b/nip05/util_tinygo.go deleted file mode 100644 index 9d8a9483..00000000 --- a/nip05/util_tinygo.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build tinygo - -package nip05 - -import "net/http" - -var httpClient = &http.Client{} 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 +} From 43371ac1eedbc5b31878a6aa9bfb59bcbc07ffc4 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Wed, 3 Dec 2025 03:12:33 +0900 Subject: [PATCH 07/24] phase 6: scceeded to run wasm_worker_testbed --- nip05/client_std.go | 11 ++++++++++ nip05/client_tinygo.go | 7 +++++++ nip05/json_std.go | 7 +++++++ nip05/json_tinygo.go | 28 ++++++++++++++++++++++++++ nip05/nip05.go | 9 +-------- nip05/nip05_test.go | 5 +++-- nip11/fetch.go | 3 +-- nip11/json_std.go | 7 +++++++ nip11/json_tinygo.go | 28 ++++++++++++++++++++++++++ nip46/client.go | 9 +++------ nip46/client_std.go | 25 +++++++++++++++++++++++ nip46/client_tinygo.go | 41 ++++++++++++++++++++++++++++++++++++++ nip46/dynamic-signer.go | 5 ++--- nip46/json_std.go | 7 +++++++ nip46/json_tinygo.go | 28 ++++++++++++++++++++++++++ nip46/nip46.go | 3 --- nip46/static-key-signer.go | 5 ++--- 17 files changed, 201 insertions(+), 27 deletions(-) create mode 100644 nip05/client_std.go create mode 100644 nip05/client_tinygo.go create mode 100644 nip05/json_std.go create mode 100644 nip05/json_tinygo.go create mode 100644 nip11/json_std.go create mode 100644 nip11/json_tinygo.go create mode 100644 nip46/client_std.go create mode 100644 nip46/client_tinygo.go create mode 100644 nip46/json_std.go create mode 100644 nip46/json_tinygo.go diff --git a/nip05/client_std.go b/nip05/client_std.go new file mode 100644 index 00000000..0fc2aebb --- /dev/null +++ b/nip05/client_std.go @@ -0,0 +1,11 @@ +//go:build !tinygo + +package nip05 + +import "net/http" + +var httpClient = &http.Client{ + CheckRedirect: func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + }, +} diff --git a/nip05/client_tinygo.go b/nip05/client_tinygo.go new file mode 100644 index 00000000..9d8a9483 --- /dev/null +++ b/nip05/client_tinygo.go @@ -0,0 +1,7 @@ +//go:build tinygo + +package nip05 + +import "net/http" + +var httpClient = &http.Client{} diff --git a/nip05/json_std.go b/nip05/json_std.go new file mode 100644 index 00000000..b749355c --- /dev/null +++ b/nip05/json_std.go @@ -0,0 +1,7 @@ +//go:build !tinygo + +package nip05 + +import jsoniter "github.com/json-iterator/go" + +var json = jsoniter.ConfigCompatibleWithStandardLibrary diff --git a/nip05/json_tinygo.go b/nip05/json_tinygo.go new file mode 100644 index 00000000..3c1e1dff --- /dev/null +++ b/nip05/json_tinygo.go @@ -0,0 +1,28 @@ +//go:build tinygo + +package nip05 + +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/nip05/nip05.go b/nip05/nip05.go index a4e1f998..a76fbe2f 100644 --- a/nip05/nip05.go +++ b/nip05/nip05.go @@ -8,7 +8,6 @@ import ( "strings" "fiatjaf.com/nostr" - jsoniter "github.com/json-iterator/go" ) var NIP05_REGEX = regexp.MustCompile(`^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$`) @@ -57,12 +56,6 @@ func QueryIdentifier(ctx context.Context, fullname string) (*nostr.ProfilePointe }, nil } -var httpClient = &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - }, -} - func Fetch(ctx context.Context, fullname string) (resp WellKnownResponse, name string, err error) { name, domain, err := ParseIdentifier(fullname) if err != nil { @@ -82,7 +75,7 @@ func Fetch(ctx context.Context, fullname string) (resp WellKnownResponse, name s defer res.Body.Close() var result WellKnownResponse - if err := jsoniter.NewDecoder(res.Body).Decode(&result); err != nil { + if err := json.NewDecoder(res.Body).Decode(&result); err != nil { return resp, name, fmt.Errorf("failed to decode json response: %w", err) } diff --git a/nip05/nip05_test.go b/nip05/nip05_test.go index ebf55fc7..3fa56a51 100644 --- a/nip05/nip05_test.go +++ b/nip05/nip05_test.go @@ -50,8 +50,9 @@ func TestQuery(t *testing.T) { if test.expectError { assert.Error(t, err, "expected error for input: %s", test.input) } else { - assert.NoError(t, err, "did not expect error for input: %s", test.input) - assert.Equal(t, nostr.MustPubKeyFromHex(test.expectedKey), pp.PublicKey, "for input: %s", test.input) + if assert.NoError(t, err, "did not expect error for input: %s", test.input) { + assert.Equal(t, nostr.MustPubKeyFromHex(test.expectedKey), pp.PublicKey, "for input: %s", test.input) + } } } } diff --git a/nip11/fetch.go b/nip11/fetch.go index 065913ab..e8373eeb 100644 --- a/nip11/fetch.go +++ b/nip11/fetch.go @@ -7,7 +7,6 @@ import ( "time" "fiatjaf.com/nostr" - jsoniter "github.com/json-iterator/go" ) // Fetch fetches the NIP-11 metadata for a relay. @@ -50,7 +49,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/json_std.go b/nip11/json_std.go new file mode 100644 index 00000000..f43186cc --- /dev/null +++ b/nip11/json_std.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 a762f86d..0160d42e 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 { @@ -22,7 +19,7 @@ type BunkerClient struct { target nostr.PubKey relays []string conversationKey [32]byte // nip44 - listeners *xsync.MapOf[string, chan Response] + listeners *listenersMap idPrefix string onAuth func(string) @@ -123,7 +120,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)), } @@ -202,7 +199,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 6beea764..dbec42a7 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) @@ -137,7 +136,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 @@ -155,7 +154,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 90e50086..1acda63a 100644 --- a/nip46/static-key-signer.go +++ b/nip46/static-key-signer.go @@ -8,7 +8,6 @@ import ( "fiatjaf.com/nostr" "fiatjaf.com/nostr/nip04" "fiatjaf.com/nostr/nip44" - "github.com/mailru/easyjson" ) var _ Signer = (*StaticKeySigner)(nil) @@ -97,7 +96,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 @@ -107,7 +106,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 { From c59c4672b985a2469f44e1f4e26cb2952fa38678 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Wed, 3 Dec 2025 04:35:21 +0900 Subject: [PATCH 08/24] phase 6: nip05 fetch, tinygo doesn't support net/http.Get for Wasm --- go.mod | 1 + go.sum | 2 ++ nip05/fetch.go | 35 +++++++++++++++++++++++++++++++++++ nip05/fetch_tinygo.go | 34 ++++++++++++++++++++++++++++++++++ nip05/nip05.go | 27 --------------------------- 5 files changed, 72 insertions(+), 27 deletions(-) create mode 100644 nip05/fetch.go create mode 100644 nip05/fetch_tinygo.go diff --git a/go.mod b/go.mod index 95864b56..9f1237f3 100644 --- a/go.mod +++ b/go.mod @@ -99,4 +99,5 @@ require ( github.com/x448/float16 v0.8.4 // indirect golang.org/x/sys v0.35.0 // indirect google.golang.org/protobuf v1.33.0 // indirect + marwan.io/wasm-fetch v0.1.0 // indirect ) diff --git a/go.sum b/go.sum index b4ececd4..e6b55f04 100644 --- a/go.sum +++ b/go.sum @@ -308,3 +308,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/nip05/fetch.go b/nip05/fetch.go new file mode 100644 index 00000000..0aff215f --- /dev/null +++ b/nip05/fetch.go @@ -0,0 +1,35 @@ +//go:build !tinygo + +package nip05 + +import ( + "context" + "fmt" + "net/http" +) + +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) + } + + req, err := http.NewRequestWithContext(ctx, "GET", + fmt.Sprintf("https://%s/.well-known/nostr.json?name=%s", domain, name), nil) + if err != nil { + return resp, name, fmt.Errorf("failed to create a request: %w", err) + } + + res, err := httpClient.Do(req) + if err != nil { + return resp, name, fmt.Errorf("request failed: %w", err) + } + defer res.Body.Close() + + var result WellKnownResponse + if err := json.NewDecoder(res.Body).Decode(&result); err != nil { + return resp, name, fmt.Errorf("failed to decode json response: %w", err) + } + + return result, name, nil +} diff --git a/nip05/fetch_tinygo.go b/nip05/fetch_tinygo.go new file mode 100644 index 00000000..10864811 --- /dev/null +++ b/nip05/fetch_tinygo.go @@ -0,0 +1,34 @@ +//go:build tinygo + +package nip05 + +import ( + "context" + "fmt" + + fetch "marwan.io/wasm-fetch" +) + +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 +} diff --git a/nip05/nip05.go b/nip05/nip05.go index a76fbe2f..a49ccbc4 100644 --- a/nip05/nip05.go +++ b/nip05/nip05.go @@ -3,7 +3,6 @@ package nip05 import ( "context" "fmt" - "net/http" "regexp" "strings" @@ -56,32 +55,6 @@ func QueryIdentifier(ctx context.Context, fullname string) (*nostr.ProfilePointe }, 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) - } - - req, err := http.NewRequestWithContext(ctx, "GET", - fmt.Sprintf("https://%s/.well-known/nostr.json?name=%s", domain, name), nil) - if err != nil { - return resp, name, fmt.Errorf("failed to create a request: %w", err) - } - - res, err := httpClient.Do(req) - if err != nil { - return resp, name, fmt.Errorf("request failed: %w", err) - } - defer res.Body.Close() - - var result WellKnownResponse - if err := json.NewDecoder(res.Body).Decode(&result); err != nil { - return resp, name, fmt.Errorf("failed to decode json response: %w", err) - } - - return result, name, nil -} - func NormalizeIdentifier(fullname string) string { if strings.HasPrefix(fullname, "_@") { return fullname[2:] From 99403ea3bad42ca5368c7754a0998e3b243be753 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Wed, 3 Dec 2025 15:18:21 +0900 Subject: [PATCH 09/24] phase 6: nip04 to nip57 pass --- nip11/fetch.go | 2 ++ nip11/fetch_tinygo.go | 56 ++++++++++++++++++++++++++++++++++ nip11/{json_std.go => json.go} | 0 3 files changed, 58 insertions(+) create mode 100644 nip11/fetch_tinygo.go rename nip11/{json_std.go => json.go} (100%) diff --git a/nip11/fetch.go b/nip11/fetch.go index e8373eeb..2a3de3ea 100644 --- a/nip11/fetch.go +++ b/nip11/fetch.go @@ -1,3 +1,5 @@ +//go:build !tinygo + package nip11 import ( 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_std.go b/nip11/json.go similarity index 100% rename from nip11/json_std.go rename to nip11/json.go From 22a49dc78a05999120cbf3c642101e68be6872d5 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Wed, 3 Dec 2025 15:23:47 +0900 Subject: [PATCH 10/24] phase 6: nip59 passes --- nip59/json_std.go | 12 ++++++++++++ nip59/json_tinygo.go | 13 +++++++++++++ nip59/nip59.go | 5 ++--- 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 nip59/json_std.go create mode 100644 nip59/json_tinygo.go 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) } From 337e995b895a2bea6345bb8326e4452ae5547b63 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Wed, 3 Dec 2025 16:12:35 +0900 Subject: [PATCH 11/24] phase 7: sdk passes --- go.mod | 20 ++++++++++---------- go.sum | 32 ++++++++++++++++---------------- nip77/envelopes.go | 10 ++++------ nip77/json_std.go | 25 +++++++++++++++++++++++++ nip77/json_tinygo.go | 23 +++++++++++++++++++++++ nip77/nip77.go | 12 ++++++++---- sdk/feeds_test.go | 2 ++ sdk/fetch_std.go | 31 +++++++++++++++++++++++++++++++ sdk/fetch_tinygo.go | 25 +++++++++++++++++++++++++ sdk/wot_test.go | 5 +++-- sdk/zap.go | 22 ++++++---------------- sdk/zap_test.go | 7 +++++++ 12 files changed, 160 insertions(+), 54 deletions(-) create mode 100644 nip77/json_std.go create mode 100644 nip77/json_tinygo.go create mode 100644 sdk/fetch_std.go create mode 100644 sdk/fetch_tinygo.go diff --git a/go.mod b/go.mod index 9f1237f3..4c4a791c 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,29 +28,31 @@ 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 ( 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 @@ -83,7 +84,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 @@ -97,7 +98,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 - marwan.io/wasm-fetch v0.1.0 // indirect ) diff --git a/go.sum b/go.sum index e6b55f04..dccba475 100644 --- a/go.sum +++ b/go.sum @@ -11,8 +11,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= @@ -156,8 +156,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= @@ -236,8 +236,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= @@ -248,8 +248,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= @@ -257,11 +257,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= @@ -275,13 +275,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= 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 599d62a6..b8ed2151 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, }) - }) + }() } go func() { 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) From 1b95b6d4876378898014978efbe45a211778f7ec Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Sat, 6 Dec 2025 03:50:01 -0300 Subject: [PATCH 12/24] grasp: pass request context to repoExists(). --- khatru/grasp/info.go | 2 +- khatru/grasp/read.go | 2 +- khatru/grasp/server.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/khatru/grasp/info.go b/khatru/grasp/info.go index a708e3a8..ff73711e 100644 --- a/khatru/grasp/info.go +++ b/khatru/grasp/info.go @@ -19,7 +19,7 @@ func (gs *GraspServer) handleInfoRefs( pubkey nostr.PubKey, repoName string, ) { - if !gs.repoExists(pubkey, repoName) { + if !gs.repoExists(r.Context(), pubkey, repoName) { w.Header().Set("content-type", "text/plain; charset=UTF-8") w.WriteHeader(404) fmt.Fprintf(w, "repository announcement event not found during info-refs\n") diff --git a/khatru/grasp/read.go b/khatru/grasp/read.go index 366197bc..78014d27 100644 --- a/khatru/grasp/read.go +++ b/khatru/grasp/read.go @@ -21,7 +21,7 @@ func (gs *GraspServer) handleGitUploadPack( repoPath := gs.getRepositoryPath(pubkey, repoName) // for upload-pack (pull), check if repository exists - if !gs.repoExists(pubkey, repoName) { + if !gs.repoExists(r.Context(), pubkey, repoName) { w.Header().Set("content-type", "text/plain; charset=UTF-8") w.WriteHeader(404) fmt.Fprintf(w, "repository announcement event not found during upload-pack\n") diff --git a/khatru/grasp/server.go b/khatru/grasp/server.go index d125373e..7ddc404a 100644 --- a/khatru/grasp/server.go +++ b/khatru/grasp/server.go @@ -53,7 +53,7 @@ func New(rl *khatru.Relay, repositoryDir string) *GraspServer { mux.HandleFunc("GET /{npub}/{repo}", func(w http.ResponseWriter, r *http.Request) { gs.handleGitRequest(w, r, base, func(w http.ResponseWriter, r *http.Request, pubkey nostr.PubKey, repoName string) { if r.URL.RawQuery == "" { - if gs.repoExists(pubkey, repoName) { + if gs.repoExists(r.Context(), pubkey, repoName) { gs.serveRepoPage(w, r, r.PathValue("npub"), repoName) } else { http.NotFound(w, r) From 00488b5a074b43a892337d68ec21433f391e8127 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Wed, 25 Feb 2026 18:13:47 +0900 Subject: [PATCH 13/24] merge upstream --- tinygotest | 2 ++ 1 file changed, 2 insertions(+) create mode 100755 tinygotest 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'` From cb6c9d94889eaf8ef1acf02007c9d4297dbe8d6f Mon Sep 17 00:00:00 2001 From: 1l0 Date: Mon, 2 Mar 2026 20:28:30 +0900 Subject: [PATCH 14/24] fix tinygo build --- envelopes_tinygo.go | 115 +++++++++++++++++++++++++-------- event_methods_tinygo.go | 99 ++++++++++++++++------------ filter_methods_tinygo.go | 88 ++++++++++++------------- go.mod | 2 +- go.sum | 4 +- relay.go | 2 +- relay_tinygo.go => relay_js.go | 2 +- 7 files changed, 193 insertions(+), 119 deletions(-) rename relay_tinygo.go => relay_js.go (99%) diff --git a/envelopes_tinygo.go b/envelopes_tinygo.go index 0be10a4d..2e8cb547 100644 --- a/envelopes_tinygo.go +++ b/envelopes_tinygo.go @@ -5,6 +5,7 @@ package nostr import ( "errors" "fmt" + "strconv" "strings" "github.com/tidwall/gjson" @@ -103,13 +104,19 @@ func (v *EventEnvelope) FromJSON(data string) error { } func (v EventEnvelope) MarshalJSON() ([]byte, error) { - // Manual marshaling to match the array structure ["EVENT", ...] - // We can use a temporary struct or build it manually. - // Building manually is safer to avoid reflection overhead if possible, but json.Marshal is fine. + var b []byte + b = append(b, `["EVENT",`...) if v.SubscriptionID != nil { - return json.Marshal([]interface{}{"EVENT", *v.SubscriptionID, v.Event}) + b = escapeString(b, *v.SubscriptionID) + b = append(b, ',') } - return json.Marshal([]interface{}{"EVENT", v.Event}) + 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. @@ -143,13 +150,19 @@ func (v *ReqEnvelope) FromJSON(data string) error { } func (v ReqEnvelope) MarshalJSON() ([]byte, error) { - data := make([]interface{}, 2+len(v.Filters)) - data[0] = "REQ" - data[1] = v.SubscriptionID - for i, f := range v.Filters { - data[2+i] = f + 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...) } - return json.Marshal(data) + b = append(b, ']') + return b, nil } // CountEnvelope represents a COUNT message. @@ -200,19 +213,28 @@ func (v *CountEnvelope) FromJSON(data string) error { } 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 { - res := struct { - Count *uint32 `json:"count"` - HLL string `json:"hll,omitempty"` - }{ - Count: v.Count, - } + b = append(b, `{"count":`...) + b = append(b, strconv.FormatUint(uint64(*v.Count), 10)...) if v.HyperLogLog != nil { - res.HLL = HexEncodeToString(v.HyperLogLog) + b = append(b, `,"hll":"`...) + b = append(b, HexEncodeToString(v.HyperLogLog)...) + b = append(b, '"') } - return json.Marshal([]interface{}{"COUNT", v.SubscriptionID, res}) + b = append(b, '}') + } else { + fb, err := v.Filter.MarshalJSON() + if err != nil { + return nil, err + } + b = append(b, fb...) } - return json.Marshal([]interface{}{"COUNT", v.SubscriptionID, v.Filter}) + b = append(b, ']') + return b, nil } // NoticeEnvelope represents a NOTICE message. @@ -235,7 +257,11 @@ func (v *NoticeEnvelope) FromJSON(data string) error { } func (v NoticeEnvelope) MarshalJSON() ([]byte, error) { - return json.Marshal([]interface{}{"NOTICE", string(v)}) + 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. @@ -258,7 +284,11 @@ func (v *EOSEEnvelope) FromJSON(data string) error { } func (v EOSEEnvelope) MarshalJSON() ([]byte, error) { - return json.Marshal([]interface{}{"EOSE", string(v)}) + var b []byte + b = append(b, `["EOSE",`...) + b = escapeString(b, string(v)) + b = append(b, ']') + return b, nil } // CloseEnvelope represents a CLOSE message. @@ -281,7 +311,11 @@ func (v *CloseEnvelope) FromJSON(data string) error { } func (v CloseEnvelope) MarshalJSON() ([]byte, error) { - return json.Marshal([]interface{}{"CLOSE", string(v)}) + var b []byte + b = append(b, `["CLOSE",`...) + b = escapeString(b, string(v)) + b = append(b, ']') + return b, nil } // ClosedEnvelope represents a CLOSED message. @@ -310,7 +344,13 @@ func (v *ClosedEnvelope) FromJSON(data string) error { } func (v ClosedEnvelope) MarshalJSON() ([]byte, error) { - return json.Marshal([]interface{}{"CLOSED", v.SubscriptionID, v.Reason}) + 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. @@ -344,7 +384,19 @@ func (v *OKEnvelope) FromJSON(data string) error { } func (v OKEnvelope) MarshalJSON() ([]byte, error) { - return json.Marshal([]interface{}{"OK", HexEncodeToString(v.EventID[:]), v.OK, v.Reason}) + 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. @@ -375,8 +427,17 @@ func (v *AuthEnvelope) FromJSON(data string) error { } func (v AuthEnvelope) MarshalJSON() ([]byte, error) { + var b []byte + b = append(b, `["AUTH",`...) if v.Challenge != nil { - return json.Marshal([]interface{}{"AUTH", *v.Challenge}) + b = escapeString(b, *v.Challenge) + } else { + eb, err := v.Event.MarshalJSON() + if err != nil { + return nil, err + } + b = append(b, eb...) } - return json.Marshal([]interface{}{"AUTH", v.Event}) + b = append(b, ']') + return b, nil } diff --git a/event_methods_tinygo.go b/event_methods_tinygo.go index 1949fa8e..99578964 100644 --- a/event_methods_tinygo.go +++ b/event_methods_tinygo.go @@ -5,6 +5,8 @@ package nostr import ( "encoding/hex" "strconv" + + "github.com/tidwall/gjson" ) func (evt Event) String() string { @@ -13,57 +15,72 @@ func (evt Event) String() string { } func (evt Event) MarshalJSON() ([]byte, error) { - type EventJSON struct { - Kind Kind `json:"kind"` - ID ID `json:"id"` - PubKey PubKey `json:"pubkey"` - CreatedAt Timestamp `json:"created_at"` - Tags Tags `json:"tags"` - Content string `json:"content"` - Sig string `json:"sig"` - } - - ej := EventJSON{ - Kind: evt.Kind, - ID: evt.ID, - PubKey: evt.PubKey, - CreatedAt: evt.CreatedAt, - Tags: evt.Tags, - Content: evt.Content, - Sig: hex.EncodeToString(evt.Sig[:]), + 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 json.Marshal(ej) + return b, nil } func (evt *Event) UnmarshalJSON(data []byte) error { - type EventJSON struct { - Kind Kind `json:"kind"` - ID ID `json:"id"` - PubKey PubKey `json:"pubkey"` - CreatedAt Timestamp `json:"created_at"` - Tags Tags `json:"tags"` - Content string `json:"content"` - Sig string `json:"sig"` + 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) } - var ej EventJSON - if err := json.Unmarshal(data, &ej); err != nil { - return err + pubkeyHex := r.Get("pubkey").String() + if len(pubkeyHex) == 64 { + b, _ := hex.DecodeString(pubkeyHex) + copy(evt.PubKey[:], b) } - evt.Kind = ej.Kind - evt.ID = ej.ID - evt.PubKey = ej.PubKey - evt.CreatedAt = ej.CreatedAt - evt.Tags = ej.Tags - evt.Content = ej.Content - - if len(ej.Sig) == 128 { - b, err := hex.DecodeString(ej.Sig) - if err != nil { - return err + 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) } diff --git a/filter_methods_tinygo.go b/filter_methods_tinygo.go index 12cc205c..b75f4868 100644 --- a/filter_methods_tinygo.go +++ b/filter_methods_tinygo.go @@ -6,10 +6,12 @@ import ( "encoding/hex" stdjson "encoding/json" "strconv" + + "github.com/tidwall/gjson" ) func (ef Filter) String() string { - j, _ := json.Marshal(ef) + j, _ := stdjson.Marshal(ef) return string(j) } @@ -101,8 +103,7 @@ func (ef Filter) MarshalJSON() ([]byte, error) { } first = false b = append(b, `"search":`...) - sb, _ := json.Marshal(ef.Search) - b = append(b, sb...) + b = escapeString(b, ef.Search) } for key, values := range ef.Tags { @@ -112,9 +113,14 @@ func (ef Filter) MarshalJSON() ([]byte, error) { first = false b = append(b, `"#`...) b = append(b, key...) - b = append(b, `":`...) - vb, _ := json.Marshal(values) - b = append(b, vb...) + b = append(b, `":[`...) + for i, v := range values { + if i > 0 { + b = append(b, ',') + } + b = escapeString(b, v) + } + b = append(b, ']') } b = append(b, '}') @@ -122,74 +128,64 @@ func (ef Filter) MarshalJSON() ([]byte, error) { } func (ef *Filter) UnmarshalJSON(data []byte) error { - var raw map[string]stdjson.RawMessage - if err := stdjson.Unmarshal(data, &raw); err != nil { - return err - } + r := gjson.ParseBytes(data) - for key, val := range raw { - switch key { + r.ForEach(func(key, val gjson.Result) bool { + switch key.String() { case "ids": - var ids []string - if err := stdjson.Unmarshal(val, &ids); err != nil { - return err - } - for _, s := range ids { + idsResult := val.Array() + for _, s := range idsResult { var id ID - if len(s) == 64 { - b, _ := hex.DecodeString(s) + hexStr := s.String() + if len(hexStr) == 64 { + b, _ := hex.DecodeString(hexStr) copy(id[:], b) } ef.IDs = append(ef.IDs, id) } case "kinds": - if err := stdjson.Unmarshal(val, &ef.Kinds); err != nil { - return err + kindsResult := val.Array() + for _, k := range kindsResult { + ef.Kinds = append(ef.Kinds, Kind(k.Int())) } case "authors": - var authors []string - if err := stdjson.Unmarshal(val, &authors); err != nil { - return err - } - for _, s := range authors { + authorsResult := val.Array() + for _, s := range authorsResult { var pk PubKey - if len(s) == 64 { - b, _ := hex.DecodeString(s) + hexStr := s.String() + if len(hexStr) == 64 { + b, _ := hex.DecodeString(hexStr) copy(pk[:], b) } ef.Authors = append(ef.Authors, pk) } case "since": - if err := stdjson.Unmarshal(val, &ef.Since); err != nil { - return err - } + ef.Since = Timestamp(val.Int()) case "until": - if err := stdjson.Unmarshal(val, &ef.Until); err != nil { - return err - } + ef.Until = Timestamp(val.Int()) case "limit": - if err := stdjson.Unmarshal(val, &ef.Limit); err != nil { - return err - } + ef.Limit = int(val.Int()) if ef.Limit == 0 { ef.LimitZero = true } case "search": - if err := stdjson.Unmarshal(val, &ef.Search); err != nil { - return err - } + ef.Search = val.String() default: - if len(key) > 1 && key[0] == '#' { + k := key.String() + if len(k) > 1 && k[0] == '#' { if ef.Tags == nil { ef.Tags = make(TagMap) } - var values []string - if err := stdjson.Unmarshal(val, &values); err != nil { - return err + valuesResult := val.Array() + values := make([]string, len(valuesResult)) + for i, v := range valuesResult { + values[i] = v.String() } - ef.Tags[key[1:]] = values + ef.Tags[k[1:]] = values } } - } + return true + }) + return nil } diff --git a/go.mod b/go.mod index b8ddef56..df132bfb 100644 --- a/go.mod +++ b/go.mod @@ -38,7 +38,7 @@ require ( ) require ( - fiatjaf.com/lib v0.3.5 + 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 diff --git a/go.sum b/go.sum index bd6e52c6..8bd5b65d 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -fiatjaf.com/lib v0.3.5 h1:9kSuAOqHuhShH5sMeLJwceojUCxQ6SS7zrfC2EnJ0+E= -fiatjaf.com/lib v0.3.5/go.mod h1:UlHaZvPHj25PtKLh9GjZkUHRmQ2xZ8Jkoa4VRaLeeQ8= +fiatjaf.com/lib v0.3.6 h1:GRZNSxHI2EWdjSKVuzaT+c0aifLDtS16SzkeJaHyJfY= +fiatjaf.com/lib v0.3.6/go.mod h1:UlHaZvPHj25PtKLh9GjZkUHRmQ2xZ8Jkoa4VRaLeeQ8= github.com/FactomProject/basen v0.0.0-20150613233007-fe3947df716e h1:ahyvB3q25YnZWly5Gq1ekg6jcmWaGj/vG/MhF4aisoc= github.com/FactomProject/basen v0.0.0-20150613233007-fe3947df716e/go.mod h1:kGUqhHd//musdITWjFvNTHn90WG9bMLBEPQZ17Cmlpw= github.com/FactomProject/btcutilecc v0.0.0-20130527213604-d3a63a5752ec h1:1Qb69mGp/UtRPn422BH4/Y4Q3SLUrD9KHuDkm8iodFc= diff --git a/relay.go b/relay.go index 513444cf..ce6c422c 100644 --- a/relay.go +++ b/relay.go @@ -1,4 +1,4 @@ -//go:build !tinygo +//go:build !js package nostr diff --git a/relay_tinygo.go b/relay_js.go similarity index 99% rename from relay_tinygo.go rename to relay_js.go index 75c9a8f8..2c4c55a5 100644 --- a/relay_tinygo.go +++ b/relay_js.go @@ -1,4 +1,4 @@ -//go:build tinygo +//go:build js package nostr From 7cd507694f6775ccd84a3fc5d6bb436549e76db8 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Thu, 5 Mar 2026 00:06:09 +0900 Subject: [PATCH 15/24] fix relay --- relay_js.go | 234 +++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 167 insertions(+), 67 deletions(-) diff --git a/relay_js.go b/relay_js.go index 2c4c55a5..22794679 100644 --- a/relay_js.go +++ b/relay_js.go @@ -18,21 +18,37 @@ import ( "sync/atomic" "time" + "fiatjaf.com/lib/channelmutex" ws "github.com/coder/websocket" ) -var ErrDisconnected = errors.New("") +var subscriptionIDCounter atomic.Int64 + +var ( + ErrDisconnected = errors.New("") + ErrPingFailed = errors.New("") +) type writeRequest struct { msg []byte answer chan error } -var subscriptionIDCounter atomic.Int64 +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 { - closeMutex sync.Mutex + closeMutex *channelmutex.Mutex URL string requestHeader http.Header // e.g. for origin header @@ -49,9 +65,10 @@ type Relay struct { connectionContext context.Context // will be canceled when the connection closes connectionContextCancel context.CancelCauseFunc - challenge string // NIP-42 challenge, we only keep the last - noticeHandler func(string) // NIP-01 NOTICEs - customHandler func(string) // nonstandard unparseable messages + 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 @@ -74,8 +91,48 @@ func NewRelay(ctx context.Context, url string, opts RelayOptions) *Relay { requestHeader: opts.RequestHeader, customHandler: opts.CustomHandler, noticeHandler: opts.NoticeHandler, + authHandler: opts.AuthHandler, + closeMutex: channelmutex.New(), + closed: &atomic.Bool{}, + closedNotify: make(chan struct{}), } + go func() { + <-ctx.Done() + + if wasClosed := r.closed.Swap(true); wasClosed { + return + } + + r.closeMutex.Invalidate() + + 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) + } + if r.closeMutex != nil { + r.closeMutex.Lock() + if r.closedNotify != nil { + close(r.closedNotify) + } + if r.writeQueue != nil { + close(r.writeQueue) + } + r.conn = nil + r.closeMutex.Unlock() + } + }() + return r } @@ -92,9 +149,12 @@ func RelayConnect(ctx context.Context, url string, opts RelayOptions) (*Relay, e } 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(notice string) + 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. @@ -114,7 +174,18 @@ func (r *Relay) String() string { 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 { return !r.closed.Load() } +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. @@ -129,7 +200,11 @@ func (r *Relay) Connect(ctx context.Context) error { // ConnectWithTLS is like Connect(), but takes a special tls.Config if you need that. func (r *Relay) ConnectWithTLS(ctx context.Context, tlsConfig *tls.Config) error { - return r.Connect(ctx) + return r.ConnectWithClient(ctx, &http.Client{ + Transport: &http.Transport{ + TLSClientConfig: tlsConfig, + }, + }) } // ConnectWithClient is like Connect(), but takes a special *http.Client if you need that. @@ -137,6 +212,9 @@ func (r *Relay) ConnectWithClient(ctx context.Context, client *http.Client) erro 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) @@ -158,18 +236,25 @@ func (r *Relay) newConnection(ctx context.Context, httpClient *http.Client) erro dialCtx, _ = context.WithTimeoutCause(ctx, 7*time.Second, errors.New("connection took too long")) } - dialOpts := &ws.DialOptions{} + // 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, dialOpts) + c, _, err := ws.Dial(dialCtx, r.URL, nil) if err != nil { return err } c.SetReadLimit(2 << 24) // 33MB - // this will tell if the connection is closed - - // ping every 29 seconds - ticker := time.NewTicker(29 * time.Second) + // ping every 19 seconds + ticker := time.NewTicker(19 * time.Second) // main websocket loop readQueue := make(chan string) @@ -179,21 +264,20 @@ func (r *Relay) newConnection(ctx context.Context, httpClient *http.Client) erro r.closed = &atomic.Bool{} r.closedNotify = make(chan struct{}) + connCtx := r.connectionContext go func() { pingAttempt := 0 for { select { - case <-ctx.Done(): - r.closeConnection(ws.StatusNormalClosure, "") - debugLogf("{%s} closing!, context done: '%s'\n", r.URL, context.Cause(ctx)) + case <-connCtx.Done(): return case <-r.closedNotify: return case <-ticker.C: debugLogf("{%s} pinging\n", r.URL) - ctx, cancel := context.WithTimeoutCause(ctx, time.Millisecond*800, errors.New("ping took too long")) - err := c.Ping(ctx) + pingCtx, cancel := context.WithTimeoutCause(connCtx, time.Millisecond*800, errors.New("ping took too long")) + err := c.Ping(pingCtx) cancel() if err != nil { @@ -202,10 +286,7 @@ func (r *Relay) newConnection(ctx context.Context, httpClient *http.Client) erro if pingAttempt >= 3 { debugLogf("{%s} error writing ping after multiple attempts; closing websocket", r.URL) - err = r.Close() // this should trigger a context cancelation - if err != nil { - debugLogf("{%s} failed to close relay: %v", r.URL, err) - } + _ = r.close(ErrPingFailed) } continue @@ -216,12 +297,12 @@ func (r *Relay) newConnection(ctx context.Context, httpClient *http.Client) erro pingAttempt = 0 case wr := <-r.writeQueue: debugLogf("{%s} sending '%v'\n", r.URL, string(wr.msg)) - ctx, cancel := context.WithTimeoutCause(ctx, time.Second*10, errors.New("write took too long")) - err := c.Write(ctx, ws.MessageText, 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.closeConnection(ws.StatusAbnormalClosure, "write failed") + _ = r.close(closeCause{code: ws.StatusAbnormalClosure, reason: "write failed"}) if wr.answer != nil { wr.answer <- err } @@ -244,19 +325,20 @@ func (r *Relay) newConnection(ctx context.Context, httpClient *http.Client) erro for { buf.Reset() - _, reader, err := c.Reader(ctx) + _, reader, err := c.Reader(connCtx) if err != nil { debugLogf("{%s} closing!, reader failure: '%s'\n", r.URL, err) - r.closeConnection(ws.StatusAbnormalClosure, "failed to get reader") + _ = 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.closeConnection(ws.StatusAbnormalClosure, "failed to read") + _ = r.close(closeCause{code: ws.StatusAbnormalClosure, reason: "failed to read"}) return } - readQueue <- string(buf.Bytes()) + msg := string(buf.Bytes()) + readQueue <- msg } }() @@ -264,16 +346,6 @@ func (r *Relay) newConnection(ctx context.Context, httpClient *http.Client) erro } func (r *Relay) closeConnection(code ws.StatusCode, reason string) { - wasClosed := r.closed.Swap(true) - if !wasClosed { - r.conn.Close(code, reason) - r.connectionContextCancel(fmt.Errorf("doClose(): %s", reason)) - r.closeMutex.Lock() - close(r.closedNotify) - close(r.writeQueue) - r.conn = nil - r.closeMutex.Unlock() - } } func (r *Relay) handleMessage(message string) { @@ -308,7 +380,7 @@ func (r *Relay) handleMessage(message string) { case *NoticeEnvelope: // see WithNoticeHandler if r.noticeHandler != nil { - r.noticeHandler(string(*env)) + r.noticeHandler(r, string(*env)) } else { log.Printf("NOTICE from %s: '%s'\n", r.URL, string(*env)) } @@ -317,6 +389,13 @@ func (r *Relay) handleMessage(message string) { 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 { @@ -365,14 +444,16 @@ func (r *Relay) handleMessage(message string) { // Write queues an arbitrary message to be sent to the relay. func (r *Relay) Write(msg []byte) { - r.closeMutex.Lock() - defer r.closeMutex.Unlock() select { + case <-r.closeMutex.C(): // this locks the mutex case <-r.closedNotify: return - default: + case <-r.connectionContext.Done(): + return } + defer r.closeMutex.Unlock() + select { case <-r.connectionContext.Done(): case r.writeQueue <- writeRequest{msg: msg, answer: nil}: @@ -382,13 +463,21 @@ func (r *Relay) Write(msg []byte) { // 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) - r.closeMutex.Lock() - defer r.closeMutex.Unlock() + select { + case <-r.closeMutex.C(): // this locks the channel/mutex case <-r.closedNotify: return fmt.Errorf("failed to write to %s: ", r.URL) - default: + case <-r.connectionContext.Done(): + return fmt.Errorf("failed to write to %s: ", r.URL) } + + defer r.closeMutex.Unlock() + + 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)) @@ -502,21 +591,23 @@ func (r *Relay) publish(ctx context.Context, id ID, env Envelope) error { // 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) { - sub := r.PrepareSubscription(ctx, filter, opts) - - if r.conn == nil { - return nil, fmt.Errorf("not connected to %s", r.URL) + 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() { select { case <-r.closedNotify: - sub.unsub(ErrDisconnected) + sub.cancel(ErrDisconnected) case <-ctx.Done(): + sub.cancel(nil) } }() @@ -541,6 +632,7 @@ func (r *Relay) PrepareSubscription(ctx context.Context, filter Filter, opts Sub ClosedReason: make(chan string, 1), Filter: filter, match: filter.Matches, + eoseTimedOut: make(chan struct{}), } sub.checkDuplicate = opts.CheckDuplicate @@ -565,12 +657,32 @@ func (r *Relay) PrepareSubscription(ctx context.Context, filter Filter, opts Sub go func() { time.Sleep(opts.MaxWaitForEOSE) + close(sub.eoseTimedOut) sub.dispatchEose() }() } // start handling events, eose, unsub etc: - go sub.start() + 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 } @@ -626,7 +738,7 @@ func (r *Relay) countInternal(ctx context.Context, filter Filter, opts Subscript return CountEnvelope{}, err } - defer sub.unsub(errors.New("countInternal() ended")) + defer sub.cancel(errors.New("countInternal() ended")) if _, ok := ctx.Deadline(); !ok { // if no timeout is set, force it to 7 seconds @@ -651,19 +763,7 @@ func (r *Relay) Close() error { } func (r *Relay) close(reason error) error { - r.closeMutex.Lock() - defer r.closeMutex.Unlock() - - if r.connectionContextCancel == nil { - return fmt.Errorf("relay already closed") - } - - if r.conn == nil { - return fmt.Errorf("relay not connected") - } - r.connectionContextCancel(reason) - return nil } From 8d93f8c49d07e245733e12fc92df4706c1db074b Mon Sep 17 00:00:00 2001 From: 1l0 Date: Mon, 9 Mar 2026 20:27:24 +0900 Subject: [PATCH 16/24] ignore tls config --- relay_js.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/relay_js.go b/relay_js.go index 22794679..92caaa62 100644 --- a/relay_js.go +++ b/relay_js.go @@ -199,11 +199,9 @@ func (r *Relay) Connect(ctx context.Context) error { } // ConnectWithTLS is like Connect(), but takes a special tls.Config if you need that. -func (r *Relay) ConnectWithTLS(ctx context.Context, tlsConfig *tls.Config) error { +func (r *Relay) ConnectWithTLS(ctx context.Context, _ *tls.Config) error { return r.ConnectWithClient(ctx, &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: tlsConfig, - }, + Transport: &http.Transport{}, }) } From ffe7ec46f8ec7859af03d8d1c8854906b3e52e13 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Mon, 16 Mar 2026 00:03:17 +0900 Subject: [PATCH 17/24] ignore some --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) 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 From a785d95af07fdb4360a1aa76df49e7c6eb47035c Mon Sep 17 00:00:00 2001 From: 1l0 Date: Mon, 16 Mar 2026 00:14:28 +0900 Subject: [PATCH 18/24] actions --- .github/workflows/test.yml | 161 +++++++++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..dbb85ff0 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,161 @@ +name: Test + +on: + push: + branches: ["**"] + pull_request: + branches: ["**"] + +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: | + # すべてのパッケージを取得し schema を除外 + PKGS=$(go list ./... | grep -v 'fiatjaf.com/nostr/schema') + 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: Set up wasmtime (Go wasm runner) + run: | + curl -fsSL https://wasmtime.dev/install.sh | bash + echo "$HOME/.wasmtime/bin" >> $GITHUB_PATH + + - name: Download go_js_wasm_exec + run: | + GOROOT=$(go env GOROOT) + cp "$GOROOT/misc/wasm/go_wasip1_wasm_exec" /usr/local/bin/go_wasip1_wasm_exec || true + # Use the standard wasm_exec runner + echo "GOARCH=wasm" >> $GITHUB_ENV + echo "GOOS=js" >> $GITHUB_ENV + + - name: Install Node.js (for GOOS=js wasm tests) + uses: actions/setup-node@v4 + with: + node-version: "22" + + - name: Run GOOS=js 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" + ) + GOROOT=$(go env GOROOT) + export PATH="$GOROOT/misc/wasm:$PATH" + GOOS=js GOARCH=wasm go test -short "${WASM_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.37.0/tinygo_0.37.0_amd64.deb + sudo dpkg -i tinygo_0.37.0_amd64.deb + + - name: Install Node.js (for TinyGo wasm tests) + uses: actions/setup-node@v4 + with: + node-version: "22" + + - 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 "${WASM_PKGS[@]}" From 2d1369df1c27689d41a6595449d0b165836eed15 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Mon, 16 Mar 2026 00:21:24 +0900 Subject: [PATCH 19/24] more skip --- .github/workflows/test.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index dbb85ff0..aa34fcdb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -20,8 +20,12 @@ jobs: - name: Run tests run: | - # すべてのパッケージを取得し schema を除外 - PKGS=$(go list ./... | grep -v 'fiatjaf.com/nostr/schema') + # すべてのパッケージを取得し除外 + PKGS=$(go list ./... | grep -v \ + -e 'fiatjaf.com/nostr/schema' \ + -e 'fiatjaf.com/nostr/nip29' \ + -e 'fiatjaf.com/nostr/khatru' \ + -e 'fiatjaf.com/nostr/sdk') go test $PKGS test-wasm-go: From af625ed20374ba836994dde81a61b82e46373805 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Mon, 16 Mar 2026 00:33:46 +0900 Subject: [PATCH 20/24] - --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index aa34fcdb..51d13915 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -162,4 +162,4 @@ jobs: "./nip92" "./nip94" ) - GOOS=js GOARCH=wasm tinygo test -short "${WASM_PKGS[@]}" + GOOS=wasip1 GOARCH=wasm tinygo test -short "${WASM_PKGS[@]}" From bb0a953d51b0b7ccf0e4750985b2914d845a202e Mon Sep 17 00:00:00 2001 From: 1l0 Date: Mon, 16 Mar 2026 00:48:55 +0900 Subject: [PATCH 21/24] relay_js: follow upstream --- .github/workflows/test.yml | 35 ++++++++------------ relay_js.go | 66 +++++++------------------------------- 2 files changed, 25 insertions(+), 76 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 51d13915..ceb96ab9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -39,23 +39,13 @@ jobs: with: go-version-file: go.mod - - name: Set up wasmtime (Go wasm runner) - run: | - curl -fsSL https://wasmtime.dev/install.sh | bash - echo "$HOME/.wasmtime/bin" >> $GITHUB_PATH + - name: Install Chrome + uses: browser-actions/setup-chrome@latest - - name: Download go_js_wasm_exec + - name: Install wasmbrowsertest run: | - GOROOT=$(go env GOROOT) - cp "$GOROOT/misc/wasm/go_wasip1_wasm_exec" /usr/local/bin/go_wasip1_wasm_exec || true - # Use the standard wasm_exec runner - echo "GOARCH=wasm" >> $GITHUB_ENV - echo "GOOS=js" >> $GITHUB_ENV - - - name: Install Node.js (for GOOS=js wasm tests) - uses: actions/setup-node@v4 - with: - node-version: "22" + 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: | @@ -97,8 +87,6 @@ jobs: "./nip92" "./nip94" ) - GOROOT=$(go env GOROOT) - export PATH="$GOROOT/misc/wasm:$PATH" GOOS=js GOARCH=wasm go test -short "${WASM_PKGS[@]}" test-wasm-tinygo: @@ -117,10 +105,13 @@ jobs: wget -q https://github.com/tinygo-org/tinygo/releases/download/v0.37.0/tinygo_0.37.0_amd64.deb sudo dpkg -i tinygo_0.37.0_amd64.deb - - name: Install Node.js (for TinyGo wasm tests) - uses: actions/setup-node@v4 - with: - node-version: "22" + - name: Install Chrome + uses: browser-actions/setup-chrome@latest + + - 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: | @@ -162,4 +153,4 @@ jobs: "./nip92" "./nip94" ) - GOOS=wasip1 GOARCH=wasm tinygo test -short "${WASM_PKGS[@]}" + GOOS=js GOARCH=wasm tinygo test -short "${WASM_PKGS[@]}" diff --git a/relay_js.go b/relay_js.go index 92caaa62..5d414659 100644 --- a/relay_js.go +++ b/relay_js.go @@ -18,7 +18,6 @@ import ( "sync/atomic" "time" - "fiatjaf.com/lib/channelmutex" ws "github.com/coder/websocket" ) @@ -48,16 +47,13 @@ func (c closeCause) Error() string { // Relay represents a connection to a Nostr relay. type Relay struct { - closeMutex *channelmutex.Mutex - URL string requestHeader http.Header // e.g. for origin header // websocket connection - conn *ws.Conn - writeQueue chan writeRequest - closed *atomic.Bool - closedNotify chan struct{} + conn *ws.Conn + writeQueue chan writeRequest + closed *atomic.Bool Subscriptions *MapOf[int64, *Subscription] @@ -92,9 +88,7 @@ func NewRelay(ctx context.Context, url string, opts RelayOptions) *Relay { customHandler: opts.CustomHandler, noticeHandler: opts.NoticeHandler, authHandler: opts.AuthHandler, - closeMutex: channelmutex.New(), closed: &atomic.Bool{}, - closedNotify: make(chan struct{}), } go func() { @@ -104,8 +98,6 @@ func NewRelay(ctx context.Context, url string, opts RelayOptions) *Relay { return } - r.closeMutex.Invalidate() - if r.conn != nil { cause := context.Cause(ctx) code := ws.StatusNormalClosure @@ -120,17 +112,6 @@ func NewRelay(ctx context.Context, url string, opts RelayOptions) *Relay { _ = r.conn.Close(code, reason) } - if r.closeMutex != nil { - r.closeMutex.Lock() - if r.closedNotify != nil { - close(r.closedNotify) - } - if r.writeQueue != nil { - close(r.writeQueue) - } - r.conn = nil - r.closeMutex.Unlock() - } }() return r @@ -255,12 +236,11 @@ func (r *Relay) newConnection(ctx context.Context, httpClient *http.Client) erro ticker := time.NewTicker(19 * time.Second) // main websocket loop - readQueue := make(chan string) + readQueue := make(chan string, 64 /* add some buffer to account for processing/IO mismatches */) r.conn = c - r.writeQueue = make(chan writeRequest) + r.writeQueue = make(chan writeRequest, 64 /* idem */) r.closed = &atomic.Bool{} - r.closedNotify = make(chan struct{}) connCtx := r.connectionContext go func() { @@ -270,8 +250,6 @@ func (r *Relay) newConnection(ctx context.Context, httpClient *http.Client) erro select { case <-connCtx.Done(): return - case <-r.closedNotify: - return case <-ticker.C: debugLogf("{%s} pinging\n", r.URL) pingCtx, cancel := context.WithTimeoutCause(connCtx, time.Millisecond*800, errors.New("ping took too long")) @@ -336,7 +314,11 @@ func (r *Relay) newConnection(ctx context.Context, httpClient *http.Client) erro } msg := string(buf.Bytes()) - readQueue <- msg + select { + case readQueue <- msg: + case <-connCtx.Done(): + return + } } }() @@ -442,16 +424,6 @@ func (r *Relay) handleMessage(message string) { // Write queues an arbitrary message to be sent to the relay. func (r *Relay) Write(msg []byte) { - select { - case <-r.closeMutex.C(): // this locks the mutex - case <-r.closedNotify: - return - case <-r.connectionContext.Done(): - return - } - - defer r.closeMutex.Unlock() - select { case <-r.connectionContext.Done(): case r.writeQueue <- writeRequest{msg: msg, answer: nil}: @@ -462,16 +434,6 @@ func (r *Relay) Write(msg []byte) { func (r *Relay) WriteWithError(msg []byte) error { ch := make(chan error) - select { - case <-r.closeMutex.C(): // this locks the channel/mutex - case <-r.closedNotify: - return fmt.Errorf("failed to write to %s: ", r.URL) - case <-r.connectionContext.Done(): - return fmt.Errorf("failed to write to %s: ", r.URL) - } - - defer r.closeMutex.Unlock() - if r.writeQueue == nil { return nil } @@ -601,12 +563,8 @@ func (r *Relay) Subscribe(ctx context.Context, filter Filter, opts SubscriptionO } go func() { - select { - case <-r.closedNotify: - sub.cancel(ErrDisconnected) - case <-ctx.Done(): - sub.cancel(nil) - } + <-ctx.Done() + sub.cancel(nil) }() return sub, nil From e7dc04a4bb490313d08f6d5a3d13e2ad0334f299 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Mon, 16 Mar 2026 00:57:20 +0900 Subject: [PATCH 22/24] Disable AppArmor --- .github/workflows/test.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ceb96ab9..ba6631f7 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -42,6 +42,9 @@ jobs: - 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 @@ -102,12 +105,15 @@ jobs: - name: Install TinyGo run: | - wget -q https://github.com/tinygo-org/tinygo/releases/download/v0.37.0/tinygo_0.37.0_amd64.deb - sudo dpkg -i tinygo_0.37.0_amd64.deb + 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 From 9a06a3cf7d64fb197dd6182b9706f9e308232d73 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Mon, 16 Mar 2026 01:07:07 +0900 Subject: [PATCH 23/24] chore --- .github/workflows/test.yml | 56 +++++++++++++++++++++++++++++--------- nip05/nip05_easyjson.go | 2 ++ 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ba6631f7..2e632372 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,9 +2,7 @@ name: Test on: push: - branches: ["**"] - pull_request: - branches: ["**"] + branches: ["tinygo"] jobs: test: @@ -20,13 +18,45 @@ jobs: - name: Run tests run: | - # すべてのパッケージを取得し除外 - PKGS=$(go list ./... | grep -v \ - -e 'fiatjaf.com/nostr/schema' \ - -e 'fiatjaf.com/nostr/nip29' \ - -e 'fiatjaf.com/nostr/khatru' \ - -e 'fiatjaf.com/nostr/sdk') - go test $PKGS + 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 @@ -52,7 +82,7 @@ jobs: - name: Run GOOS=js WASM tests run: | - WASM_PKGS=( + PKGS=( "." "./nip04" "./nip05" @@ -90,7 +120,7 @@ jobs: "./nip92" "./nip94" ) - GOOS=js GOARCH=wasm go test -short "${WASM_PKGS[@]}" + GOOS=js GOARCH=wasm go test -short "${PKGS[@]}" test-wasm-tinygo: name: TinyGo WASM Test @@ -159,4 +189,4 @@ jobs: "./nip92" "./nip94" ) - GOOS=js GOARCH=wasm tinygo test -short "${WASM_PKGS[@]}" + GOOS=js GOARCH=wasm tinygo test -short "${PKGS[@]}" 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 ( From 4fa57e7ec65793b727230765b80053c21277a028 Mon Sep 17 00:00:00 2001 From: 1l0 Date: Mon, 16 Mar 2026 01:27:56 +0900 Subject: [PATCH 24/24] fix nip05 test --- keys.go | 19 +++++++++++++++++++ nip05/nip05_test.go | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) 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_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)