summaryrefslogtreecommitdiffstats
path: root/examples/basic/main.go
blob: 0c99dd9f7cff2c4e8bc9992873022b2cf71e29aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"northwest.io/nostr"
)

// Example_basic demonstrates basic usage of the nostr library.
func main() {
	// Generate a new key pair
	key, err := nostr.GenerateKey()
	if err != nil {
		fmt.Printf("Failed to generate key: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Public key (hex):  %s...\n", key.Public()[:16])
	fmt.Printf("Public key (npub): %s...\n", key.Npub()[:20])

	// Create an event
	event := &nostr.Event{
		Kind:    nostr.KindTextNote,
		Tags:    nostr.Tags{{"t", "test"}},
		Content: "Hello from nostr-go!",
	}

	// Sign the event
	if err := key.Sign(event); err != nil {
		fmt.Printf("Failed to sign event: %v\n", err)
		os.Exit(1)
	}

	// Verify the signature
	if event.Verify() {
		fmt.Println("Event signature verified!")
	}

	// Create a filter to match our event
	filter := nostr.Filter{
		Kinds:   []int{nostr.KindTextNote},
		Authors: []string{key.Public()[:8]}, // Prefix matching
	}

	if filter.Matches(event) {
		fmt.Println("Filter matches the event!")
	}

	fmt.Println("connecting to relay...")
	ExampleRelay()
}

// ExampleRelay demonstrates connecting to a relay (requires network).
// This is a documentation example - run with: go test -v -run ExampleRelay
func ExampleRelay() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// Connect to a public relay
	relay, err := nostr.Connect(ctx, "wss://relay.damus.io")
	if err != nil {
		fmt.Printf("Failed to connect: %v\n", err)
		return
	}
	defer relay.Close()

	fmt.Println("Connected to relay!")

	// Subscribe to recent text notes
	since := time.Now().Add(-1 * time.Hour).Unix()
	sub, err := relay.Subscribe(ctx, "my-sub", nostr.Filter{
		Kinds: []int{nostr.KindTextNote},
		Since: &since,
		Limit: 5,
	})
	if err != nil {
		fmt.Printf("Failed to subscribe: %v\n", err)
		os.Exit(1)
	}

	// Listen for events in the background
	go relay.Listen(ctx)

	// Collect events until EOSE
	eventCount := 0
	for {
		select {
		case event := <-sub.Events:
			eventCount++
			fmt.Printf("Received event from %s...\n", event)
		case <-sub.EOSE:
			fmt.Printf("Received %d events before EOSE\n", eventCount)
			sub.Close(ctx)
			return
		case <-ctx.Done():
			fmt.Println("Timeout")
			return
		}
	}
}