-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.go
More file actions
210 lines (193 loc) · 4.49 KB
/
Copy pathblock.go
File metadata and controls
210 lines (193 loc) · 4.49 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package main
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
)
type Currency uint
type BlockHash [32]byte
const HASH_ZERO_PREFIX_LENGTH = 4
func TestHash(hash BlockHash) bool {
hashHex := fmt.Sprintf("%x", hash)
for i := 0; i < HASH_ZERO_PREFIX_LENGTH; i += 1 {
if hashHex[i] != '0' {
return false
}
}
return true
}
func HexToBlockHash(hexHash string) (*BlockHash, error) {
rawHash, err := hex.DecodeString(hexHash)
if err != nil {
return nil, err
}
var rawHashCopy BlockHash
for index, byt := range rawHash {
rawHashCopy[index] = byt
}
return &rawHashCopy, nil
}
type Block struct {
CreatedAt time.Time `json:"created_at"`
Previous *LazyBlock `json:"previous_block"`
Data []*Transaction `json:"data"`
Number uint `json:"number"`
Hash *BlockHash `json:"hash"`
}
func NewBlock(previous *LazyBlock, data []*Transaction) *Block {
return &Block{
CreatedAt: time.Now().UTC(),
Previous: previous,
Data: data,
Number: 0,
Hash: nil,
}
}
func NewBlockFromBytes(chain *Blockchain, bytes []byte) (*Block, error) {
sections := strings.Split(string(bytes), ".")
if len(sections) != 2 {
return nil, errors.New("Malformed hash wrapper on block!")
}
payloadBytes, err0 := base64.StdEncoding.DecodeString(sections[0])
if err0 != nil {
return nil, err0
}
payload := []byte(payloadBytes)
hash, err1 := HexToBlockHash(sections[1])
if err1 != nil {
return nil, err1
}
type BlockRawData struct {
CreatedAt time.Time `json:"created_at"`
PreviousHashHex string `json:"previous_hash"`
TransactionsRaw [][]byte `json:"transactions"`
Number uint `json:"number"`
}
var blockRawData BlockRawData
err2 := json.Unmarshal(payload, &blockRawData)
if err2 != nil {
return nil, err2
}
previousHash, err3 := HexToBlockHash(blockRawData.PreviousHashHex)
if err3 != nil {
return nil, err3
}
var transactions []*Transaction
for _, byt := range blockRawData.TransactionsRaw {
transaction, err := NewTransactionFromBytes(byt)
if err != nil {
return nil, err
}
transactions = append(transactions, transaction)
}
block := Block{
CreatedAt: blockRawData.CreatedAt,
Number: blockRawData.Number,
Previous: NewLazyBlockFromHash(chain, previousHash),
Data: transactions,
Hash: hash,
}
return &block, nil
}
func (b *Block) Serialize() ([]byte, error) {
if b.Hash == nil {
return nil, errors.New("Cannot serialize an unmined block!")
}
payload, err := b.SerializePayload()
if err != nil {
return nil, err
}
return []byte(fmt.Sprintf("%s.%x", payload, *b.Hash)), nil
}
func (b *Block) SerializePayload() ([]byte, error) {
var serializedTransactions []string = []string{}
for _, t := range b.Data {
serializedBytes, err := t.Serialize()
if err != nil {
return nil, err
}
serializedTransactions = append(serializedTransactions, string(serializedBytes))
}
previousHash := ""
if b.Previous != nil {
unwrapped := b.Previous.Unwrap()
if unwrapped != nil {
previousHash = fmt.Sprintf("%x", *unwrapped.Hash)
}
}
result, err := json.Marshal(map[string]interface{}{
"created_at": b.CreatedAt,
"previous_hash": previousHash,
"transactions": serializedTransactions,
"number": b.Number,
})
if err != nil {
return nil, err
}
return []byte(base64.StdEncoding.EncodeToString(result)), nil
}
func (b *Block) VerifyData() (bool, error) {
for _, t := range b.Data {
verified, err := t.Verify()
if err != nil {
return false, err
}
if !verified {
return false, nil
}
}
return true, nil
}
func (b *Block) VerifyHash() (*BlockHash, error) {
serialized, err := b.SerializePayload()
if err != nil {
return nil, err
}
hash := sha256.Sum256(serialized)
if TestHash(hash) {
a := BlockHash(hash)
return &a, nil
} else {
return nil, nil
}
}
func (b *Block) Verify() (bool, error) {
// Make sure transactions signatures are valid
ok, err := b.VerifyData()
if err != nil {
return false, err
}
if !ok {
return false, nil
}
// Make sure block hash is valid
hash, err2 := b.VerifyHash()
if err2 != nil {
return false, err2
}
if hash == nil {
return false, nil
}
return true, nil
}
func (b *Block) InvalidateHash() {
b.Hash = nil
}
func (b *Block) Mine() error {
for n := uint(0); n < MaxUint; n += 1 {
if n%1000 == 0 {
fmt.Printf("Mine Status: %d\n", n)
}
b.Number = n
if hash, err := b.VerifyHash(); err == nil && hash != nil {
b.Hash = hash
break
}
}
return nil
}