blocks.go 1.66 KB
Newer Older
1
// package blocks contains the lowest level of IPFS data structures,
2
// the raw block with a checksum.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
3 4 5
package blocks

import (
Jeromy's avatar
Jeromy committed
6
	"errors"
Jeromy's avatar
Jeromy committed
7 8
	"fmt"

9 10
	mh "gx/ipfs/QmYDds3421prZgqKbLpEK7T9Aa2eVdQ7o3YarX1LVLdP2J/go-multihash"
	u "gx/ipfs/Qmb912gdngC1UWwTkhuW8knyRbcWeu5kqkxBpveLmW8bSr/go-ipfs-util"
11
	cid "gx/ipfs/QmcEcrBAMrwMyhSjXt4yfyPpzgSuV8HLHavnfmiKCSRqZU/go-cid"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13
)

14
var ErrWrongHash = errors.New("data did not match given hash!")
15

16
type Block interface {
Jeromy's avatar
Jeromy committed
17
	RawData() []byte
18
	Cid() *cid.Cid
19 20 21 22
	String() string
	Loggable() map[string]interface{}
}

Jeromy's avatar
Jeromy committed
23
// Block is a singular block of data in ipfs
24
type BasicBlock struct {
25 26
	cid  *cid.Cid
	data []byte
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27 28
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
29
// NewBlock creates a Block object from opaque data. It will hash the data.
30
func NewBlock(data []byte) *BasicBlock {
31 32
	// TODO: fix assumptions
	return &BasicBlock{data: data, cid: cid.NewCidV0(u.Hash(data))}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33 34
}

Jeromy's avatar
Jeromy committed
35 36 37
// NewBlockWithHash creates a new block when the hash of the data
// is already known, this is used to save time in situations where
// we are able to be confident that the data is correct
38
func NewBlockWithCid(data []byte, c *cid.Cid) (*BasicBlock, error) {
Jeromy's avatar
Jeromy committed
39
	if u.Debug {
40 41 42 43 44
		chkc, err := c.Prefix().Sum(data)
		if err != nil {
			return nil, err
		}

45
		if !chkc.Equals(c) {
46
			return nil, ErrWrongHash
Jeromy's avatar
Jeromy committed
47 48
		}
	}
49
	return &BasicBlock{data: data, cid: c}, nil
50 51
}

52
func (b *BasicBlock) Multihash() mh.Multihash {
53
	return b.cid.Hash()
54 55
}

Jeromy's avatar
Jeromy committed
56
func (b *BasicBlock) RawData() []byte {
57
	return b.data
Jeromy's avatar
Jeromy committed
58 59
}

Jeromy's avatar
Jeromy committed
60
func (b *BasicBlock) Cid() *cid.Cid {
61
	return b.cid
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62
}
Jeromy's avatar
Jeromy committed
63

64
func (b *BasicBlock) String() string {
65
	return fmt.Sprintf("[Block %s]", b.Cid())
Jeromy's avatar
Jeromy committed
66
}
67

68
func (b *BasicBlock) Loggable() map[string]interface{} {
69
	return map[string]interface{}{
70
		"block": b.Cid().String(),
71 72
	}
}