OSDN Git Service

e2e13548fa8e1244d82a3a6d8febd8360e5afbbd
[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                         if err := node.BlockWitness.Set(uint32(i)); err != nil {
51                                 return nil, err
52                         }
53                 }
54         }
55         return node, nil
56 }
57
58 // blockHeader convert a node to the header struct
59 func (node *BlockNode) BlockHeader() *types.BlockHeader {
60         previousBlockHash := bc.Hash{}
61         if node.Parent != nil {
62                 previousBlockHash = node.Parent.Hash
63         }
64         return &types.BlockHeader{
65                 Version:           node.Version,
66                 Height:            node.Height,
67                 PreviousBlockHash: previousBlockHash,
68                 Timestamp:         node.Timestamp,
69                 BlockCommitment: types.BlockCommitment{
70                         TransactionsMerkleRoot: node.TransactionsMerkleRoot,
71                         TransactionStatusHash:  node.TransactionStatusHash,
72                 },
73         }
74 }
75
76 func (node *BlockNode) CalcPastMedianTime() uint64 {
77         timestamps := []uint64{}
78         iterNode := node
79         for i := 0; i < consensus.MedianTimeBlocks && iterNode != nil; i++ {
80                 timestamps = append(timestamps, iterNode.Timestamp)
81                 iterNode = iterNode.Parent
82         }
83
84         sort.Sort(common.TimeSorter(timestamps))
85         return timestamps[len(timestamps)/2]
86 }
87
88 // BlockIndex is the struct for help chain trace block chain as tree
89 type BlockIndex struct {
90         sync.RWMutex
91
92         index       map[bc.Hash]*BlockNode
93         heightIndex map[uint64][]*BlockNode
94         mainChain   []*BlockNode
95 }
96
97 // NewBlockIndex will create a empty BlockIndex
98 func NewBlockIndex() *BlockIndex {
99         return &BlockIndex{
100                 index:       make(map[bc.Hash]*BlockNode),
101                 heightIndex: make(map[uint64][]*BlockNode),
102                 mainChain:   make([]*BlockNode, 0, approxNodesPerDay),
103         }
104 }
105
106 // AddNode will add node to the index map
107 func (bi *BlockIndex) AddNode(node *BlockNode) {
108         bi.Lock()
109         bi.index[node.Hash] = node
110         bi.heightIndex[node.Height] = append(bi.heightIndex[node.Height], node)
111         bi.Unlock()
112 }
113
114 // GetNode will search node from the index map
115 func (bi *BlockIndex) GetNode(hash *bc.Hash) *BlockNode {
116         bi.RLock()
117         defer bi.RUnlock()
118         return bi.index[*hash]
119 }
120
121 func (bi *BlockIndex) BestNode() *BlockNode {
122         bi.RLock()
123         defer bi.RUnlock()
124         return bi.mainChain[len(bi.mainChain)-1]
125 }
126
127 // BlockExist check does the block existed in blockIndex
128 func (bi *BlockIndex) BlockExist(hash *bc.Hash) bool {
129         bi.RLock()
130         _, ok := bi.index[*hash]
131         bi.RUnlock()
132         return ok
133 }
134
135 // TODO: THIS FUNCTION MIGHT BE DELETED
136 func (bi *BlockIndex) InMainchain(hash bc.Hash) bool {
137         bi.RLock()
138         defer bi.RUnlock()
139
140         node, ok := bi.index[hash]
141         if !ok {
142                 return false
143         }
144         return bi.nodeByHeight(node.Height) == node
145 }
146
147 func (bi *BlockIndex) nodeByHeight(height uint64) *BlockNode {
148         if height >= uint64(len(bi.mainChain)) {
149                 return nil
150         }
151         return bi.mainChain[height]
152 }
153
154 // NodeByHeight returns the block node at the specified height.
155 func (bi *BlockIndex) NodeByHeight(height uint64) *BlockNode {
156         bi.RLock()
157         defer bi.RUnlock()
158         return bi.nodeByHeight(height)
159 }
160
161 // NodesByHeight return all block nodes at the specified height.
162 func (bi *BlockIndex) NodesByHeight(height uint64) []*BlockNode {
163         bi.RLock()
164         defer bi.RUnlock()
165         return bi.heightIndex[height]
166 }
167
168 // SetMainChain will set the the mainChain array
169 func (bi *BlockIndex) SetMainChain(node *BlockNode) {
170         bi.Lock()
171         defer bi.Unlock()
172
173         needed := node.Height + 1
174         if uint64(cap(bi.mainChain)) < needed {
175                 nodes := make([]*BlockNode, needed, needed+approxNodesPerDay)
176                 copy(nodes, bi.mainChain)
177                 bi.mainChain = nodes
178         } else {
179                 i := uint64(len(bi.mainChain))
180                 bi.mainChain = bi.mainChain[0:needed]
181                 for ; i < needed; i++ {
182                         bi.mainChain[i] = nil
183                 }
184         }
185
186         for node != nil && bi.mainChain[node.Height] != node {
187                 bi.mainChain[node.Height] = node
188                 node = node.Parent
189         }
190 }