blocks.go 1.31 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
	mh "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
10
	key "github.com/ipfs/go-ipfs/blocks/key"
11
	u "github.com/ipfs/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13
)

Jeromy's avatar
Jeromy committed
14
// Block is a singular block of data in ipfs
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15 16 17 18 19
type Block struct {
	Multihash mh.Multihash
	Data      []byte
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
20
// NewBlock creates a Block object from opaque data. It will hash the data.
21 22
func NewBlock(data []byte) *Block {
	return &Block{Data: data, Multihash: u.Hash(data)}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23 24
}

Jeromy's avatar
Jeromy committed
25 26 27
// 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
Jeromy's avatar
Jeromy committed
28 29 30 31 32 33 34 35 36 37
func NewBlockWithHash(data []byte, h mh.Multihash) (*Block, error) {
	if u.Debug {
		chk := u.Hash(data)
		if string(chk) != string(h) {
			return nil, errors.New("Data did not match given hash!")
		}
	}
	return &Block{Data: data, Multihash: h}, nil
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
38
// Key returns the block's Multihash as a Key value.
39 40
func (b *Block) Key() key.Key {
	return key.Key(b.Multihash)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
}
Jeromy's avatar
Jeromy committed
42 43 44 45

func (b *Block) String() string {
	return fmt.Sprintf("[Block %s]", b.Key())
}
46 47 48 49 50 51

func (b *Block) Loggable() map[string]interface{} {
	return map[string]interface{}{
		"block": b.Key().String(),
	}
}