block.go 7.91 KB
Newer Older
1 2 3 4
package commands

import (
	"bytes"
5
	"context"
6
	"errors"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	"fmt"
8
	"io"
9
	"io/ioutil"
Jan Winkelmann's avatar
Jan Winkelmann committed
10
	"os"
11

12
	util "github.com/ipfs/go-ipfs/blocks/blockstore/util"
Jan Winkelmann's avatar
Jan Winkelmann committed
13
	e "github.com/ipfs/go-ipfs/core/commands/e"
14

Steven Allen's avatar
Steven Allen committed
15
	"gx/ipfs/QmPq2D7Yoyev7yeMuMnkEYBqmQuUu5kb91UXPPoiik1Xyp/go-ipfs-cmds"
Steven Allen's avatar
Steven Allen committed
16 17
	mh "gx/ipfs/QmZyZDi491cCNTLfAhwcaDii2Kg4pwKRkhqQzURGDvY6ua/go-multihash"
	cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
18
	"gx/ipfs/QmceUdzxkimdYsgtX733uNgzf1DLHyBKN6ehGSp85ayppM/go-ipfs-cmdkit"
Steven Allen's avatar
Steven Allen committed
19
	blocks "gx/ipfs/Qmej7nf81hi2x2tvjRBF3mcp74sQyuDH4VMYDGd1YtXjb2/go-block-format"
20 21
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22 23 24 25 26 27 28
type BlockStat struct {
	Key  string
	Size int
}

func (bs BlockStat) String() string {
	return fmt.Sprintf("Key: %s\nSize: %d\n", bs.Key, bs.Size)
29 30
}

31
var BlockCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
32
	Helptext: cmdkit.HelpText{
33
		Tagline: "Interact with raw IPFS blocks.",
34
		ShortDescription: `
35
'ipfs block' is a plumbing command used to manipulate raw IPFS blocks.
36
Reads from stdin or writes to stdout, and <key> is a base58 encoded
37 38 39 40
multihash.
`,
	},

41
	Subcommands: map[string]*cmds.Command{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42 43 44
		"stat": blockStatCmd,
		"get":  blockGetCmd,
		"put":  blockPutCmd,
Kevin Atkinson's avatar
Kevin Atkinson committed
45
		"rm":   blockRmCmd,
46 47 48
	},
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49
var blockStatCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
50
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
51
		Tagline: "Print information of a raw IPFS block.",
52
		ShortDescription: `
rht's avatar
rht committed
53
'ipfs block stat' is a plumbing command for retrieving information
54
on raw IPFS blocks. It outputs the following to stdout:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55 56 57 58

	Key  - the base58 encoded multihash
	Size - the size of the block in bytes

59 60
`,
	},
61

Jan Winkelmann's avatar
Jan Winkelmann committed
62 63
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("key", true, false, "The base58 multihash of an existing block to stat.").EnableStdin(),
64
	},
Jeromy's avatar
Jeromy committed
65
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
66
		b, err := getBlockForKey(req.Context, env, req.Arguments[0])
67
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
68
			res.SetError(err, cmdkit.ErrNormal)
69
			return
70
		}
71

keks's avatar
keks committed
72
		err = cmds.EmitOnce(res, &BlockStat{
73
			Key:  b.Cid().String(),
Jeromy's avatar
Jeromy committed
74
			Size: len(b.RawData()),
75
		})
Jan Winkelmann's avatar
Jan Winkelmann committed
76 77 78
		if err != nil {
			log.Error(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
79 80
	},
	Type: BlockStat{},
Jan Winkelmann's avatar
Jan Winkelmann committed
81
	Encoders: cmds.EncoderMap{
82
		cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
Jan Winkelmann's avatar
Jan Winkelmann committed
83 84 85 86 87 88 89
			bs, ok := v.(*BlockStat)
			if !ok {
				return e.TypeErr(bs, v)
			}
			_, err := fmt.Fprintf(w, "%s", bs)
			return err
		}),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90 91
	},
}
92

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93
var blockGetCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
94
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
95
		Tagline: "Get a raw IPFS block.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96
		ShortDescription: `
97
'ipfs block get' is a plumbing command for retrieving raw IPFS blocks.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98 99 100
It outputs to stdout, and <key> is a base58 encoded multihash.
`,
	},
101

Jan Winkelmann's avatar
Jan Winkelmann committed
102 103
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("key", true, false, "The base58 multihash of an existing block to get.").EnableStdin(),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104
	},
