OSDN Git Service

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