OSDN Git Service

e7498f97001fa32d8d4a65e592a4585bcba93633
[bytom/vapor.git] / protocol / bbft.go
1 package protocol
2
3 import (
4         "encoding/hex"
5         "fmt"
6
7         log "github.com/sirupsen/logrus"
8
9         "github.com/vapor/config"
10         "github.com/vapor/errors"
11         "github.com/vapor/event"
12         "github.com/vapor/protocol/bc"
13         "github.com/vapor/protocol/bc/types"
14         "github.com/vapor/protocol/state"
15 )
16
17 const (
18         maxSignatureCacheSize = 10000
19 )
20
21 var (
22         errVotingOperationOverFlow = errors.New("voting operation result overflow")
23         errDoubleSignBlock         = errors.New("the consensus is double sign in same height of different block")
24         errInvalidSignature        = errors.New("the signature of block is invalid")
25         errSignForkChain           = errors.New("can not sign fork before the irreversible block")
26 )
27
28 func signCacheKey(blockHash, pubkey string) string {
29         return fmt.Sprintf("%s:%s", blockHash, pubkey)
30 }
31
32 func (c *Chain) isIrreversible(blockNode *state.BlockNode) bool {
33         consensusNodes, err := c.consensusNodeManager.getConsensusNodes(&blockNode.Parent.Hash)
34         if err != nil {
35                 return false
36         }
37
38         signCount := 0
39         for i := 0; i < len(consensusNodes); i++ {
40                 if ok, _ := blockNode.BlockWitness.Test(uint32(i)); ok {
41                         signCount++
42                 }
43         }
44
45         return signCount > len(consensusNodes)*2/3
46 }
47
48 // NextLeaderTime returns the start time of the specified public key as the next leader node
49 func (c *Chain) IsBlocker(prevBlockHash *bc.Hash, pubkey string, timeStamp uint64) (bool, error) {
50         return c.consensusNodeManager.isBlocker(prevBlockHash, pubkey, timeStamp)
51 }
52
53 // ProcessBlockSignature process the received block signature messages
54 // return whether a block become irreversible, if so, the chain module must update status
55 func (c *Chain) ProcessBlockSignature(signature, xPub []byte, blockHash *bc.Hash) error {
56         xpubStr := hex.EncodeToString(xPub[:])
57         blockNode := c.index.GetNode(blockHash)
58         // save the signature if the block is not exist
59         if blockNode == nil {
60                 cacheKey := signCacheKey(blockHash.String(), xpubStr)
61                 c.signatureCache.Add(cacheKey, signature)
62                 return nil
63         }
64
65         consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, xpubStr)
66         if err != nil {
67                 return err
68         }
69
70         if exist, _ := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); exist {
71                 return nil
72         }
73
74         if err := c.checkNodeSign(blockNode.BlockHeader(), consensusNode, signature); err != nil {
75                 return err
76         }
77
78         if err := c.updateBlockSignature(blockNode, consensusNode.Order, signature); err != nil {
79                 return err
80         }
81         return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub})
82 }
83
84 // validateSign verify the signatures of block, and return the number of correct signature
85 // if some signature is invalid, they will be reset to nil
86 // if the block has not the signature of blocker, it will return error
87 func (c *Chain) validateSign(block *types.Block) error {
88         consensusNodeMap, err := c.consensusNodeManager.getConsensusNodes(&block.PreviousBlockHash)
89         if err != nil {
90                 return err
91         }
92
93         hasBlockerSign := false
94         blockHash := block.Hash()
95         for pubKey, node := range consensusNodeMap {
96                 if len(block.Witness) <= int(node.Order) {
97                         continue
98                 }
99
100                 if block.Witness[node.Order] == nil {
101                         cachekey := signCacheKey(blockHash.String(), pubKey)
102                         if signature, ok := c.signatureCache.Get(cachekey); ok {
103                                 block.Witness[node.Order] = signature.([]byte)
104                         } else {
105                                 continue
106                         }
107                 }
108
109                 if err := c.checkNodeSign(&block.BlockHeader, node, block.Witness[node.Order]); err == errDoubleSignBlock {
110                         log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block")
111                         block.Witness[node.Order] = nil
112                         continue
113                 } else if err != nil {
114                         return err
115                 }
116
117                 isBlocker, err := c.consensusNodeManager.isBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
118                 if err != nil {
119                         return err
120                 }
121
122                 if isBlocker {
123                         hasBlockerSign = true
124                 }
125
126         }
127
128         if !hasBlockerSign {
129                 return errors.New("the block has no signature of the blocker")
130         }
131         return nil
132 }
133
134 func (c *Chain) checkNodeSign(bh *types.BlockHeader, consensusNode *state.ConsensusNode, signature []byte) error {
135         if !consensusNode.XPub.Verify(bh.Hash().Bytes(), signature) {
136                 return errInvalidSignature
137         }
138
139         blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(bh.Height)
140         for _, blockNode := range blockNodes {
141                 if blockNode.Hash == bh.Hash() {
142                         continue
143                 }
144
145                 consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, consensusNode.XPub.String())
146                 if err != nil && err != errNotFoundConsensusNode {
147                         return err
148                 }
149
150                 if err == errNotFoundConsensusNode {
151                         continue
152                 }
153
154                 if ok, err := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); err == nil && ok {
155                         return errDoubleSignBlock
156                 }
157         }
158         return nil
159 }
160
161 // SignBlock signing the block if current node is consensus node
162 func (c *Chain) SignBlock(block *types.Block) ([]byte, error) {
163         xprv := config.CommonConfig.PrivateKey()
164         xpubStr := xprv.XPub().String()
165         node, err := c.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, xpubStr)
166         if err == errNotFoundConsensusNode {
167                 return nil, nil
168         } else if err != nil {
169                 return nil, err
170         }
171
172         c.cond.L.Lock()
173         defer c.cond.L.Unlock()
174         //check double sign in same block height
175         blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(block.Height)
176         for _, blockNode := range blockNodes {
177                 // Has already signed the same height block
178                 if ok, err := blockNode.BlockWitness.Test(uint32(node.Order)); err == nil && ok {
179                         return nil, nil
180                 }
181         }
182
183         for blockNode := c.index.GetNode(&block.PreviousBlockHash); !c.index.InMainchain(blockNode.Hash); blockNode = blockNode.Parent {
184                 if blockNode.Height <= c.bestIrreversibleNode.Height {
185                         return nil, errSignForkChain
186                 }
187         }
188
189         signature := block.Witness[node.Order]
190         if len(signature) == 0 {
191                 signature = xprv.Sign(block.Hash().Bytes())
192                 block.Witness[node.Order] = signature
193         }
194         return signature, nil
195 }
196
197 func (c *Chain) updateBlockSignature(blockNode *state.BlockNode, nodeOrder uint64, signature []byte) error {
198         if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
199                 return err
200         }
201
202         block, err := c.store.GetBlock(&blockNode.Hash)
203         if err != nil {
204                 return err
205         }
206
207         block.Witness[nodeOrder] = signature
208         txStatus, err := c.store.GetTransactionStatus(&blockNode.Hash)
209         if err != nil {
210                 return err
211         }
212
213         if err := c.store.SaveBlock(block, txStatus); err != nil {
214                 return err
215         }
216
217         c.cond.L.Lock()
218         defer c.cond.L.Unlock()
219         if c.isIrreversible(blockNode) && blockNode.Height > c.bestIrreversibleNode.Height {
220                 if err := c.store.SaveChainStatus(c.bestNode, blockNode, state.NewUtxoViewpoint(), []*state.VoteResult{}); err != nil {
221                         return err
222                 }
223
224                 c.bestIrreversibleNode = blockNode
225         }
226         return nil
227 }