Jeromy's avatar
Jeromy committed
105
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
106
		b, err := getBlockForKey(req.Context, env, req.Arguments[0])
107
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
108
			res.SetError(err, cmdkit.ErrNormal)
109
			return
110 111
		}

Jan Winkelmann's avatar
Jan Winkelmann committed
112 113 114 115
		err = res.Emit(bytes.NewReader(b.RawData()))
		if err != nil {
			log.Error(err)
		}
116 117 118 119
	},
}

var blockPutCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
120
	Helptext: cmdkit.HelpText{
121
		Tagline: "Store input as an IPFS block.",
122
		ShortDescription: `
123
'ipfs block put' is a plumbing command for storing raw IPFS blocks.
124
It reads from stdin, and <key> is a base58 encoded multihash.
125 126 127

By default CIDv0 is going to be generated. Setting 'mhtype' to anything other
than 'sha2-256' or format to anything other than 'v0' will result in CIDv1.
128 129
`,
	},
130

Jan Winkelmann's avatar
Jan Winkelmann committed
131 132
	Arguments: []cmdkit.Argument{
		cmdkit.FileArg("data", true, false, "The data to be stored as an IPFS block.").EnableStdin(),
133
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
134
	Options: []cmdkit.Option{
135
		cmdkit.StringOption("format", "f", "cid format for blocks to be created with.").WithDefault(""),
136 137
		cmdkit.StringOption("mhtype", "multihash hash function").WithDefault("sha2-256"),
		cmdkit.IntOption("mhlen", "multihash hash length").WithDefault(-1),
138
	},
Jeromy's avatar
Jeromy committed
139
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
140
		n, err := GetNode(env)
141
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
142
			res.SetError(err, cmdkit.ErrNormal)
143
			return
144
		}
145

146
		file, err := req.Files.NextFile()
147
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
148
			res.SetError(err, cmdkit.ErrNormal)
149
			return
150 151 152 153
		}

		data, err := ioutil.ReadAll(file)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
154
			res.SetError(err, cmdkit.ErrNormal)
155
			return
156 157
		}

158
		err = file.Close()
159
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
160
			res.SetError(err, cmdkit.ErrNormal)
161
			return
162 163
		}

164 165 166 167 168 169 170 171
		mhtype, _ := req.Options["mhtype"].(string)
		mhtval, ok := mh.Names[mhtype]
		if !ok {
			err := fmt.Errorf("unrecognized multihash function: %s", mhtype)
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

172 173
		var pref cid.Prefix
		pref.Version = 1
174

175 176 177 178 179 180 181
		format := req.Options["format"].(string)
		if format == "" {
			if mhtval == mh.SHA2_256 {
				format = "v0"
			} else {
				format = "protobuf"
			}
182
		}
183

184 185 186
		if format == "v0" {
			pref.Version = 0
		}
187
		formatval, ok := cid.Codecs[format]
188
		if !ok {
189 190 191 192 193
			res.SetError(fmt.Errorf("unrecognized format: %s", format), cmdkit.ErrNormal)
			return
		}
		if mhtval != mh.SHA2_256 && pref.Version == 0 {
			res.SetError(errors.New("cannot generate CIDv0 with non-sha256 hash function"), cmdkit.ErrNormal)
194 195
			return
		}
196 197

		pref.Codec = formatval
198 199
		pref.MhType = mhtval

200 201 202
		mhlen, ok := req.Options["mhlen"].(int)
		if !ok {
			res.SetError("missing option \"mhlen\"", cmdkit.ErrNormal)
203 204 205 206
			return
		}
		pref.MhLength = mhlen

207 208
		bcid, err := pref.Sum(data)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
209
			res.SetError(err, cmdkit.ErrNormal)
210 211 212 213 214
			return
		}

		b, err := blocks.NewBlockWithCid(data, bcid)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
215
			res.SetError(err, cmdkit.ErrNormal)
216 217
			return
		}
218

219
		err = n.Blocks.AddBlock(b)
220
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
221
			res.SetError(err, cmdkit.ErrNormal)
222
			return
223 224
		}

keks's avatar
keks committed
225
		err = cmds.EmitOnce(res, &BlockStat{
226
			Key:  b.Cid().String(),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227
			Size: len(data),
228
		})
Jan Winkelmann's avatar
Jan Winkelmann committed
229 230 231
		if err != nil {
			log.Error(err)
		}
