-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.go
57 lines (51 loc) · 962 Bytes
/
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
53
54
55
56
57
package main
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
)
type Block struct {
PrevHash, Hash [32]byte
Data string
Nonce uint64
}
func NewBlock(prevHash [32]byte, data string) *Block {
b := &Block{
PrevHash: prevHash,
Data: data,
}
b.Hash = b.getHash()
return b
}
func (b *Block) getHash() [32]byte {
nonce := make([]byte, 8)
binary.LittleEndian.PutUint64(nonce, b.Nonce)
info := bytes.Join(
[][]byte{
b.PrevHash[:],
[]byte(b.Data),
nonce,
},
[]byte{},
)
return sha256.Sum256(info)
}
func (b *Block) Serialize() ([]byte, error) {
var res bytes.Buffer
encoder := gob.NewEncoder(&res)
err := encoder.Encode(*b)
if err != nil {
return nil, err
}
return res.Bytes(), nil
}
func DeserializeBlock(data []byte) (*Block, error) {
var b Block
decoder := gob.NewDecoder(bytes.NewReader(data))
err := decoder.Decode(&b)
if err != nil {
return nil, err
}
return &b, nil
}