-
Notifications
You must be signed in to change notification settings - Fork 0
/
object.go
593 lines (510 loc) · 14.5 KB
/
object.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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
package objectcmd
import (
"bytes"
"encoding/base64"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"strings"
"text/tabwriter"
mh "gx/ipfs/QmYf7ng2hG5XBtJA3tN34DQ2GUN5HNksEw1rLDkmr6vGku/go-multihash"
cmds "github.com/ipfs/go-ipfs/commands"
core "github.com/ipfs/go-ipfs/core"
dag "github.com/ipfs/go-ipfs/merkledag"
path "github.com/ipfs/go-ipfs/path"
ft "github.com/ipfs/go-ipfs/unixfs"
)
// ErrObjectTooLarge is returned when too much data was read from stdin. current limit 2m
var ErrObjectTooLarge = errors.New("input object was too large. limit is 2mbytes")
const inputLimit = 2 << 20
type Node struct {
Links []Link
Data string
}
type Link struct {
Name, Hash string
Size uint64
}
type Object struct {
Hash string `json:"Hash,omitempty"`
Links []Link `json:"Links,omitempty"`
}
var ObjectCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Interact with ipfs objects.",
ShortDescription: `
'ipfs object' is a plumbing command used to manipulate DAG objects
directly.`,
},
Subcommands: map[string]*cmds.Command{
"data": ObjectDataCmd,
"diff": ObjectDiffCmd,
"get": ObjectGetCmd,
"links": ObjectLinksCmd,
"new": ObjectNewCmd,
"patch": ObjectPatchCmd,
"put": ObjectPutCmd,
"stat": ObjectStatCmd,
},
}
var ObjectDataCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Outputs the raw bytes in an IPFS object.",
ShortDescription: `
'ipfs object data' is a plumbing command for retrieving the raw bytes stored
in a DAG node. It outputs to stdout, and <key> is a base58 encoded multihash.
`,
LongDescription: `
'ipfs object data' is a plumbing command for retrieving the raw bytes stored
in a DAG node. It outputs to stdout, and <key> is a base58 encoded multihash.
Note that the "--encoding" option does not affect the output, since the output
is the raw data of the object.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("key", true, false, "Key of the object to retrieve, in base58-encoded multihash format.").EnableStdin(),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
fpath := path.Path(req.Arguments()[0])
node, err := core.Resolve(req.Context(), n, fpath)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
res.SetOutput(bytes.NewReader(node.Data()))
},
}
var ObjectLinksCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Outputs the links pointed to by the specified object.",
ShortDescription: `
'ipfs object links' is a plumbing command for retrieving the links from
a DAG node. It outputs to stdout, and <key> is a base58 encoded
multihash.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("key", true, false, "Key of the object to retrieve, in base58-encoded multihash format.").EnableStdin(),
},
Options: []cmds.Option{
cmds.BoolOption("headers", "v", "Print table headers (Hash, Size, Name).").Default(false),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
// get options early -> exit early in case of error
if _, _, err := req.Option("headers").Bool(); err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
fpath := path.Path(req.Arguments()[0])
node, err := core.Resolve(req.Context(), n, fpath)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
output, err := getOutput(node)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
res.SetOutput(output)
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
object := res.Output().(*Object)
buf := new(bytes.Buffer)
w := tabwriter.NewWriter(buf, 1, 2, 1, ' ', 0)
headers, _, _ := res.Request().Option("headers").Bool()
if headers {
fmt.Fprintln(w, "Hash\tSize\tName\t")
}
for _, link := range object.Links {
fmt.Fprintf(w, "%s\t%v\t%s\t\n", link.Hash, link.Size, link.Name)
}
w.Flush()
return buf, nil
},
},
Type: Object{},
}
var ObjectGetCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Get and serialize the DAG node named by <key>.",
ShortDescription: `
'ipfs object get' is a plumbing command for retrieving DAG nodes.
It serializes the DAG node to the format specified by the "--encoding"
flag. It outputs to stdout, and <key> is a base58 encoded multihash.
`,
LongDescription: `
'ipfs object get' is a plumbing command for retrieving DAG nodes.
It serializes the DAG node to the format specified by the "--encoding"
flag. It outputs to stdout, and <key> is a base58 encoded multihash.
This command outputs data in the following encodings:
* "protobuf"
* "json"
* "xml"
(Specified by the "--encoding" or "--enc" flag)`,
},
Arguments: []cmds.Argument{
cmds.StringArg("key", true, false, "Key of the object to retrieve, in base58-encoded multihash format.").EnableStdin(),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
fpath := path.Path(req.Arguments()[0])
object, err := core.Resolve(req.Context(), n, fpath)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
node := &Node{
Links: make([]Link, len(object.Links)),
Data: string(object.Data()),
}
for i, link := range object.Links {
node.Links[i] = Link{
Hash: link.Hash.B58String(),
Name: link.Name,
Size: link.Size,
}
}
res.SetOutput(node)
},
Type: Node{},
Marshalers: cmds.MarshalerMap{
cmds.Protobuf: func(res cmds.Response) (io.Reader, error) {
node := res.Output().(*Node)
// deserialize the Data field as text as this was the standard behaviour
object, err := deserializeNode(node, "text")
if err != nil {
return nil, err
}
marshaled, err := object.Marshal()
if err != nil {
return nil, err
}
return bytes.NewReader(marshaled), nil
},
},
}
var ObjectStatCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Get stats for the DAG node named by <key>.",
ShortDescription: `
'ipfs object stat' is a plumbing command to print DAG node statistics.
<key> is a base58 encoded multihash. It outputs to stdout:
NumLinks int number of links in link table
BlockSize int size of the raw, encoded data
LinksSize int size of the links segment
DataSize int size of the data segment
CumulativeSize int cumulative size of object and its references
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("key", true, false, "Key of the object to retrieve, in base58-encoded multihash format.").EnableStdin(),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
fpath := path.Path(req.Arguments()[0])
object, err := core.Resolve(req.Context(), n, fpath)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
ns, err := object.Stat()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
res.SetOutput(ns)
},
Type: dag.NodeStat{},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
ns := res.Output().(*dag.NodeStat)
buf := new(bytes.Buffer)
w := func(s string, n int) {
fmt.Fprintf(buf, "%s: %d\n", s, n)
}
w("NumLinks", ns.NumLinks)
w("BlockSize", ns.BlockSize)
w("LinksSize", ns.LinksSize)
w("DataSize", ns.DataSize)
w("CumulativeSize", ns.CumulativeSize)
return buf, nil
},
},
}
var ObjectPutCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Stores input as a DAG object, outputs its key.",
ShortDescription: `
'ipfs object put' is a plumbing command for storing DAG nodes.
It reads from stdin, and the output is a base58 encoded multihash.
`,
LongDescription: `
'ipfs object put' is a plumbing command for storing DAG nodes.
It reads from stdin, and the output is a base58 encoded multihash.
Data should be in the format specified by the --inputenc flag.
--inputenc may be one of the following:
* "protobuf"
* "json" (default)
Examples:
$ echo '{ "Data": "abc" }' | ipfs object put
This creates a node with the data 'abc' and no links. For an object with
links, create a file named 'node.json' with the contents:
{
"Data": "another",
"Links": [ {
"Name": "some link",
"Hash": "QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V",
"Size": 8
} ]
}
And then run:
$ ipfs object put node.json
`,
},
Arguments: []cmds.Argument{
cmds.FileArg("data", true, false, "Data to be stored as a DAG object.").EnableStdin(),
},
Options: []cmds.Option{
cmds.StringOption("inputenc", "Encoding type of input data. One of: {\"protobuf\", \"json\"}.").Default("json"),
cmds.StringOption("datafieldenc", "Encoding type of the data field, either \"text\" or \"base64\".").Default("text"),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
input, err := req.Files().NextFile()
if err != nil && err != io.EOF {
res.SetError(err, cmds.ErrNormal)
return
}
inputenc, _, err := req.Option("inputenc").String()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
datafieldenc, _, err := req.Option("datafieldenc").String()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
output, err := objectPut(n, input, inputenc, datafieldenc)
if err != nil {
errType := cmds.ErrNormal
if err == ErrUnknownObjectEnc {
errType = cmds.ErrClient
}
res.SetError(err, errType)
return
}
res.SetOutput(output)
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
object := res.Output().(*Object)
return strings.NewReader("added " + object.Hash + "\n"), nil
},
},
Type: Object{},
}
var ObjectNewCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Creates a new object from an ipfs template.",
ShortDescription: `
'ipfs object new' is a plumbing command for creating new DAG nodes.
`,
LongDescription: `
'ipfs object new' is a plumbing command for creating new DAG nodes.
By default it creates and returns a new empty merkledag node, but
you may pass an optional template argument to create a preformatted
node.
Available templates:
* unixfs-dir
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("template", false, false, "Template to use. Optional."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
node := new(dag.Node)
if len(req.Arguments()) == 1 {
template := req.Arguments()[0]
var err error
node, err = nodeFromTemplate(template)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
}
k, err := n.DAG.Add(node)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
res.SetOutput(&Object{Hash: k.B58String()})
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
object := res.Output().(*Object)
return strings.NewReader(object.Hash + "\n"), nil
},
},
Type: Object{},
}
func nodeFromTemplate(template string) (*dag.Node, error) {
switch template {
case "unixfs-dir":
return ft.EmptyDirNode(), nil
default:
return nil, fmt.Errorf("template '%s' not found", template)
}
}
// ErrEmptyNode is returned when the input to 'ipfs object put' contains no data
var ErrEmptyNode = errors.New("no data or links in this node")
// objectPut takes a format option, serializes bytes from stdin and updates the dag with that data
func objectPut(n *core.IpfsNode, input io.Reader, encoding string, dataFieldEncoding string) (*Object, error) {
data, err := ioutil.ReadAll(io.LimitReader(input, inputLimit+10))
if err != nil {
return nil, err
}
if len(data) >= inputLimit {
return nil, ErrObjectTooLarge
}
var dagnode *dag.Node
switch getObjectEnc(encoding) {
case objectEncodingJSON:
node := new(Node)
err = json.Unmarshal(data, node)
if err != nil {
return nil, err
}
// check that we have data in the Node to add
// otherwise we will add the empty object without raising an error
if NodeEmpty(node) {
return nil, ErrEmptyNode
}
dagnode, err = deserializeNode(node, dataFieldEncoding)
if err != nil {
return nil, err
}
case objectEncodingProtobuf:
dagnode, err = dag.DecodeProtobuf(data)
case objectEncodingXML:
node := new(Node)
err = xml.Unmarshal(data, node)
if err != nil {
return nil, err
}
// check that we have data in the Node to add
// otherwise we will add the empty object without raising an error
if NodeEmpty(node) {
return nil, ErrEmptyNode
}
dagnode, err = deserializeNode(node, dataFieldEncoding)
if err != nil {
return nil, err
}
default:
return nil, ErrUnknownObjectEnc
}
if err != nil {
return nil, err
}
_, err = n.DAG.Add(dagnode)
if err != nil {
return nil, err
}
return getOutput(dagnode)
}
// ErrUnknownObjectEnc is returned if a invalid encoding is supplied
var ErrUnknownObjectEnc = errors.New("unknown object encoding")
type objectEncoding string
const (
objectEncodingJSON objectEncoding = "json"
objectEncodingProtobuf = "protobuf"
objectEncodingXML = "xml"
)
func getObjectEnc(o interface{}) objectEncoding {
v, ok := o.(string)
if !ok {
// chosen as default because it's human readable
return objectEncodingJSON
}
return objectEncoding(v)
}
func getOutput(dagnode *dag.Node) (*Object, error) {
key, err := dagnode.Key()
if err != nil {
return nil, err
}
output := &Object{
Hash: key.B58String(),
Links: make([]Link, len(dagnode.Links)),
}
for i, link := range dagnode.Links {
output.Links[i] = Link{
Name: link.Name,
Hash: link.Hash.B58String(),
Size: link.Size,
}
}
return output, nil
}
// converts the Node object into a real dag.Node
func deserializeNode(node *Node, dataFieldEncoding string) (*dag.Node, error) {
dagnode := new(dag.Node)
switch dataFieldEncoding {
case "text":
dagnode.SetData([]byte(node.Data))
case "base64":
data, _ := base64.StdEncoding.DecodeString(node.Data)
dagnode.SetData(data)
default:
return nil, fmt.Errorf("Unkown data field encoding")
}
dagnode.Links = make([]*dag.Link, len(node.Links))
for i, link := range node.Links {
hash, err := mh.FromB58String(link.Hash)
if err != nil {
return nil, err
}
dagnode.Links[i] = &dag.Link{
Name: link.Name,
Size: link.Size,
Hash: hash,
}
}
return dagnode, nil
}
func NodeEmpty(node *Node) bool {
return (node.Data == "" && len(node.Links) == 0)
}