-
Notifications
You must be signed in to change notification settings - Fork 0
/
uploader.go
336 lines (292 loc) · 8.03 KB
/
uploader.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
package main
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-libipfs/blocks"
"github.com/ipfs/go-unixfsnode/data/builder"
"github.com/ipld/go-car/v2"
"github.com/ipld/go-car/v2/blockstore"
"github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/datamodel"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
"github.com/multiformats/go-multicodec"
"github.com/multiformats/go-multihash"
"github.com/web3-storage/go-ucanto/core/delegation"
"github.com/web3-storage/go-ucanto/did"
"github.com/web3-storage/go-ucanto/principal"
"github.com/web3-storage/go-ucanto/principal/ed25519/signer"
"github.com/web3-storage/go-w3up/capability/storeadd"
"github.com/web3-storage/go-w3up/capability/uploadadd"
"github.com/web3-storage/go-w3up/client"
"github.com/web3-storage/go-w3up/cmd/util"
w3sdelegation "github.com/web3-storage/go-w3up/delegation"
)
// w3s interface to make it easier to mock w3s.
type w3s interface {
upload(cid.Cid, string) (cid.Cid, error)
}
// Uploader ...
type Uploader struct {
w3s w3s
tmpDir string
}
// UploadResult ..
type UploadResult struct {
Root cid.Cid
Shard cid.Cid
}
// NewUploader returns a new uploader.
func NewUploader(spaceID string, sk string, proofBytes []byte, tmpDir string) (*Uploader, error) {
client, err := newW3sclient(spaceID, sk, proofBytes)
if err != nil {
return nil, fmt.Errorf("creating new w3s client: %s", err)
}
return &Uploader{
w3s: client,
tmpDir: tmpDir,
}, nil
}
// Upload uploads the content of a io.Reader.
func (u *Uploader) Upload(ctx context.Context, r io.Reader) (_ UploadResult, err error) {
dest, err := u.saveTmp(r)
if err != nil {
return UploadResult{}, fmt.Errorf("failed saving into tmp: %s", err)
}
defer func() {
if cErr := u.removeTmp(dest); err == nil {
err = cErr
}
}()
root, err := u.createCar(ctx, dest)
if err != nil {
return UploadResult{}, fmt.Errorf("failed generating CAR: %s", err)
}
shard, err := u.w3s.upload(root, dest)
if err != nil {
return UploadResult{}, fmt.Errorf("failed archiving CAR: %s", err)
}
return UploadResult{
Root: root,
Shard: shard,
}, nil
}
func (u *Uploader) saveTmp(r io.Reader) (_ string, err error) {
randBytes := make([]byte, 16)
_, _ = rand.Read(randBytes)
dest := filepath.Join(u.tmpDir, hex.EncodeToString(randBytes))
f, err := os.Create(dest)
if err != nil {
return "", err
}
defer func() {
// Close file and override return error type if it is nil.
if cerr := f.Close(); err == nil {
err = cerr
}
}()
if _, err := io.Copy(f, r); err != nil {
return "", err
}
return dest, nil
}
func (u *Uploader) createCar(ctx context.Context, dest string) (cid.Cid, error) {
hasher, err := multihash.GetHasher(multihash.SHA2_256)
if err != nil {
return cid.Cid{}, err
}
digest := hasher.Sum([]byte{})
hash, err := multihash.Encode(digest, multihash.SHA2_256)
if err != nil {
return cid.Cid{}, err
}
proxyRoot := cid.NewCidV1(uint64(multicodec.DagPb), hash)
cdest, err := blockstore.OpenReadWrite(
fmt.Sprintf("%s.car", dest), []cid.Cid{proxyRoot}, []car.Option{blockstore.WriteAsCarV1(true)}...,
)
if err != nil {
return cid.Cid{}, err
}
// Write the unixfs blocks into the store.
root, _, err := writeFile(ctx, cdest, dest)
if err != nil {
return cid.Cid{}, err
}
if err := cdest.Finalize(); err != nil {
return cid.Cid{}, err
}
// re-open/finalize with the final root.
if err := car.ReplaceRootsInFile(fmt.Sprintf("%s.car", dest), []cid.Cid{root}); err != nil {
return cid.Cid{}, err
}
return root, nil
}
func (*Uploader) removeTmp(dest string) error {
if err := os.Remove(dest); err != nil {
return fmt.Errorf("failed to remove file: %s", err)
}
if err := os.Remove(fmt.Sprintf("%s.car", dest)); err != nil {
return fmt.Errorf("failed to remove car file: %s", err)
}
return nil
}
func writeFile(ctx context.Context, bs *blockstore.ReadWrite, path string) (_ cid.Cid, sz uint64, err error) {
ls := cidlink.DefaultLinkSystem()
ls.TrustedStorage = true
ls.StorageReadOpener = func(_ ipld.LinkContext, l ipld.Link) (io.Reader, error) {
cl, ok := l.(cidlink.Link)
if !ok {
return nil, fmt.Errorf("not a cidlink")
}
blk, err := bs.Get(ctx, cl.Cid)
if err != nil {
return nil, err
}
return bytes.NewBuffer(blk.RawData()), nil
}
ls.StorageWriteOpener = func(_ ipld.LinkContext) (io.Writer, ipld.BlockWriteCommitter, error) {
buf := bytes.NewBuffer(nil)
return buf, func(l ipld.Link) error {
cl, ok := l.(cidlink.Link)
if !ok {
return fmt.Errorf("not a cidlink")
}
blk, err := blocks.NewBlockWithCid(buf.Bytes(), cl.Cid)
if err != nil {
return fmt.Errorf("new block with cid: %s", err)
}
if err := bs.Put(ctx, blk); err != nil {
return fmt.Errorf("put: %s", err)
}
return nil
}, nil
}
f, err := os.Open(path)
if err != nil {
return cid.Undef, 0, err
}
defer func() {
// Close file and override return error type if it is nil.
if cerr := f.Close(); err == nil {
err = cerr
}
}()
l, size, err := builder.BuildUnixFSFile(f, "", &ls)
if err != nil {
return cid.Undef, 0, err
}
rcl, ok := l.(cidlink.Link)
if !ok {
return cid.Undef, 0, fmt.Errorf("could not interpret %s", l)
}
return rcl.Cid, size, nil
}
type w3sclient struct {
space did.DID
issuer principal.Signer
proof delegation.Delegation
}
func newW3sclient(spaceID string, sk string, proofBytes []byte) (*w3sclient, error) {
// private key to sign UCAN invocations with
issuer, err := signer.Parse(sk)
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %s", err)
}
// UCAN proof(s) that the signer can perform tasks in this space (a delegation chain)
proof, err := w3sdelegation.ExtractProof(proofBytes)
if err != nil {
return nil, fmt.Errorf("failed to extract proof: %s", err)
}
space, err := did.Parse(spaceID)
if err != nil {
return nil, fmt.Errorf("failed to parse space id: %s", err)
}
return &w3sclient{
issuer: issuer,
proof: proof,
space: space,
}, nil
}
func (c *w3sclient) upload(root cid.Cid, dest string) (_ cid.Cid, err error) {
// no need to close the file because the http client is doing that
f, err := os.Open(fmt.Sprintf("%s.car", dest))
if err != nil {
return cid.Undef, err
}
stat, err := f.Stat()
if err != nil {
return cid.Undef, err
}
size := uint64(stat.Size())
mh, err := multihash.SumStream(f, multihash.SHA2_256, -1)
if err != nil {
return cid.Undef, err
}
shardLink := cidlink.Link{Cid: cid.NewCidV1(uint64(multicodec.Car), mh)}
rcpt, err := client.StoreAdd(
c.issuer,
c.space,
&storeadd.Caveat{Link: shardLink, Size: size},
client.WithConnection(util.MustGetConnection()),
client.WithProofs([]delegation.Delegation{c.proof}),
)
if err != nil {
return cid.Undef, err
}
if rcpt.Out().Error() != nil {
return cid.Undef, fmt.Errorf(rcpt.Out().Error().Message)
}
if rcpt.Out().Ok().Status == "upload" {
_, err := f.Seek(0, io.SeekStart)
if err != nil {
return cid.Undef, err
}
hr, err := http.NewRequest("PUT", *rcpt.Out().Ok().Url, f)
if err != nil {
return cid.Undef, err
}
hdr := map[string][]string{}
for k, v := range rcpt.Out().Ok().Headers.Values {
if k == "content-length" {
continue
}
hdr[k] = []string{v}
}
hr.Header = hdr
hr.ContentLength = int64(size)
httpClient := http.Client{
Timeout: 0,
}
res, err := httpClient.Do(hr)
if err != nil {
return cid.Undef, err
}
if res.StatusCode != 200 {
return cid.Undef, fmt.Errorf("status code: %d", res.StatusCode)
}
if err := res.Body.Close(); err != nil {
return cid.Undef, fmt.Errorf("closing request body: %s", err)
}
}
rcpt2, err := client.UploadAdd(
c.issuer,
c.space,
&uploadadd.Caveat{Root: cidlink.Link{Cid: root}, Shards: []datamodel.Link{shardLink}},
client.WithConnection(util.MustGetConnection()),
client.WithProofs([]delegation.Delegation{c.proof}),
)
if err != nil {
return cid.Undef, err
}
if rcpt2.Out().Error() != nil {
return cid.Undef, fmt.Errorf(rcpt2.Out().Error().Message)
}
return shardLink.Cid, nil
}