forked from dreamerjackson/BuildingBlockChain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain_findAndgetData.go
94 lines (69 loc) · 1.65 KB
/
blockchain_findAndgetData.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
package main
import (
"bytes"
"errors"
"github.com/boltdb/bolt"
"log"
)
//查询区块链当中确实存在此笔交易
// FindTransaction finds a transaction by its ID
func (bc *Blockchain) FindTransaction(ID []byte) (Transaction, error) {
bci := bc.Iterator()
for {
block := bci.Next()
for _, tx := range block.Transactions {
if bytes.Compare(tx.ID, ID) == 0 {
return *tx, nil
}
}
if len(block.PrevBlockHash) == 0 {
break
}
}
return Transaction{}, errors.New("Transaction is not found")
}
// GetBestHeight returns the height of the latest block
func (bc *Blockchain) GetBestHeight() int {
var lastBlock Block
err := bc.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(blocksBucket))
lastHash := b.Get([]byte("l"))
blockData := b.Get(lastHash)
lastBlock = *DeserializeBlock(blockData)
return nil
})
if err != nil {
log.Panic(err)
}
return lastBlock.Height
}
// GetBlock finds a block by its hash and returns it
func (bc *Blockchain) GetBlock(blockHash []byte) (Block, error) {
var block Block
err := bc.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(blocksBucket))
blockData := b.Get(blockHash)
if blockData == nil {
return errors.New("Block is not found.")
}
block = *DeserializeBlock(blockData)
return nil
})
if err != nil {
return block, err
}
return block, nil
}
// GetBlockHashes returns a list of hashes of all the blocks in the chain
func (bc *Blockchain) GetBlockHashes() [][]byte {
var blocks [][]byte
bci := bc.Iterator()
for {
block := bci.Next()
blocks = append(blocks, block.Hash)
if len(block.PrevBlockHash) == 0 {
break
}
}
return blocks
}