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

import (
	"bytes"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
	"fmt"
6
	"io"
7
	"io/ioutil"
8
	"strings"
9

10
	util "github.com/ipfs/go-ipfs/blocks/blockstore/util"
11
	cmds "github.com/ipfs/go-ipfs/commands"
12

13 14
	mh "gx/ipfs/QmVGtdTZdTFaLsaj2RwdVG8jcjNNcp1DE914DKZ2kHmXHw/go-multihash"
	u "gx/ipfs/QmWbjfz3u6HkAdPh34dgPchGbQjob6LXLhAeCGii2TX69n/go-ipfs-util"
15
	blocks "gx/ipfs/QmXxGS5QsUxpR3iqL5DjmsYPHR1Yz74siRQ4ChJqWFosMh/go-block-format"
16
	cid "gx/ipfs/Qma4RJSuh7mMeJQYCqMbKzekn6EwBo7HEs5AQYjVRMQATB/go-cid"
17 18
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20 21 22 23 24 25
type BlockStat struct {
	Key  string
	Size int
}

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

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

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

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

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

56 57
`,
	},
58

59
	Arguments: []cmds.Argument{
60
		cmds.StringArg("key", true, false, "The base58 multihash of an existing block to stat.").EnableStdin(),
61
	},
62
	Run: func(req cmds.Request, res cmds.Response) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63
		b, err := getBlockForKey(req, req.Arguments()[0])
64
		if err != nil {
65 66
			res.SetError(err, cmds.ErrNormal)
			return
67
		}
68

69
		res.SetOutput(&BlockStat{
70
			Key:  b.Cid().String(),
Jeromy's avatar
Jeromy committed
71
			Size: len(b.RawData()),
72
		})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73 74 75 76 77 78 79 80 81
	},
	Type: BlockStat{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			bs := res.Output().(*BlockStat)
			return strings.NewReader(bs.String()), nil
		},
	},
}
82

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84
var blockGetCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
85
		Tagline: "Get a raw IPFS block.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
86
		ShortDescription: `
87
'ipfs block get' is a plumbing command for retrieving raw IPFS blocks.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88 89 90
It outputs to stdout, and <key> is a base58 encoded multihash.
`,
	},
91

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92
	Arguments: []cmds.Argument{
93
		cmds.StringArg("key", true, false, "The base58 multihash of an existing block to get.").EnableStdin(),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94
	},
95
	Run: func(req cmds.Request, res cmds.Response) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96
		b, err := getBlockForKey(req, req.Arguments()[0])
97
		if err != nil {
98 99
			res.SetError(err, cmds.ErrNormal)
			return
100 101
		}

Jeromy's avatar
Jeromy committed
102
		res.SetOutput(bytes.NewReader(b.RawData()))
103 104 105 106
	},
}

var blockPutCmd = &cmds.Command{
107
	Helptext: cmds.HelpText{
108
		Tagline: "Store input as an IPFS block.",
109
		ShortDescription: `
110
'ipfs block put' is a plumbing command for storing raw IPFS blocks.
111 112 113
It reads from stdin, and <key> is a base58 encoded multihash.
`,
	},
114

115
	Arguments: []cmds.Argument{
116
		cmds.FileArg("data", true, false, "The data to be stored as an IPFS block.").EnableStdin(),
117
	},
118 119
	Options: []cmds.Option{
		cmds.StringOption("format", "f", "cid format for blocks to be created with.").Default("v0"),
120 121
		cmds.StringOption("mhtype", "multihash hash function").Default("sha2-256"),
		cmds.IntOption("mhlen", "multihash hash length").Default(-1),
122
	},
123
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
124
		n, err := req.InvocContext().GetNode()
125
		if err != nil {
126 127
			res.SetError(err, cmds.ErrNormal)
			return
128
		}
129

130 131
		file, err := req.Files().NextFile()
		if err != nil {
132 133
			res.SetError(err, cmds.ErrNormal)
			return
134 135 136 137
		}

		data, err := ioutil.ReadAll(file)
		if err != nil {
138 139
			res.SetError(err, cmds.ErrNormal)
			return
140 141
		}

142
		err = file.Close()
143
		if err != nil {
144 145
			res.SetError(err, cmds.ErrNormal)
			return
146 147
		}

148 149
		var pref cid.Prefix
		pref.Version = 1
150 151

		format, _, _ := req.Option("format").String()
152 153
		formatval, ok := cid.Codecs[format]
		if !ok {
154 155 156
			res.SetError(fmt.Errorf("unrecognized format: %s", format), cmds.ErrNormal)
			return
		}
157 158 159 160
		if format == "v0" {
			pref.Version = 0
		}
		pref.Codec = formatval
161

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
		mhtype, _, _ := req.Option("mhtype").String()
		mhtval, ok := mh.Names[mhtype]
		if !ok {
			res.SetError(fmt.Errorf("unrecognized multihash function: %s", mhtype), cmds.ErrNormal)
			return
		}
		pref.MhType = mhtval

		mhlen, _, err := req.Option("mhlen").Int()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		pref.MhLength = mhlen

177 178 179 180 181 182 183 184 185 186 187
		bcid, err := pref.Sum(data)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		b, err := blocks.NewBlockWithCid(data, bcid)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
188
		log.Debugf("BlockPut key: '%q'", b.Cid())
189

190
		k, err := n.Blocks.AddBlock(b)
191
		if err != nil {
192 193
			res.SetError(err, cmds.ErrNormal)
			return
194 195
		}

196
		res.SetOutput(&BlockStat{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197 198
			Key:  k.String(),
			Size: len(data),
199
		})
200
	},
201
	Marshalers: cmds.MarshalerMap{
202
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203 204
			bs := res.Output().(*BlockStat)
			return strings.NewReader(bs.Key + "\n"), nil
205 206
		},
	},
Matt Bell's avatar
Matt Bell committed
207
	Type: BlockStat{},
208
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209

210
func getBlockForKey(req cmds.Request, skey string) (blocks.Block, error) {
211 212 213 214
	if len(skey) == 0 {
		return nil, fmt.Errorf("zero length cid invalid")
	}

Jeromy's avatar
Jeromy committed
215
	n, err := req.InvocContext().GetNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
216 217 218 219
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
220
	c, err := cid.Decode(skey)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221 222 223 224
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
225
	b, err := n.Blocks.GetBlock(req.Context(), c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
226 227 228
	if err != nil {
		return nil, err
	}
229

230
	log.Debugf("ipfs block: got block with key: %s", b.Cid())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231 232
	return b, nil
}
Kevin Atkinson's avatar
Kevin Atkinson committed
233 234 235 236 237 238 239 240 241 242 243 244

var blockRmCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		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.
`,
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("hash", true, true, "Bash58 encoded multihash of block(s) to remove."),
	},
