This repository has been archived by the owner on Jun 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathnamesys.go
349 lines (298 loc) · 9.46 KB
/
namesys.go
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// Package namesys defines Resolver and Publisher interfaces for IPNS paths,
// that is, IPFS paths in the form of /ipns/<name_to_be_resolved>. A "resolved"
// IPNS path becomes an /ipfs/<cid> path.
//
// Traditionally, these paths would be in the form of /ipns/peer_id, which
// references an IPNS record in a distributed ValueStore (usually the IPFS
// DHT).
//
// Additionally, the /ipns/ namespace can also be used with domain names that
// use DNSLink (/ipns/<dnslink_name>, https://docs.ipfs.io/concepts/dnslink/)
//
// The package provides implementations for all three resolvers.
package namesys
import (
"context"
"fmt"
"os"
"strings"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/ipfs/go-cid"
ds "github.com/ipfs/go-datastore"
dssync "github.com/ipfs/go-datastore/sync"
"github.com/ipfs/go-path"
iface "github.com/ipfs/interface-go-ipfs-core"
opts "github.com/ipfs/interface-go-ipfs-core/options/namesys"
ci "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/routing"
"github.com/miekg/dns"
madns "github.com/multiformats/go-multiaddr-dns"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
// mpns (a multi-protocol NameSystem) implements generic IPFS naming.
//
// Uses several Resolvers:
// (a) IPFS routing naming: SFS-like PKI names.
// (b) dns domains: resolves using links in DNS TXT records
//
// It can only publish to: (a) IPFS routing naming.
type mpns struct {
ds ds.Datastore
dnsResolver, ipnsResolver resolver
ipnsPublisher Publisher
staticMap map[string]path.Path
cache *lru.Cache
}
// Deprecated: use github.com/ipfs/boxo/namesys.Option
type Option func(*mpns) error
// WithCache is an option that instructs the name system to use a (LRU) cache of the given size.
//
// Deprecated: use github.com/ipfs/boxo/namesys.WithCache
func WithCache(size int) Option {
return func(ns *mpns) error {
if size <= 0 {
return fmt.Errorf("invalid cache size %d; must be > 0", size)
}
cache, err := lru.New(size)
if err != nil {
return err
}
ns.cache = cache
return nil
}
}
// WithDNSResolver is an option that supplies a custom DNS resolver to use instead of the system
// default.
//
// Deprecated: use github.com/ipfs/boxo/namesys.WithDNSResolver
func WithDNSResolver(rslv madns.BasicResolver) Option {
return func(ns *mpns) error {
ns.dnsResolver = NewDNSResolver(rslv.LookupTXT)
return nil
}
}
// WithDatastore is an option that supplies a datastore to use instead of an in-memory map datastore. The datastore is used to store published IPNS records and make them available for querying.
//
// Deprecated: use github.com/ipfs/boxo/namesys.WithDatastore
func WithDatastore(ds ds.Datastore) Option {
return func(ns *mpns) error {
ns.ds = ds
return nil
}
}
func loadStaticMap(list string) (map[string]path.Path, error) {
staticMap := make(map[string]path.Path)
for _, pair := range strings.Split(list, ",") {
mapping := strings.SplitN(pair, ":", 2)
key := mapping[0]
value := path.FromString(mapping[1])
ipnsKey, err := peer.Decode(key)
if err == nil {
key = iface.FormatKeyID(ipnsKey)
}
staticMap[key] = value
}
return staticMap, nil
}
// NewNameSystem will construct the IPFS naming system based on Routing
//
// Deprecated: use github.com/ipfs/boxo/namesys.NewNameSystem
func NewNameSystem(r routing.ValueStore, opts ...Option) (NameSystem, error) {
var staticMap map[string]path.Path
// Prewarm namesys cache with static records for deterministic tests and debugging.
// Useful for testing things like DNSLink without real DNS lookup.
// Example:
// IPFS_NS_MAP="dnslink-test.example.com:/ipfs/bafkreicysg23kiwv34eg2d7qweipxwosdo2py4ldv42nbauguluen5v6am"
if list := os.Getenv("IPFS_NS_MAP"); list != "" {
var err error
staticMap, err = loadStaticMap(list)
if err != nil {
return nil, err
}
}
ns := &mpns{
staticMap: staticMap,
}
for _, opt := range opts {
err := opt(ns)
if err != nil {
return nil, err
}
}
if ns.ds == nil {
ns.ds = dssync.MutexWrap(ds.NewMapDatastore())
}
if ns.dnsResolver == nil {
ns.dnsResolver = NewDNSResolver(madns.DefaultResolver.LookupTXT)
}
ns.ipnsResolver = NewIpnsResolver(r)
ns.ipnsPublisher = NewIpnsPublisher(r, ns.ds)
return ns, nil
}
// DefaultResolverCacheTTL defines max ttl of a record placed in namesys cache.
//
// Deprecated: use github.com/ipfs/boxo/namesys.DefaultResolverCacheTTL
const DefaultResolverCacheTTL = time.Minute
// Resolve implements Resolver.
func (ns *mpns) Resolve(ctx context.Context, name string, options ...opts.ResolveOpt) (path.Path, error) {
ctx, span := StartSpan(ctx, "MPNS.Resolve", trace.WithAttributes(attribute.String("Name", name)))
defer span.End()
if strings.HasPrefix(name, "/ipfs/") {
return path.ParsePath(name)
}
if !strings.HasPrefix(name, "/") {
return path.ParsePath("/ipfs/" + name)
}
return resolve(ctx, ns, name, opts.ProcessOpts(options))
}
func (ns *mpns) ResolveAsync(ctx context.Context, name string, options ...opts.ResolveOpt) <-chan Result {
ctx, span := StartSpan(ctx, "MPNS.ResolveAsync", trace.WithAttributes(attribute.String("Name", name)))
defer span.End()
if strings.HasPrefix(name, "/ipfs/") {
p, err := path.ParsePath(name)
res := make(chan Result, 1)
res <- Result{p, err}
close(res)
return res
}
if !strings.HasPrefix(name, "/") {
p, err := path.ParsePath("/ipfs/" + name)
res := make(chan Result, 1)
res <- Result{p, err}
close(res)
return res
}
return resolveAsync(ctx, ns, name, opts.ProcessOpts(options))
}
// resolveOnce implements resolver.
func (ns *mpns) resolveOnceAsync(ctx context.Context, name string, options opts.ResolveOpts) <-chan onceResult {
ctx, span := StartSpan(ctx, "MPNS.ResolveOnceAsync")
defer span.End()
out := make(chan onceResult, 1)
if !strings.HasPrefix(name, ipnsPrefix) {
name = ipnsPrefix + name
}
segments := strings.SplitN(name, "/", 4)
if len(segments) < 3 || segments[0] != "" {
log.Debugf("invalid name syntax for %s", name)
out <- onceResult{err: ErrResolveFailed}
close(out)
return out
}
key := segments[2]
// Resolver selection:
// 1. if it is a PeerID/CID/multihash resolve through "ipns".
// 2. if it is a domain name, resolve through "dns"
var res resolver
ipnsKey, err := peer.Decode(key)
// CIDs in IPNS are expected to have libp2p-key multicodec
// We ease the transition by returning a more meaningful error with a valid CID
if err != nil {
ipnsCid, cidErr := cid.Decode(key)
if cidErr == nil && ipnsCid.Version() == 1 && ipnsCid.Type() != cid.Libp2pKey {
fixedCid := cid.NewCidV1(cid.Libp2pKey, ipnsCid.Hash()).String()
codecErr := fmt.Errorf("peer ID represented as CIDv1 require libp2p-key multicodec: retry with /ipns/%s", fixedCid)
log.Debugf("RoutingResolver: could not convert public key hash %q to peer ID: %s\n", key, codecErr)
out <- onceResult{err: codecErr}
close(out)
return out
}
}
cacheKey := key
if err == nil {
cacheKey = iface.FormatKeyID(ipnsKey)
}
if p, ok := ns.cacheGet(cacheKey); ok {
var err error
if len(segments) > 3 {
p, err = path.FromSegments("", strings.TrimRight(p.String(), "/"), segments[3])
}
span.SetAttributes(attribute.Bool("CacheHit", true))
span.RecordError(err)
out <- onceResult{value: p, err: err}
close(out)
return out
}
span.SetAttributes(attribute.Bool("CacheHit", false))
if err == nil {
res = ns.ipnsResolver
} else if _, ok := dns.IsDomainName(key); ok {
res = ns.dnsResolver
} else {
out <- onceResult{err: fmt.Errorf("invalid IPNS root: %q", key)}
close(out)
return out
}
resCh := res.resolveOnceAsync(ctx, key, options)
var best onceResult
go func() {
defer close(out)
for {
select {
case res, ok := <-resCh:
if !ok {
if best != (onceResult{}) {
ns.cacheSet(cacheKey, best.value, best.ttl)
}
return
}
if res.err == nil {
best = res
}
p := res.value
err := res.err
ttl := res.ttl
// Attach rest of the path
if len(segments) > 3 {
p, err = path.FromSegments("", strings.TrimRight(p.String(), "/"), segments[3])
}
emitOnceResult(ctx, out, onceResult{value: p, ttl: ttl, err: err})
case <-ctx.Done():
return
}
}
}()
return out
}
func emitOnceResult(ctx context.Context, outCh chan<- onceResult, r onceResult) {
select {
case outCh <- r:
case <-ctx.Done():
}
}
// Publish implements Publisher
func (ns *mpns) Publish(ctx context.Context, name ci.PrivKey, value path.Path, options ...opts.PublishOption) error {
ctx, span := StartSpan(ctx, "MPNS.Publish")
defer span.End()
// This is a bit hacky. We do this because the EOL is based on the current
// time, but also needed in the end of the function. Therefore, we parse
// the options immediately and add an option PublishWithEOL with the EOL
// calculated in this moment.
publishOpts := opts.ProcessPublishOptions(options)
options = append(options, opts.PublishWithEOL(publishOpts.EOL))
id, err := peer.IDFromPrivateKey(name)
if err != nil {
span.RecordError(err)
return err
}
span.SetAttributes(attribute.String("ID", id.String()))
if err := ns.ipnsPublisher.Publish(ctx, name, value, options...); err != nil {
// Invalidate the cache. Publishing may _partially_ succeed but
// still return an error.
ns.cacheInvalidate(string(id))
span.RecordError(err)
return err
}
ttl := DefaultResolverCacheTTL
if publishOpts.TTL >= 0 {
ttl = publishOpts.TTL
}
if ttEOL := time.Until(publishOpts.EOL); ttEOL < ttl {
ttl = ttEOL
}
ns.cacheSet(string(id), value, ttl)
return nil
}