-
Notifications
You must be signed in to change notification settings - Fork 211
/
multi_node.go
328 lines (282 loc) · 9.25 KB
/
multi_node.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package node
import (
"github.com/spacemeshos/go-spacemesh/activation"
"github.com/spacemeshos/go-spacemesh/amcl"
"github.com/spacemeshos/go-spacemesh/amcl/BLS381"
"github.com/spacemeshos/go-spacemesh/api"
"github.com/spacemeshos/go-spacemesh/collector"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/common/util"
"github.com/spacemeshos/go-spacemesh/config"
"github.com/spacemeshos/go-spacemesh/eligibility"
"github.com/spacemeshos/go-spacemesh/events"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/oracle"
"github.com/spacemeshos/go-spacemesh/p2p/service"
"github.com/spacemeshos/go-spacemesh/signing"
"github.com/spacemeshos/go-spacemesh/timesync"
"strconv"
"sync"
"time"
)
type ManualClock struct {
subs map[timesync.LayerTimer]struct{}
layerChannels map[types.LayerID]chan struct{}
m sync.Mutex
currentLayer types.LayerID
genesisTime time.Time
}
// LayerToTime returns the time of the provided layer
func (lc ManualClock) LayerToTime(id types.LayerID) time.Time {
return time.Now().Add(1000 * time.Hour) //hack so this wont take affect in the mock
}
func NewManualClock(genesisTime time.Time) *ManualClock {
t := &ManualClock{
subs: make(map[timesync.LayerTimer]struct{}),
layerChannels: make(map[types.LayerID]chan struct{}),
currentLayer: 0, // genesis
genesisTime: genesisTime,
}
return t
}
func (t *ManualClock) Unsubscribe(ch timesync.LayerTimer) {
t.m.Lock()
delete(t.subs, ch)
t.m.Unlock()
}
func (t *ManualClock) StartNotifying() {
}
var closedChannel chan struct{}
func init() {
closedChannel = make(chan struct{})
close(closedChannel)
}
func (t *ManualClock) AwaitLayer(layerId types.LayerID) chan struct{} {
t.m.Lock()
defer t.m.Unlock()
if layerId <= t.currentLayer {
return closedChannel
}
if ch, found := t.layerChannels[layerId]; found {
return ch
}
ch := make(chan struct{})
t.layerChannels[layerId] = ch
return ch
}
func (t *ManualClock) Subscribe() timesync.LayerTimer {
ch := make(timesync.LayerTimer)
t.m.Lock()
t.subs[ch] = struct{}{}
t.m.Unlock()
return ch
}
func (t *ManualClock) Tick() {
t.m.Lock()
defer t.m.Unlock()
t.currentLayer++
if ch, found := t.layerChannels[t.currentLayer]; found {
close(ch)
delete(t.layerChannels, t.currentLayer)
}
for s := range t.subs {
s <- t.currentLayer
}
}
func (t ManualClock) GetCurrentLayer() types.LayerID {
t.m.Lock()
defer t.m.Unlock()
return t.currentLayer
}
func (t ManualClock) GetGenesisTime() time.Time {
t.m.Lock()
defer t.m.Unlock()
return t.genesisTime
}
func (t ManualClock) Close() {
}
func getTestDefaultConfig() *config.Config {
cfg, err := LoadConfigFromFile()
if err != nil {
log.Error("cannot load config from file")
}
cfg.POST = activation.DefaultConfig()
cfg.POST.Difficulty = 5
cfg.POST.NumProvenLabels = 10
cfg.POST.SpacePerUnit = 1 << 10 // 1KB.
cfg.POST.NumFiles = 1
cfg.HARE.N = 5
cfg.HARE.F = 2
cfg.HARE.RoundDuration = 3
cfg.HARE.WakeupDelta = 5
cfg.HARE.ExpectedLeaders = 5
cfg.HARE.SuperHare = true
cfg.LayerAvgSize = 5
cfg.LayersPerEpoch = 3
cfg.Hdist = 5
cfg.LayerDurationSec = 20
cfg.HareEligibility.ConfidenceParam = 4
cfg.HareEligibility.EpochOffset = 0
cfg.StartMining = true
cfg.SyncRequestTimeout = 2000
cfg.SyncInterval = 2
cfg.SyncValidationDelta = 5
return cfg
}
// ActivateGrpcServer starts a grpc server on the provided node
func ActivateGrpcServer(smApp *SpacemeshApp) {
smApp.Config.API.StartGrpcServer = true
layerDuration := smApp.Config.LayerDurationSec
smApp.grpcAPIService = api.NewGrpcService(smApp.Config.API.GrpcServerPort, smApp.P2P, smApp.state, smApp.mesh, smApp.txPool, smApp.atxBuilder, smApp.oracle, smApp.clock, nil, layerDuration, nil, nil, nil)
smApp.grpcAPIService.StartService()
}
// GracefulShutdown stops the current services running in apps
func GracefulShutdown(apps []*SpacemeshApp) {
log.Info("Graceful shutdown begin")
var wg sync.WaitGroup
for _, app := range apps {
wg.Add(1)
go func(app *SpacemeshApp) {
app.stopServices()
wg.Done()
}(app)
}
wg.Wait()
log.Info("Graceful shutdown end")
}
type Network interface {
NewNode() *service.Node
}
//initialize a network mock object to simulate network between nodes.
//var net = service.NewSimulator()
// InitSingleInstance initializes a node instance with given
// configuration and parameters, it does not stop the instance.
func InitSingleInstance(cfg config.Config, i int, genesisTime string, rng *amcl.RAND, storePath string, rolacle *eligibility.FixedRolacle, poetClient *activation.HTTPPoetClient, fastHare bool, clock TickProvider, net Network) (*SpacemeshApp, error) {
smApp := NewSpacemeshApp()
smApp.Config = &cfg
smApp.Config.CoinbaseAccount = strconv.Itoa(i + 1)
smApp.Config.GenesisTime = genesisTime
edSgn := signing.NewEdSigner()
pub := edSgn.PublicKey()
vrfPriv, vrfPub := BLS381.GenKeyPair(rng)
vrfSigner := BLS381.NewBlsSigner(vrfPriv)
nodeID := types.NodeId{Key: pub.String(), VRFPublicKey: vrfPub}
swarm := net.NewNode()
dbStorepath := storePath
hareOracle := oracle.NewLocalOracle(rolacle, 5, nodeID)
hareOracle.Register(true, pub.String())
postClient, err := activation.NewPostClient(&smApp.Config.POST, util.Hex2Bytes(nodeID.Key))
if err != nil {
return nil, err
}
err = smApp.initServices(nodeID, swarm, dbStorepath, edSgn, false, hareOracle, uint32(smApp.Config.LayerAvgSize), postClient, poetClient, vrfSigner, uint16(smApp.Config.LayersPerEpoch), clock)
if err != nil {
return nil, err
}
return smApp, err
}
// Starts the run of a number of nodes, running in process consensus between them.
// this also runs a single transaction between the nodes.
func StartMultiNode(numOfinstances, layerAvgSize int, runTillLayer uint32, dbPath string) {
cfg := getTestDefaultConfig()
cfg.LayerAvgSize = layerAvgSize
numOfInstances := numOfinstances
net := service.NewSimulator()
path := dbPath + time.Now().Format(time.RFC3339)
genesisTime := time.Now().Add(20 * time.Second).Format(time.RFC3339)
poetHarness, err := activation.NewHTTPPoetHarness(false)
if err != nil {
log.Panic("failed creating poet client harness: %v", err)
}
defer poetHarness.Teardown(true)
rolacle := eligibility.New()
rng := BLS381.DefaultSeed()
gTime, err := time.Parse(time.RFC3339, genesisTime)
if err != nil {
log.Error("cannot parse genesis time %v", err)
}
pubsubAddr := "tcp://localhost:56565"
events.InitializeEventPubsub(pubsubAddr)
clock := NewManualClock(gTime)
apps := make([]*SpacemeshApp, 0, numOfInstances)
name := 'a'
for i := 0; i < numOfInstances; i++ {
dbStorepath := path + string(name)
smApp, err := InitSingleInstance(*cfg, i, genesisTime, rng, dbStorepath, rolacle, poetHarness.HTTPPoetClient, true, clock, net)
if err != nil {
log.Error("cannot run multi node %v", err)
return
}
apps = append(apps, smApp)
name++
}
eventDb := collector.NewMemoryCollector()
collect := collector.NewCollector(eventDb, pubsubAddr)
for _, a := range apps {
a.startServices()
}
collect.Start(false)
ActivateGrpcServer(apps[0])
if err := poetHarness.Start([]string{"127.0.0.1:9091"}); err != nil {
log.Panic("failed to start poet server: %v", err)
}
//startInLayer := 5 // delayed pod will start in this layer
defer GracefulShutdown(apps)
timeout := time.After(time.Duration(runTillLayer*60) * time.Second)
//stickyClientsDone := 0
startLayer := time.Now()
clock.Tick()
errors := 0
loop:
for {
select {
// Got a timeout! fail with a timeout error
case <-timeout:
log.Panic("run timed out", err)
return
default:
if errors > 100 {
log.Panic("too many errors and retries")
break loop
}
layer := clock.GetCurrentLayer()
if eventDb.GetBlockCreationDone(layer) < numOfInstances {
log.Info("blocks done in layer %v: %v", layer, eventDb.GetBlockCreationDone(layer))
time.Sleep(500 * time.Millisecond)
errors++
continue
}
log.Info("all miners tried to create block in %v", layer)
if eventDb.GetNumOfCreatedBlocks(layer)*numOfInstances != eventDb.GetReceivedBlocks(layer) {
log.Info("finished: %v, block received %v layer %v", eventDb.GetNumOfCreatedBlocks(layer), eventDb.GetReceivedBlocks(layer), layer)
time.Sleep(500 * time.Millisecond)
errors++
continue
}
log.Info("all miners got blocks for layer: %v created: %v received: %v", layer, eventDb.GetNumOfCreatedBlocks(layer), eventDb.GetReceivedBlocks(layer))
epoch := layer.GetEpoch(uint16(cfg.LayersPerEpoch))
if !(eventDb.GetAtxCreationDone(epoch) >= numOfInstances && eventDb.GetAtxCreationDone(epoch)%numOfInstances == 0) {
log.Info("atx not created %v in epoch %v, created only %v atxs", numOfInstances-eventDb.GetAtxCreationDone(epoch), epoch, eventDb.GetAtxCreationDone(epoch))
time.Sleep(500 * time.Millisecond)
errors++
continue
}
log.Info("all miners finished reading %v atxs, layer %v done in %v", eventDb.GetAtxCreationDone(epoch), layer, time.Since(startLayer))
for _, atxId := range eventDb.GetCreatedAtx(epoch) {
if _, found := eventDb.Atxs[atxId]; !found {
log.Info("atx %v not propagated", atxId)
errors++
continue
}
}
errors = 0
startLayer = time.Now()
clock.Tick()
if apps[0].mesh.LatestLayer() >= types.LayerID(runTillLayer) {
break loop
}
time.Sleep(200 * time.Millisecond)
}
}
collect.Stop()
}