/
block.go
68 lines (53 loc) · 1.17 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"log"
"time"
)
type Block struct {
Nonce int
Timestamp int64
Transactions []*Txn
PrevHash []byte
CurrHash []byte
}
func NewBlock(transactions []*Txn, prevHash []byte) *Block {
block := &Block{0, time.Now().Unix(), transactions, prevHash, []byte{}}
pow := NewProof(block)
nonce, hash := pow.CheckPOW()
block.Nonce = nonce
block.CurrHash = hash[:]
return block
}
func NewGenesisBlock(coinbase *Txn) *Block {
return NewBlock([]*Txn{coinbase}, []byte{})
}
func (block *Block) HashTransactions() []byte {
var txHashes [][]byte
var txHash [32]byte
for _, tx := range block.Transactions {
txHashes = append(txHashes, tx.ID)
}
txHash = sha256.Sum256(bytes.Join(txHashes, []byte{}))
return txHash[:]
}
func (block *Block) BlockToBytes() []byte {
var bytes bytes.Buffer
encoder := gob.NewEncoder(&bytes)
err := encoder.Encode(block)
if err != nil {
log.Panic(err)
}
return bytes.Bytes()
}
func BytesToBlock(seq []byte) *Block {
var block Block
decoder := gob.NewDecoder(bytes.NewReader(seq))
err := decoder.Decode(&block)
if err != nil {
log.Panic(err)
}
return &block
}