-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.go
52 lines (45 loc) · 1.03 KB
/
block.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package blockchain
import (
"bytes"
"crypto/sha256"
"errors"
"time"
"github.com/cbergoon/merkletree"
)
// Block represents a
// bitcoin blockchain block
type Block struct {
Header
Transactions []Transaction
}
// Header represents a block's header
type Header struct {
Timestamp time.Time
Target int
Nonce int
HashPrevBlock string
// MerkleRoot is the hash of the block's
// transactions merkle tree root
MerkleRoot string
}
// MerkleRoot creates a merkle root from
// transactions
func MerkleRoot(txs []Transaction) ([]byte, error) {
t, err := merkletree.NewTree(merkleTree.Content(txs))
if err != nil {
return nil, err
}
return t.MerkleRoot(), nil
}
// Validate validates the block is valid
func (b Block) Validate() error {
if b.Header.MerkleRoot+b.Header.Nonce >= target {
return errors.New("invalid nonce: %v")
}
}
// Hash returns the hashed header
func (h Header) Hash() []byte {
sha256.New().Sum(bytes.Join([][]byte{
h.Timestamp, h.Target, h.Nonce, h.HashPrevBlock, h.MerkleRoot,
}, []byte{}))
}