go實現區塊鏈[3]-遍歷區塊鏈與數據庫持久化

新建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
package main

import (
"github.com/boltdb/bolt"
"log"
"fmt"
)

const dbFile = "blockchain.db"
const blockBucket = "blocks"
type Blockchain struct{
tip []byte //最近的一個區塊的hash值
db * bolt.DB
}


func (bc * Blockchain) AddBlock(){
var lasthash []byte

err := bc.db.View(func(tx * bolt.Tx) error{
b:= tx.Bucket([]byte(blockBucket))
lasthash = b.Get([]byte("l"))
return nil
})
if err!=nil{
log.Panic(err)
}
newBlock := NewBlock(lasthash)


bc.db.Update(func(tx *bolt.Tx) error {
b:=tx.Bucket([]byte(blockBucket))
err:= b.Put(newBlock.Hash,newBlock.Serialize())
if err!=nil{
log.Panic(err)
}
err = b.Put([]byte("l"),newBlock.Hash)

if err!=nil{
log.Panic(err)
}
bc.tip = newBlock.Hash
return nil
})
}


func NewBlockchain() * Blockchain{
var tip []byte
db,err := bolt.Open(dbFile,0600,nil)
if err!=nil{
log.Panic(err)
}

err = db.Update(func(tx * bolt.Tx) error{

b:= tx.Bucket([]byte(blockBucket))

if b==nil{

fmt.Println("區塊鏈不存在,創建一個新的區塊鏈")

genesis := NewGensisBlock()
b,err:=tx.CreateBucket([]byte(blockBucket))
if err!=nil{
log.Panic(err)
}

err = b.Put(genesis.Hash,genesis.Serialize())
if err!=nil{
log.Panic(err)
}
err =  b.Put([]byte("l"),genesis.Hash)
tip = genesis.Hash

}else{
tip  =  b.Get([]byte("l"))
}

return nil
})

if err!=nil{
log.Panic(err)
}

bc:=Blockchain{tip,db}
return &bc
}

增加newBlock的方法,根據前一個區塊的hash創建區塊:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func NewBlock(prevBlockHash []byte) * Block{

block := &Block{
2,
prevBlockHash,
[]byte{},
[]byte{},
int32(time.Now().Unix()),
404454260,
0,
[]*Transation{},
}

pow := NewProofofWork(block)

nonce,hash := pow.Run()

block.Hash = hash
block.Nonce = nonce

return block
}

image.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章