OSDN Git Service

61b11646f2b8af2ae91c3b5bde0d1e0da67275d3
[bytom/vapor.git] / protocol / state / blockindex.go
1 package state
2
3 import (
4         "errors"
5         "sort"
6         "sync"
7
8         "github.com/vapor/common"
9         "github.com/vapor/consensus"
10         "github.com/vapor/protocol/bc"
11         "github.com/vapor/protocol/bc/types"
12 )
13
14 // approxNodesPerDay is an approximation of the number of new blocks there are
15 // in a day on average.
16 const approxNodesPerDay = 24 * 24
17
18 // BlockNode represents a block within the block chain and is primarily used to
19 // aid in selecting the best chain to be the main chain.
20 type BlockNode struct {
21         Parent *BlockNode // parent is the parent block for this node.
22         Hash   bc.Hash    // hash of the block.
23
24         Version                uint64
25         Height                 uint64
26         Timestamp              uint64
27         BlockWitness           *common.BitMap
28         TransactionsMerkleRoot bc.Hash
29         TransactionStatusHash  bc.Hash
30 }
31
32 func NewBlockNode(bh *types.BlockHeader, parent *BlockNode) (*BlockNode, error) {
33         if bh.Height != 0 && parent == nil {
34                 return nil, errors.New("parent node can not be nil")
35         }
36
37         node := &BlockNode{
38                 Parent:                 parent,
39                 Hash:                   bh.Hash(),
40                 Version:                bh.Version,
41                 Height:                 bh.Height,
42                 Timestamp:              bh.Timestamp,
43                 TransactionsMerkleRoot: bh.TransactionsMerkleRoot,
44                 TransactionStatusHash:  bh.TransactionStatusHash,
45         }
46
47         node.BlockWitness = common.NewBitMap(uint32(len(bh.Witness)))
48         for i, witness := range bh.Witness {
49                 if len(witness) != 0 {
50                         node.BlockWitness.Set(uint32(i))
51                 }
52         }
53         return node, nil
54 }
55
56 // blockHeader convert a node to the header struct
57 func (node *BlockNode) BlockHeader() *types.BlockHeader {
58         previousBlockHash := bc.Hash{}
59         if node.Parent != nil {
60                 previousBlockHash = node.Parent.Hash
61         }
62         return &types.BlockHeader{
63                 Version:           node.Version,
64                 Height:            node.Height,
65                 PreviousBlockHash: previousBlockHash,
66                 Timestamp:         node.Timestamp,
67                 BlockCommitment: types.BlockCommitment{
68                         TransactionsMerkleRoot: node.TransactionsMerkleRoot,
69                         TransactionStatusHash:  node.TransactionStatusHash,
70                 },
71         }
72 }
73
74 func (node *BlockNode) CalcPastMedianTime() uint64 {
75         timestamps := []uint64{}
76         iterNode := node
77         for i := 0; i < consensus.MedianTimeBlocks && iterNode != nil; i++ {
78                 timestamps = append(timestamps, iterNode.Timestamp)
79                 iterNode = iterNode.Parent
80         }
81
82         sort.Sort(common.TimeSorter(timestamps))
83         return timestamps[len(timestamps)/2]
84 }
85
86 // BlockIndex is the struct for help chain trace block chain as tree
87 type BlockIndex struct {
88         sync.RWMutex
89
90         index       map[bc.Hash]*BlockNode
91         heightIndex map[uint64][]*BlockNode
92         mainChain   []*BlockNode
93 }
94
95 // NewBlockIndex will create a empty BlockIndex
96 func NewBlockIndex() *BlockIndex {
97         return &BlockIndex{
98                 index:     make(map[bc.Hash]*BlockNode),
99                 heightIndex: make(map[uint64][]*BlockNode),
100                 mainChain: make([]*BlockNode, 0, approxNodesPerDay),
101         }
102 }
103
104 // AddNode will add node to the index map
105 func (bi *BlockIndex) AddNode(node *BlockNode) {
106         bi.Lock()
107         bi.index[node.Hash] = node
108         bi.heightIndex[node.Height] = append(bi.heightIndex[node.Height], node)
109         bi.Unlock()
110 }
111
112 // GetNode will search node from the index map
113 func (bi *BlockIndex) GetNode(hash *bc.Hash) *BlockNode {
114         bi.RLock()
115         defer bi.RUnlock()
116         return bi.index[*hash]
117 }
118
119 func (bi *BlockIndex) BestNode() *BlockNode {
120         bi.RLock()
121         defer bi.RUnlock()
122         return bi.mainChain[len(bi.mainChain)-1]
123 }
124
125 // BlockExist check does the block existed in blockIndex
126 func (bi *BlockIndex) BlockExist(hash *bc.Hash) bool {
127         bi.RLock()
128         _, ok := bi.index[*hash]
129         bi.RUnlock()
130         return ok
131 }
132
133 // TODO: THIS FUNCTION MIGHT BE DELETED
134 func (bi *BlockIndex) InMainchain(hash bc.Hash) bool {
135         bi.RLock()
136         defer bi.RUnlock()
137
138         node, ok := bi.index[hash]
139         if !ok {
140                 return false
141         }
142         return bi.nodeByHeight(node.Height) == node
143 }
144
145 func (bi *BlockIndex) nodeByHeight(height uint64) *BlockNode {
146         if height >= uint64(len(bi.mainChain)) {
147                 return nil
148         }
149         return bi.mainChain[height]
150 }
151
152 // NodeByHeight returns the block node at the specified height.
153 func (bi *BlockIndex) NodeByHeight(height uint64) *BlockNode {
154         bi.RLock()
155         defer bi.RUnlock()
156         return bi.nodeByHeight(height)
157 }
158
159 // NodesByHeight return all block nodes at the specified height.
160 func (bi *BlockIndex) NodesByHeight(height uint64) []*BlockNode {
161         bi.RLock()
162         defer bi.RUnlock()
163         return bi.heightIndex[height]
164 }
165
166 // SetMainChain will set the the mainChain array
167 func (bi *BlockIndex) SetMainChain(node *BlockNode) {
168         bi.Lock()
169         defer bi.Unlock()
170
171         needed := node.Height + 1
172         if uint64(cap(bi.mainChain)) < needed {
173                 nodes := make([]*BlockNode, needed, needed+approxNodesPerDay)
174                 copy(nodes, bi.mainChain)
175                 bi.mainChain = nodes
176         } else {
177                 i := uint64(len(bi.mainChain))
178                 bi.mainChain = bi.mainChain[0:needed]
179                 for ; i < needed; i++ {
180                         bi.mainChain[i] = nil
181                 }
182         }
183
184         for node != nil && bi.mainChain[node.Height] != node {
185                 bi.mainChain[node.Height] = node
186                 node = node.Parent
187         }
188 }