1 // Package discovery turns a relay address into a gateway connection.
2 //
3 // A user should not have to know a gateway's public key or its relay list. Given one relay and a
4 // chain name, this asks the relay for gateway announcements (kind 30333), picks the gateway that
5 // serves the chain, and returns a connection URI whose relay list is the gateway's own advertised
6 // relays merged with the seed. A client that dials with that URI is connected to every relay the
7 // gateway announced, so one relay going down is not a single point of failure.
8 //
9 // It is deliberately read-only and needs no identity: an announcement is public, and a relay that
10 // requires NIP-42 for writes still answers a REQ.
11 package discovery
12 13 import (
14 "context"
15 "fmt"
16 "strings"
17 "time"
18 19 "encoding/hex"
20 21 "git.smesh.lol/nostrino/pkg/chain"
22 "git.smesh.lol/nostrino/pkg/registry"
23 "git.smesh.lol/nostrino/pkg/relay"
24 "git.smesh.lol/nostrino/pkg/tunnel"
25 )
26 27 // DefaultCollect is how long to wait for announcements after EOSE. A busy relay answers within a
28 // second; the grace period is what lets several relays be merged.
29 const DefaultCollect = 1500 * time.Millisecond
30 31 // Lookup finds a gateway for chain among seed relays and returns its connection URI.
32 //
33 // The returned URI carries every relay the announcement names plus the seeds, so the caller gets
34 // the gateway's own redundancy without knowing about it. When several gateways serve the chain,
35 // the one with the most chains (then the newest announcement) wins; callers that want the whole
36 // set can use Announcements and choose for themselves.
37 func Lookup(ctx context.Context, factory func(string) (relay.Transport, error), seeds []string, chainName string, collect time.Duration) (*tunnel.URI, error) {
38 if len(seeds) == 0 {
39 return nil, fmt.Errorf("discovery: no relay to ask")
40 }
41 42 infos, err := registry.Discover(ctx, factory, seeds, chainName, collect)
43 44 if err != nil {
45 return nil, fmt.Errorf("discovery: %w", err)
46 }
47 48 if len(infos) == 0 {
49 return nil, fmt.Errorf("discovery: no gateway for chain %q on %s", chainName, strings.Join(seeds, ", "))
50 }
51 52 best := infos[0]
53 54 for _, info := range infos[1:] {
55 if len(info.Chains) > len(best.Chains) || (len(info.Chains) == len(best.Chains) && info.UpdatedAt > best.UpdatedAt) {
56 best = info
57 }
58 }
59 60 rawGateway, err := hex.DecodeString(strings.TrimSpace(best.Gateway))
61 62 if err != nil || len(rawGateway) != 32 {
63 return nil, fmt.Errorf("discovery: gateway %q is not a 32-byte public key", best.Gateway)
64 }
65 66 var gateway [32]byte
67 68 copy(gateway[:], rawGateway)
69 70 uri := &tunnel.URI{
71 Gateway: gateway,
72 Relays: mergeRelays(seeds, best.Relays),
73 Chains: best.Chains,
74 Version: 1,
75 }
76 77 // A gateway that was announced with a websocket bridge keeps it: the client tries that first
78 // and falls back to the relays, which is the same preference the URI itself expresses.
79 if parsed, err := tunnel.ParseURI(best.URI); err == nil {
80 uri.Bridges = parsed.Bridges
81 82 if len(uri.Chains) == 0 {
83 uri.Chains = parsed.Chains
84 }
85 }
86 87 // A gateway may serve the chain under another of its names; xbt and blake are one chain, and
88 // refusing the listing because it spells it differently would hide a working gateway.
89 if !containsAny(uri.Chains, chain.Aliases(chainName)) && len(uri.Chains) > 0 {
90 return nil, fmt.Errorf("discovery: %s announces %v, not %q", best.Gateway, uri.Chains, chainName)
91 }
92 93 return uri, nil
94 }
95 96 // Announcements returns every announcement found among the seeds, for a caller that wants to
97 // aggregate all the back ends rather than pick one.
98 func Announcements(ctx context.Context, factory func(string) (relay.Transport, error), seeds []string, chainName string, collect time.Duration) ([]registry.Info, error) {
99 return registry.Discover(ctx, factory, seeds, chainName, collect)
100 }
101 102 // mergeRelays returns the seeds followed by the advertised relays, each normalised and unique.
103 // The seed first is deliberate: it is the relay the caller knows works.
104 func mergeRelays(seeds, advertised []string) []string {
105 out := make([]string, 0, len(seeds)+len(advertised))
106 seen := make(map[string]struct{}, len(seeds)+len(advertised))
107 108 for _, list := range [][]string{seeds, advertised} {
109 for _, raw := range list {
110 relayURL := strings.TrimSpace(raw)
111 112 if relayURL == "" {
113 continue
114 }
115 116 relayURL = strings.TrimRight(relayURL, "/")
117 118 if _, ok := seen[relayURL]; ok {
119 continue
120 }
121 122 seen[relayURL] = struct{}{}
123 out = append(out, relayURL)
124 }
125 }
126 127 return out
128 }
129 130 // contains reports whether values contains want.
131 func contains(values []string, want string) bool {
132 for _, value := range values {
133 if value == want {
134 return true
135 }
136 }
137 138 return false
139 }
140 141 func containsAny(have, want []string) bool {
142 for _, name := range want {
143 if contains(have, name) {
144 return true
145 }
146 }
147 148 return false
149 }
150