232
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
233
	Encoders: cmds.EncoderMap{
234
		cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
Jan Winkelmann's avatar
Jan Winkelmann committed
235 236 237 238 239 240 241
			bs, ok := v.(*BlockStat)
			if !ok {
				return e.TypeErr(bs, v)
			}
			_, err := fmt.Fprintf(w, "%s\n", bs.Key)
			return err
		}),
242
	},
Matt Bell's avatar
Matt Bell committed
243
	Type: BlockStat{},
244
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245

Jeromy's avatar
Jeromy committed
246
func getBlockForKey(ctx context.Context, env cmds.Environment, skey string) (blocks.Block, error) {
247 248 249 250
	if len(skey) == 0 {
		return nil, fmt.Errorf("zero length cid invalid")
	}

251
	n, err := GetNode(env)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252 253 254 255
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
256
	c, err := cid.Decode(skey)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
257 258 259 260
	if err != nil {
		return nil, err
	}

261
	b, err := n.Blocks.GetBlock(ctx, c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
262 263 264
	if err != nil {
		return nil, err
	}
265

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
266 267
	return b, nil
}
Kevin Atkinson's avatar
Kevin Atkinson committed
268 269

var blockRmCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
270
	Helptext: cmdkit.HelpText{
Kevin Atkinson's avatar
Kevin Atkinson committed
271 272 273 274 275 276
		Tagline: "Remove IPFS block(s).",
		ShortDescription: `
'ipfs block rm' is a plumbing command for removing raw ipfs blocks.
It takes a list of base58 encoded multihashs to remove.
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
277 278
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("hash", true, true, "Bash58 encoded multihash of block(s) to remove."),
Kevin Atkinson's avatar
Kevin Atkinson committed
279
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
280
	Options: []cmdkit.Option{
281 282
		cmdkit.BoolOption("force", "f", "Ignore nonexistent blocks."),
		cmdkit.BoolOption("quiet", "q", "Write minimal output."),
283
	},
Jeromy's avatar
Jeromy committed
284
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
285
		n, err := GetNode(env)
Kevin Atkinson's avatar
Kevin Atkinson committed
286
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
287
			res.SetError(err, cmdkit.ErrNormal)
Kevin Atkinson's avatar
Kevin Atkinson committed
288 289
			return
		}
290 291 292
		hashes := req.Arguments
		force, _ := req.Options["force"].(bool)
		quiet, _ := req.Options["quiet"].(bool)
Jeromy's avatar
Jeromy committed
293
		cids := make([]*cid.Cid, 0, len(hashes))
Kevin Atkinson's avatar
Kevin Atkinson committed
294
		for _, hash := range hashes {
Jeromy's avatar
Jeromy committed
295 296
			c, err := cid.Decode(hash)
			if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
297 298
				err = fmt.Errorf("invalid content id: %s (%s)", hash, err)
				res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
299 300 301 302
				return
			}

			cids = append(cids, c)
Kevin Atkinson's avatar
Kevin Atkinson committed
303
		}
304
		ch, err := util.RmBlocks(n.Blockstore, n.Pinning, cids, util.RmBlocksOpts{
305 306 307
			Quiet: quiet,
			Force: force,
		})
Jan Winkelmann's avatar
Jan Winkelmann committed
308

309
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
310
			res.SetError(err, cmdkit.ErrNormal)
311 312
			return
		}
Jan Winkelmann's avatar
Jan Winkelmann committed
313 314 315 316 317

		err = res.Emit(ch)
		if err != nil {
			log.Error(err)
		}
Kevin Atkinson's avatar
Kevin Atkinson committed
318
	},
319
	PostRun: cmds.PostRunMap{
320
		cmds.CLI: func(req *cmds.Request, re cmds.ResponseEmitter) cmds.ResponseEmitter {
Jan Winkelmann's avatar
Jan Winkelmann committed
321 322 323 324 325 326 327 328
			reNext, res := cmds.NewChanResponsePair(req)

			go func() {
				defer re.Close()

				err := util.ProcRmOutput(res.Next, os.Stdout, os.Stderr)
				cmds.HandleError(err, res, re)
			}()
329

Jan Winkelmann's avatar
Jan Winkelmann committed
330
			return reNext
331
		},
Kevin Atkinson's avatar
Kevin Atkinson committed
332
	},
333
	Type: util.RemovedBlock{},
Kevin Atkinson's avatar
Kevin Atkinson committed
334
}