blocks.go 1.67 KB
Newer Older
1 2
// package blocks contains the lowest level of ipfs data structures,
// 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
	key "github.com/ipfs/go-ipfs/blocks/key"
10 11
	mh "gx/ipfs/QmYf7ng2hG5XBtJA3tN34DQ2GUN5HNksEw1rLDkmr6vGku/go-multihash"
	u "gx/ipfs/QmZNVWh8LLjAavuQ2JXuFmuYH3C11xo988vSgp7UQrTRj1/go-ipfs-util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13
)

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

16 17 18 19 20 21 22 23
type Block interface {
	Multihash() mh.Multihash
	Data() []byte
	Key() key.Key
	String() string
	Loggable() map[string]interface{}
}

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

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
30
// NewBlock creates a Block object from opaque data. It will hash the data.
31 32
func NewBlock(data []byte) *BasicBlock {
	return &BasicBlock{data: data, multihash: 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 NewBlockWithHash(data []byte, h mh.Multihash) (*BasicBlock, error) {
Jeromy's avatar
Jeromy committed
39 40 41
	if u.Debug {
		chk := u.Hash(data)
		if string(chk) != string(h) {
42
			return nil, ErrWrongHash
Jeromy's avatar
Jeromy committed
43 44
		}
	}
45
	return &BasicBlock{data: data, multihash: h}, nil
46 47
}

48
func (b *BasicBlock) Multihash() mh.Multihash {
49 50 51
	return b.multihash
}

52
func (b *BasicBlock) Data() []byte {
53
	return b.data
Jeromy's avatar
Jeromy committed
54 55
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
56
// Key returns the block's Multihash as a Key value.
57
func (b *BasicBlock) Key() key.Key {
58
	return key.Key(b.multihash)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59
}
Jeromy's avatar
Jeromy committed
60

61
func (b *BasicBlock) String() string {
Jeromy's avatar
Jeromy committed
62 63
	return fmt.Sprintf("[Block %s]", b.Key())
}
64

65
func (b *BasicBlock) Loggable() map[string]interface{} {
66 67 68 69
	return map[string]interface{}{
		"block": b.Key().String(),
	}
}