Refactored into namespaced packages.
This commit is contained in:
65
README.md
65
README.md
@@ -31,13 +31,24 @@ mechanisms, and user interfaces.
|
||||
go get git.wisehodl.dev/jay/go-roots
|
||||
```
|
||||
|
||||
2. Import it with:
|
||||
If the primary repository is unavailable, use the `replace` directive in your go.mod file to get the package from the github mirror:
|
||||
|
||||
```golang
|
||||
import "git.wisehodl.dev/jay/go-roots"
|
||||
```
|
||||
replace git.wisehodl.dev/jay/go-roots => github.com/wisehodl/go-roots latest
|
||||
```
|
||||
|
||||
3. Access it with the `roots` namespace.
|
||||
2. Import the packages:
|
||||
|
||||
```golang
|
||||
import (
|
||||
"git.wisehodl.dev/jay/go-roots/errors"
|
||||
"git.wisehodl.dev/jay/go-roots/events"
|
||||
"git.wisehodl.dev/jay/go-roots/filters"
|
||||
"git.wisehodl.dev/jay/go-roots/keys"
|
||||
)
|
||||
```
|
||||
|
||||
3. Access functions with appropriate namespaces.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
@@ -46,12 +57,12 @@ import "git.wisehodl.dev/jay/go-roots"
|
||||
#### Generate a new keypair
|
||||
|
||||
```go
|
||||
privateKey, err := roots.GeneratePrivateKey()
|
||||
privateKey, err := keys.GeneratePrivateKey()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
publicKey, err := roots.GetPublicKey(privateKey)
|
||||
publicKey, err := keys.GetPublicKey(privateKey)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -61,7 +72,7 @@ if err != nil {
|
||||
|
||||
```go
|
||||
privateKey := "f43a0435f69529f310bbd1d6263d2fbf0977f54bfe2310cc37ae5904b83bb167"
|
||||
publicKey, err := roots.GetPublicKey(privateKey)
|
||||
publicKey, err := keys.GetPublicKey(privateKey)
|
||||
// publicKey: "cfa87f35acbde29ba1ab3ee42de527b2cad33ac487e80cf2d6405ea0042c8fef"
|
||||
```
|
||||
|
||||
@@ -73,11 +84,11 @@ publicKey, err := roots.GetPublicKey(privateKey)
|
||||
|
||||
```go
|
||||
// 1. Build the event structure
|
||||
event := roots.Event{
|
||||
event := events.Event{
|
||||
PubKey: publicKey,
|
||||
CreatedAt: int(time.Now().Unix()),
|
||||
Kind: 1,
|
||||
Tags: []roots.Tag{
|
||||
Tags: []events.Tag{
|
||||
{"e", "5c83da77af1dec6d7289834998ad7aafbd9e2191396d75ec3cc27f5a77226f36"},
|
||||
{"p", "91cf9b32f3735070f46c0a86a820a47efa08a5be6c9f4f8cf68e5b5b75c92d60"},
|
||||
},
|
||||
@@ -92,7 +103,7 @@ if err != nil {
|
||||
event.ID = id
|
||||
|
||||
// 3. Sign the event
|
||||
sig, err := roots.SignEvent(id, privateKey)
|
||||
sig, err := events.SignEvent(id, privateKey)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -168,7 +179,7 @@ if err != nil {
|
||||
#### Unmarshal event from JSON
|
||||
|
||||
```go
|
||||
var event roots.Event
|
||||
var event events.Event
|
||||
err := json.Unmarshal(jsonBytes, &event)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
@@ -190,7 +201,7 @@ if err := event.Validate(); err != nil {
|
||||
since := int(time.Now().Add(-24 * time.Hour).Unix())
|
||||
limit := 50
|
||||
|
||||
filter := roots.Filter{
|
||||
filter := filters.Filter{
|
||||
IDs: []string{"abc123", "def456"}, // Prefix match
|
||||
Authors: []string{"cfa87f35"}, // Prefix match
|
||||
Kinds: []int{1, 6, 7},
|
||||
@@ -202,9 +213,9 @@ filter := roots.Filter{
|
||||
#### Filter with tag conditions
|
||||
|
||||
```go
|
||||
filter := roots.Filter{
|
||||
filter := filters.Filter{
|
||||
Kinds: []int{1},
|
||||
Tags: roots.TagFilters{
|
||||
Tags: filters.TagFilters{
|
||||
"e": {"5c83da77af1dec6d7289834998ad7aafbd9e2191396d75ec3cc27f5a77226f36"},
|
||||
"p": {"91cf9b32f3735070f46c0a86a820a47efa08a5be6c9f4f8cf68e5b5b75c92d60"},
|
||||
},
|
||||
@@ -216,9 +227,9 @@ filter := roots.Filter{
|
||||
```go
|
||||
// Extensions allow arbitrary JSON fields beyond the standard filter spec.
|
||||
// For example, this is how to implement non-standard filters like 'search'.
|
||||
filter := roots.Filter{
|
||||
filter := filters.Filter{
|
||||
Kinds: []int{1},
|
||||
Extensions: roots.FilterExtensions{
|
||||
Extensions: filters.FilterExtensions{
|
||||
"search": json.RawMessage(`"bitcoin"`),
|
||||
},
|
||||
}
|
||||
@@ -234,7 +245,7 @@ filter := roots.Filter{
|
||||
#### Match single event
|
||||
|
||||
```go
|
||||
filter := roots.Filter{
|
||||
filter := filters.Filter{
|
||||
Authors: []string{"cfa87f35"},
|
||||
Kinds: []int{1},
|
||||
}
|
||||
@@ -248,15 +259,15 @@ if filter.Matches(&event) {
|
||||
|
||||
```go
|
||||
since := int(time.Now().Add(-1 * time.Hour).Unix())
|
||||
filter := roots.Filter{
|
||||
filter := filters.Filter{
|
||||
Kinds: []int{1},
|
||||
Since: &since,
|
||||
Tags: roots.TagFilters{
|
||||
Tags: filters.TagFilters{
|
||||
"p": {"abc123", "def456"}, // OR within tag values
|
||||
},
|
||||
}
|
||||
|
||||
var matches []roots.Event
|
||||
var matches []events.Event
|
||||
for _, event := range events {
|
||||
if filter.Matches(&event) {
|
||||
matches = append(matches, event)
|
||||
@@ -271,13 +282,13 @@ for _, event := range events {
|
||||
#### Marshal filter to JSON
|
||||
|
||||
```go
|
||||
filter := roots.Filter{
|
||||
filter := filters.Filter{
|
||||
IDs: []string{"abc123"},
|
||||
Kinds: []int{1},
|
||||
Tags: roots.TagFilters{
|
||||
Tags: filters.TagFilters{
|
||||
"e": {"event-id"},
|
||||
},
|
||||
Extensions: roots.FilterExtensions{
|
||||
Extensions: filters.FilterExtensions{
|
||||
"search": json.RawMessage(`"nostr"`),
|
||||
},
|
||||
}
|
||||
@@ -297,7 +308,7 @@ jsonData := `{
|
||||
"search": "bitcoin"
|
||||
}`
|
||||
|
||||
var filter roots.Filter
|
||||
var filter filters.Filter
|
||||
err := filter.UnmarshalJSON([]byte(jsonData))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
@@ -323,9 +334,9 @@ During marshaling, Extensions merge into the output JSON. During unmarshaling, u
|
||||
Example implementing search filter:
|
||||
|
||||
```go
|
||||
filter := roots.Filter{
|
||||
filter := filters.Filter{
|
||||
Kinds: []int{1},
|
||||
Extensions: roots.FilterExtensions{
|
||||
Extensions: filters.FilterExtensions{
|
||||
"search": json.RawMessage(`"bitcoin"`),
|
||||
},
|
||||
}
|
||||
@@ -343,5 +354,5 @@ if searchRaw, ok := filter.Extensions["search"]; ok {
|
||||
This library contains a comprehensive suite of unit tests. Run them with:
|
||||
|
||||
```bash
|
||||
go test
|
||||
go test ./...
|
||||
```
|
||||
|
||||
31
errors/errors.go
Normal file
31
errors/errors.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
// MalformedPubKey indicates a public key is not 64 lowercase hex characters.
|
||||
MalformedPubKey = errors.New("public key must be 64 lowercase hex characters")
|
||||
|
||||
// MalformedPrivKey indicates a private key is not 64 lowercase hex characters.
|
||||
MalformedPrivKey = errors.New("private key must be 64 lowercase hex characters")
|
||||
|
||||
// MalformedID indicates an event id is not 64 hex characters.
|
||||
MalformedID = errors.New("event id must be 64 hex characters")
|
||||
|
||||
// MalformedSig indicates an event signature is not 128 hex characters.
|
||||
MalformedSig = errors.New("event signature must be 128 hex characters")
|
||||
|
||||
// MalformedTag indicates an event tag contains fewer than 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 = errors.New("event id is empty")
|
||||
|
||||
// InvalidSig indicates the event signature failed cryptographic validation.
|
||||
InvalidSig = errors.New("event signature is invalid")
|
||||
)
|
||||
62
event.go
62
event.go
@@ -1,62 +0,0 @@
|
||||
// Roots is a purposefully minimal Nostr protocol library that provides only
|
||||
// the primitives that define protocol compliance: event structure,
|
||||
// serialization, cryptographic signatures, and subscription filters.
|
||||
package roots
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// Tag represents a single tag within an event as an array of strings.
|
||||
// The first element identifies the tag name, the second contains the value,
|
||||
// and subsequent elements are optional.
|
||||
type Tag []string
|
||||
|
||||
// Event represents a Nostr protocol event, with its seven required fields.
|
||||
// All fields must be present for a valid event.
|
||||
type Event struct {
|
||||
ID string `json:"id"`
|
||||
PubKey string `json:"pubkey"`
|
||||
CreatedAt int `json:"created_at"`
|
||||
Kind int `json:"kind"`
|
||||
Tags []Tag `json:"tags"`
|
||||
Content string `json:"content"`
|
||||
Sig string `json:"sig"`
|
||||
}
|
||||
|
||||
var (
|
||||
// Hex64Pattern matches 64-character, lowercase, hexadecimal strings.
|
||||
// Used for validating event IDs and cryptographic keys.
|
||||
Hex64Pattern = regexp.MustCompile("^[a-f0-9]{64}$")
|
||||
|
||||
// Hex128Pattern matches 128-character, lowercase, hexadecimal strings.
|
||||
// Used for validating signatures.
|
||||
Hex128Pattern = regexp.MustCompile("^[a-f0-9]{128}$")
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrMalformedPubKey indicates a public key is not 64 lowercase hex characters.
|
||||
ErrMalformedPubKey = errors.New("public key must be 64 lowercase hex characters")
|
||||
|
||||
// ErrMalformedPrivKey indicates a private key is not 64 lowercase hex characters.
|
||||
ErrMalformedPrivKey = errors.New("private key must be 64 lowercase hex characters")
|
||||
|
||||
// ErrMalformedID indicates an event id is not 64 hex characters.
|
||||
ErrMalformedID = errors.New("event id must be 64 hex characters")
|
||||
|
||||
// ErrMalformedSig indicates an event signature is not 128 hex characters.
|
||||
ErrMalformedSig = errors.New("event signature must be 128 hex characters")
|
||||
|
||||
// ErrMalformedTag indicates an event tag contains fewer than two elements.
|
||||
ErrMalformedTag = errors.New("tags must contain at least two elements")
|
||||
|
||||
// ErrFailedIDComp indicates the event ID could not be computed during validation.
|
||||
ErrFailedIDComp = errors.New("failed to compute event id")
|
||||
|
||||
// ErrNoEventID indicates the event ID field is empty.
|
||||
ErrNoEventID = errors.New("event id is empty")
|
||||
|
||||
// ErrInvalidSig indicates the event signature failed cryptographic validation.
|
||||
ErrInvalidSig = errors.New("event signature is invalid")
|
||||
)
|
||||
35
events/event.go
Normal file
35
events/event.go
Normal file
@@ -0,0 +1,35 @@
|
||||
// Roots is a purposefully minimal Nostr protocol library that provides only
|
||||
// the primitives that define protocol compliance: event structure,
|
||||
// serialization, cryptographic signatures, and subscription filters.
|
||||
package events
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// Tag represents a single tag within an event as an array of strings.
|
||||
// The first element identifies the tag name, the second contains the value,
|
||||
// and subsequent elements are optional.
|
||||
type Tag []string
|
||||
|
||||
// Event represents a Nostr protocol event, with its seven required fields.
|
||||
// All fields must be present for a valid event.
|
||||
type Event struct {
|
||||
ID string `json:"id"`
|
||||
PubKey string `json:"pubkey"`
|
||||
CreatedAt int `json:"created_at"`
|
||||
Kind int `json:"kind"`
|
||||
Tags []Tag `json:"tags"`
|
||||
Content string `json:"content"`
|
||||
Sig string `json:"sig"`
|
||||
}
|
||||
|
||||
var (
|
||||
// Hex64Pattern matches 64-character, lowercase, hexadecimal strings.
|
||||
// Used for validating event IDs and cryptographic keys.
|
||||
Hex64Pattern = regexp.MustCompile("^[a-f0-9]{64}$")
|
||||
|
||||
// Hex128Pattern matches 128-character, lowercase, hexadecimal strings.
|
||||
// Used for validating signatures.
|
||||
Hex128Pattern = regexp.MustCompile("^[a-f0-9]{128}$")
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
package roots
|
||||
package events
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -1,4 +1,4 @@
|
||||
package roots
|
||||
package events
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -1,4 +1,4 @@
|
||||
package roots
|
||||
package events
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
@@ -1,4 +1,4 @@
|
||||
package roots
|
||||
package events
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -1,8 +1,9 @@
|
||||
package roots
|
||||
package events
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"git.wisehodl.dev/jay/go-roots/errors"
|
||||
"github.com/btcsuite/btcd/btcec/v2"
|
||||
"github.com/btcsuite/btcd/btcec/v2/schnorr"
|
||||
)
|
||||
@@ -12,12 +13,12 @@ import (
|
||||
func SignEvent(eventID, privateKeyHex string) (string, error) {
|
||||
skBytes, err := hex.DecodeString(privateKeyHex)
|
||||
if err != nil {
|
||||
return "", ErrMalformedPrivKey
|
||||
return "", errors.MalformedPrivKey
|
||||
}
|
||||
|
||||
idBytes, err := hex.DecodeString(eventID)
|
||||
if err != nil {
|
||||
return "", ErrMalformedID
|
||||
return "", errors.MalformedID
|
||||
}
|
||||
|
||||
// discard public key return value
|
||||
@@ -1,4 +1,4 @@
|
||||
package roots
|
||||
package events
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -1,4 +1,4 @@
|
||||
package roots
|
||||
package events
|
||||
|
||||
func intPtr(i int) *int {
|
||||
return &i
|
||||
@@ -1,9 +1,9 @@
|
||||
package roots
|
||||
package events
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
"git.wisehodl.dev/jay/go-roots/errors"
|
||||
"github.com/btcsuite/btcd/btcec/v2/schnorr"
|
||||
)
|
||||
|
||||
@@ -25,20 +25,20 @@ func (e *Event) Validate() error {
|
||||
// specification: hex lengths, tag structure, and field formats.
|
||||
func (e *Event) ValidateStructure() error {
|
||||
if !Hex64Pattern.MatchString(e.PubKey) {
|
||||
return ErrMalformedPubKey
|
||||
return errors.MalformedPubKey
|
||||
}
|
||||
|
||||
if !Hex64Pattern.MatchString(e.ID) {
|
||||
return ErrMalformedID
|
||||
return errors.MalformedID
|
||||
}
|
||||
|
||||
if !Hex128Pattern.MatchString(e.Sig) {
|
||||
return ErrMalformedSig
|
||||
return errors.MalformedSig
|
||||
}
|
||||
|
||||
for _, tag := range e.Tags {
|
||||
if len(tag) < 2 {
|
||||
return ErrMalformedTag
|
||||
return errors.MalformedTag
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,10 +49,10 @@ func (e *Event) ValidateStructure() error {
|
||||
func (e *Event) ValidateID() error {
|
||||
computedID, err := e.GetID()
|
||||
if err != nil {
|
||||
return ErrFailedIDComp
|
||||
return errors.FailedIDComp
|
||||
}
|
||||
if e.ID == "" {
|
||||
return ErrNoEventID
|
||||
return errors.NoEventID
|
||||
}
|
||||
if computedID != e.ID {
|
||||
return fmt.Errorf("event id %q does not match computed id %q", e.ID, computedID)
|
||||
@@ -91,6 +91,6 @@ func (e *Event) ValidateSignature() error {
|
||||
if signature.Verify(idBytes, publicKey) {
|
||||
return nil
|
||||
} else {
|
||||
return ErrInvalidSig
|
||||
return errors.InvalidSig
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package roots
|
||||
package events
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -1,7 +1,8 @@
|
||||
package roots
|
||||
package filters
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"git.wisehodl.dev/jay/go-roots/events"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -181,7 +182,7 @@ func (f *Filter) UnmarshalJSON(data []byte) error {
|
||||
// Matches returns true if the event satisfies all filter conditions.
|
||||
// Supports prefix matching for IDs and authors, and tag filtering.
|
||||
// Does not account for custom extensions.
|
||||
func (f *Filter) Matches(event *Event) bool {
|
||||
func (f *Filter) Matches(event *events.Event) bool {
|
||||
// Check ID
|
||||
if len(f.IDs) > 0 {
|
||||
if !matchesPrefix(event.ID, f.IDs) {
|
||||
@@ -246,7 +247,7 @@ func matchesTimeRange(timestamp int, since *int, until *int) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func matchesTags(eventTags []Tag, tagFilters *TagFilters) bool {
|
||||
func matchesTags(eventTags []events.Tag, tagFilters *TagFilters) bool {
|
||||
// Build index of tags and values
|
||||
eventIndex := make(map[string][]string, len(eventTags))
|
||||
for _, tag := range eventTags {
|
||||
@@ -1,4 +1,4 @@
|
||||
package roots
|
||||
package filters
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -1,13 +1,14 @@
|
||||
package roots
|
||||
package filters
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"git.wisehodl.dev/jay/go-roots/events"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var testEvents []Event
|
||||
var testEvents []events.Event
|
||||
|
||||
func init() {
|
||||
data, err := os.ReadFile("testdata/test_events.json")
|
||||
@@ -403,8 +404,8 @@ func TestEventFilterMatching(t *testing.T) {
|
||||
// TestEventFilterMatchingSkipMalformedTags documents that filter.Matches()
|
||||
// skips malformed tags during tag matching
|
||||
func TestEventFilterMatchingSkipMalformedTags(t *testing.T) {
|
||||
event := Event{
|
||||
Tags: []Tag{
|
||||
event := events.Event{
|
||||
Tags: []events.Tag{
|
||||
{"malformed"},
|
||||
{"valid", "value"},
|
||||
},
|
||||
5
filters/util_test.go
Normal file
5
filters/util_test.go
Normal file
@@ -0,0 +1,5 @@
|
||||
package filters
|
||||
|
||||
func intPtr(i int) *int {
|
||||
return &i
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
package roots
|
||||
package keys
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"git.wisehodl.dev/jay/go-roots/errors"
|
||||
"github.com/decred/dcrd/dcrec/secp256k1/v4"
|
||||
)
|
||||
|
||||
@@ -20,11 +21,11 @@ func GeneratePrivateKey() (string, error) {
|
||||
// and returns the x-coordinate as 64 lowercase hex characters.
|
||||
func GetPublicKey(privateKeyHex string) (string, error) {
|
||||
if len(privateKeyHex) != 64 {
|
||||
return "", ErrMalformedPrivKey
|
||||
return "", errors.MalformedPrivKey
|
||||
}
|
||||
skBytes, err := hex.DecodeString(privateKeyHex)
|
||||
if err != nil {
|
||||
return "", ErrMalformedPrivKey
|
||||
return "", errors.MalformedPrivKey
|
||||
}
|
||||
|
||||
pk := secp256k1.PrivKeyFromBytes(skBytes).PubKey()
|
||||
@@ -1,10 +1,16 @@
|
||||
package roots
|
||||
package keys
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const testSK = "f43a0435f69529f310bbd1d6263d2fbf0977f54bfe2310cc37ae5904b83bb167"
|
||||
const testPK = "cfa87f35acbde29ba1ab3ee42de527b2cad33ac487e80cf2d6405ea0042c8fef"
|
||||
|
||||
var Hex64Pattern = regexp.MustCompile("^[a-f0-9]{64}$")
|
||||
|
||||
func TestGeneratePrivateKey(t *testing.T) {
|
||||
sk, err := GeneratePrivateKey()
|
||||
|
||||
Reference in New Issue
Block a user