-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
495 lines (410 loc) · 14.6 KB
/
main.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
package main
import (
"context"
"fmt"
"log"
"net/url"
"os"
"path"
"strings"
"time"
"github.com/ipfs/go-cid"
pinclient "github.com/ipfs/go-pinning-service-http-client"
"github.com/ipld/go-car/v2"
"github.com/ipld/go-car/v2/blockstore"
"github.com/ipld/go-car/v2/index"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p-core/event"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
routinghelpers "github.com/libp2p/go-libp2p-routing-helpers"
"github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
"github.com/multiformats/go-multicodec"
"github.com/urfave/cli/v2" // imports as package "cli"
"github.com/briandowns/spinner"
"github.com/ipfs/go-bitswap"
bsnet "github.com/ipfs/go-bitswap/network"
)
var (
servicesEndpoints = map[string]string{
"web3.storage": "https://api.web3.storage",
"nft.storage": "https://nft.storage/api",
"pinata": "https://api.pinata.cloud/psa",
"estuary": "https://api.estuary.tech/pinning",
}
serviceFlag = &cli.StringFlag{
Name: "service", Usage: "Pinning service to use, e.g. web3.storage, nft.storage, pinata, estuary, or pinning service url, e.g. https://api.pinata.cloud/psa", Required: true,
}
tokenFlag = &cli.StringFlag{
Name: "token", Usage: "Bearer token for the pinning service sent in the HTTP Authorization header. Can be set with an environment variable:", Required: true, EnvVars: []string{"PIN_TOKEN"},
}
passOrigins = &cli.BoolFlag{
Name: "pass-origins", Usage: "Enable NAT port mapping with UPnP and NAT hole punching and passes the public address in the pin request's origins. Use when behind NAT with pinning services that don't return delegates",
}
nameFlag = &cli.StringFlag{
Name: "name", Usage: "Optional name for pinned data; can be used for lookups later", Required: false,
}
)
func main() {
// Spinner to visualise ongoing operation
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
s.Color("magenta")
app := &cli.App{
Name: "auspinner",
Usage: `stateless CLI tool to pin CAR files to IPFS pinning services`,
Commands: []*cli.Command{
{
Name: "list",
Aliases: []string{"ls"},
Usage: "list pins",
Flags: []cli.Flag{
serviceFlag,
tokenFlag,
&cli.StringFlag{
Name: "status", Usage: "filter based on pin status (if empty returns all), e.g. pinned, failed, pinning, queued", Required: false,
},
},
Action: func(c *cli.Context) error {
endpoint, err := getServiceEndpoint(c.String(serviceFlag.Name))
if err != nil {
return err
}
pinClient := pinclient.NewClient(endpoint, c.String(tokenFlag.Name)) // instantiate client with token
s.Start()
pins, err := listPins(c.Context, *pinClient, pinclient.Status(c.String("status")))
s.Stop()
if err != nil {
return err
}
fmt.Println("CID | Pin Request ID | Created | Status | Name")
for _, pin := range pins {
p := pin.GetPin()
fmt.Printf("%s %s %s (%s) %s\n", p.GetCid().String(), pin.GetRequestId(), pin.GetCreated().Format(time.RFC822), pin.GetStatus(), p.GetName())
}
if err != nil {
return err
}
return nil
},
},
{
Name: "remove",
Aliases: []string{"rm"},
Usage: `remove a pin request`, // auspinner remove --service [SERVICE] --token [TOKEN] [PIN_REQUEST_ID]
Flags: []cli.Flag{
serviceFlag,
tokenFlag,
},
Action: func(c *cli.Context) error {
endpoint, err := getServiceEndpoint(c.String(serviceFlag.Name))
if err != nil {
return err
}
var pinID string
if pinID = c.Args().First(); pinID == "" {
return fmt.Errorf("pin request ID is required")
}
pinClient := pinclient.NewClient(endpoint, c.String(tokenFlag.Name)) // instantiate client with token
s.Start()
err = pinClient.DeleteByID(c.Context, pinID)
s.Stop()
if err != nil {
return err
}
fmt.Printf("Deleted Pin Request ID: %s\n", pinID)
return nil
},
},
{
Name: "pin",
Usage: `pin a car file to a pinning service by pinning the root CID and serving the CIDs over Bitswap to the delegate returned from the pinning service
auspinner pin --service web3.storage --token [TOKEN] file.car
`,
Flags: []cli.Flag{
serviceFlag,
tokenFlag,
nameFlag,
passOrigins,
},
Action: func(c *cli.Context) error {
endpoint, err := getServiceEndpoint(c.String(serviceFlag.Name))
if err != nil {
return err
}
var carFilePath string
if carFilePath = c.Args().First(); carFilePath == "" {
return fmt.Errorf(".car file is required")
}
f, err := os.Open(carFilePath)
if err != nil {
return err
}
defer f.Close()
r, err := car.NewReader(f)
if err != nil {
return err
}
roots, err := r.Roots()
if err != nil {
return err
}
if len(roots) > 1 {
return fmt.Errorf(".car files with only one root CID are supported")
}
pinClient := pinclient.NewClient(endpoint, c.String(tokenFlag.Name)) // instantiate client with token
config := []libp2p.Option{}
if c.Bool(passOrigins.Name) {
// To pass the origins we typically need to port map assuming we're behind NAT
// enable port mapping so that our host can be connected by passing our address as origins
config = append(config, libp2p.NATPortMap(), libp2p.EnableHolePunching())
}
// Create libp2p host
host, err := libp2p.New(config...)
if err != nil {
return err
}
bsopts := []bitswap.Option{
bitswap.EngineBlockstoreWorkerCount(600),
bitswap.TaskWorkerCount(600),
bitswap.MaxOutstandingBytesPerPeer(int(5 << 20)),
}
robs, err := getCarBlockstore(r)
if err != nil {
return err
}
// Create a Bitswap server.
bswap := bitswap.New(c.Context, // Make a new Bitswap server (actually it's both a client and a server, but for now you only care about the server aspect)
bsnet.NewFromIpfsHost( // There's some abstraction layer here and bad naming, but basically it's asking for pieces it need
host, // libp2p host used for communicating with others
&routinghelpers.Null{}, // a routing system for finding content for the client (also it does this wacky thing where it advertises new blocks it learns about ...)
),
robs, // this is the blockstore from the car file we're serving over bitswap
bsopts..., // some configuration options and tuning
)
_ = bswap
var pinRequest pinclient.PinStatusGetter
if c.Bool(passOrigins.Name) {
subs, err := host.EventBus().Subscribe(new(event.EvtLocalAddressesUpdated))
if err != nil {
return err
}
fmt.Println("Waiting to get public multiaddress from UPnP port mapping")
addrLoop:
for {
select {
// Wait for the public IP after mapping the port
case <-subs.Out():
origins, err := getPublicAddr(host)
if err != nil {
return err
}
if len(origins) > 0 {
pinRequest, err = addPin(c.Context, *pinClient, roots[0], c.String(nameFlag.Name), origins)
if err != nil {
return err
}
break addrLoop
}
case <-time.After(1 * time.Minute):
return fmt.Errorf("couldn't make auspinner publicly reachable for passing in origins. Try enabling UPnP in your router")
}
}
} else {
origins, err := getPublicAddr(host)
if err != nil {
return err
}
pinRequest, err = addPin(c.Context, *pinClient, roots[0], c.String(nameFlag.Name), origins)
if err != nil {
return err
}
// If there are no delegates, we need to wait for the port mapping to happen and update the pin request with the origins
// Otherwise there's no way for the pinning service to fetch the CID if we're the only provider on the network
if len(pinRequest.GetDelegates()) == 0 {
return fmt.Errorf("no delegates were returned. Try again with the --pass-origins flag")
}
}
// Connect to the delegates returned from the pinning service
for _, d := range pinRequest.GetDelegates() {
p, err := peer.AddrInfoFromP2pAddr(d)
if err != nil {
return err
}
fmt.Printf("Connecting local Bitswap host to delegate: (%s)\n", p.String())
if err := host.Connect(c.Context, *p); err != nil {
log.Fatalf("error connecting to remote pin delegate %v : %v", d, err)
}
}
fmt.Println("Waiting for the blocks to be transferred...")
s.Start()
// Track status of pin requests
for range time.Tick(5 * time.Second) {
current, err := pinClient.GetStatusByID(c.Context, pinRequest.GetRequestId())
if err != nil {
fmt.Println("failed getting pin request status")
continue
}
if pinRequest.GetStatus() != current.GetStatus() {
s.Stop()
fmt.Printf("Pin requestId: %s status change: (%s) -> (%s) | (%s)\n", current.GetRequestId(), pinRequest.GetStatus(), current.GetStatus(), time.Now().Format(time.RFC822))
pinRequest = current
}
if current.GetStatus() == "pinned" {
s.Stop()
fmt.Printf("Pin requestId: %s successfully pinned CID: %s! 🎉\n", current.GetRequestId(), current.GetPin().GetCid())
break
}
if current.GetStatus() == "failed" {
fmt.Printf("Pin requestId: %s failed to pin CID: 😭\n", current.GetRequestId())
s.Stop()
break
}
}
return nil
},
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func getCarBlockstore(r *car.Reader) (*blockstore.ReadOnly, error) {
var idx index.Index
backingReader := r.DataReader()
if r.Version == 1 || !r.Header.HasIndex() {
idx, err := index.New(multicodec.CarMultihashIndexSorted)
if err != nil {
return nil, err
}
// TODO: Read more about how LoadIndex works for car files without an index
if err := car.LoadIndex(idx, r.DataReader()); err != nil {
return nil, err
}
// TODO: Save newly created index somewhere
} else {
i, err := index.ReadFrom(r.IndexReader())
if err != nil {
return nil, err
}
if i.Codec() != multicodec.CarMultihashIndexSorted {
return nil, fmt.Errorf("codec %s not supported for CAR files", i.Codec())
}
idx = i
}
return blockstore.NewReadOnly(backingReader, idx)
}
func addPin(ctx context.Context, client pinclient.Client, cid cid.Cid, name string, origins []multiaddr.Multiaddr) (pinclient.PinStatusGetter, error) {
opts := []pinclient.AddOption{
pinclient.PinOpts.WithName(name), // Pass the name
}
if origins != nil {
opts = append(opts, pinclient.PinOpts.WithOrigins(origins...)) // Pass our address so that the pinning service can fetch the
}
pinRequest, err := client.Add(ctx, cid, opts...)
if err != nil {
return nil, err
}
fmt.Printf("Created pin request: %s for root CID %s | status: %s | name: %s | origins: %v \n", pinRequest.GetRequestId(), cid, pinRequest.GetStatus(), name, origins)
return pinRequest, nil
}
func updatePinRequestOrigins(ctx context.Context, client pinclient.Client, pin pinclient.PinStatusGetter, origins []multiaddr.Multiaddr) (pinclient.PinStatusGetter, error) {
opts := []pinclient.AddOption{
pinclient.PinOpts.WithName(pin.GetPin().GetName()), // Pass the name
pinclient.PinOpts.WithOrigins(origins...), // Pass our address so that the pinning service can fetch the
}
updatedPinRequest, err := client.Replace(ctx, pin.GetRequestId(), pin.GetPin().GetCid(), opts...)
if err != nil {
return nil, err
}
fmt.Printf("Updated pin request: %s %s | status: %s\n", updatedPinRequest.GetRequestId(), time.Now().Format(time.RFC822), updatedPinRequest.GetStatus())
fmt.Printf("Original pin request: %s | New pin request: %s\n", pin.GetRequestId(), updatedPinRequest.GetRequestId())
return updatedPinRequest, nil
}
// func connectToDelegates(ctx context.Context, h host.Host, delegates []string) error {
// peers := make(map[peer.ID][]multiaddr.Multiaddr)
// for _, d := range delegates {
// ai, err := peer.AddrInfoFromString(d)
// if err != nil {
// return err
// }
// peers[ai.ID] = append(peers[ai.ID], ai.Addrs...)
// }
// for p, addrs := range peers {
// h.Peerstore().AddAddrs(p, addrs, time.Hour)
// if h.Network().Connectedness(p) != network.Connected {
// if err := h.Connect(ctx, peer.AddrInfo{
// ID: p,
// }); err != nil {
// return err
// }
// h.ConnManager().Protect(p, "pinning")
// }
// }
// return nil
// }
// `svc` can be either a valid key service from servicesEndpoints or a url
func getServiceEndpoint(service string) (string, error) {
if endpoint, ok := servicesEndpoints[service]; ok {
return endpoint, nil
}
endpoint, err := normalizeEndpoint(service)
if err != nil {
return "", err
}
return endpoint, nil
}
func listPins(ctx context.Context, c pinclient.Client, status pinclient.Status) ([]pinclient.PinStatusGetter, error) {
var opts pinclient.LsOption
if status == "" {
// If status is empty, list all statuses
opts = pinclient.PinOpts.FilterStatus(pinclient.StatusPinned, pinclient.StatusPinning, pinclient.StatusFailed, pinclient.StatusQueued)
} else {
s := pinclient.Status(status)
if s.String() == string(pinclient.StatusUnknown) {
return nil, fmt.Errorf("status %s is not valid", status)
}
opts = pinclient.PinOpts.FilterStatus(status)
}
return c.LsSync(ctx, opts)
}
func normalizeEndpoint(endpoint string) (string, error) {
uri, err := url.ParseRequestURI(endpoint)
if err != nil || !(uri.Scheme == "http" || uri.Scheme == "https") {
return "", fmt.Errorf("service endpoint must be a valid HTTP URL")
}
// cleanup trailing and duplicate slashes (https://github.com/ipfs/go-ipfs/issues/7826)
uri.Path = path.Clean(uri.Path)
uri.Path = strings.TrimSuffix(uri.Path, ".")
uri.Path = strings.TrimSuffix(uri.Path, "/")
// remove any query params
if uri.RawQuery != "" {
return "", fmt.Errorf("service endpoint should be provided without any query parameters")
}
if strings.HasSuffix(uri.Path, "/pins") {
return "", fmt.Errorf("service endpoint should be provided without the /pins suffix")
}
return uri.String(), nil
}
// Get public multi addresses of a host
func getPublicAddr(host host.Host) ([]multiaddr.Multiaddr, error) {
addr := peer.AddrInfo{
ID: host.ID(),
Addrs: host.Addrs(),
}
// All multi addresses including private
maddr, err := peer.AddrInfoToP2pAddrs(&addr)
if err != nil {
return nil, err
}
var origins []multiaddr.Multiaddr
for _, m := range maddr {
// Check if I have public addresse
if manet.IsPublicAddr(m) {
origins = append(origins, m)
}
}
return origins, nil
}