blocks.go 1.05 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package blocks

import (
Jeromy's avatar
Jeromy committed
4
	"errors"
Jeromy's avatar
Jeromy committed
5 6
	"fmt"

7
	mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9 10
)

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

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

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

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