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"
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},
26 // ConsensusNode represents a consensus node
27 type ConsensusNode struct {
33 type byVote []*ConsensusNode
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())
39 func (c byVote) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
41 // CoinbaseReward contains receiver and reward
42 type CoinbaseReward struct {
47 // SortByAmount implements sort.Interface for CoinbaseReward slices
48 type SortByAmount []CoinbaseReward
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))
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()
62 return nil, errors.New("not found coinbase receiver")
65 result.Amount = consensus.BlockSubsidy(block.BlockHeader.Height)
66 for _, tx := range block.Transactions {
67 txFee, err := arithmetic.CalculateTxFee(tx)
69 return nil, errors.Wrap(checked.ErrOverflow, "calculate transaction fee")
72 result.Amount += txFee
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 {
86 return (blockHeight-1)/consensus.ActiveNetParams.RoundVoteBlockNums + 1
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 {
95 NumOfVote map[string]uint64
96 CoinbaseReward map[string]uint64
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")
107 if err := c.AttachCoinbaseReward(block); err != nil {
111 for _, tx := range block.Transactions {
112 if err := c.ApplyTransaction(tx); err != nil {
117 c.BlockHash = block.Hash()
118 c.BlockHeight = block.Height
119 c.Seq = CalcVoteSeq(block.Height)
123 // ApplyTransaction calculate the consensus result for transaction
124 func (c *ConsensusResult) ApplyTransaction(tx *types.Tx) error {
125 for _, input := range tx.Inputs {
126 vetoInput, ok := input.TypedInput.(*types.VetoInput)
131 pubkey := hex.EncodeToString(vetoInput.Vote)
132 c.NumOfVote[pubkey], ok = checked.SubUint64(c.NumOfVote[pubkey], vetoInput.Amount)
134 return checked.ErrOverflow
137 if c.NumOfVote[pubkey] == 0 {
138 delete(c.NumOfVote, pubkey)
142 for _, output := range tx.Outputs {
143 voteOutput, ok := output.TypedOutput.(*types.VoteOutput)
148 pubkey := hex.EncodeToString(voteOutput.Vote)
149 if c.NumOfVote[pubkey], ok = checked.AddUint64(c.NumOfVote[pubkey], voteOutput.Amount); !ok {
150 return checked.ErrOverflow
156 // AttachCoinbaseReward attach coinbase reward
157 func (c *ConsensusResult) AttachCoinbaseReward(block *types.Block) error {
158 reward, err := CalCoinbaseReward(block)
163 if block.Height%consensus.ActiveNetParams.RoundVoteBlockNums == 1 {
164 c.CoinbaseReward = map[string]uint64{}
168 program := hex.EncodeToString(reward.ControlProgram)
169 c.CoinbaseReward[program], ok = checked.AddUint64(c.CoinbaseReward[program], reward.Amount)
171 return checked.ErrOverflow
176 // ConsensusNodes returns all consensus nodes
177 func (c *ConsensusResult) ConsensusNodes() (map[string]*ConsensusNode, error) {
178 var nodes []*ConsensusNode
179 for pubkey, voteNum := range c.NumOfVote {
180 if voteNum >= consensus.ActiveNetParams.MinConsensusNodeVoteNum {
181 var xpub chainkd.XPub
182 if err := xpub.UnmarshalText([]byte(pubkey)); err != nil {
186 nodes = append(nodes, &ConsensusNode{XPub: xpub, VoteNum: voteNum})
189 // In principle, there is no need to sort all voting nodes.
190 // if there is a performance problem, consider the optimization later.
191 sort.Sort(byVote(nodes))
192 result := make(map[string]*ConsensusNode)
193 for i := 0; i < len(nodes) && int64(i) < consensus.ActiveNetParams.NumOfConsensusNode; i++ {
194 nodes[i].Order = uint64(i)
195 result[nodes[i].XPub.String()] = nodes[i]
198 if len(result) != 0 {
201 return federationNodes(), nil
204 // DetachBlock calculate the consensus result for detach block
205 func (c *ConsensusResult) DetachBlock(block *types.Block) error {
206 if c.BlockHash != block.Hash() {
207 return errors.New("block hash is not equals last block hash of vote result")
210 if err := c.DetachCoinbaseReward(block); err != nil {
214 for i := len(block.Transactions) - 1; i >= 0; i-- {
215 tx := block.Transactions[i]
216 for _, input := range tx.Inputs {
217 vetoInput, ok := input.TypedInput.(*types.VetoInput)
222 pubkey := hex.EncodeToString(vetoInput.Vote)
223 if c.NumOfVote[pubkey], ok = checked.AddUint64(c.NumOfVote[pubkey], vetoInput.Amount); !ok {
224 return checked.ErrOverflow
228 for _, output := range tx.Outputs {
229 voteOutput, ok := output.TypedOutput.(*types.VoteOutput)
234 pubkey := hex.EncodeToString(voteOutput.Vote)
235 c.NumOfVote[pubkey], ok = checked.SubUint64(c.NumOfVote[pubkey], voteOutput.Amount)
237 return checked.ErrOverflow
240 if c.NumOfVote[pubkey] == 0 {
241 delete(c.NumOfVote, pubkey)
246 c.BlockHash = block.PreviousBlockHash
247 c.BlockHeight = block.Height - 1
248 c.Seq = CalcVoteSeq(block.Height - 1)
252 // DetachCoinbaseReward detach coinbase reward
253 func (c *ConsensusResult) DetachCoinbaseReward(block *types.Block) error {
254 reward, err := CalCoinbaseReward(block)
260 program := hex.EncodeToString(reward.ControlProgram)
261 if c.CoinbaseReward[program], ok = checked.SubUint64(c.CoinbaseReward[program], reward.Amount); !ok {
262 return checked.ErrOverflow
265 if c.CoinbaseReward[program] == 0 {
266 delete(c.CoinbaseReward, program)
269 if block.Height%consensus.ActiveNetParams.RoundVoteBlockNums == 1 {
270 c.CoinbaseReward = map[string]uint64{}
271 for i, output := range block.Transactions[0].Outputs {
275 program := output.ControlProgram()
276 c.CoinbaseReward[hex.EncodeToString(program)] = output.AssetAmount().Amount
282 // Fork copy the ConsensusResult struct
283 func (c *ConsensusResult) Fork() *ConsensusResult {
284 f := &ConsensusResult{
286 NumOfVote: map[string]uint64{},
287 CoinbaseReward: map[string]uint64{},
288 BlockHash: c.BlockHash,
289 BlockHeight: c.BlockHeight,
292 for key, value := range c.NumOfVote {
293 f.NumOfVote[key] = value
296 for key, value := range c.CoinbaseReward {
297 f.CoinbaseReward[key] = value
302 // IsFinalize check if the result is end of consensus round
303 func (c *ConsensusResult) IsFinalize() bool {
304 return c.BlockHeight%consensus.ActiveNetParams.RoundVoteBlockNums == 0
307 // GetCoinbaseRewards convert into CoinbaseReward array and sort it by amount
308 func (c *ConsensusResult) GetCoinbaseRewards(blockHeight uint64) ([]CoinbaseReward, error) {
309 rewards := []CoinbaseReward{}
310 if blockHeight%consensus.ActiveNetParams.RoundVoteBlockNums != 0 {
314 for p, amount := range c.CoinbaseReward {
315 program, err := hex.DecodeString(p)
320 rewards = append(rewards, CoinbaseReward{
322 ControlProgram: program,
325 sort.Sort(SortByAmount(rewards))
329 func federationNodes() map[string]*ConsensusNode {
330 consensusResult := map[string]*ConsensusNode{}
331 for i, xpub := range config.CommonConfig.Federation.Xpubs {
332 derivedXPub := xpub.Derive(fedConsensusPath)
333 consensusResult[derivedXPub.String()] = &ConsensusNode{XPub: derivedXPub, VoteNum: 0, Order: uint64(i)}
335 return consensusResult