forked from BytomDAO/bytom
/
protocol.go
242 lines (200 loc) · 6.97 KB
/
protocol.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package protocol
import (
"sync"
log "github.com/sirupsen/logrus"
"github.com/hyper-fi/bytom/config"
"github.com/hyper-fi/bytom/event"
"github.com/hyper-fi/bytom/protocol/bc"
"github.com/hyper-fi/bytom/protocol/bc/types"
"github.com/hyper-fi/bytom/protocol/casper"
"github.com/hyper-fi/bytom/protocol/state"
)
const (
maxProcessBlockChSize = 1024
)
// Chain provides functions for working with the Bytom block chain.
type Chain struct {
orphanManage *OrphanManage
txPool *TxPool
store state.Store
casper *casper.Casper
processBlockCh chan *processBlockMsg
eventDispatcher *event.Dispatcher
cond sync.Cond
bestBlockHeader *types.BlockHeader // the last block on current main chain
}
// NewChain returns a new Chain using store as the underlying storage.
func NewChain(store state.Store, txPool *TxPool, eventDispatcher *event.Dispatcher) (*Chain, error) {
return NewChainWithOrphanManage(store, txPool, NewOrphanManage(), eventDispatcher)
}
func NewChainWithOrphanManage(store state.Store, txPool *TxPool, manage *OrphanManage, eventDispatcher *event.Dispatcher) (*Chain, error) {
c := &Chain{
orphanManage: manage,
eventDispatcher: eventDispatcher,
txPool: txPool,
store: store,
processBlockCh: make(chan *processBlockMsg, maxProcessBlockChSize),
}
c.cond.L = new(sync.Mutex)
storeStatus := store.GetStoreStatus()
if storeStatus == nil {
if err := c.initChainStatus(); err != nil {
return nil, err
}
storeStatus = store.GetStoreStatus()
}
var err error
c.bestBlockHeader, err = c.store.GetBlockHeader(storeStatus.Hash)
if err != nil {
return nil, err
}
casper, err := newCasper(store, eventDispatcher, storeStatus)
if err != nil {
return nil, err
}
c.casper = casper
go c.blockProcessor()
return c, nil
}
func (c *Chain) initChainStatus() error {
genesisBlock := config.GenesisBlock()
if err := c.store.SaveBlock(genesisBlock); err != nil {
return err
}
checkpoint := &state.Checkpoint{
Height: 0,
Hash: genesisBlock.Hash(),
Timestamp: genesisBlock.Timestamp,
Status: state.Justified,
}
if err := c.store.SaveCheckpoints([]*state.Checkpoint{checkpoint}); err != nil {
return err
}
utxoView := state.NewUtxoViewpoint()
bcBlock := types.MapBlock(genesisBlock)
if err := utxoView.ApplyBlock(bcBlock); err != nil {
return err
}
contractView := state.NewContractViewpoint()
genesisBlockHeader := &genesisBlock.BlockHeader
return c.store.SaveChainStatus(genesisBlockHeader, []*types.BlockHeader{genesisBlockHeader}, utxoView, contractView, 0, &checkpoint.Hash)
}
func newCasper(store state.Store, e *event.Dispatcher, storeStatus *state.BlockStoreState) (*casper.Casper, error) {
checkpoints, err := store.CheckpointsFromNode(storeStatus.FinalizedHeight, storeStatus.FinalizedHash)
if err != nil {
return nil, err
}
return casper.NewCasper(store, e, checkpoints), nil
}
// LastJustifiedHeader return the last justified block header of the block chain
func (c *Chain) LastJustifiedHeader() (*types.BlockHeader, error) {
_, hash := c.casper.LastJustified()
return c.store.GetBlockHeader(&hash)
}
// LastFinalizedHeader return the last finalized block header of the block chain
func (c *Chain) LastFinalizedHeader() (*types.BlockHeader, error) {
_, hash := c.casper.LastFinalized()
return c.store.GetBlockHeader(&hash)
}
// ProcessBlockVerification process block verification
func (c *Chain) ProcessBlockVerification(v *casper.ValidCasperSignMsg) error {
return c.casper.AuthVerification(v)
}
// BestBlockHeight returns the current height of the blockchain.
func (c *Chain) BestBlockHeight() uint64 {
c.cond.L.Lock()
defer c.cond.L.Unlock()
return c.bestBlockHeader.Height
}
// BestBlockHash return the hash of the chain tail block
func (c *Chain) BestBlockHash() *bc.Hash {
c.cond.L.Lock()
defer c.cond.L.Unlock()
bestHash := c.bestBlockHeader.Hash()
return &bestHash
}
// BestChain return the current height and block hash of the chain
func (c *Chain) BestChain() (uint64, bc.Hash) {
c.cond.L.Lock()
defer c.cond.L.Unlock()
return c.bestBlockHeader.Height, c.bestBlockHeader.Hash()
}
func (c *Chain) FinalizedHeight() uint64 {
finalizedHeight, _ := c.casper.LastFinalized()
return finalizedHeight
}
// AllValidators return all validators has vote num
func (c *Chain) AllValidators(blockHash *bc.Hash) ([]*state.Validator, error) {
parentCheckpoint, err := c.casper.ParentCheckpoint(blockHash)
if err != nil {
return nil, err
}
return parentCheckpoint.AllValidators(), nil
}
// GetValidator return validator by specified blockHash and timestamp
func (c *Chain) GetValidator(prevHash *bc.Hash, timeStamp uint64) (*state.Validator, error) {
parentCheckpoint, err := c.casper.ParentCheckpointByPrevHash(prevHash)
if err != nil {
return nil, err
}
return parentCheckpoint.GetValidator(timeStamp), nil
}
// BestBlockHeader returns the chain tail block
func (c *Chain) BestBlockHeader() *types.BlockHeader {
c.cond.L.Lock()
defer c.cond.L.Unlock()
return c.bestBlockHeader
}
// InMainChain checks wheather a block is in the main chain
func (c *Chain) InMainChain(hash bc.Hash) bool {
blockHeader, err := c.store.GetBlockHeader(&hash)
if err != nil {
return false
}
blockHash, err := c.store.GetMainChainHash(blockHeader.Height)
if err != nil {
log.WithFields(log.Fields{"module": logModule, "height": blockHeader.Height}).Debug("not contain block hash in main chain for specified height")
return false
}
return *blockHash == hash
}
func (c *Chain) SignBlockHeader(blockHeader *types.BlockHeader) {
xprv := config.CommonConfig.PrivateKey()
signature := xprv.Sign(blockHeader.Hash().Bytes())
blockHeader.Set(signature)
}
// This function must be called with mu lock in above level
func (c *Chain) setState(blockHeader *types.BlockHeader, mainBlockHeaders []*types.BlockHeader, view *state.UtxoViewpoint, contractView *state.ContractViewpoint) error {
finalizedHeight, finalizedHash := c.casper.LastFinalized()
if err := c.store.SaveChainStatus(blockHeader, mainBlockHeaders, view, contractView, finalizedHeight, &finalizedHash); err != nil {
return err
}
c.cond.L.Lock()
defer c.cond.L.Unlock()
c.bestBlockHeader = blockHeader
hash := c.bestBlockHeader.Hash()
log.WithFields(log.Fields{"module": logModule, "height": c.bestBlockHeader.Height, "hash": hash.String()}).Debug("chain best status has been update")
c.cond.Broadcast()
return nil
}
// BlockWaiter returns a channel that waits for the block at the given height.
func (c *Chain) BlockWaiter(height uint64) <-chan struct{} {
ch := make(chan struct{}, 1)
go func() {
c.cond.L.Lock()
defer c.cond.L.Unlock()
for c.bestBlockHeader.Height < height {
c.cond.Wait()
}
ch <- struct{}{}
}()
return ch
}
// GetTxPool return chain txpool.
func (c *Chain) GetTxPool() *TxPool {
return c.txPool
}
// PrevCheckpointByPrevHash get previous checkpoint by previous block hash
func (c *Chain) PrevCheckpointByPrevHash(preBlockHash *bc.Hash) (*state.Checkpoint, error) {
return c.casper.ParentCheckpointByPrevHash(preBlockHash)
}