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

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

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

Jeromy's avatar
Jeromy committed
24 25 26
// 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
27 28 29 30 31 32 33 34 35 36
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
37
// Key returns the block's Multihash as a Key value.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38 39 40
func (b *Block) Key() u.Key {
	return u.Key(b.Multihash)
}
Jeromy's avatar
Jeromy committed
41 42 43 44

func (b *Block) String() string {
	return fmt.Sprintf("[Block %s]", b.Key())
}