-
Notifications
You must be signed in to change notification settings - Fork 9
/
bbft.go
257 lines (214 loc) · 7.39 KB
/
bbft.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package protocol
import (
"encoding/hex"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/bytom/vapor/config"
"github.com/bytom/vapor/crypto/ed25519/chainkd"
"github.com/bytom/vapor/errors"
"github.com/bytom/vapor/event"
"github.com/bytom/vapor/protocol/bc"
"github.com/bytom/vapor/protocol/bc/types"
"github.com/bytom/vapor/protocol/state"
)
const (
maxSignatureCacheSize = 10000
)
var (
errDoubleSignBlock = errors.New("the consensus is double sign in same height of different block")
errInvalidSignature = errors.New("the signature of block is invalid")
errSignForkChain = errors.New("can not sign fork before the irreversible block")
)
func signCacheKey(blockHash, pubkey string) string {
return fmt.Sprintf("%s:%s", blockHash, pubkey)
}
func (c *Chain) checkDoubleSign(bh *types.BlockHeader, xPub string) error {
blockHashes, err := c.store.GetBlockHashesByHeight(bh.Height)
if err != nil {
return err
}
for _, blockHash := range blockHashes {
if *blockHash == bh.Hash() {
continue
}
blockHeader, err := c.store.GetBlockHeader(blockHash)
if err != nil {
return err
}
consensusNode, err := c.getConsensusNode(&blockHeader.PreviousBlockHash, xPub)
if err == errNotFoundConsensusNode {
continue
} else if err != nil {
return err
}
if blockHeader.BlockWitness.Get(consensusNode.Order) != nil {
return errDoubleSignBlock
}
}
return nil
}
func (c *Chain) checkNodeSign(bh *types.BlockHeader, consensusNode *state.ConsensusNode, signature []byte) error {
if !consensusNode.XPub.Verify(bh.Hash().Bytes(), signature) {
return errInvalidSignature
}
return c.checkDoubleSign(bh, consensusNode.XPub.String())
}
func (c *Chain) isIrreversible(blockHeader *types.BlockHeader) bool {
consensusNodes, err := c.getConsensusNodes(&blockHeader.PreviousBlockHash)
if err != nil {
return false
}
signCount := 0
for i := 0; i < len(consensusNodes); i++ {
if blockHeader.BlockWitness.Get(uint64(i)) != nil {
signCount++
}
}
return signCount > len(consensusNodes)*2/3
}
func (c *Chain) updateBlockSignature(blockHeader *types.BlockHeader, nodeOrder uint64, signature []byte) error {
blockHeader.Set(nodeOrder, signature)
if err := c.store.SaveBlockHeader(blockHeader); err != nil {
return err
}
if !c.isIrreversible(blockHeader) || blockHeader.Height <= c.lastIrrBlockHeader.Height {
return nil
}
if c.InMainChain(blockHeader.Hash()) {
if err := c.store.SaveChainStatus(c.bestBlockHeader, blockHeader, []*types.BlockHeader{}, state.NewUtxoViewpoint(), []*state.ConsensusResult{}); err != nil {
return err
}
c.lastIrrBlockHeader = blockHeader
} else {
// block is on a forked chain
log.WithFields(log.Fields{"module": logModule}).Info("majority votes received on forked chain")
tail, err := c.traceLongestChainTail(blockHeader)
if err != nil {
return err
}
return c.reorganizeChain(tail)
}
return nil
}
// validateSign verify the signatures of block, and return the number of correct signature
// if some signature is invalid, they will be reset to nil
// if the block does not have the signature of blocker, it will return error
func (c *Chain) validateSign(block *types.Block) error {
consensusNodeMap, err := c.getConsensusNodes(&block.PreviousBlockHash)
if err != nil {
return err
}
blocker, err := c.GetBlocker(&block.PreviousBlockHash, block.Timestamp)
if err != nil {
return err
}
hasBlockerSign := false
blockHash := block.Hash()
for pubKey, node := range consensusNodeMap {
if block.BlockWitness.Get(node.Order) == nil {
cachekey := signCacheKey(blockHash.String(), pubKey)
if signature, ok := c.signatureCache.Get(cachekey); ok {
block.Set(node.Order, signature.([]byte))
c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: blockHash, Signature: signature.([]byte), XPub: node.XPub[:]})
c.signatureCache.Remove(cachekey)
} else {
continue
}
}
if err := c.checkNodeSign(&block.BlockHeader, node, block.Get(node.Order)); err == errDoubleSignBlock {
log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block")
// if the blocker double sign & become the mainchain, that means
// all the side chain will reject the main chain make the chain
// fork. All the node will ban each other & can't roll back
if blocker != pubKey {
block.BlockWitness.Delete(node.Order)
continue
}
} else if err != nil {
return err
}
if blocker == pubKey {
hasBlockerSign = true
}
}
if !hasBlockerSign {
return errors.New("the block has no signature of the blocker")
}
return nil
}
// ProcessBlockSignature process the received block signature messages
// return whether a block become irreversible, if so, the chain module must update status
func (c *Chain) ProcessBlockSignature(signature, xPub []byte, blockHash *bc.Hash) error {
xpubStr := hex.EncodeToString(xPub[:])
blockHeader, _ := c.store.GetBlockHeader(blockHash)
// save the signature if the block is not exist
if blockHeader == nil {
var xPubKey chainkd.XPub
copy(xPubKey[:], xPub[:])
if !xPubKey.Verify(blockHash.Bytes(), signature) {
return errInvalidSignature
}
cacheKey := signCacheKey(blockHash.String(), xpubStr)
c.signatureCache.Add(cacheKey, signature)
return nil
}
consensusNode, err := c.getConsensusNode(&blockHeader.PreviousBlockHash, xpubStr)
if err != nil {
return err
}
if blockHeader.BlockWitness.Get(consensusNode.Order) != nil {
return nil
}
c.cond.L.Lock()
defer c.cond.L.Unlock()
if err := c.checkNodeSign(blockHeader, consensusNode, signature); err != nil {
return err
}
if err := c.updateBlockSignature(blockHeader, consensusNode.Order, signature); err != nil {
return err
}
return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub})
}
// SignBlockHeader signing the block if current node is consensus node
func (c *Chain) SignBlockHeader(blockHeader *types.BlockHeader) error {
_, err := c.signBlockHeader(blockHeader)
return err
}
func (c *Chain) applyBlockSign(blockHeader *types.BlockHeader) error {
signature, err := c.signBlockHeader(blockHeader)
if err != nil {
return err
}
if len(signature) == 0 {
return nil
}
if err := c.store.SaveBlockHeader(blockHeader); err != nil {
return err
}
xpub := config.CommonConfig.PrivateKey().XPub()
return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: blockHeader.Hash(), Signature: signature, XPub: xpub[:]})
}
func (c *Chain) signBlockHeader(blockHeader *types.BlockHeader) ([]byte, error) {
xprv := config.CommonConfig.PrivateKey()
xpub := xprv.XPub()
node, err := c.getConsensusNode(&blockHeader.PreviousBlockHash, xpub.String())
blockHash := blockHeader.Hash()
if err == errNotFoundConsensusNode {
log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String()}).Debug("can't find consensus node of current node")
return nil, nil
} else if err != nil {
return nil, err
}
if len(blockHeader.Get(node.Order)) != 0 {
return nil, nil
}
if err := c.checkDoubleSign(blockHeader, node.XPub.String()); err == errDoubleSignBlock {
log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String()}).Warn("current node has double sign the block")
return nil, nil
} else if err != nil {
return nil, err
}
signature := xprv.Sign(blockHeader.Hash().Bytes())
blockHeader.Set(node.Order, signature)
return signature, nil
}