245 246 247 248
	Options: []cmds.Option{
		cmds.BoolOption("force", "f", "Ignore nonexistent blocks.").Default(false),
		cmds.BoolOption("quiet", "q", "Write minimal output.").Default(false),
	},
Kevin Atkinson's avatar
Kevin Atkinson committed
249 250 251 252 253 254 255
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		hashes := req.Arguments()
256 257
		force, _, _ := req.Option("force").Bool()
		quiet, _, _ := req.Option("quiet").Bool()
Jeromy's avatar
Jeromy committed
258
		cids := make([]*cid.Cid, 0, len(hashes))
Kevin Atkinson's avatar
Kevin Atkinson committed
259
		for _, hash := range hashes {
Jeromy's avatar
Jeromy committed
260 261 262 263 264 265 266
			c, err := cid.Decode(hash)
			if err != nil {
				res.SetError(fmt.Errorf("invalid content id: %s (%s)", hash, err), cmds.ErrNormal)
				return
			}

			cids = append(cids, c)
Kevin Atkinson's avatar
Kevin Atkinson committed
267
		}
268
		ch, err := util.RmBlocks(n.Blockstore, n.Pinning, cids, util.RmBlocksOpts{
269 270 271 272 273 274 275
			Quiet: quiet,
			Force: force,
		})
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
276
		res.SetOutput(ch)
Kevin Atkinson's avatar
Kevin Atkinson committed
277
	},
278 279 280 281 282 283
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			outChan, ok := res.Output().(<-chan interface{})
			if !ok {
				return nil, u.ErrCast()
			}
284

285
			err := util.ProcRmOutput(outChan, res.Stdout(), res.Stderr())
286
			return nil, err
287
		},
Kevin Atkinson's avatar
Kevin Atkinson committed
288
	},
289
	Type: util.RemovedBlock{},
Kevin Atkinson's avatar
Kevin Atkinson committed
290
}