From 41f613da2d19fdcdf77cd6d657b01fc74ccdc2b9 Mon Sep 17 00:00:00 2001 From: mleku Date: Sun, 30 Mar 2025 13:23:22 -0106 Subject: [PATCH] clean up some names and complete doc comments for event --- auth/nip42.go | 2 +- cmd/realy/app/main.go | 20 ++-- ec/ecdsa/example_test.go | 2 +- ec/ecdsa/signature_test.go | 4 +- envelopes/authenvelope/authenvelope.go | 14 +-- envelopes/closedenvelope/closedenvelope.go | 12 +- .../closedenvelope/closedenvelope_test.go | 2 +- envelopes/closeenvelope/closeenvelope.go | 17 +-- envelopes/closeenvelope/closeenvelope_test.go | 2 +- envelopes/countenvelope/countenvelope.go | 12 +- envelopes/eoseenvelope/eoseenvelope.go | 23 ++-- envelopes/eoseenvelope/eoseenvelope_test.go | 4 +- envelopes/eventenvelope/eventenvelope.go | 38 +++--- envelopes/noticeenvelope/noticeenvelope.go | 19 +-- .../noticeenvelope/noticeenvelope_test.go | 2 +- envelopes/okenvelope/okenvelope.go | 23 ++-- envelopes/process.go | 6 +- envelopes/reqenvelope/reqenvelope.go | 19 +-- event/canonical.go | 21 ++-- event/codectester/divider/main.go | 2 +- event/compact.go | 6 +- event/event.go | 109 ++++++++++++++---- event/json.go | 43 +++---- event/signatures.go | 36 +++--- event/sort.go | 3 +- event/wirecompact.go | 7 +- eventid/eventid.go | 8 +- filter/filter.go | 4 +- filter/simple.go | 4 +- httpauth/validate.go | 2 +- layer2/badgerbadger/badgerbadger.go | 2 +- layer2/badgerbadger/tester/badgerbadger.go | 2 +- layer2/layer2.go | 8 +- p256k/btcec/btcec.go | 2 +- p256k/btcec/btcec_test.go | 6 +- p256k/p256k.go | 4 +- p256k/p256k_test.go | 10 +- p256k/secp256k1_test.go | 4 +- ratel/countevents.go | 2 +- ratel/deleteevent.go | 4 +- ratel/gcsweep.go | 4 +- ratel/getecounterkey.go | 2 +- ratel/getindexkeysforevent.go | 10 +- ratel/keys/id/id.go | 2 +- ratel/main.go | 2 +- ratel/prefixes/prefixes.go | 8 +- ratel/preparequeries.go | 2 +- ratel/queryevents.go | 14 +-- ratel/queryforids.go | 8 +- ratel/saveevent.go | 8 +- realy/addEvent.go | 6 +- realy/handleAuth.go | 10 +- realy/handleEvent.go | 60 +++++----- realy/handleHTTP.go | 2 +- realy/handleReq.go | 2 +- realy/http-event.go | 18 +-- realy/http-events.go | 2 +- realy/listeners/listeners.go | 4 +- relay/wrapper/relay_interface.go | 10 +- store/helpers.go | 2 +- subscription/subscriptionid.go | 6 +- text/escape.go | 6 +- ws/client.go | 4 +- ws/client_test.go | 12 +- ws/pool.go | 4 +- ws/subscription.go | 2 +- ws/subscription_test.go | 2 +- 67 files changed, 399 insertions(+), 323 deletions(-) diff --git a/auth/nip42.go b/auth/nip42.go index a2c655b..2c845b1 100644 --- a/auth/nip42.go +++ b/auth/nip42.go @@ -27,7 +27,7 @@ func GenerateChallenge() (b []byte) { // If the authentication succeeds, the user will be authenticated as pubkey. func CreateUnsigned(pubkey, challenge []byte, relayURL string) (ev *event.T) { return &event.T{ - PubKey: pubkey, + Pubkey: pubkey, CreatedAt: timestamp.Now(), Kind: kind.ClientAuthentication, Tags: tags.New(tag.New("relay", relayURL), diff --git a/cmd/realy/app/main.go b/cmd/realy/app/main.go index 03067ac..025cfc0 100644 --- a/cmd/realy/app/main.go +++ b/cmd/realy/app/main.go @@ -123,7 +123,7 @@ func (r *Relay) AcceptEvent(c context.T, evt *event.T, hr *http.Request, // followed can access the relay and upload DM events and such for owner // followed users. for o := range r.OwnersFollowed { - if bytes.Equal([]byte(o), evt.PubKey) { + if bytes.Equal([]byte(o), evt.Pubkey) { return true, "", func() { r.ZeroLists() r.CheckOwnerLists(context.Bg()) @@ -134,7 +134,7 @@ func (r *Relay) AcceptEvent(c context.T, evt *event.T, hr *http.Request, if evt.Kind.Equal(kind.MuteList) { // only owners control the mute list for _, o := range r.owners { - if bytes.Equal(o, evt.PubKey) { + if bytes.Equal(o, evt.Pubkey) { return true, "", func() { r.ZeroLists() r.CheckOwnerLists(context.Bg()) @@ -143,8 +143,8 @@ func (r *Relay) AcceptEvent(c context.T, evt *event.T, hr *http.Request, } } for _, o := range r.owners { - log.T.F("%0x,%0x", o, evt.PubKey) - if bytes.Equal(o, evt.PubKey) { + log.T.F("%0x,%0x", o, evt.Pubkey) + if bytes.Equal(o, evt.Pubkey) { // prevent owners from deleting their own mute/follow lists in case of bad // client implementation if evt.Kind.Equal(kind.Deletion) { @@ -189,8 +189,8 @@ func (r *Relay) AcceptEvent(c context.T, evt *event.T, hr *http.Request, // check the mute list, and reject events authored by muted pubkeys, even if // they come from a pubkey that is on the follow list. for pk := range r.Muted { - if bytes.Equal(evt.PubKey, []byte(pk)) { - return false, "rejecting event with pubkey " + hex.Enc(evt.PubKey) + + if bytes.Equal(evt.Pubkey, []byte(pk)) { + return false, "rejecting event with pubkey " + hex.Enc(evt.Pubkey) + " because on owner mute list", nil } } @@ -199,7 +199,7 @@ func (r *Relay) AcceptEvent(c context.T, evt *event.T, hr *http.Request, // allow all events from follows of owners if bytes.Equal(authedPubkey, []byte(pk)) { log.I.F("accepting event %0x because %0x on owner follow list", - evt.ID, []byte(pk)) + evt.Id, []byte(pk)) return true, "", nil } } @@ -367,7 +367,7 @@ func (r *Relay) CheckOwnerLists(c context.T) { Kinds: kinds.New(kind.FollowList)}); chk.E(err) { } for _, ev := range evs { - r.OwnersFollowLists = append(r.OwnersFollowLists, ev.ID) + r.OwnersFollowLists = append(r.OwnersFollowLists, ev.Id) for _, t := range ev.Tags.F() { if bytes.Equal(t.Key(), []byte("p")) { var p []byte @@ -393,7 +393,7 @@ func (r *Relay) CheckOwnerLists(c context.T) { for _, ev := range evs { // we want to protect the follow lists of users as well so they also cannot be // deleted, only replaced. - r.OwnersFollowLists = append(r.OwnersFollowLists, ev.ID) + r.OwnersFollowLists = append(r.OwnersFollowLists, ev.Id) for _, t := range ev.Tags.F() { if bytes.Equal(t.Key(), []byte("p")) { var p []byte @@ -414,7 +414,7 @@ func (r *Relay) CheckOwnerLists(c context.T) { Kinds: kinds.New(kind.MuteList)}); chk.E(err) { } for _, ev := range evs { - r.OwnersMuteLists = append(r.OwnersMuteLists, ev.ID) + r.OwnersMuteLists = append(r.OwnersMuteLists, ev.Id) for _, t := range ev.Tags.F() { if bytes.Equal(t.Key(), []byte("p")) { var p []byte diff --git a/ec/ecdsa/example_test.go b/ec/ecdsa/example_test.go index acdb38b..3b4ca8b 100644 --- a/ec/ecdsa/example_test.go +++ b/ec/ecdsa/example_test.go @@ -28,7 +28,7 @@ package ecdsa_test // fmt.Printf("Serialized Signature: %x\n", signature.Serialize()) // // // Verify the signature for the message using the public key. -// pubKey := secKey.PubKey() +// pubKey := secKey.Pubkey() // verified := signature.Verify(messageHash[:], pubKey) // fmt.Printf("Signature Verified? %v\n", verified) // diff --git a/ec/ecdsa/signature_test.go b/ec/ecdsa/signature_test.go index cffc6b2..dff2592 100644 --- a/ec/ecdsa/signature_test.go +++ b/ec/ecdsa/signature_test.go @@ -549,7 +549,7 @@ type signTest struct { // } // // // Ensure the produced signature verifies. -// pubKey := secKey.PubKey() +// pubKey := secKey.Pubkey() // if !gotSig.Verify(hash, pubKey) { // t.Errorf("%s: signature failed to verify", test.name) // continue @@ -771,7 +771,7 @@ func TestSignatureIsEqual(t *testing.T) { // // // Parse test data. // secKey := secp256k1.NewSecretKey(hexToModNScalar(test.key)) -// pubKey := secKey.PubKey() +// pubKey := secKey.Pubkey() // hash := hexToBytes(test.hash) // wantSig := hexToBytes("00" + test.wantSigR + test.wantSigS) // diff --git a/envelopes/authenvelope/authenvelope.go b/envelopes/authenvelope/authenvelope.go index 3fc00cb..2115274 100644 --- a/envelopes/authenvelope/authenvelope.go +++ b/envelopes/authenvelope/authenvelope.go @@ -22,18 +22,18 @@ type Challenge struct { var _ codec.Envelope = (*Challenge)(nil) -// NewChallenge creates a new empty Challenge. +// NewChallenge creates a new empty authenvelope.Challenge. func NewChallenge() *Challenge { return &Challenge{} } -// NewChallengeWith creates a new Challenge with provided bytes. +// NewChallengeWith creates a new authenvelope.Challenge with provided bytes. func NewChallengeWith[V string | []byte](challenge V) *Challenge { return &Challenge{[]byte(challenge)} } -// Label returns the label of a Challenge envelope. +// Label returns the label of a authenvelope.Challenge. func (en *Challenge) Label() string { return L } -// Write the Challenge to a provided io.Writer. +// Write the authenvelope.Challenge to a provided io.Writer. func (en *Challenge) Write(w io.Writer) (err error) { var b []byte b = en.Marshal(b) @@ -42,7 +42,7 @@ func (en *Challenge) Write(w io.Writer) (err error) { return } -// Marshal a Challenge to minified JSON, appending to a provided destination +// Marshal a authenvelope.Challenge to minified JSON, appending to a provided destination // slice. Note that this ensures correct string escaping on the challenge field. func (en *Challenge) Marshal(dst []byte) (b []byte) { b = dst @@ -59,7 +59,7 @@ func (en *Challenge) Marshal(dst []byte) (b []byte) { return } -// Unmarshal a Challenge from minified JSON, returning the remainder after the +// Unmarshal a authenvelope.Challenge from minified JSON, returning the remainder after the // end of the envelope. Note that this ensures the challenge string was // correctly escaped by NIP-01 escaping rules. func (en *Challenge) Unmarshal(b []byte) (r []byte, err error) { @@ -76,7 +76,7 @@ func (en *Challenge) Unmarshal(b []byte) (r []byte, err error) { return } -// ParseChallenge reads a Challenge encoded in minified JSON and unpacks it to +// ParseChallenge reads a authenvelope.Challenge encoded in minified JSON and unpacks it to // the runtime format. func ParseChallenge(b []byte) (t *Challenge, rem []byte, err error) { t = NewChallenge() diff --git a/envelopes/closedenvelope/closedenvelope.go b/envelopes/closedenvelope/closedenvelope.go index 66f9fcf..6eaa363 100644 --- a/envelopes/closedenvelope/closedenvelope.go +++ b/envelopes/closedenvelope/closedenvelope.go @@ -30,16 +30,16 @@ func New() *T { return &T{Subscription: subscription.NewStd()} } -// NewFrom creates a new T populated with subscription Id and Reason. +// NewFrom creates a new closedenvelope.T populated with subscription Id and Reason. func NewFrom(id *subscription.Id, msg []byte) *T { return &T{Subscription: id, Reason: msg} } -// Label returns the label of a CLOSED envelope. +// Label returns the label of a closedenvelope.T. func (en *T) Label() string { return L } // ReasonString returns the Reason in the form of a string. func (en *T) ReasonString() string { return string(en.Reason) } -// Write the CLOSED T to a provided io.Writer. +// Write the closedenvelope.T to a provided io.Writer. func (en *T) Write(w io.Writer) (err error) { var b []byte b = en.Marshal(b) @@ -47,7 +47,7 @@ func (en *T) Write(w io.Writer) (err error) { return } -// Marshal a CLOSED T envelope in minified JSON, appending to a provided +// Marshal a closedenvelope.T envelope in minified JSON, appending to a provided // destination slice. Note that this ensures correct string escaping on the // Reason field. func (en *T) Marshal(dst []byte) (b []byte) { @@ -65,7 +65,7 @@ func (en *T) Marshal(dst []byte) (b []byte) { return } -// Unmarshal a CLOSED T from minified JSON, returning the remainder after the end +// Unmarshal a closedenvelope.T from minified JSON, returning the remainder after the end // of the envelope. Note that this ensures the Reason string is correctly // unescaped by NIP-01 escaping rules. func (en *T) Unmarshal(b []byte) (r []byte, err error) { @@ -85,7 +85,7 @@ func (en *T) Unmarshal(b []byte) (r []byte, err error) { return } -// Parse reads a CLOSED T from minified JSON into a newly allocated T. +// Parse reads a closedenvelope.T from minified JSON into a newly allocated closedenvelope.T. func Parse(b []byte) (t *T, rem []byte, err error) { t = New() if rem, err = t.Unmarshal(b); chk.E(err) { diff --git a/envelopes/closedenvelope/closedenvelope_test.go b/envelopes/closedenvelope/closedenvelope_test.go index a3bbfd4..2ff2e08 100644 --- a/envelopes/closedenvelope/closedenvelope_test.go +++ b/envelopes/closedenvelope/closedenvelope_test.go @@ -50,7 +50,7 @@ func TestMarshalUnmarshal(t *testing.T) { if rem, err = req2.Unmarshal(rb); chk.E(err) { t.Fatal(err) } - // log.I.Ln(req2.ID) + // log.I.Ln(req2.Id) if len(rem) > 0 { t.Fatalf("unmarshal failed, remainder\n%d %s", len(rem), rem) diff --git a/envelopes/closeenvelope/closeenvelope.go b/envelopes/closeenvelope/closeenvelope.go index 7fd9bd5..2b27c09 100644 --- a/envelopes/closeenvelope/closeenvelope.go +++ b/envelopes/closeenvelope/closeenvelope.go @@ -21,22 +21,22 @@ type T struct { var _ codec.Envelope = (*T)(nil) -// New creates an empty new standard formatted T. +// New creates an empty new standard formatted closeenvelope.T. func New() *T { return &T{ID: subscription.NewStd()} } -// NewFrom creates a new T populated with subscription Id. +// NewFrom creates a new closeenvelope.T populated with subscription Id. func NewFrom(id *subscription.Id) *T { return &T{ID: id} } -// Label returns the label of a CLOSE envelope. +// Label returns the label of a closeenvelope.T. func (en *T) Label() string { return L } -// Write the CLOSE T to a provided io.Writer. +// Write the closeenvelope.T to a provided io.Writer. func (en *T) Write(w io.Writer) (err error) { _, err = w.Write(en.Marshal(nil)) return } -// Marshal a CLOSE T envelope in minified JSON, appending to a provided +// Marshal a closeenvelope.T envelope in minified JSON, appending to a provided // destination slice. func (en *T) Marshal(dst []byte) (b []byte) { b = dst @@ -49,8 +49,8 @@ func (en *T) Marshal(dst []byte) (b []byte) { return } -// Unmarshal a CLOSE T from minified JSON, returning the remainder after the end -// of the envelope. +// Unmarshal a closeenvelope.T from minified JSON, returning the remainder after +// the end of the envelope. func (en *T) Unmarshal(b []byte) (r []byte, err error) { r = b if en.ID, err = subscription.NewId([]byte{0}); chk.E(err) { @@ -65,7 +65,8 @@ func (en *T) Unmarshal(b []byte) (r []byte, err error) { return } -// Parse reads a CLOSE T in minified JSON into a newly allocated T. +// Parse reads a CLOSE envelope from minified JSON into a newly allocated +// closeenvelope.T. func Parse(b []byte) (t *T, rem []byte, err error) { t = New() if rem, err = t.Unmarshal(b); chk.E(err) { diff --git a/envelopes/closeenvelope/closeenvelope_test.go b/envelopes/closeenvelope/closeenvelope_test.go index 7a7b76c..f79256a 100644 --- a/envelopes/closeenvelope/closeenvelope_test.go +++ b/envelopes/closeenvelope/closeenvelope_test.go @@ -32,7 +32,7 @@ func TestMarshalUnmarshal(t *testing.T) { if rem, err = req2.Unmarshal(rb); chk.E(err) { t.Fatal(err) } - // log.I.Ln(req2.ID) + // log.I.Ln(req2.Id) if len(rem) > 0 { t.Fatalf("unmarshal failed, remainder\n%d %s", len(rem), rem) diff --git a/envelopes/countenvelope/countenvelope.go b/envelopes/countenvelope/countenvelope.go index 10bacce..2cbed75 100644 --- a/envelopes/countenvelope/countenvelope.go +++ b/envelopes/countenvelope/countenvelope.go @@ -108,11 +108,11 @@ type Response struct { var _ codec.Envelope = (*Response)(nil) -// NewResponse creates a new empty COUNT Response with a standard formatted +// NewResponse creates a new empty countenvelope.Response with a standard formatted // subscription.Id. func NewResponse() *Response { return &Response{ID: subscription.NewStd()} } -// NewResponseFrom creates a new response with provided string for the +// NewResponseFrom creates a new countenvelope.Response with provided string for the // subscription.Id, a count and optional variadic approximate flag, which is // otherwise false and does not get rendered into the JSON. func NewResponseFrom[V string | []byte](s V, cnt int, @@ -138,8 +138,8 @@ func (en *Response) Write(w io.Writer) (err error) { return } -// Marshal a COUNT Response envelope in minified JSON, appending to a provided -// destination slice. +// Marshal a countenvelope.Response envelope in minified JSON, appending to a +// provided destination slice. func (en *Response) Marshal(dst []byte) (b []byte) { var err error b = dst @@ -166,7 +166,7 @@ func (en *Response) Unmarshal(b []byte) (r []byte, err error) { r = b var inID, inCount bool for ; len(r) > 0; r = r[1:] { - // first we should be finding a subscription ID + // first we should be finding a subscription Id if !inID && r[0] == '"' { r = r[1:] // so we don't do this twice @@ -222,7 +222,7 @@ func (en *Response) Unmarshal(b []byte) (r []byte, err error) { } // Parse reads a Count Response in minified JSON into a newly allocated -// Response. +// countenvelope.Response. func Parse(b []byte) (t *Response, rem []byte, err error) { t = NewResponse() if rem, err = t.Unmarshal(b); chk.E(err) { diff --git a/envelopes/eoseenvelope/eoseenvelope.go b/envelopes/eoseenvelope/eoseenvelope.go index 1c4682a..0fb10e9 100644 --- a/envelopes/eoseenvelope/eoseenvelope.go +++ b/envelopes/eoseenvelope/eoseenvelope.go @@ -15,34 +15,34 @@ import ( // L is the label associated with this type of codec.Envelope. const L = "EOSE" -// T is an EOSE envelope, that signals the end of events that are stored and the -// beginning of a subscription. This is necessitated by the confusing -// multiplexing of websockets for multiple requests, and an ugly merging of two -// distinct API calls, filter and subscribe. +// T is an EOSE envelope (End of Stored Events), that signals the end of events +// that are stored and the beginning of a subscription. This is necessitated by +// the confusing multiplexing of websockets for multiple requests, and an ugly +// merging of two distinct API calls, filter and subscribe. type T struct { Subscription *subscription.Id } var _ codec.Envelope = (*T)(nil) -// New creates a new EOSE T with a standard form subscription.Id. +// New creates a new eoseenvelope.T with a standard form subscription.Id. func New() *T { return &T{Subscription: subscription.NewStd()} } -// NewFrom creates a new EOSE T using a provided subscription.Id. +// NewFrom creates a new eoseenvelope.T using a provided subscription.Id. func NewFrom(id *subscription.Id) *T { return &T{Subscription: id} } // Label returns the label of a EOSE envelope. func (en *T) Label() string { return L } -// Write the EOSE T to a provided io.Writer. +// Write the eoseenvelope.T to a provided io.Writer. func (en *T) Write(w io.Writer) (err error) { _, err = w.Write(en.Marshal(nil)) return } -// Marshal a EOSE T envelope in minified JSON, appending to a provided +// Marshal a eoseenvelope.T envelope in minified JSON, appending to a provided // destination slice. func (en *T) Marshal(dst []byte) (b []byte) { var err error @@ -58,8 +58,8 @@ func (en *T) Marshal(dst []byte) (b []byte) { return } -// Unmarshal a EOSE T from minified JSON, returning the remainder after the -// end of the envelope. +// Unmarshal a eoseenvelope.T from minified JSON, returning the remainder after +// the end of the envelope. func (en *T) Unmarshal(b []byte) (r []byte, err error) { r = b if en.Subscription, err = subscription.NewId([]byte{0}); chk.E(err) { @@ -74,7 +74,8 @@ func (en *T) Unmarshal(b []byte) (r []byte, err error) { return } -// Parse reads a EOSE T in minified JSON into a newly allocated T. +// Parse reads a EOSE envelope in minified JSON into a newly allocated +// eoseenvelope.T. func Parse(b []byte) (t *T, rem []byte, err error) { t = New() if rem, err = t.Unmarshal(b); chk.E(err) { diff --git a/envelopes/eoseenvelope/eoseenvelope_test.go b/envelopes/eoseenvelope/eoseenvelope_test.go index c806886..ee82d64 100644 --- a/envelopes/eoseenvelope/eoseenvelope_test.go +++ b/envelopes/eoseenvelope/eoseenvelope_test.go @@ -18,7 +18,7 @@ func TestMarshalUnmarshal(t *testing.T) { } req := NewFrom(s) rb = req.Marshal(rb) - // log.I.Ln(req.ID) + // log.I.Ln(req.Id) rb1 = rb1[:len(rb)] copy(rb1, rb) var rem []byte @@ -33,7 +33,7 @@ func TestMarshalUnmarshal(t *testing.T) { if rem, err = req2.Unmarshal(rb); chk.E(err) { t.Fatal(err) } - // log.I.Ln(req2.ID) + // log.I.Ln(req2.Id) if len(rem) > 0 { t.Fatalf("unmarshal failed, remainder\n%d %s", len(rem), rem) diff --git a/envelopes/eventenvelope/eventenvelope.go b/envelopes/eventenvelope/eventenvelope.go index 8972ec2..5d5929d 100644 --- a/envelopes/eventenvelope/eventenvelope.go +++ b/envelopes/eventenvelope/eventenvelope.go @@ -21,13 +21,13 @@ type Submission struct { var _ codec.Envelope = (*Submission)(nil) -// NewSubmission creates an empty new Submission. +// NewSubmission creates an empty new eventenvelope.Submission. func NewSubmission() *Submission { return &Submission{T: &event.T{}} } -// NewSubmissionWith creates a new Submission with a provided event.T. +// NewSubmissionWith creates a new eventenvelope.Submission with a provided event.T. func NewSubmissionWith(ev *event.T) *Submission { return &Submission{T: ev} } -// Label returns the label of a event Submission envelope. +// Label returns the label of a event eventenvelope.Submission envelope. func (en *Submission) Label() string { return L } // Write the Submission to a provided io.Writer. @@ -36,8 +36,8 @@ func (en *Submission) Write(w io.Writer) (err error) { return } -// Marshal a event Submission T envelope in minified JSON, appending to a provided -// destination slice. +// Marshal an event Submission envelope in minified JSON, appending to a +// provided destination slice. func (en *Submission) Marshal(dst []byte) (b []byte) { var err error b = dst @@ -51,8 +51,8 @@ func (en *Submission) Marshal(dst []byte) (b []byte) { return } -// Unmarshal an event Submission from minified JSON, returning the remainder -// after the end of the envelope. +// Unmarshal an event eventenvelope.Submission from minified JSON, returning the +// remainder after the end of the envelope. func (en *Submission) Unmarshal(b []byte) (r []byte, err error) { r = b en.T = event.New() @@ -66,8 +66,8 @@ func (en *Submission) Unmarshal(b []byte) (r []byte, err error) { return } -// ParseSubmission reads an event Submission from minified JSON into a newly -// allocated Submission. +// ParseSubmission reads an event envelope Submission from minified JSON into a newly +// allocated eventenvelope.Submission. func ParseSubmission(b []byte) (t *Submission, rem []byte, err error) { t = NewSubmission() if rem, err = t.Unmarshal(b); chk.E(err) { @@ -84,11 +84,11 @@ type Result struct { var _ codec.Envelope = (*Result)(nil) -// NewResult creates a new empty event Result. +// NewResult creates a new empty eventenvelope.Result. func NewResult() *Result { return &Result{} } -// NewResultWith creates a new Result with a provided subscription.Id string and -// event.T. +// NewResultWith creates a new eventenvelope.Result with a provided +// subscription.Id string and event.T. func NewResultWith[V string | []byte](s V, ev *event.T) (res *Result, err error) { if len(s) < 0 || len(s) > 64 { err = errorf.E("subscription id must be length > 0 and <= 64") @@ -97,17 +97,17 @@ func NewResultWith[V string | []byte](s V, ev *event.T) (res *Result, err error) return &Result{subscription.MustNew(s), ev}, nil } -// Label returns the label of a event Result envelope. +// Label returns the label of a event eventenvelope.Result envelope. func (en *Result) Label() string { return L } -// Write the event Result T to a provided io.Writer. +// Write the eventenvelope.Result to a provided io.Writer. func (en *Result) Write(w io.Writer) (err error) { _, err = w.Write(en.Marshal(nil)) return } -// Marshal a event Result envelope in minified JSON, appending to a provided -// destination slice. +// Marshal an eventenvelope.Result envelope in minified JSON, appending to a +// provided destination slice. func (en *Result) Marshal(dst []byte) (b []byte) { var err error b = dst @@ -123,8 +123,8 @@ func (en *Result) Marshal(dst []byte) (b []byte) { return } -// Unmarshal a event Result from minified JSON, returning the remainder after -// the end of the envelope. +// Unmarshal an event Result envelope from minified JSON, returning the +// remainder after the end of the envelope. func (en *Result) Unmarshal(b []byte) (r []byte, err error) { r = b if en.Subscription, err = subscription.NewId([]byte{0}); chk.E(err) { @@ -143,6 +143,8 @@ func (en *Result) Unmarshal(b []byte) (r []byte, err error) { return } +// ParseResult allocates a new eventenvelope.Result and unmarshalls an EVENT +// envelope into it. func ParseResult(b []byte) (t *Result, rem []byte, err error) { t = NewResult() if rem, err = t.Unmarshal(b); chk.E(err) { diff --git a/envelopes/noticeenvelope/noticeenvelope.go b/envelopes/noticeenvelope/noticeenvelope.go index b9be72f..2bb729e 100644 --- a/envelopes/noticeenvelope/noticeenvelope.go +++ b/envelopes/noticeenvelope/noticeenvelope.go @@ -23,10 +23,10 @@ type T struct { var _ codec.Envelope = (*T)(nil) -// New creates a new empty NOTICE T. +// New creates a new empty NOTICE noticeenvelope.T. func New() *T { return &T{} } -// NewFrom creates a new NOTICE T with a provided message. +// NewFrom creates a new noticeenvelope.T with a provided message. func NewFrom[V string | []byte](msg V) *T { return &T{Message: []byte(msg)} } // Label returns the label of a NOTICE envelope. @@ -38,9 +38,9 @@ func (en *T) Write(w io.Writer) (err error) { return } -// Marshal a NOTICE T envelope in minified JSON, appending to a provided -// destination slice. Note that this ensures correct string escaping on the -// Reason field. +// Marshal a NOTICE envelope in minified JSON into an noticeenvelope.T, +// appending to a provided destination slice. Note that this ensures correct +// string escaping on the Reason field. func (en *T) Marshal(dst []byte) (b []byte) { var err error _ = err @@ -56,9 +56,9 @@ func (en *T) Marshal(dst []byte) (b []byte) { return } -// Unmarshal a NOTICE T from minified JSON, returning the remainder after the -// end of the envelope. Note that this ensures the Reason string is correctly -// unescaped by NIP-01 escaping rules. +// Unmarshal a noticeenvelope.T from minified JSON, returning the remainder +// after the end of the envelope. Note that this ensures the Reason string is +// correctly unescaped by NIP-01 escaping rules. func (en *T) Unmarshal(b []byte) (r []byte, err error) { r = b if en.Message, r, err = text.UnmarshalQuoted(r); chk.E(err) { @@ -70,7 +70,8 @@ func (en *T) Unmarshal(b []byte) (r []byte, err error) { return } -// Parse reads a NOTICE T in minified JSON into a newly allocated T. +// Parse reads a NOTICE envelope in minified JSON into a newly allocated +// noticeenvelope.T. func Parse(b []byte) (t *T, rem []byte, err error) { t = New() if rem, err = t.Unmarshal(b); chk.E(err) { diff --git a/envelopes/noticeenvelope/noticeenvelope_test.go b/envelopes/noticeenvelope/noticeenvelope_test.go index f6058bc..22483b7 100644 --- a/envelopes/noticeenvelope/noticeenvelope_test.go +++ b/envelopes/noticeenvelope/noticeenvelope_test.go @@ -28,7 +28,7 @@ func TestMarshalUnmarshal(t *testing.T) { if rem, err = req2.Unmarshal(rb); chk.E(err) { t.Fatal(err) } - // log.I.Ln(req2.ID) + // log.I.Ln(req2.Id) if len(rem) > 0 { t.Fatalf("unmarshal failed, remainder\n%d %s", len(rem), rem) diff --git a/envelopes/okenvelope/okenvelope.go b/envelopes/okenvelope/okenvelope.go index 1fc93e3..6f33861 100644 --- a/envelopes/okenvelope/okenvelope.go +++ b/envelopes/okenvelope/okenvelope.go @@ -29,33 +29,33 @@ var _ codec.Envelope = (*T)(nil) // New creates a new empty OK T. func New() *T { return &T{} } -// NewFrom creates a new OK T with a string for the subscription.Id and the -// Reason. +// NewFrom creates a new okenvelope.T with a string for the subscription.Id and +// the Reason. func NewFrom[V string | []byte](eid V, ok bool, msg ...V) *T { var m []byte if len(msg) > 0 { m = []byte(msg[0]) } if len(eid) != sha256.Size { - log.W.F("event ID unexpected length, expect %d got %d", + log.W.F("event Id unexpected length, expect %d got %d", len(eid), sha256.Size) } return &T{EventID: eventid.NewWith(eid), OK: ok, Reason: m} } -// Label returns the label of an OK envelope. +// Label returns the label of an okenvelope.T. func (en *T) Label() string { return L } // ReasonString returns the Reason in the form of a string. func (en *T) ReasonString() string { return string(en.Reason) } -// Write the OK T to a provided io.Writer. +// Write the okenvelope.T to a provided io.Writer. func (en *T) Write(w io.Writer) (err error) { _, err = w.Write(en.Marshal(nil)) return } -// Marshal a CLOSED T envelope in minified JSON, appending to a provided +// Marshal a okenvelope.T from minified JSON, appending to a provided // destination slice. Note that this ensures correct string escaping on the // subscription.Id and Reason fields. func (en *T) Marshal(dst []byte) (b []byte) { @@ -79,9 +79,9 @@ func (en *T) Marshal(dst []byte) (b []byte) { return } -// Unmarshal a CLOSED T from minified JSON, returning the remainder after the -// end of the envelope. Note that this ensures the Reason and subscription.Id -// strings are correctly unescaped by NIP-01 escaping rules. +// Unmarshal a okenvelope.T from minified JSON, returning the remainder after +// the end of the envelope. Note that this ensures the Reason and +// subscription.Id strings are correctly unescaped by NIP-01 escaping rules. func (en *T) Unmarshal(b []byte) (r []byte, err error) { r = b var idHex []byte @@ -89,7 +89,7 @@ func (en *T) Unmarshal(b []byte) (r []byte, err error) { return } if len(idHex) != sha256.Size { - err = errorf.E("invalid size for ID, require %d got %d", + err = errorf.E("invalid size for Id, require %d got %d", len(idHex), sha256.Size) } en.EventID = eventid.NewWith(idHex) @@ -111,7 +111,8 @@ func (en *T) Unmarshal(b []byte) (r []byte, err error) { return } -// Parse reads a OK T in minified JSON into a newly allocated T. +// Parse reads a OK envelope in minified JSON into a newly allocated +// okenvelope.T. func Parse(b []byte) (t *T, rem []byte, err error) { t = New() if rem, err = t.Unmarshal(b); chk.E(err) { diff --git a/envelopes/process.go b/envelopes/process.go index b32c80c..11d6671 100644 --- a/envelopes/process.go +++ b/envelopes/process.go @@ -4,15 +4,15 @@ import ( "io" ) -// Marshaler is a function signature the same as the codec.JSON Marshal but +// Marshaller is a function signature the same as the codec.JSON Marshal but // without the requirement of there being a full implementation or declared // receiver variable of this interface. Used here to encapsulate one or more // other data structures into an envelope. -type Marshaler func(dst []byte) (b []byte) +type Marshaller func(dst []byte) (b []byte) // Marshal is a parser for dynamic typed arrays like nosttr codec.Envelope // types. -func Marshal(dst []byte, label string, m Marshaler) (b []byte) { +func Marshal(dst []byte, label string, m Marshaller) (b []byte) { b = dst b = append(b, '[', '"') b = append(b, label...) diff --git a/envelopes/reqenvelope/reqenvelope.go b/envelopes/reqenvelope/reqenvelope.go index 150aa40..aab4573 100644 --- a/envelopes/reqenvelope/reqenvelope.go +++ b/envelopes/reqenvelope/reqenvelope.go @@ -26,19 +26,21 @@ type T struct { var _ codec.Envelope = (*T)(nil) -// New creates a new REQ T with a standard subscription.Id and empty filters.T. +// New creates a new reqenvelope.T with a standard subscription.Id and empty +// filters.T. func New() *T { return &T{Subscription: subscription.NewStd(), Filters: filters.New()} } -// NewFrom creates a new REQ T with a provided subscription.Id and filters.T. +// NewFrom creates a new reqenvelope.T with a provided subscription.Id and +// filters.T. func NewFrom(id *subscription.Id, filters *filters.T) *T { return &T{Subscription: id, Filters: filters} } -// Label returns the label of a REQ envelope. +// Label returns the label of a reqenvelope.T. func (en *T) Label() string { return L } // Write the REQ T to a provided io.Writer. @@ -47,7 +49,7 @@ func (en *T) Write(w io.Writer) (err error) { return } -// Marshal a REQ T envelope in minified JSON, appending to a provided +// Marshal a reqenvelope.T envelope into minified JSON, appending to a provided // destination slice. Note that this ensures correct string escaping on the // subscription.Id field. func (en *T) Marshal(dst []byte) (b []byte) { @@ -67,9 +69,9 @@ func (en *T) Marshal(dst []byte) (b []byte) { return } -// Unmarshal a REQ T from minified JSON, returning the remainder after the end -// of the envelope. Note that this ensures the subscription.Id string is -// correctly unescaped by NIP-01 escaping rules. +// Unmarshal into a reqenvelope.T from minified JSON, returning the remainder +// after the end of the envelope. Note that this ensures the subscription.Id +// string is correctly unescaped by NIP-01 escaping rules. func (en *T) Unmarshal(b []byte) (r []byte, err error) { r = b if en.Subscription, err = subscription.NewId([]byte{0}); chk.E(err) { @@ -91,7 +93,8 @@ func (en *T) Unmarshal(b []byte) (r []byte, err error) { return } -// Parse reads a REQ T from minified JSON into a newly allocated T. +// Parse reads a REQ envelope from minified JSON into a newly allocated +// reqenvelope.T. func (en *T) Parse(b []byte) (t *T, rem []byte, err error) { t = New() if rem, err = t.Unmarshal(b); chk.E(err) { diff --git a/event/canonical.go b/event/canonical.go index f26daf5..c23ae26 100644 --- a/event/canonical.go +++ b/event/canonical.go @@ -13,11 +13,11 @@ import ( ) // ToCanonical converts the event to the canonical encoding used to derive the -// event ID. +// event Id. func (ev *T) ToCanonical(dst []byte) (b []byte) { b = dst b = append(b, "[0,\""...) - b = hex.EncAppend(b, ev.PubKey) + b = hex.EncAppend(b, ev.Pubkey) b = append(b, "\","...) b = ev.CreatedAt.Marshal(b) b = append(b, ',') @@ -30,9 +30,10 @@ func (ev *T) ToCanonical(dst []byte) (b []byte) { return } -// GetIDBytes returns the raw SHA256 hash of the canonical form of an T. +// GetIDBytes returns the raw SHA256 hash of the canonical form of an event.T. func (ev *T) GetIDBytes() []byte { return Hash(ev.ToCanonical(nil)) } +// New func NewCanonical() (a *json.Array) { a = &json.Array{ V: []codec.JSON{ @@ -48,10 +49,11 @@ func NewCanonical() (a *json.Array) { } // this is an absolute minimum length canonical encoded event -var minimal = len(`[0,"0123456789abcdef0123456789abcdef",1733739427,0,[],""]`) +var minimal = len(`[0,"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",1733739427,0,[],""]`) -// FromCanonical reverses the process of creating the canonical encoding, note that the signature is missing in this -// form. Allocate an event.T before calling this. +// FromCanonical reverses the process of creating the canonical encoding, note +// that the signature is missing in this form. Allocate an event.T before +// calling this. func (ev *T) FromCanonical(b []byte) (rem []byte, err error) { rem = b id := Hash(rem) @@ -71,14 +73,14 @@ func (ev *T) FromCanonical(b []byte) (rem []byte, err error) { return } } - // create the event, use the ID hash to populate the ID - ev.ID = id + // create the event, use the Id hash to populate the Id + ev.Id = id // unwrap the pubkey if v, ok := x[1].(*json.Hex); !ok { err = errorf.E("failed to decode pubkey from canonical form of event %s", b) return } else { - ev.PubKey = v.V + ev.Pubkey = v.V } // populate the timestamp field if v, ok := x[2].(*timestamp.T); !ok { @@ -108,6 +110,5 @@ func (ev *T) FromCanonical(b []byte) (rem []byte, err error) { } else { ev.Content = v.V } - return } diff --git a/event/codectester/divider/main.go b/event/codectester/divider/main.go index 97ff054..6b7bfd1 100644 --- a/event/codectester/divider/main.go +++ b/event/codectester/divider/main.go @@ -99,7 +99,7 @@ func main() { } can := ev.ToCanonical(nil) eh := event.Hash(can) - eq := bytes.Equal(ev.ID, eh) + eq := bytes.Equal(ev.Id, eh) if !eq { _, err = fmt.Fprintf(ids, "%s\n", ev.Serialize()) if chk.E(err) { diff --git a/event/compact.go b/event/compact.go index 42bf897..92359b9 100644 --- a/event/compact.go +++ b/event/compact.go @@ -5,7 +5,7 @@ import ( ) // MarshalCompact encodes an event as the canonical form followed by the raw binary -// signature (64 bytes) which hashes to form the ID, thus a compact form for the +// signature (64 bytes) which hashes to form the Id, thus a compact form for the // database that is smaller and fast to decode. func (ev *T) MarshalCompact(dst []byte) (b []byte) { b = dst @@ -14,6 +14,8 @@ func (ev *T) MarshalCompact(dst []byte) (b []byte) { return } +// UnmarshalCompact decodes an event encoded as the canonical form followed by +// 64 bytes of binary for the signature. func (ev *T) UnmarshalCompact(b []byte) (rem []byte, err error) { rem = b end := len(rem) - schnorr.SignatureSize @@ -22,7 +24,7 @@ func (ev *T) UnmarshalCompact(b []byte) (rem []byte, err error) { return } ev.Sig = rem[:schnorr.SignatureSize] - ev.ID = id + ev.Id = id rem = rem[schnorr.SignatureSize:] return } diff --git a/event/event.go b/event/event.go index 30b85f3..f995cdb 100644 --- a/event/event.go +++ b/event/event.go @@ -7,6 +7,7 @@ package event import ( "lukechampine.com/frand" + "realy.lol/ec/schnorr" "realy.lol/eventid" "realy.lol/hex" "realy.lol/kind" @@ -21,53 +22,89 @@ import ( // T is the primary datatype of nostr. This is the form of the structure that // defines its JSON string based format. type T struct { - // ID is the SHA256 hash of the canonical encoding of the event in binary format - ID []byte - // PubKey is the public key of the event creator in binary format - PubKey []byte + + // Id is the SHA256 hash of the canonical encoding of the event in binary format + Id []byte + + // Pubkey is the public key of the event creator in binary format + Pubkey []byte + // CreatedAt is the UNIX timestamp of the event according to the event // creator (never trust a timestamp!) CreatedAt *timestamp.T + // Kind is the nostr protocol code for the type of event. See kind.T Kind *kind.T + // Tags are a list of tags, which are a list of strings usually structured // as a 3 layer scheme indicating specific features of an event. Tags *tags.T + // Content is an arbitrary string that can contain anything, but usually // conforming to a specification relating to the Kind and the Tags. Content []byte - // Sig is the signature on the ID hash that validates as coming from the + + // Sig is the signature on the Id hash that validates as coming from the // Pubkey in binary format. Sig []byte } -// Ts is an array of T that sorts in reverse chronological order. +// Ts is an array of event.T that sorts in reverse chronological order. type Ts []*T -func (ev Ts) Len() int { return len(ev) } -func (ev Ts) Less(i, j int) bool { return ev[i].CreatedAt.I64() > ev[j].CreatedAt.I64() } -func (ev Ts) Swap(i, j int) { ev[i], ev[j] = ev[j], ev[i] } +// Len returns the length of the event.Ts. +func (ev Ts) Len() int { return len(ev) } +// Less returns whether the first is newer than the second (larger unix +// timestamp). +func (ev Ts) Less(i, j int) bool { return ev[i].CreatedAt.I64() > ev[j].CreatedAt.I64() } + +// Swap two indexes of the event.Ts with each other. +func (ev Ts) Swap(i, j int) { ev[i], ev[j] = ev[j], ev[i] } + +// C is a channel that carries event.T. type C chan *T +// New makes a new event.T. func New() (ev *T) { return &T{} } +// Serialize renders an event.T into minified JSON. func (ev *T) Serialize() (b []byte) { return ev.Marshal(nil) } -func (ev *T) SerializeIndented() (b []byte) { return ev.marshalWithWhitespace(nil, true) } +// SerializeIndented renders an event.T into nicely readable whitespaced JSON. +func (ev *T) SerializeIndented() (b []byte) { + return ev.marshalWithWhitespace(nil, true) +} -func (ev *T) EventID() (eid *eventid.T) { return eventid.NewWith(ev.ID) } +// EventId returns the event.T Id as an eventid.T. +func (ev *T) EventId() (eid *eventid.T) { + return eventid.NewWith(ev.Id) +} // stringy/numbery functions for retarded other libraries -func (ev *T) IDString() (s string) { return hex.Enc(ev.ID) } -func (ev *T) CreatedAtInt64() (i int64) { return ev.CreatedAt.I64() } -func (ev *T) KindInt32() (i int32) { return int32(ev.Kind.K) } -func (ev *T) PubKeyString() (s string) { return hex.Enc(ev.PubKey) } -func (ev *T) SigString() (s string) { return hex.Enc(ev.Sig) } -func (ev *T) TagStrings() (s [][]string) { return ev.Tags.ToStringSlice() } -func (ev *T) ContentString() (s string) { return string(ev.Content) } +// IdString returns the event Id as a hex encoded string. +func (ev *T) IdString() (s string) { return hex.Enc(ev.Id) } +// CreatedAtInt64 returns the created_at timestamp as a standard int64. +func (ev *T) CreatedAtInt64() (i int64) { return ev.CreatedAt.I64() } + +// KindInt32 returns the kind as an int32, as is often needed for JSON. +func (ev *T) KindInt32() (i int32) { return int32(ev.Kind.K) } + +// PubKeyString returns the pubkey as a hex encoded string. +func (ev *T) PubKeyString() (s string) { return hex.Enc(ev.Pubkey) } + +// SigString returns the signature as a hex encoded string. +func (ev *T) SigString() (s string) { return hex.Enc(ev.Sig) } + +// TagStrings returns the tags as a slice of slice of strings. +func (ev *T) TagStrings() (s [][]string) { return ev.Tags.ToStringSlice() } + +// ContentString returns the content field as a string. +func (ev *T) ContentString() (s string) { return string(ev.Content) } + +// J is an event.T encoded in more basic types than used in this library. type J struct { Id string `json:"id"` Pubkey string `json:"pubkey"` @@ -78,9 +115,10 @@ type J struct { Sig string `json:"sig"` } +// ToEventJ converts an event.T into an event.J. func (ev *T) ToEventJ() (j *J) { j = &J{} - j.Id = ev.IDString() + j.Id = ev.IdString() j.Pubkey = ev.PubKeyString() j.CreatedAt = ev.CreatedAt.I64() j.Kind = ev.KindInt32() @@ -90,32 +128,48 @@ func (ev *T) ToEventJ() (j *J) { return } -func (ev *T) IDFromString(s string) (err error) { - ev.ID, err = hex.Dec(s) +// IdFromString decodes an event ID and loads it into an event.T Id. +func (ev *T) IdFromString(s string) (err error) { + ev.Id, err = hex.Dec(s) return } +// CreatedAtFromInt64 encodes a unix timestamp into the CreatedAt field of an +// event.T. func (ev *T) CreatedAtFromInt64(i int64) { ev.CreatedAt = timestamp.FromUnix(i) return } +// KindFromInt32 encodes an int32 representation of a kind.T into an event.T. func (ev *T) KindFromInt32(i int32) { ev.Kind = &kind.T{} ev.Kind.K = uint16(i) return } +// PubKeyFromString decodes a hex-encoded string into the event.T Pubkey field. func (ev *T) PubKeyFromString(s string) (err error) { - ev.PubKey, err = hex.Dec(s) + if len(s) != 2*schnorr.PubKeyBytesLen { + err = errorf.E("invalid length public key hex, got %d require %d", + len(s), 2*schnorr.PubKeyBytesLen) + } + ev.Pubkey, err = hex.Dec(s) return } +// SigFromString decodes a hex-encoded string into the event.T Sig field. func (ev *T) SigFromString(s string) (err error) { + if len(s) != 2*schnorr.SignatureSize { + err = errorf.E("invalid length signature hex, got %d require %d", + len(s), 2*schnorr.SignatureSize) + } ev.Sig, err = hex.Dec(s) return } +// TagsFromStrings converts a slice of slice of strings into a tags.T for the +// event.T. func (ev *T) TagsFromStrings(s ...[]string) { ev.Tags = tags.NewWithCap(len(s)) var tgs []*tag.T @@ -127,15 +181,16 @@ func (ev *T) TagsFromStrings(s ...[]string) { return } +// ContentFromString imports a content string into the event.T Content field. func (ev *T) ContentFromString(s string) { ev.Content = []byte(s) return } -// ToEvent converts this above format to the realy native form +// ToEvent converts event.J format to the realy native form. func (e J) ToEvent() (ev *T, err error) { ev = &T{} - if err = ev.IDFromString(e.Id); chk.E(err) { + if err = ev.IdFromString(e.Id); chk.E(err) { return } ev.CreatedAtFromInt64(e.CreatedAt) @@ -151,17 +206,21 @@ func (e J) ToEvent() (ev *T, err error) { return } +// Hash is a little helper generate a hash and return a slice instead of an +// array. func Hash(in []byte) (out []byte) { h := sha256.Sum256(in) return h[:] } +// GenerateRandomTextNoteEvent creates a generic event.T with random text +// content. func GenerateRandomTextNoteEvent(sign signer.I, maxSize int) (ev *T, err error) { l := frand.Intn(maxSize * 6 / 8) // account for base64 expansion ev = &T{ - PubKey: sign.Pub(), + Pubkey: sign.Pub(), Kind: kind.TextNote, CreatedAt: timestamp.Now(), Content: text.NostrEscape(nil, frand.Bytes(l)), diff --git a/event/json.go b/event/json.go index 7ed95b9..2c17cdd 100644 --- a/event/json.go +++ b/event/json.go @@ -24,65 +24,61 @@ var ( jSig = []byte("sig") ) +// Marshal appends an event.T to a provided destination slice. func (ev *T) Marshal(dst []byte) (b []byte) { b = ev.marshalWithWhitespace(dst, false) return } +// marshalWithWhitespace adds tabs and newlines to make the JSON more readable +// for humans, if the on flag is set to true. func (ev *T) marshalWithWhitespace(dst []byte, on bool) (b []byte) { // open parentheses dst = append(dst, '{') - // ID + // Id if on { - dst = append(dst, '\n') - dst = append(dst, '\t') + dst = append(dst, '\n', '\t') } dst = text.JSONKey(dst, jId) - dst = text.AppendQuote(dst, ev.ID, hex.EncAppend) + dst = text.AppendQuote(dst, ev.Id, hex.EncAppend) dst = append(dst, ',') - // PubKey + // Pubkey if on { - dst = append(dst, '\n') - dst = append(dst, '\t') + dst = append(dst, '\n', '\t') } dst = text.JSONKey(dst, jPubkey) - dst = text.AppendQuote(dst, ev.PubKey, hex.EncAppend) + dst = text.AppendQuote(dst, ev.Pubkey, hex.EncAppend) dst = append(dst, ',') if on { - dst = append(dst, '\n') - dst = append(dst, '\t') + dst = append(dst, '\n', '\t') } // CreatedAt dst = text.JSONKey(dst, jCreatedAt) dst = ev.CreatedAt.Marshal(dst) dst = append(dst, ',') if on { - dst = append(dst, '\n') - dst = append(dst, '\t') + dst = append(dst, '\n', '\t') } // Kind dst = text.JSONKey(dst, jKind) dst = ev.Kind.Marshal(dst) dst = append(dst, ',') if on { - dst = append(dst, '\n') - dst = append(dst, '\t') + dst = append(dst, '\n', '\t') } // Tags dst = text.JSONKey(dst, jTags) dst = ev.Tags.Marshal(dst) dst = append(dst, ',') if on { - dst = append(dst, '\n') - dst = append(dst, '\t') + dst = append(dst, '\n', '\t') } // Content dst = text.JSONKey(dst, jContent) dst = text.AppendQuote(dst, ev.Content, text.NostrEscape) dst = append(dst, ',') if on { - dst = append(dst, '\n') - dst = append(dst, '\t') + dst = append(dst, '\n', '\t') } // jSig dst = text.JSONKey(dst, jSig) @@ -96,8 +92,11 @@ func (ev *T) marshalWithWhitespace(dst []byte, on bool) (b []byte) { return } +// Marshal is a normal function that is the same as event.T Marshal method +// except you explicitly specify the receiver. func Marshal(ev *T, dst []byte) (b []byte) { return ev.Marshal(dst) } +// Unmarshal an event from minified JSON into an event.T. func (ev *T) Unmarshal(b []byte) (r []byte, err error) { // this parser does not cope with whitespaces in valid places in json, so we // scan first for linebreaks, as these indicate that it is probably not gona work and fall back to json.Unmarshal @@ -162,11 +161,11 @@ InVal: return } if len(id) != sha256.Size { - err = errorf.E("invalid ID, require %d got %d", sha256.Size, + err = errorf.E("invalid Id, require %d got %d", sha256.Size, len(id)) return } - ev.ID = id + ev.Id = id goto BetweenKV case jPubkey[0]: if !bytes.Equal(jPubkey, key) { @@ -181,7 +180,7 @@ InVal: schnorr.PubKeyBytesLen, len(pk)) return } - ev.PubKey = pk + ev.Pubkey = pk goto BetweenKV case jKind[0]: if !bytes.Equal(jKind, key) { @@ -269,4 +268,6 @@ eof: return } +// Unmarshal is the same as the event.T Unmarshal method except you give it the +// event to marshal into instead of call it as a method of the type. func Unmarshal(ev *T, b []byte) (r []byte, err error) { return ev.Unmarshal(b) } diff --git a/event/signatures.go b/event/signatures.go index 074dc3a..7a827bb 100644 --- a/event/signatures.go +++ b/event/signatures.go @@ -12,12 +12,12 @@ import ( // Sign the event using the signer.I. Uses github.com/bitcoin-core/secp256k1 if // available for much faster signatures. // -// Note that this only populates the PubKey, ID and Sig. The caller must +// Note that this only populates the Pubkey, Id and Sig. The caller must // set the CreatedAt timestamp as intended. func (ev *T) Sign(keys signer.I) (err error) { - ev.PubKey = keys.Pub() - ev.ID = ev.GetIDBytes() - if ev.Sig, err = keys.Sign(ev.ID); chk.E(err) { + ev.Pubkey = keys.Pub() + ev.Id = ev.GetIDBytes() + if ev.Sig, err = keys.Sign(ev.Id); chk.E(err) { return } return @@ -27,20 +27,20 @@ func (ev *T) Sign(keys signer.I) (err error) { // github.com/bitcoin-core/secp256k1 if available for faster verification. func (ev *T) Verify() (valid bool, err error) { keys := p256k.Signer{} - if err = keys.InitPub(ev.PubKey); chk.E(err) { + if err = keys.InitPub(ev.Pubkey); chk.E(err) { return } - if valid, err = keys.Verify(ev.ID, ev.Sig); chk.T(err) { - // check that this isn't because of a bogus ID + if valid, err = keys.Verify(ev.Id, ev.Sig); chk.T(err) { + // check that this isn't because of a bogus Id id := ev.GetIDBytes() - if !bytes.Equal(id, ev.ID) { - log.E.Ln("event ID incorrect") - ev.ID = id + if !bytes.Equal(id, ev.Id) { + log.E.Ln("event Id incorrect") + ev.Id = id err = nil - if valid, err = keys.Verify(ev.ID, ev.Sig); chk.E(err) { + if valid, err = keys.Verify(ev.Id, ev.Sig); chk.E(err) { return } - err = errorf.W("event ID incorrect but signature is valid on correct ID") + err = errorf.W("event Id incorrect but signature is valid on correct Id") } return } @@ -55,25 +55,25 @@ func (ev *T) SignWithSecKey(sk *k1.SecretKey, // sign the event. var sig *sch.Signature - ev.ID = ev.GetIDBytes() - if sig, err = sch.Sign(sk, ev.ID, so...); chk.D(err) { + ev.Id = ev.GetIDBytes() + if sig, err = sch.Sign(sk, ev.Id, so...); chk.D(err) { return } // we know secret key is good so we can generate the public key. - ev.PubKey = sch.SerializePubKey(sk.PubKey()) + ev.Pubkey = sch.SerializePubKey(sk.PubKey()) ev.Sig = sig.Serialize() return } // CheckSignature returns whether an event signature is authentic and matches -// the event ID and Pubkey. +// the event Id and Pubkey. // // Deprecated: use Verify func (ev *T) CheckSignature() (valid bool, err error) { // parse pubkey bytes. var pk *k1.PublicKey - if pk, err = sch.ParsePubKey(ev.PubKey); chk.D(err) { - err = errorf.E("event has invalid pubkey '%0x': %v", ev.PubKey, err) + if pk, err = sch.ParsePubKey(ev.Pubkey); chk.D(err) { + err = errorf.E("event has invalid pubkey '%0x': %v", ev.Pubkey, err) return } // parse signature bytes. diff --git a/event/sort.go b/event/sort.go index 6a5d612..b38180e 100644 --- a/event/sort.go +++ b/event/sort.go @@ -1,6 +1,7 @@ package event -// Ascending is a slice of events that sorts in ascending chronological order +// Ascending is a slice of events that sorts in chronological order (oldest +// first. type Ascending []*T func (ev Ascending) Len() int { return len(ev) } diff --git a/event/wirecompact.go b/event/wirecompact.go index c146c1c..446516c 100644 --- a/event/wirecompact.go +++ b/event/wirecompact.go @@ -5,7 +5,7 @@ import ( ) // MarshalWireCompact encodes an event as the canonical form wrapped in an array -// with the signature encoded in raw Base64 URL +// with the signature encoded in raw Base64 URL (86 bytes instead of 128 of hex). func (ev *T) MarshalWireCompact(dst []byte) (b []byte) { b = dst b = append(b, '[') @@ -18,6 +18,9 @@ func (ev *T) MarshalWireCompact(dst []byte) (b []byte) { return } +// UnmarshalWireCompact decodes an event encoded in minified Wire Compact form - +// with an enclosing array around the canonical form of the event with the +// signature encoded in Base64 URL (86 bytes instead of 128 of hex). func (ev *T) UnmarshalWireCompact(b []byte) (rem []byte, err error) { startEv := 1 endSig := len(b) - 2 @@ -31,6 +34,6 @@ func (ev *T) UnmarshalWireCompact(b []byte) (rem []byte, err error) { sigB := make([]byte, 64) _, err = base64.RawURLEncoding.Decode(sigB, b[startSig:endSig]) ev.Sig = sigB - ev.ID = id + ev.Id = id return } diff --git a/eventid/eventid.go b/eventid/eventid.go index 31ea50f..f9c121c 100644 --- a/eventid/eventid.go +++ b/eventid/eventid.go @@ -33,7 +33,7 @@ func (ei *T) Set(b []byte) (err error) { return } if len(b) != sha256.Size { - err = errorf.E("ID bytes incorrect size, got %d require %d", len(b), sha256.Size) + err = errorf.E("Id bytes incorrect size, got %d require %d", len(b), sha256.Size) return } copy(ei[:], b) @@ -90,7 +90,7 @@ func (ei *T) Unmarshal(b []byte) (rem []byte, err error) { // trim off the quotes. b = b[1 : 2*sha256.Size+1] if len(b) != 2*sha256.Size { - err = errorf.E("event ID hex incorrect size, got %d require %d", + err = errorf.E("event Id hex incorrect size, got %d require %d", len(b), 2*sha256.Size) log.E.Ln(string(b)) return @@ -107,7 +107,7 @@ func (ei *T) Unmarshal(b []byte) (rem []byte, err error) { // hexadecimal string, returns the string coerced to the type. func NewFromString(s string) (ei *T, err error) { if len(s) != 2*sha256.Size { - return nil, errorf.E("event ID hex wrong size, got %d require %d", + return nil, errorf.E("event Id hex wrong size, got %d require %d", len(s), 2*sha256.Size) } ei = &T{} @@ -117,7 +117,7 @@ func NewFromString(s string) (ei *T, err error) { return } -// Gen creates a fake pseudorandom generated event ID for tests. +// Gen creates a fake pseudorandom generated event Id for tests. func Gen() (ei *T) { b := frand.Bytes(sha256.Size) ei = &T{} diff --git a/filter/filter.go b/filter/filter.go index 4ac1a48..53defff 100644 --- a/filter/filter.go +++ b/filter/filter.go @@ -420,7 +420,7 @@ func (f *T) Matches(ev *event.T) bool { // log.T.F("nil event") return false } - if f.IDs.Len() > 0 && !f.IDs.Contains(ev.ID) { + if f.IDs.Len() > 0 && !f.IDs.Contains(ev.Id) { // log.T.F("no ids in filter match event\nEVENT %s\nFILTER %s", ev.ToObject().String(), f.ToObject().String()) return false } @@ -428,7 +428,7 @@ func (f *T) Matches(ev *event.T) bool { // log.T.F("no matching kinds in filter\nEVENT %s\nFILTER %s", ev.ToObject().String(), f.ToObject().String()) return false } - if f.Authors.Len() > 0 && !f.Authors.Contains(ev.PubKey) { + if f.Authors.Len() > 0 && !f.Authors.Contains(ev.Pubkey) { // log.T.F("no matching authors in filter\nEVENT %s\nFILTER %s", ev.ToObject().String(), f.ToObject().String()) return false } diff --git a/filter/simple.go b/filter/simple.go index 5880993..fc0c6aa 100644 --- a/filter/simple.go +++ b/filter/simple.go @@ -17,7 +17,7 @@ import ( ) // S is a simplified filter that only covers the nip-01 REQ filter minus the -// separate and superseding ID list. The search field is from a different NIP, +// separate and superseding Id list. The search field is from a different NIP, // but it is a separate API for which reason it is also not here. type S struct { Kinds *kinds.T `json:"kinds,omitempty"` @@ -315,7 +315,7 @@ func (f *S) Matches(ev *event.T) bool { // log.T.F("no matching kinds in filter\nEVENT %s\nFILTER %s", ev.ToObject().String(), s.ToObject().String()) return false } - if f.Authors.Len() > 0 && !f.Authors.Contains(ev.PubKey) { + if f.Authors.Len() > 0 && !f.Authors.Contains(ev.Pubkey) { // log.T.F("no matching authors in filter\nEVENT %s\nFILTER %s", ev.ToObject().String(), s.ToObject().String()) return false } diff --git a/httpauth/validate.go b/httpauth/validate.go index e22bda4..cb00113 100644 --- a/httpauth/validate.go +++ b/httpauth/validate.go @@ -120,7 +120,7 @@ func CheckAuth(r *http.Request, vfn VerifyJWTFunc, tolerance ...time.Duration) ( if !valid { return } - pubkey = ev.PubKey + pubkey = ev.Pubkey case strings.HasPrefix(val, JWTPrefix): if vfn == nil { err = errorf.E("JWT bearer header found but no JWT verifier function provided") diff --git a/layer2/badgerbadger/badgerbadger.go b/layer2/badgerbadger/badgerbadger.go index f5d3efb..bc5512b 100644 --- a/layer2/badgerbadger/badgerbadger.go +++ b/layer2/badgerbadger/badgerbadger.go @@ -35,7 +35,7 @@ func GetBackend(c context.T, wg *sync.WaitGroup, L1, L2 *ratel.T) (es store.I) { // Init sets up the badger event store and connects to the configured IC // canister. // -// required params are address, canister ID and the badger event store size +// required params are address, canister Id and the badger event store size // limit (which can be 0) func (b *Backend) Init(path string) (err error) { return b.Backend.Init(path) } diff --git a/layer2/badgerbadger/tester/badgerbadger.go b/layer2/badgerbadger/tester/badgerbadger.go index f99ee17..08934c6 100644 --- a/layer2/badgerbadger/tester/badgerbadger.go +++ b/layer2/badgerbadger/tester/badgerbadger.go @@ -171,7 +171,7 @@ end: return } mx.Lock() - counter = append(counter, Counter{id: ev.ID, size: bs, requested: 1}) + counter = append(counter, Counter{id: ev.Id, size: bs, requested: 1}) total += bs if total > TotalSize*10*units.Gb { log.I.Ln(total, TotalSize*units.Gb) diff --git a/layer2/layer2.go b/layer2/layer2.go index ee6daca..18793b2 100644 --- a/layer2/layer2.go +++ b/layer2/layer2.go @@ -131,14 +131,14 @@ func (b *Backend) QueryEvents(c context.T, f *filter.T) (evs event.Ts, err error if evs, err = b.L1.QueryEvents(c, f); chk.E(err) { return } - // if there is pruned events (have only ID, no pubkey), they will also be in the + // if there is pruned events (have only Id, no pubkey), they will also be in the // L2 result, save these to the L1. var revives [][]byte var founds event.Ts for _, ev := range evs { - if len(ev.PubKey) == 0 { - // note the event ID to fetch - revives = append(revives, ev.ID) + if len(ev.Pubkey) == 0 { + // note the event Id to fetch + revives = append(revives, ev.Id) } else { founds = append(founds, ev) } diff --git a/p256k/btcec/btcec.go b/p256k/btcec/btcec.go index 6270052..c2fc7b3 100644 --- a/p256k/btcec/btcec.go +++ b/p256k/btcec/btcec.go @@ -67,7 +67,7 @@ func (s *Signer) Sign(msg []byte) (sig []byte, err error) { func (s *Signer) Verify(msg, sig []byte) (valid bool, err error) { if s.PublicKey == nil { - err = errorf.E("btcec: PubKey not initialized") + err = errorf.E("btcec: Pubkey not initialized") return } var si *schnorr.Signature diff --git a/p256k/btcec/btcec_test.go b/p256k/btcec/btcec_test.go index 4a8be0e..db0d152 100644 --- a/p256k/btcec/btcec_test.go +++ b/p256k/btcec/btcec_test.go @@ -52,14 +52,14 @@ func TestBTCECSignerVerify(t *testing.T) { t.Errorf("id should be 32 bytes, got %d", len(id)) continue } - if err = signer.InitPub(ev.PubKey); chk.E(err) { + if err = signer.InitPub(ev.Pubkey); chk.E(err) { t.Errorf("failed to init pub key: %s\n%0x", err, b) } if valid, err = signer.Verify(id, ev.Sig); chk.E(err) { t.Errorf("failed to verify: %s\n%0x", err, b) } if !valid { - t.Errorf("invalid signature for pub %0x %0x %0x", ev.PubKey, id, + t.Errorf("invalid signature for pub %0x %0x %0x", ev.Pubkey, id, ev.Sig) } evs = append(evs, ev) @@ -97,7 +97,7 @@ func TestBTCECSignerSign(t *testing.T) { var valid bool sig := make([]byte, schnorr.SignatureSize) for _, ev := range evs { - ev.PubKey = pkb + ev.Pubkey = pkb id := ev.GetIDBytes() if sig, err = signer.Sign(id); chk.E(err) { t.Errorf("failed to sign: %s\n%0x", err, id) diff --git a/p256k/p256k.go b/p256k/p256k.go index 257ca8e..919f1f8 100644 --- a/p256k/p256k.go +++ b/p256k/p256k.go @@ -92,7 +92,7 @@ func (s *Signer) Sign(msg []byte) (sig []byte, err error) { func (s *Signer) Verify(msg, sig []byte) (valid bool, err error) { if s.PublicKey == nil { - err = errorf.E("p256k: PubKey not initialized") + err = errorf.E("p256k: Pubkey not initialized") return } var uMsg, uSig *Uchar @@ -118,4 +118,4 @@ func (s *Signer) ECDH(pubkeyBytes []byte) (secret []byte, err error) { return } -func (s *Signer) Zero() { Zero(s.SecretKey) } \ No newline at end of file +func (s *Signer) Zero() { Zero(s.SecretKey) } diff --git a/p256k/p256k_test.go b/p256k/p256k_test.go index ffdcfdc..a2cb807 100644 --- a/p256k/p256k_test.go +++ b/p256k/p256k_test.go @@ -57,17 +57,17 @@ func TestSignerVerify(t *testing.T) { t.Errorf("id should be 32 bytes, got %d", len(id)) continue } - if err = signer.InitPub(ev.PubKey); chk.T(err) { - t.Errorf("failed to init pub key: %s\n%0x", err, ev.PubKey) + if err = signer.InitPub(ev.Pubkey); chk.T(err) { + t.Errorf("failed to init pub key: %s\n%0x", err, ev.Pubkey) continue } if valid, err = signer.Verify(id, ev.Sig); chk.E(err) { - t.Errorf("failed to verify: %s\n%0x", err, ev.ID) + t.Errorf("failed to verify: %s\n%0x", err, ev.Id) continue } if !valid { t.Errorf("invalid signature for\npub %0x\neid %0x\nsig %0x\n%s", - ev.PubKey, id, ev.Sig, bc) + ev.Pubkey, id, ev.Sig, bc) continue } // fmt.Printf("%s\n", bc) @@ -105,7 +105,7 @@ func TestSignerSign(t *testing.T) { var valid bool sig := make([]byte, schnorr.SignatureSize) for _, ev := range evs { - ev.PubKey = pkb + ev.Pubkey = pkb id := ev.GetIDBytes() if sig, err = signer.Sign(id); chk.E(err) { t.Errorf("failed to sign: %s\n%0x", err, id) diff --git a/p256k/secp256k1_test.go b/p256k/secp256k1_test.go index 77028dc..46dc482 100644 --- a/p256k/secp256k1_test.go +++ b/p256k/secp256k1_test.go @@ -37,7 +37,7 @@ func TestVerify(t *testing.T) { t.Errorf("id should be 32 bytes, got %d", len(id)) continue } - if err = p256k.VerifyFromBytes(id, ev.Sig, ev.PubKey); chk.E(err) { + if err = p256k.VerifyFromBytes(id, ev.Sig, ev.Pubkey); chk.E(err) { t.Error(err) continue } @@ -67,7 +67,7 @@ func TestSign(t *testing.T) { } sig := make([]byte, schnorr.SignatureSize) for _, ev := range evs { - ev.PubKey = pb + ev.Pubkey = pb var uid *p256k.Uchar if uid, err = p256k.Msg(ev.GetIDBytes()); chk.E(err) { t.Fatal(err) diff --git a/ratel/countevents.go b/ratel/countevents.go index d2185d6..e552bfc 100644 --- a/ratel/countevents.go +++ b/ratel/countevents.go @@ -116,7 +116,7 @@ func (r *T) CountEvents(c context.T, f *filter.T) (count int, approx bool, err e } if int64(exp) > time.Now().Unix() { // this needs to be deleted - delEvs = append(delEvs, ev.ID) + delEvs = append(delEvs, ev.Id) return } } diff --git a/ratel/deleteevent.go b/ratel/deleteevent.go index 6cff78b..392d01b 100644 --- a/ratel/deleteevent.go +++ b/ratel/deleteevent.go @@ -69,7 +69,7 @@ func (r *T) DeleteEvent(c context.T, eid *eventid.T, noTombstone ...bool) (err e // we don't make tombstones for replacements, but it is better to shift that // logic outside of this closure. if len(noTombstone) > 0 && !noTombstone[0] { - ts := tombstone.NewWith(ev.EventID()) + ts := tombstone.NewWith(ev.EventId()) tombstoneKey = prefixes.Tombstone.Key(ts, createdat.New(timestamp.Now())) } return @@ -88,7 +88,7 @@ func (r *T) DeleteEvent(c context.T, eid *eventid.T, noTombstone ...bool) (err e } if len(tombstoneKey) > 0 { // write tombstone - log.W.F("writing tombstone %0x for event %0x", tombstoneKey, ev.ID) + log.W.F("writing tombstone %0x for event %0x", tombstoneKey, ev.Id) if err = txn.Set(tombstoneKey, nil); chk.E(err) { return } diff --git a/ratel/gcsweep.go b/ratel/gcsweep.go index c7b2488..8b63f49 100644 --- a/ratel/gcsweep.go +++ b/ratel/gcsweep.go @@ -58,7 +58,7 @@ func (r *T) GCSweep(evs, idxs DelItems) (err error) { if item.ValueSize() == sha256.Size { return } - // if there is L2 we are only pruning (replacing event with the ID hash) + // if there is L2 we are only pruning (replacing event with the Id hash) var evb []byte if evb, err = item.ValueCopy(nil); chk.E(err) { return @@ -75,7 +75,7 @@ func (r *T) GCSweep(evs, idxs DelItems) (err error) { if err = batch.Delete(key); chk.E(err) { return } - if err = batch.Set(key, ev.ID); chk.E(err) { + if err = batch.Set(key, ev.Id); chk.E(err) { return } return diff --git a/ratel/getecounterkey.go b/ratel/getecounterkey.go index 3c97dd9..2759c43 100644 --- a/ratel/getecounterkey.go +++ b/ratel/getecounterkey.go @@ -5,7 +5,7 @@ import ( "realy.lol/ratel/prefixes" ) -// GetCounterKey returns the proper counter key for a given event ID. This needs +// GetCounterKey returns the proper counter key for a given event Id. This needs // a separate function because of what it does, but is generated in the general // GetIndexKeysForEvent function. func GetCounterKey(ser *serial.T) (key []byte) { diff --git a/ratel/getindexkeysforevent.go b/ratel/getindexkeysforevent.go index 50cfdd7..e15c23e 100644 --- a/ratel/getindexkeysforevent.go +++ b/ratel/getindexkeysforevent.go @@ -25,12 +25,12 @@ func GetIndexKeysForEvent(ev *event.T, ser *serial.T) (keyz [][]byte) { var err error keyz = make([][]byte, 0, 18) - ID := id.New(eventid.NewWith(ev.ID)) + ID := id.New(eventid.NewWith(ev.Id)) CA := createdat.New(ev.CreatedAt) K := kinder.New(ev.Kind.ToU16()) - PK, _ := pubkey.New(ev.PubKey) - FID := fullid.New(eventid.NewWith(ev.ID)) - FPK := fullpubkey.New(ev.PubKey) + PK, _ := pubkey.New(ev.Pubkey) + FID := fullid.New(eventid.NewWith(ev.Id)) + FPK := fullpubkey.New(ev.Pubkey) // indexes { // ~ by id k := prefixes.Id.Key(ID, ser) @@ -100,7 +100,7 @@ func GetIndexKeysForEvent(ev *event.T, ser *serial.T) (keyz [][]byte) { k := GetCounterKey(ser) keyz = append(keyz, k) } - { // - full ID index - enabling retrieving the event ID without unmarshalling the data + { // - full Id index - enabling retrieving the event Id without unmarshalling the data k := prefixes.FullIndex.Key(ser, FID, FPK, CA) // log.T.F("full id: %x %0x %0x", k[0], k[1:9], k[9:]) keyz = append(keyz, k) diff --git a/ratel/keys/id/id.go b/ratel/keys/id/id.go index 3cef36e..cf7bdbe 100644 --- a/ratel/keys/id/id.go +++ b/ratel/keys/id/id.go @@ -42,7 +42,7 @@ func New(evID ...*eventid.T) (p *T) { func NewFromBytes(b []byte) (p *T, err error) { if len(b) != sha256.Size { - err = errorf.E("event ID must be 32 bytes got: %d %0x", len(b), b) + err = errorf.E("event Id must be 32 bytes got: %d %0x", len(b), b) return } p = &T{Val: b[:Len]} diff --git a/ratel/main.go b/ratel/main.go index a4c6b0f..6eadf4f 100644 --- a/ratel/main.go +++ b/ratel/main.go @@ -52,7 +52,7 @@ type T struct { // triggered by running an import Flatten bool // UseCompact uses a compact encoding based on the canonical format (generate - // hash of it to get ID field with the signature in raw binary after. + // hash of it to get Id field with the signature in raw binary after. UseCompact bool // Compression sets the compression to use, none/snappy/zstd Compression string diff --git a/ratel/prefixes/prefixes.go b/ratel/prefixes/prefixes.go index 0927ae9..84530ea 100644 --- a/ratel/prefixes/prefixes.go +++ b/ratel/prefixes/prefixes.go @@ -35,7 +35,7 @@ const ( // [ 1 ][ 8 bytes timestamp.T ][ 8 bytes Serial ] CreatedAt - // Id contains the first 8 bytes of the ID of the event and the 8 + // Id contains the first 8 bytes of the Id of the event and the 8 // byte Serial of the event record. // // [ 2 ][ 8 bytes eventid.T prefix ][ 8 bytes Serial ] @@ -79,13 +79,13 @@ const ( // [ 9 ][ 8 bytes Serial ] : value: [ 8 bytes timestamp ] Counter - // Tombstone is an index that contains the left half of an event ID that has + // Tombstone is an index that contains the left half of an event Id that has // been deleted. The purpose of this event is to stop the event being // republished, as a delete event may not be respected by other relays and // eventually lead to a republication. The timestamp is added at the end to // enable pruning the oldest tombstones. // - // [ 10 ][ 16 bytes first/left half of event ID ][ 8 bytes timestamp ] + // [ 10 ][ 16 bytes first/left half of event Id ][ 8 bytes timestamp ] Tombstone // PubkeyIndex is the prefix for an index that stores a mapping between pubkeys @@ -103,7 +103,7 @@ const ( // ultimately be deprecated in favor of this because returning event Ids and // letting the client handle pagination reduces relay complexity. // - // In addition, as a mechanism of sorting, the event ID bears also a timestamp + // In addition, as a mechanism of sorting, the event Id bears also a timestamp // from its created_at field. The serial acts as a "first seen" ordering, then // you also have the (claimed) chronological ordering. // diff --git a/ratel/preparequeries.go b/ratel/preparequeries.go index 85b0e3b..85cc986 100644 --- a/ratel/preparequeries.go +++ b/ratel/preparequeries.go @@ -49,7 +49,7 @@ func PrepareQueries(f *filter.T) ( for i, idB := range f.IDs.F() { ih := id.New(eventid.NewWith(idB)) if ih == nil { - log.E.F("failed to decode event ID: %s", idB) + log.E.F("failed to decode event Id: %s", idB) // just ignore it, clients will be clients continue } diff --git a/ratel/queryevents.go b/ratel/queryevents.go index 356f5ad..c66876e 100644 --- a/ratel/queryevents.go +++ b/ratel/queryevents.go @@ -127,7 +127,7 @@ func (r *T) QueryEvents(c context.T, f *filter.T) (evs event.Ts, err error) { // accumulating to propagate the query (this means response lag also) // // this is a stub entry that indicates an L2 needs to be accessed for it, so we - // populate only the event.T.ID and return the result, the caller will expect + // populate only the event.T.Id and return the result, the caller will expect // this as a signal to query the L2 event store. var eventValue []byte ev := &event.T{} @@ -135,7 +135,7 @@ func (r *T) QueryEvents(c context.T, f *filter.T) (evs event.Ts, err error) { continue } log.T.F("found event stub %0x must seek in L2", eventValue) - ev.ID = eventValue + ev.Id = eventValue select { case <-c.Done(): return @@ -144,7 +144,7 @@ func (r *T) QueryEvents(c context.T, f *filter.T) (evs event.Ts, err error) { return default: } - evMap[hex.Enc(ev.ID)] = ev + evMap[hex.Enc(ev.Id)] = ev return } ev := &event.T{} @@ -163,7 +163,7 @@ func (r *T) QueryEvents(c context.T, f *filter.T) (evs event.Ts, err error) { } if int64(exp) > time.Now().Unix() { // this needs to be deleted - delEvs = append(delEvs, ev.ID) + delEvs = append(delEvs, ev.Id) ev = nil return } @@ -176,7 +176,7 @@ func (r *T) QueryEvents(c context.T, f *filter.T) (evs event.Ts, err error) { continue } if ext == nil || ext.Matches(ev) { - evMap[hex.Enc(ev.ID)] = ev + evMap[hex.Enc(ev.Id)] = ev // add event counter key to accessed ser := serial.FromKey(eventKey) accessed[string(ser.Val)] = struct{}{} @@ -214,7 +214,7 @@ func (r *T) QueryEvents(c context.T, f *filter.T) (evs event.Ts, err error) { } if len(evMap) > 0 { for i := range evMap { - if len(evMap[i].PubKey) == 0 { + if len(evMap[i].Pubkey) == 0 { log.I.S(evMap[i]) continue } @@ -227,7 +227,7 @@ func (r *T) QueryEvents(c context.T, f *filter.T) (evs event.Ts, err error) { // log.T.C(func() string { // evIds := make([]string, len(evs)) // for i, ev := range evs { - // evIds[i] = hex.Enc(ev.ID) + // evIds[i] = hex.Enc(ev.Id) // } // heading := fmt.Sprintf("query complete,%d events found,%s", len(evs), // f.Serialize()) diff --git a/ratel/queryforids.go b/ratel/queryforids.go index c5b8c23..530c3d9 100644 --- a/ratel/queryforids.go +++ b/ratel/queryforids.go @@ -100,7 +100,7 @@ func (r *T) QueryForIds(c context.T, f *filter.T) (founds []store.IdTsPk, err er item := it.Item() if r.HasL2 && item.ValueSize() == sha256.Size { // this is a stub entry that indicates an L2 needs to be accessed for - // it, so we populate only the event.T.ID and return the result, the + // it, so we populate only the event.T.Id and return the result, the // caller will expect this as a signal to query the L2 event store. var eventValue []byte ev := &event.T{} @@ -108,8 +108,8 @@ func (r *T) QueryForIds(c context.T, f *filter.T) (founds []store.IdTsPk, err er continue } log.T.F("found event stub %0x must seek in L2", eventValue) - ev.ID = eventValue - l2Map[hex.Enc(ev.ID)] = ev + ev.Id = eventValue + l2Map[hex.Enc(ev.Id)] = ev return } ev := &event.T{} @@ -128,7 +128,7 @@ func (r *T) QueryForIds(c context.T, f *filter.T) (founds []store.IdTsPk, err er } if int64(exp) > time.Now().Unix() { // this needs to be deleted - delEvs = append(delEvs, ev.ID) + delEvs = append(delEvs, ev.Id) return } } diff --git a/ratel/saveevent.go b/ratel/saveevent.go index 2e620ff..a7eb8db 100644 --- a/ratel/saveevent.go +++ b/ratel/saveevent.go @@ -25,14 +25,14 @@ func (r *T) SaveEvent(c context.T, ev *event.T) (err error) { // make sure Close waits for this to complete r.WG.Add(1) defer r.WG.Done() - // first, search to see if the event ID already exists. + // first, search to see if the event Id already exists. var foundSerial []byte var deleted bool seri := serial.New(nil) var ts []byte err = r.View(func(txn *badger.Txn) (err error) { // query event by id to ensure we don't try to save duplicates - prf := prefixes.Id.Key(id.New(eventid.NewWith(ev.ID))) + prf := prefixes.Id.Key(id.New(eventid.NewWith(ev.Id))) it := txn.NewIterator(badger.IteratorOptions{}) defer it.Close() it.Seek(prf) @@ -46,7 +46,7 @@ func (r *T) SaveEvent(c context.T, ev *event.T) (err error) { foundSerial = seri.Val } // if the event was deleted we don't want to save it again - ts = prefixes.Tombstone.Key(id.New(eventid.NewWith(ev.ID))) + ts = prefixes.Tombstone.Key(id.New(eventid.NewWith(ev.Id))) it.Seek(ts) if it.ValidForPrefix(ts) { deleted = true @@ -70,7 +70,7 @@ func (r *T) SaveEvent(c context.T, ev *event.T) (err error) { if it.ValidForPrefix(evKey) { if it.Item().ValueSize() != sha256.Size { // not a stub, we already have it - // log.D.F("duplicate event %0x", ev.ID) + // log.D.F("duplicate event %0x", ev.Id) return eventstore.ErrDupEvent } // we only need to restore the event binary and write the access counter key diff --git a/realy/addEvent.go b/realy/addEvent.go index 8c343d4..4d467d2 100644 --- a/realy/addEvent.go +++ b/realy/addEvent.go @@ -28,11 +28,11 @@ func (s *Server) addEvent(c context.T, rl relay.I, ev *event.T, advancedSaver, _ := sto.(relay.AdvancedSaver) // don't allow storing event with protected marker as per nip-70 with auth enabled. if (s.authRequired || !s.publicReadable) && ev.Tags.ContainsProtectedMarker() { - if len(authedPubkey) == 0 || !bytes.Equal(ev.PubKey, authedPubkey) { + if len(authedPubkey) == 0 || !bytes.Equal(ev.Pubkey, authedPubkey) { return false, []byte(fmt.Sprintf("event with relay marker tag '-' (nip-70 protected event) "+ "may only be published by matching npub: %0x is not %0x", - authedPubkey, ev.PubKey)) + authedPubkey, ev.Pubkey)) } } if ev.Kind.IsEphemeral() { @@ -67,6 +67,6 @@ func (s *Server) addEvent(c context.T, rl relay.I, ev *event.T, } s.Listeners.NotifyListeners(authRequired, s.publicReadable, ev) accepted = true - log.I.F("event id %0x stored", ev.ID) + log.I.F("event id %0x stored", ev.Id) return } diff --git a/realy/handleAuth.go b/realy/handleAuth.go index 1403e79..cada332 100644 --- a/realy/handleAuth.go +++ b/realy/handleAuth.go @@ -28,23 +28,23 @@ func (s *Server) handleAuth(ws *web.Socket, req []byte) (msg []byte) { var valid bool if valid, err = auth.Validate(env.Event, []byte(ws.Challenge()), svcUrl); chk.E(err) { e := err.Error() - if err = okenvelope.NewFrom(env.Event.ID, false, + if err = okenvelope.NewFrom(env.Event.Id, false, normalize.Error.F(err.Error())).Write(ws); chk.E(err) { return []byte(err.Error()) } return normalize.Error.F(e) } else if !valid { - if err = okenvelope.NewFrom(env.Event.ID, false, + if err = okenvelope.NewFrom(env.Event.Id, false, normalize.Error.F("failed to authenticate")).Write(ws); chk.E(err) { return []byte(err.Error()) } return normalize.Restricted.F("auth response does not validate") } else { - if err = okenvelope.NewFrom(env.Event.ID, true, []byte{}).Write(ws); chk.E(err) { + if err = okenvelope.NewFrom(env.Event.Id, true, []byte{}).Write(ws); chk.E(err) { return } - log.D.F("%s authed to pubkey,%0x", ws.RealRemote(), env.Event.PubKey) - ws.SetAuthed(string(env.Event.PubKey)) + log.D.F("%s authed to pubkey,%0x", ws.RealRemote(), env.Event.Pubkey) + ws.SetAuthed(string(env.Event.Pubkey)) } } return diff --git a/realy/handleEvent.go b/realy/handleEvent.go index 0b78580..46b773c 100644 --- a/realy/handleEvent.go +++ b/realy/handleEvent.go @@ -38,7 +38,7 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. ws.RealRemote(), ws.AuthedBytes()) if !accept { if strings.Contains(notice, "mute") { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Blocked.F(notice)).Write(ws); chk.T(err) { } } else { @@ -47,7 +47,7 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. if auther, ok = s.relay.(relay.Authenticator); ok && auther.AuthEnabled() { if !ws.AuthRequested() { ws.RequestAuth() - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.AuthRequired.F("auth required for storing events")).Write(ws); chk.T(err) { } log.I.F("requesting auth from client %s", ws.RealRemote()) @@ -56,7 +56,7 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. } return } else { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.AuthRequired.F("auth required for storing events")).Write(ws); chk.T(err) { } log.I.F("requesting auth again from client %s", ws.RealRemote()) @@ -69,25 +69,25 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. log.W.F("didn't find authentication method") } } - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Invalid.F(notice)).Write(ws); chk.T(err) { } return } - if !bytes.Equal(env.GetIDBytes(), env.ID) { - if err = okenvelope.NewFrom(env.ID, false, + if !bytes.Equal(env.GetIDBytes(), env.Id) { + if err = okenvelope.NewFrom(env.Id, false, normalize.Invalid.F("event id is computed incorrectly")).Write(ws); chk.E(err) { return } return } if ok, err = env.Verify(); chk.T(err) { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Error.F("failed to verify signature")).Write(ws); chk.E(err) { return } } else if !ok { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Error.F("signature is invalid")).Write(ws); chk.E(err) { return } @@ -110,7 +110,7 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. } res, err = storage.QueryEvents(c, &filter.T{IDs: tag.New(evId)}) if err != nil { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Error.F("failed to query for target event")).Write(ws); chk.E(err) { return } @@ -118,14 +118,14 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. } for i := range res { if res[i].Kind.Equal(kind.Deletion) { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Blocked.F("not processing or storing delete event containing delete event references")).Write(ws); chk.E(err) { return } return } - if !bytes.Equal(res[i].PubKey, env.T.PubKey) { - if err = okenvelope.NewFrom(env.ID, false, + if !bytes.Equal(res[i].Pubkey, env.T.Pubkey) { + if err = okenvelope.NewFrom(env.Id, false, normalize.Blocked.F("cannot delete other users' events (delete by e tag)")).Write(ws); chk.E(err) { return } @@ -139,7 +139,7 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. } var pk []byte if pk, err = hex.DecAppend(nil, split[1]); chk.E(err) { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Invalid.F("delete event a tag pubkey value invalid: %s", t.Value())).Write(ws); chk.E(err) { return @@ -148,7 +148,7 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. } kin := ints.New(uint16(0)) if _, err = kin.Unmarshal(split[0]); chk.E(err) { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Invalid.F("delete event a tag kind value invalid: %s", t.Value())).Write(ws); chk.E(err) { return @@ -157,22 +157,22 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. } kk := kind.New(kin.Uint16()) if kk.Equal(kind.Deletion) { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Blocked.F("delete event kind may not be deleted")).Write(ws); chk.E(err) { return } return } if !kk.IsParameterizedReplaceable() { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Error.F("delete tags with a tags containing non-parameterized-replaceable events cannot be processed")).Write(ws); chk.E(err) { return } return } - if !bytes.Equal(pk, env.T.PubKey) { - log.I.S(pk, env.T.PubKey, env.T) - if err = okenvelope.NewFrom(env.ID, false, + if !bytes.Equal(pk, env.T.Pubkey) { + log.I.S(pk, env.T.Pubkey, env.T) + if err = okenvelope.NewFrom(env.Id, false, normalize.Blocked.F("cannot delete other users' events (delete by a tag)")).Write(ws); chk.E(err) { return } @@ -188,7 +188,7 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. f.Tags.AppendTags(tag.New([]byte{'#', 'd'}, split[2])) res, err = storage.QueryEvents(c, f) if err != nil { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Error.F("failed to query for target event")).Write(ws); chk.E(err) { return } @@ -208,9 +208,9 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. res = resTmp for _, target := range res { if target.Kind.K == kind.Deletion.K { - if err = okenvelope.NewFrom(env.ID, false, + if err = okenvelope.NewFrom(env.Id, false, normalize.Error.F("cannot delete delete event %s", - env.ID)).Write(ws); chk.E(err) { + env.Id)).Write(ws); chk.E(err) { return } } @@ -219,37 +219,37 @@ func (s *Server) handleEvent(c context.T, ws *web.Socket, req []byte, sto store. target.CreatedAt.Int(), env.T.CreatedAt.Int()) continue } - if !bytes.Equal(target.PubKey, env.PubKey) { - if err = okenvelope.NewFrom(env.ID, false, + if !bytes.Equal(target.Pubkey, env.Pubkey) { + if err = okenvelope.NewFrom(env.Id, false, normalize.Error.F("only author can delete event")).Write(ws); chk.E(err) { return } return } if advancedDeleter != nil { - advancedDeleter.BeforeDelete(c, t.Value(), env.PubKey) + advancedDeleter.BeforeDelete(c, t.Value(), env.Pubkey) } - if err = sto.DeleteEvent(c, target.EventID()); chk.T(err) { - if err = okenvelope.NewFrom(env.ID, false, + if err = sto.DeleteEvent(c, target.EventId()); chk.T(err) { + if err = okenvelope.NewFrom(env.Id, false, normalize.Error.F(err.Error())).Write(ws); chk.E(err) { return } return } if advancedDeleter != nil { - advancedDeleter.AfterDelete(t.Value(), env.PubKey) + advancedDeleter.AfterDelete(t.Value(), env.Pubkey) } } res = nil } - if err = okenvelope.NewFrom(env.ID, true).Write(ws); chk.E(err) { + if err = okenvelope.NewFrom(env.Id, true).Write(ws); chk.E(err) { return } } var reason []byte ok, reason = s.addEvent(c, s.relay, env.T, ws.Req(), ws.RealRemote(), ws.AuthedBytes()) log.I.F("event added %v, %s", ok, reason) - if err = okenvelope.NewFrom(env.ID, ok, reason).Write(ws); chk.E(err) { + if err = okenvelope.NewFrom(env.Id, ok, reason).Write(ws); chk.E(err) { return } if after != nil { diff --git a/realy/handleHTTP.go b/realy/handleHTTP.go index a78228f..348e61f 100644 --- a/realy/handleHTTP.go +++ b/realy/handleHTTP.go @@ -41,7 +41,7 @@ func (s *Server) JWTVerifyFunc(npub string) (jwtPub string, pk []byte, err error npub, ev.SerializeIndented()) return } - pk = ev.PubKey + pk = ev.Pubkey jwtPub = string(jtag.F()[0].Value()) return } diff --git a/realy/handleReq.go b/realy/handleReq.go index b1be0dd..ade145c 100644 --- a/realy/handleReq.go +++ b/realy/handleReq.go @@ -144,7 +144,7 @@ func (s *Server) handleReq(c context.T, ws *web.Socket, req []byte, sto store.I) var tmp event.Ts for _, ev := range events { for _, pk := range mutePubs { - if bytes.Equal(ev.PubKey, pk) { + if bytes.Equal(ev.Pubkey, pk) { continue } tmp = append(tmp, ev) diff --git a/realy/http-event.go b/realy/http-event.go index e94b67b..cffa151 100644 --- a/realy/http-event.go +++ b/realy/http-event.go @@ -83,7 +83,7 @@ func (ep *Event) RegisterEvent(api huma.API) { err = huma.Error401Unauthorized(notice) return } - if !bytes.Equal(ev.GetIDBytes(), ev.ID) { + if !bytes.Equal(ev.GetIDBytes(), ev.Id) { err = huma.Error400BadRequest("event id is computed incorrectly") return } @@ -118,7 +118,7 @@ func (ep *Event) RegisterEvent(api huma.API) { if res[i].Kind.Equal(kind.Deletion) { err = huma.Error409Conflict("not processing or storing delete event containing delete event references") } - if !bytes.Equal(res[i].PubKey, ev.PubKey) { + if !bytes.Equal(res[i].Pubkey, ev.Pubkey) { err = huma.Error409Conflict("cannot delete other users' events (delete by e tag)") return } @@ -149,8 +149,8 @@ func (ep *Event) RegisterEvent(api huma.API) { err = huma.Error403Forbidden("delete tags with a tags containing non-parameterized-replaceable events cannot be processed") return } - if !bytes.Equal(pk, ev.PubKey) { - log.I.S(pk, ev.PubKey, ev) + if !bytes.Equal(pk, ev.Pubkey) { + log.I.S(pk, ev.Pubkey, ev) err = huma.Error403Forbidden("cannot delete other users' events (delete by a tag)") return } @@ -178,7 +178,7 @@ func (ep *Event) RegisterEvent(api huma.API) { for _, target := range res { if target.Kind.K == kind.Deletion.K { err = huma.Error403Forbidden(fmt.Sprintf( - "cannot delete delete event %s", ev.ID)) + "cannot delete delete event %s", ev.Id)) return } if target.CreatedAt.Int() > ev.CreatedAt.Int() { @@ -187,19 +187,19 @@ func (ep *Event) RegisterEvent(api huma.API) { target.CreatedAt.Int(), ev.CreatedAt.Int()) continue } - if !bytes.Equal(target.PubKey, ev.PubKey) { + if !bytes.Equal(target.Pubkey, ev.Pubkey) { err = huma.Error403Forbidden("only author can delete event") return } if advancedDeleter != nil { - advancedDeleter.BeforeDelete(ctx, t.Value(), ev.PubKey) + advancedDeleter.BeforeDelete(ctx, t.Value(), ev.Pubkey) } - if err = sto.DeleteEvent(ctx, target.EventID()); chk.T(err) { + if err = sto.DeleteEvent(ctx, target.EventId()); chk.T(err) { err = huma.Error500InternalServerError(err.Error()) return } if advancedDeleter != nil { - advancedDeleter.AfterDelete(t.Value(), ev.PubKey) + advancedDeleter.AfterDelete(t.Value(), ev.Pubkey) } } res = nil diff --git a/realy/http-events.go b/realy/http-events.go index 9156c04..6f4859c 100644 --- a/realy/http-events.go +++ b/realy/http-events.go @@ -107,7 +107,7 @@ func (ep *Events) RegisterEvents(api huma.API) { } if len(idb) != sha256.Size { err = huma.Error422UnprocessableEntity( - fmt.Sprintf("event ID must be 64 hex characters: '%s'", id)) + fmt.Sprintf("event Id must be 64 hex characters: '%s'", id)) } evIds = append(evIds, idb) } diff --git a/realy/listeners/listeners.go b/realy/listeners/listeners.go index 392358e..1fce670 100644 --- a/realy/listeners/listeners.go +++ b/realy/listeners/listeners.go @@ -176,7 +176,7 @@ func (l *T) NotifyListeners(authRequired, publicReadable bool, ev *event.T) { if ev.Tags != nil { containsPubkey = ev.Tags.ContainsAny([]byte{'p'}, tag.New(ab)) } - if !bytes.Equal(ev.PubKey, ab) || containsPubkey { + if !bytes.Equal(ev.Pubkey, ab) || containsPubkey { log.I.F("authed user %0x not privileged to receive event\n%s", ab, ev.Serialize()) continue @@ -224,7 +224,7 @@ func (l *T) NotifyListeners(authRequired, publicReadable bool, ev *event.T) { if ev.Tags != nil { containsPubkey = ev.Tags.ContainsAny([]byte{'p'}, tag.New(ab)) } - if !bytes.Equal(ev.PubKey, ab) || containsPubkey { + if !bytes.Equal(ev.Pubkey, ab) || containsPubkey { continue } } diff --git a/relay/wrapper/relay_interface.go b/relay/wrapper/relay_interface.go index 4f34e10..2ea90e9 100644 --- a/relay/wrapper/relay_interface.go +++ b/relay/wrapper/relay_interface.go @@ -39,7 +39,7 @@ func (w Relay) Publish(c context.T, evt *event.T) (err error) { // replaceable event, delete before storing var evs []*event.T f := filter.New() - f.Authors = tag.New(evt.PubKey) + f.Authors = tag.New(evt.Pubkey) f.Kinds = kinds.New(evt.Kind) evs, err = w.I.QueryEvents(c, f) if err != nil { @@ -49,7 +49,7 @@ func (w Relay) Publish(c context.T, evt *event.T) (err error) { log.T.F("found %d possible duplicate events", len(evs)) for _, ev := range evs { del := true - if bytes.Equal(ev.ID, evt.ID) { + if bytes.Equal(ev.Id, evt.Id) { continue } if ev.CreatedAt.Int() > evt.CreatedAt.Int() { @@ -74,7 +74,7 @@ func (w Relay) Publish(c context.T, evt *event.T) (err error) { }) // replaceable events we don't tombstone when replacing, so if deleted, old // versions can be restored - if err = w.I.DeleteEvent(c, ev.EventID(), true); chk.E(err) { + if err = w.I.DeleteEvent(c, ev.EventId(), true); chk.E(err) { return } }() @@ -86,7 +86,7 @@ func (w Relay) Publish(c context.T, evt *event.T) (err error) { // parameterized replaceable event, delete before storing var evs []*event.T f := filter.New() - f.Authors = tag.New(evt.PubKey) + f.Authors = tag.New(evt.Pubkey) f.Kinds = kinds.New(evt.Kind) log.I.F("filter for parameterized replaceable %v %s", f.Tags.ToStringSlice(), f.Serialize()) @@ -125,7 +125,7 @@ func (w Relay) Publish(c context.T, evt *event.T) (err error) { }) // replaceable events we don't tombstone when replacing, so if deleted, old // versions can be restored - if err = w.I.DeleteEvent(c, ev.EventID(), true); chk.E(err) { + if err = w.I.DeleteEvent(c, ev.EventId(), true); chk.E(err) { return } }() diff --git a/store/helpers.go b/store/helpers.go index 714879f..2e4368a 100644 --- a/store/helpers.go +++ b/store/helpers.go @@ -8,5 +8,5 @@ import ( func isOlder(prev, next *event.T) bool { return prev.CreatedAt.I64() < next.CreatedAt.I64() || - (prev.CreatedAt == next.CreatedAt && bytes.Compare(prev.ID, next.ID) < 0) + (prev.CreatedAt == next.CreatedAt && bytes.Compare(prev.Id, next.Id) < 0) } diff --git a/subscription/subscriptionid.go b/subscription/subscriptionid.go index ab4978e..2c289d0 100644 --- a/subscription/subscriptionid.go +++ b/subscription/subscriptionid.go @@ -30,13 +30,13 @@ func NewId[V string | []byte](s V) (*Id, error) { // remove invalid return value si.T = si.T[:0] return si, errorf.E( - "invalid subscription ID - length %d < 1 or > 64", len(si.T)) + "invalid subscription Id - length %d < 1 or > 64", len(si.T)) } } // MustNew is the same as NewId except it doesn't check if you feed it rubbish. // -// DO NOT USE WITHOUT CHECKING THE ID IS NOT NIL AND > 0 AND <= 64 +// DO NOT USE WITHOUT CHECKING THE Id IS NOT NIL AND > 0 AND <= 64 func MustNew[V string | []byte](s V) *Id { return &Id{T: []byte(s)} } @@ -70,7 +70,7 @@ func NewStd() (t *Id) { func (si *Id) Marshal(dst []byte) (b []byte) { ue := text.NostrEscape(nil, si.T) if len(ue) < 1 || len(ue) > 64 { - log.E.F("invalid subscription ID, must be between 1 and 64 "+ + log.E.F("invalid subscription Id, must be between 1 and 64 "+ "characters, got %d (possibly due to escaping)", len(ue)) return } diff --git a/text/escape.go b/text/escape.go index fa2915d..f94333c 100644 --- a/text/escape.go +++ b/text/escape.go @@ -4,7 +4,7 @@ package text // // This is the efficient implementation based on the NIP-01 specification: // -// To prevent implementation differences from creating a different event ID for +// To prevent implementation differences from creating a different event Id for // the same event, the following rules MUST be followed while serializing: // // No whitespace, line breaks or other unnecessary formatting should be included @@ -90,7 +90,7 @@ func NostrUnescape(dst []byte) (b []byte) { dst[w] = '\r' w++ - // special cases for non-nip-01 specified json escapes (must be preserved for ID + // special cases for non-nip-01 specified json escapes (must be preserved for Id // generation). case c == 'u': dst[w] = '\\' @@ -103,7 +103,7 @@ func NostrUnescape(dst []byte) (b []byte) { dst[w] = '/' w++ - // special case for octal escapes (must be preserved for ID generation). + // special case for octal escapes (must be preserved for Id generation). case c >= '0' && c <= '9': dst[w] = '\\' w++ diff --git a/ws/client.go b/ws/client.go index 1f5b553..004138e 100644 --- a/ws/client.go +++ b/ws/client.go @@ -257,7 +257,7 @@ func (r *Client) ConnectWithTLS(ctx context.T, tlsConfig *tls.Config) error { // check signature, ignore invalid, except from trusted (AssumeValid) relays if !r.AssumeValid { if ok = r.signatureChecker(env.Event); !ok { - log.E.F("{%s} bad signature on %s\n", r.URL, env.Event.ID) + log.E.F("{%s} bad signature on %s\n", r.URL, env.Event.Id) continue } } @@ -343,7 +343,7 @@ func (r *Client) publish(ctx context.T, ev *event.T) (err error) { } // listen for an OK callback gotOk := false - id := ev.IDString() + id := ev.IdString() r.okCallbacks.Store(id, func(ok bool, reason string) { gotOk = true if !ok { diff --git a/ws/client_test.go b/ws/client_test.go index 84c12e0..996ba25 100644 --- a/ws/client_test.go +++ b/ws/client_test.go @@ -38,7 +38,7 @@ func TestPublish(t *testing.T) { Content: []byte("hello"), CreatedAt: timestamp.FromUnix(1672068534), // random fixed timestamp Tags: tags.New(tag.New("foo", "bar")), - PubKey: signer.Pub(), + Pubkey: signer.Pub(), } if err = textNote.Sign(signer); chk.E(err) { t.Fatalf("textNote.Sign: %v", err) @@ -69,7 +69,7 @@ func TestPublish(t *testing.T) { } // send back an ok nip-20 command result var res []byte - if res = okenvelope.NewFrom(textNote.ID, true, nil).Marshal(res); chk.E(err) { + if res = okenvelope.NewFrom(textNote.Id, true, nil).Marshal(res); chk.E(err) { t.Fatal(err) } if err := websocket.Message.Send(conn, res); chk.T(err) { @@ -99,7 +99,7 @@ func TestPublishBlocked(t *testing.T) { Kind: kind.TextNote, Content: []byte("hello"), CreatedAt: timestamp.FromUnix(1672068534), // random fixed timestamp - PubKey: signer.Pub(), + Pubkey: signer.Pub(), } if err = textNote.Sign(signer); chk.E(err) { t.Fatalf("textNote.Sign: %v", err) @@ -113,14 +113,14 @@ func TestPublishBlocked(t *testing.T) { } // send back a not ok nip-20 command result var res []byte - if res = okenvelope.NewFrom(textNote.ID, false, + if res = okenvelope.NewFrom(textNote.Id, false, normalize.Msg(normalize.Blocked, "no reason")).Marshal(res); chk.E(err) { t.Fatal(err) } if err := websocket.Message.Send(conn, res); chk.T(err) { t.Errorf("websocket.JSON.Send: %v", err) } - // res := []any{"OK", textNote.ID, false, "blocked"} + // res := []any{"OK", textNote.Id, false, "blocked"} chk.E(websocket.JSON.Send(conn, res)) }) defer ws.Close() @@ -143,7 +143,7 @@ func TestPublishWriteFailed(t *testing.T) { Kind: kind.TextNote, Content: []byte("hello"), CreatedAt: timestamp.FromUnix(1672068534), // random fixed timestamp - PubKey: signer.Pub(), + Pubkey: signer.Pub(), } if err = textNote.Sign(signer); chk.E(err) { t.Fatalf("textNote.Sign: %v", err) diff --git a/ws/pool.go b/ws/pool.go index af6bf72..c7906e8 100644 --- a/ws/pool.go +++ b/ws/pool.go @@ -214,7 +214,7 @@ func (pool *SimplePool) subMany(c context.T, urls []string, ff *filters.T, mh(ie) } if unique { - if _, seen := seenAlready.LoadOrStore(evt.EventID().String(), + if _, seen := seenAlready.LoadOrStore(evt.EventId().String(), evt.CreatedAt); seen { continue } @@ -334,7 +334,7 @@ func (pool *SimplePool) subManyEose(c context.T, urls []string, ff *filters.T, } if unique { - if _, seen := seenAlready.LoadOrStore(evt.EventID().String(), + if _, seen := seenAlready.LoadOrStore(evt.EventId().String(), true); seen { continue } diff --git a/ws/subscription.go b/ws/subscription.go index 82e4f6b..f02c360 100644 --- a/ws/subscription.go +++ b/ws/subscription.go @@ -67,7 +67,7 @@ func (_ WithLabel) IsSubscriptionOption() {} var _ SubscriptionOption = (WithLabel)("") -// GetID return the Nostr subscription ID as given to the Client +// GetID return the Nostr subscription Id as given to the Client // it is a concatenation of the label and a serial number. func (sub *Subscription) GetID() (id *subscription.Id) { var err error diff --git a/ws/subscription_test.go b/ws/subscription_test.go index fad6bca..04a3606 100644 --- a/ws/subscription_test.go +++ b/ws/subscription_test.go @@ -80,7 +80,7 @@ func TestNestedSubscriptions(t *testing.T) { var lim uint = 1 sub, err := rl.Subscribe(context.Bg(), filters.New(&filter.T{Kinds: kinds.New(kind.ProfileMetadata), - Authors: tag.New(event.PubKey), Limit: &lim})) + Authors: tag.New(event.Pubkey), Limit: &lim})) if err != nil { t.Fatalf("subscription 2 failed: %v", err) return