forked from hyperledger-labs/bdls-lab
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
305 lines (273 loc) · 6.74 KB
/
main.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package main
import (
"bytes"
"crypto/ecdsa"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/big"
"net"
"os"
"time"
"github.com/BDLS-bft/bdls"
"github.com/BDLS-bft/bdls/agent-tcp"
"github.com/BDLS-bft/bdls/crypto/blake2b"
"github.com/urfave/cli/v2"
)
// A quorum set for consenus
type Quorum struct {
Keys []*big.Int `json:"keys"` // pem formatted keys
}
func main() {
app := &cli.App{
Name: "BDLS consensus protocol emulator",
Usage: "Generate quorum then emulate participants",
EnableBashCompletion: true,
Commands: []*cli.Command{
{
Name: "genkeys",
Usage: "generate quorum to participant in consensus",
Flags: []cli.Flag{
&cli.IntFlag{
Name: "count",
Value: 4,
Usage: "number of participant in quorum",
},
&cli.StringFlag{
Name: "config",
Value: "./quorum.json",
Usage: "output quorum file",
},
&cli.IntFlag{
Name: "append",
Value: 0,
Usage: "append key to quorum file",
},
},
Action: func(c *cli.Context) error {
count := c.Int("count")
quorum := &Quorum{}
// generate private keys
for i := 0; i < count; i++ {
privateKey, err := ecdsa.GenerateKey(bdls.S256Curve, rand.Reader)
if err != nil {
return err
}
quorum.Keys = append(quorum.Keys, privateKey.D)
}
newKey := c.Int("append")
if newKey != 0 {
quorum := &Quorum{}
fileBytes, _ := os.ReadFile(c.String("config"))
err := json.Unmarshal(fileBytes, quorum)
if err != nil {
fmt.Println("JSON decode error!")
return err
}
// generate private keys
for i := 0; i < newKey; i++ {
privateKey, err := ecdsa.GenerateKey(bdls.S256Curve, rand.Reader)
if err != nil {
return err
}
quorum.Keys = append(quorum.Keys, privateKey.D)
}
existFile, err := os.Create(c.String("config"))
if err != nil {
return err
}
enc := json.NewEncoder(existFile)
enc.SetIndent("", "\t")
err = enc.Encode(quorum)
if err != nil {
return err
}
existFile.Close()
log.Println("generate", c.Int("append"), "keys")
return nil
}
file, err := os.Create(c.String("config"))
if err != nil {
return err
}
enc := json.NewEncoder(file)
enc.SetIndent("", "\t")
err = enc.Encode(quorum)
if err != nil {
return err
}
file.Close()
log.Println("generate", c.Int("count"), "keys")
return nil
},
},
{
Name: "run",
Usage: "start a consensus agent",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "listen",
Value: ":4680",
Usage: "the client's listening port",
},
&cli.IntFlag{
Name: "id",
Value: 0,
Usage: "the node id, will use the n-th private key in quorum.json",
},
&cli.StringFlag{
Name: "config",
Value: "./quorum.json",
Usage: "the shared quorum config file",
},
&cli.StringFlag{
Name: "peers",
Value: "./peers.json",
Usage: "all peers's ip:port list to connect, as a json array",
},
},
Action: func(c *cli.Context) error {
// open quorum config
file, err := os.Open(c.String("config"))
if err != nil {
return err
}
defer file.Close()
quorum := new(Quorum)
err = json.NewDecoder(file).Decode(quorum)
if err != nil {
return err
}
id := c.Int("id")
if id >= len(quorum.Keys) {
return errors.New(fmt.Sprint("cannot locate private key for id:", id))
}
log.Println("identity:", id)
// create configuration
config := new(bdls.Config)
config.Epoch = time.Now()
config.CurrentHeight = 0
config.StateCompare = func(a bdls.State, b bdls.State) int { return bytes.Compare(a, b) }
config.StateValidate = func(bdls.State) bool { return true }
for k := range quorum.Keys {
priv := new(ecdsa.PrivateKey)
priv.PublicKey.Curve = bdls.S256Curve
priv.D = quorum.Keys[k]
priv.PublicKey.X, priv.PublicKey.Y = bdls.S256Curve.ScalarBaseMult(priv.D.Bytes())
// myself
if id == k {
config.PrivateKey = priv
}
// set validator sequence
config.Participants = append(config.Participants, bdls.DefaultPubKeyToIdentity(&priv.PublicKey))
}
if err := startConsensus(c, config); err != nil {
return err
}
return nil
},
},
},
Action: func(c *cli.Context) error {
cli.ShowAppHelp(c)
return nil
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
// consensus for one round with full procedure
func startConsensus(c *cli.Context, config *bdls.Config) error {
// create consensus
consensus, err := bdls.NewConsensus(config)
if err != nil {
return err
}
consensus.SetLatency(200 * time.Millisecond)
// load endpoints
file, err := os.Open(c.String("peers"))
if err != nil {
return err
}
defer file.Close()
var peers []string
err = json.NewDecoder(file).Decode(&peers)
if err != nil {
return err
}
// start listener
tcpaddr, err := net.ResolveTCPAddr("tcp", c.String("listen"))
if err != nil {
return err
}
l, err := net.ListenTCP("tcp", tcpaddr)
if err != nil {
return err
}
defer l.Close()
log.Println("listening on:", c.String("listen"))
// initiate tcp agent
tagent := agent.NewTCPAgent(consensus, config.PrivateKey)
if err != nil {
return err
}
// start updater
tagent.Update()
// passive connection from peers
go func() {
for {
conn, err := l.Accept()
if err != nil {
return
}
log.Println("peer connected from:", conn.RemoteAddr())
// peer endpoint created
p := agent.NewTCPPeer(conn, tagent)
tagent.AddPeer(p)
// prove my identity to this peer
p.InitiatePublicKeyAuthentication()
}
}()
// active connections to peers
for k := range peers {
go func(raddr string) {
for {
conn, err := net.Dial("tcp", raddr)
if err == nil {
log.Println("connected to peer:", conn.RemoteAddr())
// peer endpoint created
p := agent.NewTCPPeer(conn, tagent)
tagent.AddPeer(p)
// prove my identity to this peer
p.InitiatePublicKeyAuthentication()
return
}
<-time.After(time.Second)
}
}(peers[k])
}
lastHeight := uint64(0)
NEXTHEIGHT:
for {
data := make([]byte, 1024)
io.ReadFull(rand.Reader, data)
tagent.Propose(data)
for {
newHeight, newRound, newState := tagent.GetLatestState()
if newHeight > lastHeight {
h := blake2b.Sum256(newState)
log.Printf("<decide> at height:%v round:%v hash:%v", newHeight, newRound, hex.EncodeToString(h[:]))
lastHeight = newHeight
continue NEXTHEIGHT
}
// wait
<-time.After(20 * time.Millisecond)
}
}
}