-
Notifications
You must be signed in to change notification settings - Fork 5
/
blockchain.go
254 lines (210 loc) · 5.38 KB
/
blockchain.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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package main
import (
"bytes"
"errors"
"github.com/boltdb/bolt" // Run "go get github.com/boltdb/bolt/..."
"log"
)
type Blockchain struct {
tipHash []byte // Tip of chain
db *bolt.DB // DB connection
height uint64
bucketName string
blockhashes [][]byte
}
// To iterate over blocks
type BlockchainIterator struct {
currentHash []byte // Hash of current block
db *bolt.DB // DB connection
bucketName string
}
type BlockchainForwardIterator struct {
hashes [][]byte // Hash of current block
currentIndex int
db *bolt.DB // DB connection
bucketName string
}
func NewBlockchain(db *bolt.DB, symbol string) *Blockchain {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(symbol)) // Get bucket storing blocks
if b == nil {
// Create bucket
_, err := tx.CreateBucket([]byte(symbol))
if err != nil {
log.Panic(err)
}
}
return nil
})
if err != nil {
log.Panic(err)
}
blockchain := Blockchain{[]byte{}, db, 0, symbol, [][]byte{}}
blockchain.tipHash = blockchain.getTipHash()
blockchain.blockhashes = blockchain.getBlockhashes()
return &blockchain
}
func (bc *Blockchain) AddBlock(block Block) {
// Read-write transaction to store new block in DB
bc.db.Update(func(tx *bolt.Tx) error {
// Store block in bucket
b := tx.Bucket([]byte(bc.bucketName))
err := b.Put(block.Hash, block.Serialize())
if err != nil {
log.Panic(err)
}
// Update "l" key
err = b.Put([]byte("l"), block.Hash)
if err != nil {
log.Panic(err)
}
// Update tip
temp := make([]byte, len(block.Hash))
copy(temp, block.Hash)
bc.tipHash = temp
return nil
})
bc.height += 1
bc.blockhashes = append([][]byte{block.Hash}, bc.blockhashes...)
}
func (bc *Blockchain) RemoveLastBlock() BlockData {
var lastBlock *Block
bc.db.Update(func(tx *bolt.Tx) error {
// Get bucket
b := tx.Bucket([]byte(bc.bucketName))
// Get second to last block
bci := bc.Iterator()
lastBlock, _ = bci.Prev()
// Delete last bock
b.Delete(bc.getTipHash())
// Update "l" key to second to last block
err := b.Put([]byte("l"), lastBlock.PrevBlockHash)
if err != nil {
log.Panic(err)
}
// Update tip to second to last block
temp := make([]byte, len(lastBlock.PrevBlockHash))
copy(temp, lastBlock.PrevBlockHash)
bc.tipHash = temp
return nil
})
bc.height -= 1
bc.blockhashes = bc.blockhashes[1:]
return lastBlock.Data
}
func (bc *Blockchain) DeleteStorage() {
bc.db.Update(func(tx *bolt.Tx) error {
// Get bucket
tx.DeleteBucket([]byte(bc.bucketName))
return nil
})
}
//
// Create iterator for a blockchain
//
func (bc *Blockchain) Iterator() *BlockchainIterator {
bci := &BlockchainIterator{bc.tipHash, bc.db, bc.bucketName}
return bci
}
func (bc *Blockchain) ForwardIterator() *BlockchainForwardIterator {
hashes := bc.blockhashes
return &BlockchainForwardIterator{hashes, len(hashes) - 1, bc.db, bc.bucketName}
}
//
// Next returns next block starting from the tip
//
func (bci *BlockchainIterator) Prev() (*Block, error) {
var block *Block
// Read only transaction to get next block
err := bci.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bci.bucketName))
encodedBlock := b.Get(bci.currentHash)
if encodedBlock == nil {
return errors.New("out of blocks")
}
block = DeserializeBlock(encodedBlock)
return nil
})
if err == nil {
// Blocks are obtained newest to oldest
bci.currentHash = block.PrevBlockHash
}
return block, err
}
func (bci *BlockchainForwardIterator) Next() (*Block, error) {
var block *Block
if bci.currentIndex < 0 {
return nil, errors.New("out of blocks")
}
// Read only transaction to get next block
err := bci.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bci.bucketName))
encodedBlock := b.Get(bci.hashes[bci.currentIndex])
if encodedBlock == nil {
return errors.New("out of blocks")
}
block = DeserializeBlock(encodedBlock)
return nil
})
if err == nil {
// Blocks are obtained newest to oldest
bci.currentIndex--
}
return block, err
}
func (bci *BlockchainForwardIterator) Undo() {
bci.currentIndex++
}
func (bc *Blockchain) getBlockhashes() [][]byte {
blockhashes := make([][]byte, 0)
bci := bc.Iterator()
block, err := bci.Prev()
for err == nil {
blockhashes = append(blockhashes, block.Hash)
block, err = bci.Prev()
}
return blockhashes
}
func (bc *Blockchain) GetBlock(blockhash []byte) (*Block, error) {
bci := bc.Iterator()
block, err := bci.Prev()
for err == nil {
if bytes.Equal(block.Hash, blockhash) {
return block, nil
}
block, err = bci.Prev()
}
return nil, errors.New("block not found")
}
func (bc *Blockchain) getTipHash() []byte {
var lastHash []byte // Hash of last block
// Read-only transaction to get hash of last block
err := bc.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bc.bucketName))
temp := b.Get([]byte("l"))
if temp == nil {
return errors.New("No hash stored")
}
buf := make([]byte, len(temp))
copy(buf, temp)
lastHash = buf
return nil
})
if err != nil || lastHash == nil {
return []byte{}
} else {
return lastHash
}
}
func (bc *Blockchain) DumpChain(amtRequested uint64) (string, uint64) {
var buffer bytes.Buffer
var i uint64
bci := bc.Iterator()
block, err := bci.Prev()
for i = 0; i < amtRequested && err == nil; i++ {
buffer.WriteString(block.Dump())
buffer.WriteString("\n")
block, err = bci.Prev()
}
return buffer.String(), i
}