Performant event serialization. Update README.

This commit is contained in:
Jay
2026-04-20 22:59:28 -04:00
parent b545f9370f
commit 62aeef4eaf
5 changed files with 72 additions and 43 deletions
+3 -12
View File
@@ -96,10 +96,7 @@ event := events.Event{
} }
// 2. Compute the event ID // 2. Compute the event ID
id, err := events.GetID(event) id := events.GetID(event)
if err != nil {
log.Fatal(err)
}
event.ID = id event.ID = id
// 3. Sign the event // 3. Sign the event
@@ -114,19 +111,13 @@ event.Sig = sig
```go ```go
// Returns canonical JSON: [0, pubkey, created_at, kind, tags, content] // Returns canonical JSON: [0, pubkey, created_at, kind, tags, content]
serialized, err := events.Serialize(event) serialized := events.Serialize(event)
if err != nil {
log.Fatal(err)
}
``` ```
#### Compute event ID manually #### Compute event ID manually
```go ```go
id, err := events.GetID(event) id := events.GetID(event)
if err != nil {
log.Fatal(err)
}
// Returns lowercase hex SHA-256 hash of serialized form // Returns lowercase hex SHA-256 hash of serialized form
``` ```
-3
View File
@@ -20,9 +20,6 @@ var (
// MalformedTag indicates an event tag contains fewer than two elements. // MalformedTag indicates an event tag contains fewer than two elements.
MalformedTag = errors.New("tags must contain at least two elements") MalformedTag = errors.New("tags must contain at least two elements")
// FailedIDComp indicates the event ID could not be computed during validation.
FailedIDComp = errors.New("failed to compute event id")
// NoEventID indicates the event ID field is empty. // NoEventID indicates the event ID field is empty.
NoEventID = errors.New("event id is empty") NoEventID = errors.New("event id is empty")
+67 -22
View File
@@ -3,35 +3,80 @@ package events
import ( import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"encoding/json" "strconv"
) )
// Serialize returns the canonical JSON array representation of the event. // Serialize returns the canonical JSON array representation of the event.
// used for ID computation: [0, pubkey, created_at, kind, tags, content]. // used for ID computation: [0, pubkey, created_at, kind, tags, content].
func Serialize(e Event) ([]byte, error) { func Serialize(e Event) []byte {
serialized := []interface{}{ buf := make([]byte, 0, 100+len(e.Content)+len(e.Tags)*80)
0, return appendSerialized(buf, e)
e.PubKey,
e.CreatedAt,
e.Kind,
e.Tags,
e.Content,
}
bytes, err := json.Marshal(serialized)
if err != nil {
return []byte{}, err
}
return bytes, nil
} }
// GetID computes and returns the event ID as a lowercase, hex-encoded SHA-256 hash // GetID computes and returns the event ID as a lowercase, hex-encoded SHA-256 hash
// of the serialized event. // of the serialized event.
func GetID(e Event) (string, error) { func GetID(e Event) string {
bytes, err := Serialize(e) bytes := Serialize(e)
if err != nil {
return "", err
}
hash := sha256.Sum256(bytes) hash := sha256.Sum256(bytes)
return hex.EncodeToString(hash[:]), nil return hex.EncodeToString(hash[:])
}
func appendSerialized(dst []byte, e Event) []byte {
dst = append(dst, "[0,\""...)
dst = append(dst, e.PubKey...)
dst = append(dst, "\","...)
dst = strconv.AppendInt(dst, int64(e.CreatedAt), 10)
dst = append(dst, ',')
dst = strconv.AppendInt(dst, int64(e.Kind), 10)
dst = append(dst, ",["...)
for i, tag := range e.Tags {
if i > 0 {
dst = append(dst, ',')
}
dst = append(dst, '[')
for j, s := range tag {
if j > 0 {
dst = append(dst, ',')
}
dst = appendEscapedString(dst, s)
}
dst = append(dst, ']')
}
dst = append(dst, "],"...)
dst = appendEscapedString(dst, e.Content)
return append(dst, ']')
}
func appendEscapedString(dst []byte, s string) []byte {
dst = append(dst, '"')
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == '"':
dst = append(dst, '\\', '"')
case c == '\\':
dst = append(dst, '\\', '\\')
case c >= 0x20:
dst = append(dst, c)
case c == 0x08:
dst = append(dst, '\\', 'b')
case c == 0x09:
dst = append(dst, '\\', 't')
case c == 0x0a:
dst = append(dst, '\\', 'n')
case c == 0x0c:
dst = append(dst, '\\', 'f')
case c == 0x0d:
dst = append(dst, '\\', 'r')
case c < 0x09:
dst = append(dst, '\\', 'u', '0', '0', '0', '0'+c)
case c < 0x10:
dst = append(dst, '\\', 'u', '0', '0', '0', 0x57+c)
case c < 0x1a:
dst = append(dst, '\\', 'u', '0', '0', '1', 0x20+c)
case c < 0x20:
dst = append(dst, '\\', 'u', '0', '0', '1', 0x47+c)
}
}
return append(dst, '"')
} }
+1 -2
View File
@@ -196,8 +196,7 @@ var idTestCases = []IDTestCase{
func TestEventGetId(t *testing.T) { func TestEventGetId(t *testing.T) {
for _, tc := range idTestCases { for _, tc := range idTestCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
actual, err := GetID(tc.event) actual := GetID(tc.event)
assert.NoError(t, err)
assert.Equal(t, tc.expected, actual) assert.Equal(t, tc.expected, actual)
}) })
} }
+1 -4
View File
@@ -47,10 +47,7 @@ func ValidateStructure(e Event) error {
// ValidateID recomputes the event ID and verifies it matches the stored ID field. // ValidateID recomputes the event ID and verifies it matches the stored ID field.
func ValidateID(e Event) error { func ValidateID(e Event) error {
computedID, err := GetID(e) computedID := GetID(e)
if err != nil {
return errors.FailedIDComp
}
if e.ID == "" { if e.ID == "" {
return errors.NoEventID return errors.NoEventID
} }