-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.go
117 lines (86 loc) · 2.29 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
package block_chain
import (
"github.com/boltdb/bolt"
"os"
"fmt"
)
const dbfile = "blockChainDb.db"
const blockBuckit = "blockBuckit"
const LASTHASH = "LASTHASH"
type BlockChain struct {
//Blocks [] *Block
db *bolt.DB
lastHash []byte
}
func NewBlockChain() *BlockChain {
//return &BlockChain{ []*Block{NewGenesisBlock()},
//}
db, err := bolt.Open(dbfile, 0600, nil)
CheckErr("newblockchain", err)
lastHash:=[]byte{}
db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(blockBuckit))
if bucket != nil {
//读取hash即可
lastHash = bucket.Get([]byte(LASTHASH))
} else {
//创建bucket
//与数据
genesis := NewGenesisBlock()
bucket, err := tx.CreateBucket([]byte(blockBuckit))
CheckErr("newblockchain", err)
err = bucket.Put(genesis.Hash, genesis.Serialize()) //todo
CheckErr("newblockchain", err)
err = bucket.Put([]byte(LASTHASH), genesis.Hash)
CheckErr("newblockchain", err)
}
return nil
})
return &BlockChain{db, lastHash}
}
func (bc *BlockChain) AddBlock(data string) {
var prevBlockHash []byte
err := bc.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(blockBuckit))
lastHash := bucket.Get([]byte(LASTHASH))
prevBlockHash = lastHash
return nil
})
CheckErr("", err)
block := NewBlock(data, prevBlockHash)
err = bc.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(blockBuckit))
err := bucket.Put(block.Hash, block.Serialize())
CheckErr("", err)
err = bucket.Put([]byte(LASTHASH), block.Hash)
CheckErr("AddBlock3", err)
bc.lastHash = block.Hash
fmt.Printf("after create block bc last hash is %x\n",bc.lastHash)
return nil
})
CheckErr("", err)
}
type BlockChainIterator struct {
db *bolt.DB
currentHash []byte
}
func (bc *BlockChain) Iterator() *BlockChainIterator {
return &BlockChainIterator{bc.db, bc.lastHash}
}
func (it *BlockChainIterator) Next() *Block {
var block *Block
//fmt.Printf("iter current hash:%x\n",it.currentHash)
err := it.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(blockBuckit))
if bucket == nil {
fmt.Println("get bucket failed")
os.Exit(1)
}
blockTmp := bucket.Get(it.currentHash)
block = Deserialize(blockTmp)
it.currentHash = block.PrevBlockHash
return nil
})
CheckErr("Next", err)
return block
}