-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipfs.go
89 lines (75 loc) · 1.97 KB
/
ipfs.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
package ipfs
import (
"bufio"
"context"
"os"
"github.com/filecoin-project/go-commp-utils/writer"
"github.com/filecoin-project/lotus/api"
"github.com/google/uuid"
"github.com/ipfs/go-cid"
ipfsfiles "github.com/ipfs/go-ipfs-files"
httpapi "github.com/ipfs/go-ipfs-http-client"
ipfsIO "github.com/ipfs/go-unixfs/io"
"github.com/ipfs/interface-go-ipfs-core/options"
"github.com/ipld/go-car"
"github.com/multiformats/go-multiaddr"
)
func InitIPFSClient(addr string) (*httpapi.HttpApi, error) {
ma, err := multiaddr.NewMultiaddr(addr)
if err != nil {
return nil, err
}
return httpapi.NewApi(ma)
}
func CreateBatch(ctx context.Context, i *httpapi.HttpApi, cids []cid.Cid) (cid.Cid, error) {
batch := ipfsIO.NewDirectory(i.Dag())
for _, c := range cids {
node, err := i.Dag().Get(ctx, c)
if err != nil {
return cid.Undef, err
}
err = batch.AddChild(ctx, uuid.New().String(), node)
if err != nil {
return cid.Undef, err
}
}
node, err := batch.GetNode()
if err != nil {
return cid.Undef, err
}
err = i.Dag().Add(ctx, node)
if err != nil {
return cid.Undef, err
}
err = i.Dag().Pinning().Add(ctx, node)
if err != nil {
return cid.Undef, err
}
return node.Cid(), nil
}
func ClientDealPieceCID(ctx context.Context, i *httpapi.HttpApi, root cid.Cid) (api.DataCIDSize, error) {
dag := i.Dag()
w := &writer.Writer{}
bw := bufio.NewWriterSize(w, int(writer.CommPBuf))
err := car.WriteCar(ctx, dag, []cid.Cid{root}, w)
if err != nil {
return api.DataCIDSize{}, err
}
if err := bw.Flush(); err != nil {
return api.DataCIDSize{}, err
}
dataCIDSize, err := w.Sum()
return api.DataCIDSize(dataCIDSize), err
}
func UploadAndPin(ctx context.Context, i *httpapi.HttpApi, pth string) (cid.Cid, error) {
file, err := os.Open(pth)
if err != nil {
return cid.Undef, err
}
defer file.Close()
resp, err := i.Unixfs().Add(ctx, ipfsfiles.NewReaderFile(file), options.Unixfs.Pin(true))
if err != nil {
return cid.Undef, err
}
return resp.Cid(), nil
}