OSDN Git Service

fix: use fedConsensusPath to derive for consensus federationNodes (#290)
[bytom/vapor.git] / protocol / state / consensus_result.go
1 package state
2
3 import (
4         "encoding/hex"
5         "sort"
6
7         "github.com/vapor/common/arithmetic"
8         "github.com/vapor/config"
9         "github.com/vapor/consensus"
10         "github.com/vapor/crypto/ed25519/chainkd"
11         "github.com/vapor/errors"
12         "github.com/vapor/math/checked"
13         "github.com/vapor/protocol/bc"
14         "github.com/vapor/protocol/bc/types"
15 )
16
17 // fedConsensusPath is used to derive federation root xpubs for signing blocks
18 var fedConsensusPath = [][]byte{
19         []byte{0xff, 0xff, 0xff, 0xff},
20         []byte{0xff, 0x00, 0x00, 0x00},
21         []byte{0xff, 0xff, 0xff, 0xff},
22         []byte{0xff, 0x00, 0x00, 0x00},
23         []byte{0xff, 0x00, 0x00, 0x00},
24 }
25
26 // ConsensusNode represents a consensus node
27 type ConsensusNode struct {
28         XPub    chainkd.XPub
29         VoteNum uint64
30         Order   uint64
31 }
32
33 type byVote []*ConsensusNode
34
35 func (c byVote) Len() int { return len(c) }
36 func (c byVote) Less(i, j int) bool {
37         return c[i].VoteNum > c[j].VoteNum || (c[i].VoteNum == c[j].VoteNum && c[i].XPub.String() > c[j].XPub.String())
38 }
39 func (c byVote) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
40
41 // CoinbaseReward contains receiver and reward
42 type CoinbaseReward struct {
43         Amount         uint64
44         ControlProgram []byte
45 }
46
47 // SortByAmount implements sort.Interface for CoinbaseReward slices
48 type SortByAmount []CoinbaseReward
49
50 func (a SortByAmount) Len() int      { return len(a) }
51 func (a SortByAmount) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
52 func (a SortByAmount) Less(i, j int) bool {
53         return a[i].Amount > a[j].Amount || (a[i].Amount == a[j].Amount && hex.EncodeToString(a[i].ControlProgram) > hex.EncodeToString(a[j].ControlProgram))
54 }
55
56 // CalCoinbaseReward calculate the coinbase reward for block
57 func CalCoinbaseReward(block *types.Block) (*CoinbaseReward, error) {
58         result := &CoinbaseReward{}
59         if len(block.Transactions) > 0 && len(block.Transactions[0].Outputs) > 0 {
60                 result.ControlProgram = block.Transactions[0].Outputs[0].ControlProgram()
61         } else {
62                 return nil, errors.New("not found coinbase receiver")
63         }
64
65         result.Amount = consensus.BlockSubsidy(block.BlockHeader.Height)
66         for _, tx := range block.Transactions {
67                 txFee, err := arithmetic.CalculateTxFee(tx)
68                 if err != nil {
69                         return nil, errors.Wrap(checked.ErrOverflow, "calculate transaction fee")
70                 }
71
72                 result.Amount += txFee
73         }
74         return result, nil
75 }
76
77 // CalcVoteSeq calculate the vote sequence
78 // seq 0 is the genesis block
79 // seq 1 is the the block height 1, to block height RoundVoteBlockNums
80 // seq 2 is the block height RoundVoteBlockNums + 1 to block height 2 * RoundVoteBlockNums
81 // consensus node of the current round is the final result of previous round
82 func CalcVoteSeq(blockHeight uint64) uint64 {
83         if blockHeight == 0 {
84                 return 0
85         }
86         return (blockHeight-1)/consensus.ActiveNetParams.RoundVoteBlockNums + 1
87 }
88
89 // ConsensusResult represents a snapshot of each round of DPOS voting
90 // Seq indicates the sequence of current votes, which start from zero
91 // NumOfVote indicates the number of votes each consensus node receives, the key of map represent public key
92 // CoinbaseReward indicates the coinbase receiver and reward
93 type ConsensusResult struct {
94         Seq            uint64
95         NumOfVote      map[string]uint64
96         CoinbaseReward map[string]uint64
97         BlockHash      bc.Hash
98         BlockHeight    uint64
99 }
100
101 // ApplyBlock calculate the consensus result for new block
102 func (c *ConsensusResult) ApplyBlock(block *types.Block) error {
103         if c.BlockHash != block.PreviousBlockHash {
104                 return errors.New("block parent hash is not equals last block hash of vote result")
105         }
106
107         if err := c.AttachCoinbaseReward(block); err != nil {
108                 return err
109         }
110
111         for _, tx := range block.Transactions {
112                 for _, input := range tx.Inputs {
113                         vetoInput, ok := input.TypedInput.(*types.VetoInput)
114                         if !ok {
115                                 continue
116                         }
117
118                         pubkey := hex.EncodeToString(vetoInput.Vote)
119                         c.NumOfVote[pubkey], ok = checked.SubUint64(c.NumOfVote[pubkey], vetoInput.Amount)
120                         if !ok {
121                                 return checked.ErrOverflow
122                         }
123
124                         if c.NumOfVote[pubkey] == 0 {
125                                 delete(c.NumOfVote, pubkey)
126                         }
127                 }
128
129                 for _, output := range tx.Outputs {
130                         voteOutput, ok := output.TypedOutput.(*types.VoteOutput)
131                         if !ok {
132                                 continue
133                         }
134
135                         pubkey := hex.EncodeToString(voteOutput.Vote)
136                         if c.NumOfVote[pubkey], ok = checked.AddUint64(c.NumOfVote[pubkey], voteOutput.Amount); !ok {
137                                 return checked.ErrOverflow
138                         }
139                 }
140         }
141
142         c.BlockHash = block.Hash()
143         c.BlockHeight = block.Height
144         c.Seq = CalcVoteSeq(block.Height)
145         return nil
146 }
147
148 // AttachCoinbaseReward attach coinbase reward
149 func (c *ConsensusResult) AttachCoinbaseReward(block *types.Block) error {
150         reward, err := CalCoinbaseReward(block)
151         if err != nil {
152                 return err
153         }
154
155         if block.Height%consensus.ActiveNetParams.RoundVoteBlockNums == 1 {
156                 c.CoinbaseReward = map[string]uint64{}
157         }
158
159         var ok bool
160         program := hex.EncodeToString(reward.ControlProgram)
161         c.CoinbaseReward[program], ok = checked.AddUint64(c.CoinbaseReward[program], reward.Amount)
162         if !ok {
163                 return checked.ErrOverflow
164         }
165         return nil
166 }
167
168 // ConsensusNodes returns all consensus nodes
169 func (c *ConsensusResult) ConsensusNodes() (map[string]*ConsensusNode, error) {
170         var nodes []*ConsensusNode
171         for pubkey, voteNum := range c.NumOfVote {
172                 if voteNum >= consensus.ActiveNetParams.MinConsensusNodeVoteNum {
173                         var xpub chainkd.XPub
174                         if err := xpub.UnmarshalText([]byte(pubkey)); err != nil {
175                                 return nil, err
176                         }
177
178                         nodes = append(nodes, &ConsensusNode{XPub: xpub, VoteNum: voteNum})
179                 }
180         }
181         // In principle, there is no need to sort all voting nodes.
182         // if there is a performance problem, consider the optimization later.
183         sort.Sort(byVote(nodes))
184         result := make(map[string]*ConsensusNode)
185         for i := 0; i < len(nodes) && int64(i) < consensus.ActiveNetParams.NumOfConsensusNode; i++ {
186                 nodes[i].Order = uint64(i)
187                 result[nodes[i].XPub.String()] = nodes[i]
188         }
189
190         if len(result) != 0 {
191                 return result, nil
192         }
193         return federationNodes(), nil
194 }
195
196 // DetachBlock calculate the consensus result for detach block
197 func (c *ConsensusResult) DetachBlock(block *types.Block) error {
198         if c.BlockHash != block.Hash() {
199                 return errors.New("block hash is not equals last block hash of vote result")
200         }
201
202         if err := c.DetachCoinbaseReward(block); err != nil {
203                 return err
204         }
205
206         for i := len(block.Transactions) - 1; i >= 0; i-- {
207                 tx := block.Transactions[i]
208                 for _, input := range tx.Inputs {
209                         vetoInput, ok := input.TypedInput.(*types.VetoInput)
210                         if !ok {
211                                 continue
212                         }
213
214                         pubkey := hex.EncodeToString(vetoInput.Vote)
215                         if c.NumOfVote[pubkey], ok = checked.AddUint64(c.NumOfVote[pubkey], vetoInput.Amount); !ok {
216                                 return checked.ErrOverflow
217                         }
218                 }
219
220                 for _, output := range tx.Outputs {
221                         voteOutput, ok := output.TypedOutput.(*types.VoteOutput)
222                         if !ok {
223                                 continue
224                         }
225
226                         pubkey := hex.EncodeToString(voteOutput.Vote)
227                         c.NumOfVote[pubkey], ok = checked.SubUint64(c.NumOfVote[pubkey], voteOutput.Amount)
228                         if !ok {
229                                 return checked.ErrOverflow
230                         }
231
232                         if c.NumOfVote[pubkey] == 0 {
233                                 delete(c.NumOfVote, pubkey)
234                         }
235                 }
236         }
237
238         c.BlockHash = block.PreviousBlockHash
239         c.BlockHeight = block.Height - 1
240         c.Seq = CalcVoteSeq(block.Height - 1)
241         return nil
242 }
243
244 // DetachCoinbaseReward detach coinbase reward
245 func (c *ConsensusResult) DetachCoinbaseReward(block *types.Block) error {
246         if block.Height%consensus.ActiveNetParams.RoundVoteBlockNums == 0 {
247                 for i, output := range block.Transactions[0].Outputs {
248                         if i == 0 {
249                                 continue
250                         }
251                         program := output.ControlProgram()
252                         c.CoinbaseReward[hex.EncodeToString(program)] = output.AssetAmount().Amount
253                 }
254         }
255
256         reward, err := CalCoinbaseReward(block)
257         if err != nil {
258                 return err
259         }
260
261         var ok bool
262         program := hex.EncodeToString(reward.ControlProgram)
263         if c.CoinbaseReward[program], ok = checked.SubUint64(c.CoinbaseReward[program], reward.Amount); !ok {
264                 return checked.ErrOverflow
265         }
266
267         if c.CoinbaseReward[program] == 0 {
268                 delete(c.CoinbaseReward, program)
269         }
270         return nil
271 }
272
273 // Fork copy the ConsensusResult struct
274 func (c *ConsensusResult) Fork() *ConsensusResult {
275         f := &ConsensusResult{
276                 Seq:            c.Seq,
277                 NumOfVote:      map[string]uint64{},
278                 CoinbaseReward: map[string]uint64{},
279                 BlockHash:      c.BlockHash,
280                 BlockHeight:    c.BlockHeight,
281         }
282
283         for key, value := range c.NumOfVote {
284                 f.NumOfVote[key] = value
285         }
286
287         for key, value := range c.CoinbaseReward {
288                 f.CoinbaseReward[key] = value
289         }
290         return f
291 }
292
293 // IsFinalize check if the result is end of consensus round
294 func (c *ConsensusResult) IsFinalize() bool {
295         return c.BlockHeight%consensus.ActiveNetParams.RoundVoteBlockNums == 0
296 }
297
298 // GetCoinbaseRewards convert into CoinbaseReward array and sort it by amount
299 func (c *ConsensusResult) GetCoinbaseRewards(blockHeight uint64) ([]CoinbaseReward, error) {
300         rewards := []CoinbaseReward{}
301         if blockHeight%consensus.ActiveNetParams.RoundVoteBlockNums != 0 {
302                 return rewards, nil
303         }
304
305         for p, amount := range c.CoinbaseReward {
306                 program, err := hex.DecodeString(p)
307                 if err != nil {
308                         return nil, err
309                 }
310
311                 rewards = append(rewards, CoinbaseReward{
312                         Amount:         amount,
313                         ControlProgram: program,
314                 })
315         }
316         sort.Sort(SortByAmount(rewards))
317         return rewards, nil
318 }
319
320 func federationNodes() map[string]*ConsensusNode {
321         consensusResult := map[string]*ConsensusNode{}
322         for i, xpub := range config.CommonConfig.Federation.Xpubs {
323                 derivedXPub := xpub.Derive(fedConsensusPath)
324                 consensusResult[derivedXPub.String()] = &ConsensusNode{XPub: derivedXPub, VoteNum: 0, Order: uint64(i)}
325         }
326         return consensusResult
327 }