Skip to content

Commit

Permalink
splitting the code into multiple packages (wip)
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed May 29, 2024
1 parent 31e0645 commit a4852ef
Show file tree
Hide file tree
Showing 39 changed files with 255 additions and 153 deletions.
2 changes: 1 addition & 1 deletion envelopes.go → core/envelopes.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import (
"bytes"
Expand Down
2 changes: 1 addition & 1 deletion envelopes_test.go → core/envelopes_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import (
"encoding/json"
Expand Down
2 changes: 1 addition & 1 deletion event.go → core/event.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import (
"crypto/sha256"
Expand Down
2 changes: 1 addition & 1 deletion event_easyjson.go → core/event_easyjson.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import (
json "encoding/json"
Expand Down
2 changes: 1 addition & 1 deletion event_extra.go → core/event_extra.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

// SetExtra sets an out-of-the-spec value under the given key into the event object.
func (evt *Event) SetExtra(key string, value any) {
Expand Down
2 changes: 1 addition & 1 deletion event_test.go → core/event_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import (
"encoding/json"
Expand Down
2 changes: 1 addition & 1 deletion filter.go → core/filter.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import (
"encoding/json"
Expand Down
2 changes: 1 addition & 1 deletion filter_easyjson.go → core/filter_easyjson.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import (
json "encoding/json"
Expand Down
2 changes: 1 addition & 1 deletion filter_test.go → core/filter_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import (
"encoding/json"
Expand Down
20 changes: 1 addition & 19 deletions helpers.go → core/helpers.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,9 @@
package nostr
package core

import (
"sync"
"unsafe"

"golang.org/x/exp/constraints"
)

const MAX_LOCKS = 50

var namedMutexPool = make([]sync.Mutex, MAX_LOCKS)

//go:noescape
//go:linkname memhash runtime.memhash
func memhash(p unsafe.Pointer, h, s uintptr) uintptr

func namedLock(name string) (unlock func()) {
sptr := unsafe.StringData(name)
idx := uint64(memhash(unsafe.Pointer(sptr), 0, uintptr(len(name)))) % MAX_LOCKS
namedMutexPool[idx].Lock()
return namedMutexPool[idx].Unlock
}

func similar[E constraints.Ordered](as, bs []E) bool {
if len(as) != len(bs) {
return false
Expand Down
2 changes: 1 addition & 1 deletion keys.go → core/keys.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import (
"crypto/rand"
Expand Down
2 changes: 1 addition & 1 deletion pointers.go → core/pointers.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

type ProfilePointer struct {
PublicKey string `json:"pubkey"`
Expand Down
2 changes: 1 addition & 1 deletion tag_test.go → core/tag_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import (
"testing"
Expand Down
7 changes: 4 additions & 3 deletions tags.go → core/tags.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package nostr
package core

import (
"encoding/json"
"errors"
"slices"
"strings"

"slices"
"github.com/nbd-wtf/go-nostr/utils"
)

type Tag []string
Expand Down Expand Up @@ -54,7 +55,7 @@ func (tag Tag) Value() string {

func (tag Tag) Relay() string {
if (tag[0] == "e" || tag[0] == "p") && len(tag) > 2 {
return NormalizeURL(tag[2])
return utils.NormalizeURL(tag[2])
}
return ""
}
Expand Down
2 changes: 1 addition & 1 deletion timestamp.go → core/timestamp.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package core

import "time"

Expand Down
61 changes: 61 additions & 0 deletions lib.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package nostr

import (
"github.com/nbd-wtf/go-nostr/core"
"github.com/nbd-wtf/go-nostr/relays"
"github.com/nbd-wtf/go-nostr/utils"
)

type (
Event core.Event
Filter core.Filter
Filters core.Filters
Timestamp core.Timestamp
Tag core.Tag
TagMap core.TagMap

ProfilePointer core.ProfilePointer
EventPointer core.EventPointer
EntityPointer core.EntityPointer

AuthEnvelope core.AuthEnvelope
OKEnvelope core.OKEnvelope
NoticeEnvelope core.NoticeEnvelope
EventEnvelope core.EventEnvelope
CloseEnvelope core.CloseEnvelope
ClosedEnvelope core.ClosedEnvelope
CountEnvelope core.CountEnvelope
EOSEEnvelope core.EOSEEnvelope
ReqEnvelope core.ReqEnvelope
Envelope core.Envelope

Relay relays.Relay
RelayOption relays.RelayOption
SimplePool relays.SimplePool
PoolOption relays.PoolOption
Subscription relays.Subscription
SubscriptionOption relays.SubscriptionOption
IncomingEvent relays.IncomingEvent
WithAuthHandler relays.WithAuthHandler
WithLabel relays.WithLabel
WithNoticeHandler relays.WithNoticeHandler

RelayStore relays.RelayStore
MultiStore relays.MultiStore
)

var (
Now = core.Now
FilterEqual = core.FilterEqual
GeneratePrivateKey = core.GeneratePrivateKey
GetPublicKey = core.GetPublicKey
IsValidPublicKey = core.IsValidPublicKey

NewSimplePool = relays.NewSimplePool
NewRelay = relays.NewRelay

IsValid32ByteHex = utils.IsValid32ByteHex
IsValidRelayURL = utils.IsValidRelayURL
NormalizeOKMessage = utils.NormalizeOKMessage
NormalizeURL = utils.NormalizeURL
)
4 changes: 4 additions & 0 deletions libsecp256k1/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ cpu: AMD Ryzen 3 3200G with Radeon Vega Graphics
BenchmarkSignatureVerification/btcec-4 145 7873130 ns/op 127069 B/op 579 allocs/op
BenchmarkSignatureVerification/libsecp256k1-4 502 2314573 ns/op 112241 B/op 392 allocs/op
```

To use this manually, just import it.

To use it for the `Relay` subscriptions automatic signature verification, compile your application with the Go build tag `libsecp256k1`.
8 changes: 4 additions & 4 deletions libsecp256k1/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import (
"encoding/json"
"testing"

"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/core"
"github.com/nbd-wtf/go-nostr/test_common"
)

func BenchmarkSignatureVerification(b *testing.B) {
events := make([]*nostr.Event, len(test_common.NormalEvents))
events := make([]*core.Event, len(test_common.NormalEvents))
for i, jevt := range test_common.NormalEvents {
evt := &nostr.Event{}
evt := &core.Event{}
json.Unmarshal([]byte(jevt), evt)
events[i] = evt
}
Expand All @@ -27,7 +27,7 @@ func BenchmarkSignatureVerification(b *testing.B) {
b.Run("libsecp256k1", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, evt := range events {
CheckSignature(evt)
CheckSignature(*evt)
}
}
})
Expand Down
6 changes: 3 additions & 3 deletions libsecp256k1/signverify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import (
"encoding/json"
"testing"

"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/core"
"github.com/nbd-wtf/go-nostr/test_common"
"github.com/stretchr/testify/assert"
)

func TestEventVerification(t *testing.T) {
for _, jevt := range test_common.NormalEvents {
evt := &nostr.Event{}
json.Unmarshal([]byte(jevt), evt)
evt := core.Event{}
json.Unmarshal([]byte(jevt), &evt)
ok, _ := CheckSignature(evt)
shouldBe, _ := evt.CheckSignature()
assert.Equal(t, ok, shouldBe, "%s signature must be %s", jevt, shouldBe)
Expand Down
4 changes: 2 additions & 2 deletions libsecp256k1/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import (
"encoding/hex"
"fmt"

"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/core"
)

func CheckSignature(evt *nostr.Event) (bool, error) {
func CheckSignature(evt core.Event) (bool, error) {
var pk [32]byte
_, err := hex.Decode(pk[:], []byte(evt.PubKey))
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion connection.go → relays/connection.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package relays

import (
"bytes"
Expand Down
8 changes: 5 additions & 3 deletions count_test.go → relays/count_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package nostr
package relays

import (
"context"
"testing"

"github.com/nbd-wtf/go-nostr/core"
)

func TestCount(t *testing.T) {
Expand All @@ -11,8 +13,8 @@ func TestCount(t *testing.T) {
rl := mustRelayConnect(RELAY)
defer rl.Close()

count, err := rl.Count(context.Background(), Filters{
{Kinds: []int{KindContactList}, Tags: TagMap{"p": []string{"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d"}}},
count, err := rl.Count(context.Background(), core.Filters{
{Kinds: []int{core.KindContactList}, Tags: core.TagMap{"p": []string{"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d"}}},
})
if err != nil {
t.Errorf("count request failed: %v", err)
Expand Down
8 changes: 5 additions & 3 deletions eose_test.go → relays/eose_test.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
package nostr
package relays

import (
"context"
"testing"
"time"

"github.com/nbd-wtf/go-nostr/core"
)

func TestEOSEMadness(t *testing.T) {
rl := mustRelayConnect(RELAY)
defer rl.Close()

sub, err := rl.Subscribe(context.Background(), Filters{
{Kinds: []int{KindTextNote}, Limit: 2},
sub, err := rl.Subscribe(context.Background(), core.Filters{
{Kinds: []int{core.KindTextNote}, Limit: 2},
})
if err != nil {
t.Errorf("subscription failed: %v", err)
Expand Down
22 changes: 22 additions & 0 deletions relays/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package relays

import (
"sync"
"unsafe"
)

const MAX_LOCKS = 50

var namedMutexPool = make([]sync.Mutex, MAX_LOCKS)

//go:noescape
//go:linkname memhash runtime.memhash
func memhash(p unsafe.Pointer, h, s uintptr) uintptr

func namedLock(name string) (unlock func()) {
sptr := unsafe.StringData(name)
idx := uint64(memhash(unsafe.Pointer(sptr), 0, uintptr(len(name)))) % MAX_LOCKS
l := &namedMutexPool[idx]
l.Lock()
return l.Unlock
}
2 changes: 1 addition & 1 deletion helpers_test.go → relays/helpers_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package relays

import (
"testing"
Expand Down
16 changes: 9 additions & 7 deletions interface.go → relays/interface.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package nostr
package relays

import (
"context"
"errors"
"slices"

"github.com/nbd-wtf/go-nostr/core"
)

type RelayStore interface {
Publish(ctx context.Context, event Event) error
QuerySync(ctx context.Context, filter Filter, opts ...SubscriptionOption) ([]*Event, error)
Publish(ctx context.Context, event core.Event) error
QuerySync(ctx context.Context, filter core.Filter, opts ...SubscriptionOption) ([]*core.Event, error)
}

var (
Expand All @@ -18,23 +20,23 @@ var (

type MultiStore []RelayStore

func (multi MultiStore) Publish(ctx context.Context, event Event) error {
func (multi MultiStore) Publish(ctx context.Context, event core.Event) error {
errs := make([]error, len(multi))
for i, s := range multi {
errs[i] = s.Publish(ctx, event)
}
return errors.Join(errs...)
}

func (multi MultiStore) QuerySync(ctx context.Context, filter Filter, opts ...SubscriptionOption) ([]*Event, error) {
func (multi MultiStore) QuerySync(ctx context.Context, filter core.Filter, opts ...SubscriptionOption) ([]*core.Event, error) {
errs := make([]error, len(multi))
events := make([]*Event, 0, max(filter.Limit, 10))
events := make([]*core.Event, 0, max(filter.Limit, 10))
for i, s := range multi {
res, err := s.QuerySync(ctx, filter, opts...)
errs[i] = err
events = append(events, res...)
}
slices.SortFunc(events, func(a, b *Event) int {
slices.SortFunc(events, func(a, b *core.Event) int {
if b.CreatedAt > a.CreatedAt {
return 1
} else if b.CreatedAt < a.CreatedAt {
Expand Down
2 changes: 1 addition & 1 deletion log.go → relays/log.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nostr
package relays

import (
"log"
Expand Down
Loading

0 comments on commit a4852ef

Please sign in to comment.