OSDN Git Service

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