forked from Titannet-dao/titan-storage-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcar.go
290 lines (259 loc) · 8.04 KB
/
car.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
package storage
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"path"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-unixfsnode/data/builder"
carv1 "github.com/ipld/go-car"
"github.com/ipld/go-car/v2"
"github.com/ipld/go-car/v2/blockstore"
carstorage "github.com/ipld/go-car/v2/storage"
dagpb "github.com/ipld/go-codec-dagpb"
"github.com/ipld/go-ipld-prime"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
"github.com/multiformats/go-multicodec"
"github.com/multiformats/go-multihash"
)
// createCar creates a car
func createCar(input string, output string) (cid.Cid, error) {
// make a cid with the right length that we eventually will patch with the root.
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(output, []cid.Cid{proxyRoot})
if err != nil {
return cid.Cid{}, err
}
// Write the unixfs blocks into the store.
root, err := writeFiles(context.TODO(), true, cdest, input)
if err != nil {
return cid.Cid{}, err
}
if err := cdest.Finalize(); err != nil {
return cid.Cid{}, err
}
return root, car.ReplaceRootsInFile(output, []cid.Cid{root})
}
// writeFiles writes files to the blockstore and returns the root CID.
func writeFiles(ctx context.Context, noWrap bool, bs *blockstore.ReadWrite, paths ...string) (cid.Cid, 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 err
}
bs.Put(ctx, blk)
return nil
}, nil
}
topLevel := make([]dagpb.PBLink, 0, len(paths))
for _, p := range paths {
l, size, err := builder.BuildUnixFSRecursive(p, &ls)
if err != nil {
return cid.Undef, err
}
if noWrap {
rcl, ok := l.(cidlink.Link)
if !ok {
return cid.Undef, fmt.Errorf("could not interpret %s", l)
}
return rcl.Cid, nil
}
name := path.Base(p)
entry, err := builder.BuildUnixFSDirectoryEntry(name, int64(size), l)
if err != nil {
return cid.Undef, err
}
topLevel = append(topLevel, entry)
}
// make a directory for the file(s).
root, _, err := builder.BuildUnixFSDirectory(topLevel, &ls)
if err != nil {
return cid.Undef, nil
}
rcl, ok := root.(cidlink.Link)
if !ok {
return cid.Undef, fmt.Errorf("could not interpret %s", root)
}
return rcl.Cid, nil
}
// CalculateCid calculates the CID for the given reader.
func CalculateCid(r io.Reader) (cid.Cid, error) {
ls := cidlink.DefaultLinkSystem()
ls.TrustedStorage = true
ls.StorageReadOpener = func(_ ipld.LinkContext, l ipld.Link) (io.Reader, error) {
return nil, nil
}
ls.StorageWriteOpener = func(_ ipld.LinkContext) (io.Writer, ipld.BlockWriteCommitter, error) {
buf := bytes.NewBuffer(nil)
return buf, func(l ipld.Link) error {
return nil
}, nil
}
link, _, err := builder.BuildUnixFSFile(r, "", &ls)
if err != nil {
return cid.Cid{}, err
}
root := link.(cidlink.Link)
return root.Cid, nil
}
// CarStream is an interface that combines io.ReadWriter, io.ReaderAt, io.WriterAt, io.Seeker.
type CarStream interface {
io.ReadWriter
io.ReaderAt
io.WriterAt
io.Seeker
}
// createCarStream creates a car using a CarStream.
func createCarStream(r io.Reader, carStream CarStream) (cid.Cid, error) {
// make a cid with the right length that we eventually will patch with the root.
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)
// proxyRoot, err := CalculateCID(r)
// if err != nil {
// return cid.Cid{}, err
// }
wCar, err := carstorage.NewWritable(carStream, []cid.Cid{proxyRoot})
if err != nil {
return cid.Cid{}, err
}
// Write the unixfs blocks into the store.
root, err := writeBuffer(context.TODO(), r, wCar)
if err != nil {
return cid.Cid{}, err
}
if err := wCar.Finalize(); err != nil {
return cid.Cid{}, err
}
return root, replaceRootsInCar(carStream, []cid.Cid{root})
}
// writeBuffer writes data to the car using a CarStream.
func writeBuffer(ctx context.Context, r io.Reader, wCar carstorage.WritableCar) (cid.Cid, error) {
sCar := wCar.(*carstorage.StorageCar)
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 := sCar.Get(ctx, cl.Cid.KeyString())
if err != nil {
return nil, err
}
return bytes.NewBuffer(blk), 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 err
}
sCar.Put(ctx, blk.Cid().KeyString(), blk.RawData())
return nil
}, nil
}
link, _, err := builder.BuildUnixFSFile(r, "", &ls)
if err != nil {
return cid.Cid{}, err
}
root := link.(cidlink.Link)
return root.Cid, nil
}
// replaceRootsInCar replaces the roots in the car header.
func replaceRootsInCar(carStream CarStream, roots []cid.Cid, opts ...car.Option) (err error) {
var v2h car.Header
if _, err = v2h.ReadFrom(carStream); err != nil {
return err
}
var newHeaderOffset = int64(v2h.DataOffset)
if _, err = carStream.Seek(newHeaderOffset, io.SeekStart); err != nil {
return err
}
var innerV1Header *carv1.CarHeader
innerV1Header, err = carv1.ReadHeader(bufio.NewReader(carStream))
if err != nil {
return err
}
fmt.Println("innerV1Header", innerV1Header)
if innerV1Header.Version != 1 {
err = fmt.Errorf("invalid data payload header: expected version 1, got %d", innerV1Header.Version)
return err
}
var readSoFar int64
readSoFar, err = carStream.Seek(0, io.SeekCurrent)
if err != nil {
return err
}
var currentSize = readSoFar - newHeaderOffset
newHeader := &carv1.CarHeader{
Roots: roots,
Version: 1,
}
size, _ := carv1.HeaderSize(newHeader)
fmt.Printf("newHeader %v, size %d", newHeader, size)
// Serialize the new header straight up instead of using carv1.HeaderSize.
// Because, carv1.HeaderSize serialises it to calculate size anyway.
// By serializing straight up we get the replacement bytes and size.
// Otherwise, we end up serializing the new header twice:
// once through carv1.HeaderSize, and
// once to write it out.
var buf bytes.Buffer
if err = carv1.WriteHeader(newHeader, &buf); err != nil {
return err
}
// Assert the header sizes are consistent.
newSize := int64(buf.Len())
if currentSize < newSize {
return fmt.Errorf("current header size (%d) must match replacement header size (%d)", currentSize, newSize)
}
// Seek to the offset at which the new header should be written.
if _, err = carStream.Seek(newHeaderOffset, io.SeekStart); err != nil {
return err
}
_, err = carStream.Write(buf.Bytes())
return err
}