forked from DNAProject/DNA
-
Notifications
You must be signed in to change notification settings - Fork 1
/
consensus_context.go
231 lines (205 loc) · 6.42 KB
/
consensus_context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/*
* Copyright (C) 2018 The DNA Authors
* This file is part of The DNA library.
*
* The DNA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The DNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The DNA. If not, see <http://www.gnu.org/licenses/>.
*/
package dbft
import (
"fmt"
"github.com/dnaproject2/DNA/account"
"github.com/dnaproject2/DNA/common"
"github.com/dnaproject2/DNA/common/log"
"github.com/dnaproject2/DNA/core/ledger"
"github.com/dnaproject2/DNA/core/types"
"github.com/dnaproject2/DNA/core/vote"
msg "github.com/dnaproject2/DNA/p2pserver/message/types"
"github.com/ontio/ontology-crypto/keypair"
)
const ContextVersion uint32 = 0
type ConsensusContext struct {
State ConsensusState
PrevHash common.Uint256
Height uint32
ViewNumber byte
Bookkeepers []keypair.PublicKey
NextBookkeepers []keypair.PublicKey
Owner keypair.PublicKey
BookkeeperIndex int
PrimaryIndex uint32
Timestamp uint32
Nonce uint64
NextBookkeeper common.Address
Transactions []*types.Transaction
Signatures [][]byte
ExpectedView []byte
header *types.Block
isBookkeeperChanged bool
nmChangedblkHeight uint32
}
func (ctx *ConsensusContext) M() int {
log.Debug()
return len(ctx.Bookkeepers) - (len(ctx.Bookkeepers)-1)/3
}
func NewConsensusContext() *ConsensusContext {
log.Debug()
return &ConsensusContext{}
}
func (ctx *ConsensusContext) ChangeView(viewNum byte) {
log.Debug()
p := (ctx.Height - uint32(viewNum)) % uint32(len(ctx.Bookkeepers))
ctx.State &= SignatureSent
ctx.ViewNumber = viewNum
if p >= 0 {
ctx.PrimaryIndex = uint32(p)
} else {
ctx.PrimaryIndex = uint32(p) + uint32(len(ctx.Bookkeepers))
}
if ctx.State == Initial {
ctx.Transactions = nil
ctx.Signatures = make([][]byte, len(ctx.Bookkeepers))
ctx.header = nil
}
}
func (ctx *ConsensusContext) MakeChangeView() *msg.ConsensusPayload {
log.Debug()
cv := &ChangeView{
NewViewNumber: ctx.ExpectedView[ctx.BookkeeperIndex],
}
cv.msgData.Type = ChangeViewMsg
return ctx.MakePayload(cv)
}
func (ctx *ConsensusContext) MakeHeader() *types.Block {
if ctx.header == nil {
txHash := make([]common.Uint256, 0, len(ctx.Transactions))
for _, t := range ctx.Transactions {
txHash = append(txHash, t.Hash())
}
txRoot := common.ComputeMerkleRoot(txHash)
blockRoot := ledger.DefLedger.GetBlockRootWithNewTxRoots(ctx.Height, []common.Uint256{txRoot})
header := &types.Header{
Version: ContextVersion,
PrevBlockHash: ctx.PrevHash,
TransactionsRoot: txRoot,
BlockRoot: blockRoot,
Timestamp: ctx.Timestamp,
Height: ctx.Height,
ConsensusData: ctx.Nonce,
NextBookkeeper: ctx.NextBookkeeper,
}
ctx.header = &types.Block{
Header: header,
Transactions: []*types.Transaction{},
}
}
return ctx.header
}
func (ctx *ConsensusContext) MakePayload(message ConsensusMessage) *msg.ConsensusPayload {
log.Debug()
message.ConsensusMessageData().ViewNumber = ctx.ViewNumber
sink := common.NewZeroCopySink(nil)
message.Serialization(sink)
return &msg.ConsensusPayload{
Version: ContextVersion,
PrevHash: ctx.PrevHash,
Height: ctx.Height,
BookkeeperIndex: uint16(ctx.BookkeeperIndex),
Timestamp: ctx.Timestamp,
Data: sink.Bytes(),
Owner: ctx.Owner,
}
}
func (ctx *ConsensusContext) MakePrepareRequest() *msg.ConsensusPayload {
log.Debug()
preReq := &PrepareRequest{
Nonce: ctx.Nonce,
NextBookkeeper: ctx.NextBookkeeper,
Transactions: ctx.Transactions,
Signature: ctx.Signatures[ctx.BookkeeperIndex],
}
preReq.msgData.Type = PrepareRequestMsg
return ctx.MakePayload(preReq)
}
func (ctx *ConsensusContext) MakePrepareResponse(signature []byte) *msg.ConsensusPayload {
log.Debug()
preRes := &PrepareResponse{
Signature: signature,
}
preRes.msgData.Type = PrepareResponseMsg
return ctx.MakePayload(preRes)
}
func (ctx *ConsensusContext) MakeBlockSignatures(signatures []SignaturesData) *msg.ConsensusPayload {
log.Debug()
sigs := &BlockSignatures{
Signatures: signatures,
}
sigs.msgData.Type = BlockSignaturesMsg
return ctx.MakePayload(sigs)
}
func (ctx *ConsensusContext) GetSignaturesCount() (count int) {
log.Debug()
count = 0
for _, sig := range ctx.Signatures {
if sig != nil {
count += 1
}
}
return count
}
func (ctx *ConsensusContext) GetStateDetail() string {
return fmt.Sprintf("Initial: %t, Primary: %t, Backup: %t, RequestSent: %t, RequestReceived: %t, SignatureSent: %t, BlockGenerated: %t, ",
ctx.State.HasFlag(Initial),
ctx.State.HasFlag(Primary),
ctx.State.HasFlag(Backup),
ctx.State.HasFlag(RequestSent),
ctx.State.HasFlag(RequestReceived),
ctx.State.HasFlag(SignatureSent),
ctx.State.HasFlag(BlockGenerated))
}
func (ctx *ConsensusContext) Reset(bkAccount *account.Account) {
preHash := ledger.DefLedger.GetCurrentBlockHash()
height := ledger.DefLedger.GetCurrentBlockHeight()
header := ctx.MakeHeader()
if height != ctx.Height || header == nil || header.Hash() != preHash || len(ctx.NextBookkeepers) == 0 {
log.Info("[ConsensusContext] Calculate Bookkeepers from db")
var err error
ctx.Bookkeepers, err = vote.GetValidators([]*types.Transaction{})
if err != nil {
log.Error("[ConsensusContext] GetNextBookkeeper failed", err)
}
} else {
ctx.Bookkeepers = ctx.NextBookkeepers
}
ctx.State = Initial
ctx.PrevHash = preHash
ctx.Height = height + 1
ctx.ViewNumber = 0
ctx.BookkeeperIndex = -1
ctx.NextBookkeepers = nil
bookkeeperLen := len(ctx.Bookkeepers)
ctx.PrimaryIndex = ctx.Height % uint32(bookkeeperLen)
ctx.Transactions = nil
ctx.header = nil
ctx.Signatures = make([][]byte, bookkeeperLen)
ctx.ExpectedView = make([]byte, bookkeeperLen)
log.Debugf("bookkeepers number: %d", bookkeeperLen)
for i := 0; i < bookkeeperLen; i++ {
if keypair.ComparePublicKey(bkAccount.PublicKey, ctx.Bookkeepers[i]) {
log.Debugf("this node is bookkeeper %d", i)
ctx.BookkeeperIndex = i
ctx.Owner = ctx.Bookkeepers[i]
break
}
}
}