-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlock.go
More file actions
95 lines (78 loc) · 1.82 KB
/
Copy pathBlock.go
File metadata and controls
95 lines (78 loc) · 1.82 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"time"
"bytes"
"encoding/gob"
"log"
"crypto/sha256"
)
/*
Base type for the BlockChain contains initial information for the block
(version, date or timestamp, hash of current and previous blocks.
Note: By bitcoin spec extract Timestamp, PrevBlockHash, Hash into separate struct.
For simplification we keep it as part of the current struct.
*/
type Block struct {
Timestamp int64 // date of creation
Transactions []*Transaction // transactions
PrevBlockHash []byte // previous block hash
Hash []byte // current block hash
Nonce int // counter
}
/*
Constructor of Blocks
*/
func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block {
block := &Block{
time.Now().Unix(),
transactions,
prevBlockHash,
[]byte{},
0 }
pow := NewProofOfWork(block)
nonce, hash := pow.Run()
block.Hash = hash[:]
block.Nonce = nonce
return block
}
/*
Add Genesis-block (first block) into BlockChain
*/
func NewGenesisBlock(coinbase *Transaction) *Block {
return NewBlock([]*Transaction{coinbase}, []byte{})
}
/*
*/
func (b* Block) HashTransactions() []byte {
var txHashes [][]byte
var txHash [32]byte
for _, tx := range b.Transactions {
txHashes = append(txHashes, tx.ID)
}
txHash = sha256.Sum256(bytes.Join(txHashes, []byte{}))
return txHash[:]
}
/*
Serialization Block to byte array
*/
func (b *Block) Serialize() []byte {
var result bytes.Buffer
encoder := gob.NewEncoder(&result)
err := encoder.Encode(b)
if err != nil {
log.Printf("Error serializing block: %s", err)
}
return result.Bytes()
}
/*
Deserialization byte array to block
*/
func Deserialize(d []byte) *Block {
var block Block
decoder := gob.NewDecoder(bytes.NewReader(d))
err := decoder.Decode(&block)
if err != nil {
log.Printf("Error serializing block: %s", err)
}
return &block
}