block.go 7.98 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/blockstoreutil"
13
	cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv"
Jan Winkelmann's avatar
Jan Winkelmann committed
14
	e "github.com/ipfs/go-ipfs/core/commands/e"
15

16
	"gx/ipfs/QmPTfgFTo9PFr1PvPKyKoeMgBvYPh6cX3aDP7DHKVbnCbi/go-ipfs-cmds"
17
	mh "gx/ipfs/QmPnFwZ2JXKnXgMw8CdBPxn7FWh6LLdjUjxV1fKHuJnkr8/go-multihash"
18 19 20
	"gx/ipfs/QmSP88ryZkHSRn1fnngAaV2Vcn63WUJzAavnRM9CVdU1Ky/go-ipfs-cmdkit"
	blocks "gx/ipfs/QmWAzSEoqZ6xU6pu8yL8e5WaMb7wtbfbhhN4p1DknUPtr3/go-block-format"
	cid "gx/ipfs/QmZFbDTY9jfSBms2MchvYM9oYRbAF19K7Pby47yDBfpPrb/go-cid"
21 22
)

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

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

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

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

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

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

60 61
`,
	},
62

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

keks's avatar
keks committed
73
		err = cmds.EmitOnce(res, &BlockStat{
74
			Key:  b.Cid().String(),
Jeromy's avatar
Jeromy committed
75
			Size: len(b.RawData()),
76
		})
Jan Winkelmann's avatar
Jan Winkelmann committed
77 78 79
		if err != nil {
			log.Error(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
80 81
	},
	Type: BlockStat{},
Jan Winkelmann's avatar
Jan Winkelmann committed
82
	Encoders: cmds.EncoderMap{
83
		cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
Jan Winkelmann's avatar
Jan Winkelmann committed
84 85 86 87 88 89 90
			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
91 92
	},
}
93

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

Jan Winkelmann's avatar
Jan Winkelmann committed
103 104
	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
105
	},
Jeromy's avatar
Jeromy committed
106
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
107
		b, err := getBlockForKey(req.Context, env, req.Arguments[0])
108
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
109
			res.SetError(err, cmdkit.ErrNormal)
110
			return
111 112
		}

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

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

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.
129 130
`,
	},
131

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

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

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

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

165 166 167 168 169 170 171 172
		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
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			go func() {
				defer re.Close()

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

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