summaryrefslogtreecommitdiff
path: root/agreement/proposalTracker_test.go
blob: 885933df12461076d2f52cd96c28ef4abcd6c5e6 (plain)
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// Copyright (C) 2019-2024 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package agreement

import (
	"math/rand"
	"sort"
	"testing"

	"github.com/algorand/go-algorand/test/partitiontest"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func sortedVoteGen(t *testing.T) (votes []vote) {
	ledger, addresses, vrfs, ots := readOnlyFixture100()

	for i, addr := range addresses {
		pv := proposalValue{
			OriginalProposer: addr,
			BlockDigest:      randomBlockHash(),
			EncodingDigest:   randomBlockHash(),
		}
		rv := rawVote{Round: ledger.NextRound(), Sender: addr, Proposal: pv}
		uv, err := makeVote(rv, ots[i], vrfs[i], ledger)
		require.NoError(t, err)
		v, err := uv.verify(ledger)
		if err == nil {
			votes = append(votes, v)
		}
	}

	sort.Slice(votes, func(i, j int) bool {
		return votes[i].Cred.Less(votes[j].Cred)
	})

	return
}

func TestProposalTrackerProposalSeeker(t *testing.T) {
	partitiontest.PartitionTest(t)

	votes := sortedVoteGen(t)
	for len(votes) < 4 {
		votes = sortedVoteGen(t)
	}

	var s proposalSeeker
	var err error
	assert.False(t, s.Frozen)
	assert.False(t, s.Filled)
	assert.False(t, s.hasLowestIncludingLate)

	// issue events in the following order: 2, 3, 1, (freeze), 0
	var effect LateCredentialTrackingEffect
	s, effect, err = s.accept(votes[2])
	assert.NoError(t, err)
	assert.Equal(t, effect, VerifiedBetterLateCredentialForTracking)
	assert.False(t, s.Frozen)
	assert.True(t, s.Filled)
	assert.True(t, s.Lowest.equals(votes[2]))
	assert.True(t, s.hasLowestIncludingLate)
	assert.Equal(t, s.Lowest, s.lowestIncludingLate)

	s, effect, err = s.accept(votes[3])
	assert.Error(t, err)
	assert.Equal(t, effect, NoLateCredentialTrackingImpact)
	assert.False(t, s.Frozen)
	assert.True(t, s.Filled)
	assert.True(t, s.Lowest.equals(votes[2]))
	assert.True(t, s.hasLowestIncludingLate)
	assert.Equal(t, s.Lowest, s.lowestIncludingLate)

	s, effect, err = s.accept(votes[1])
	assert.NoError(t, err)
	assert.Equal(t, effect, VerifiedBetterLateCredentialForTracking)
	assert.False(t, s.Frozen)
	assert.True(t, s.Filled)
	assert.True(t, s.Lowest.equals(votes[1]))
	assert.True(t, s.hasLowestIncludingLate)
	assert.Equal(t, s.Lowest, s.lowestIncludingLate)

	lowestBeforeFreeze := s.Lowest
	s = s.freeze()
	assert.True(t, s.Frozen)
	assert.True(t, s.Filled)
	assert.True(t, s.Lowest.equals(votes[1]))
	assert.True(t, s.hasLowestIncludingLate)
	assert.Equal(t, s.Lowest, s.lowestIncludingLate)

	s, effect, err = s.accept(votes[0])
	assert.Error(t, err)
	assert.Equal(t, effect, VerifiedBetterLateCredentialForTracking)
	assert.Equal(t, s.Lowest, lowestBeforeFreeze)
	assert.True(t, s.Frozen)
	assert.True(t, s.Filled)
	assert.True(t, s.Lowest.equals(votes[1]))
	assert.True(t, s.hasLowestIncludingLate)
	assert.True(t, s.lowestIncludingLate.equals(votes[0]))
	assert.NotEqual(t, s.Lowest, s.lowestIncludingLate)
	assert.True(t, !s.Lowest.Cred.Less(s.lowestIncludingLate.Cred))
	assert.True(t, s.lowestIncludingLate.Cred.Less(s.Lowest.Cred))
}

// mimics a proposalTracker, producing a trace of events
type proposalTrackerTestShadow struct {
	// trace
	inputs  []event
	outputs []event

	// all votes seen
	seen map[vote]bool

	// running lowest
	lowest vote

	// frozen?
	frozen bool

	// frozen value
	leader proposalValue

	// staged?
	staged bool

	// staging value
	staging proposalValue

	// round and period (set on init)
	round  round
	period period
}

func makeProposalTrackerTestShadow(r round, p period) *proposalTrackerTestShadow {
	s := new(proposalTrackerTestShadow)
	s.seen = make(map[vote]bool)
	s.round = r
	s.period = p
	return s
}

func makeProposalTrackerZero() listener {
	return checkedListener{listener: new(proposalTracker), listenerContract: new(proposalTrackerContract)}
}

func (s *proposalTrackerTestShadow) execute(t *testing.T, errstr string) {
	testCase := determisticTraceTestCase{
		inputs:          s.inputs,
		expectedOutputs: s.outputs,
	}
	proposalTrackerAutomata := &ioAutomataConcrete{
		listener: makeProposalTrackerZero(),
	}
	res, err := testCase.Validate(proposalTrackerAutomata)
	require.NoError(t, err)

	if res == nil {
		return
	}
	div, ok := res.(errIOTraceDiverge)
	if ok {
		require.Equal(t, div.expected, div.actual, errstr)
	} else {
		require.NoErrorf(t, res, errstr)
	}
}

// assumes sender has not been seen yet
func (s *proposalTrackerTestShadow) addVote(v vote) {
	defer func() {
		// state updates
		s.seen[v] = true
		if s.lowest.R.Proposal == bottom || v.Cred.Less(s.lowest.Cred) {
			s.lowest = v
		}
	}()

	var req, res event
	round := v.R.Round
	period := v.R.Period
	sender := v.R.Sender

	// check seen before
	req = voteFilterRequestEvent{RawVote: v.R}
	res = filteredEvent{T: voteFiltered, Err: makeSerErr(errProposalTrackerSenderDup{Round: round, Period: period})}
	if !s.seen[v] {
		res = emptyEvent{}
	}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)

	// check staging
	req = stagingValueEvent{}
	res = stagingValueEvent{Proposal: s.staging}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)

	// deliver
	req = messageEvent{T: voteVerified, Input: message{Vote: v, UnauthenticatedVote: v.u()}}
	if s.seen[v] {
		res = filteredEvent{T: voteFiltered, Err: makeSerErr(errProposalTrackerSenderDup{Sender: sender, Round: round, Period: period})}
	} else if s.staged {
		res = filteredEvent{T: voteFiltered, Err: makeSerErr(errProposalTrackerStaged{})}
	} else if s.frozen {
		res = filteredEvent{T: voteFiltered, Err: makeSerErr(errProposalTrackerPS{Sub: errProposalSeekerFrozen{}})}
	} else if s.lowest.R.Proposal != bottom && !v.Cred.Less(s.lowest.Cred) {
		sub := errProposalSeekerNotLess{
			NewSender:    v.R.Sender,
			LowestSender: s.lowest.R.Sender,
		}
		res = filteredEvent{T: voteFiltered, Err: makeSerErr(errProposalTrackerPS{Sub: sub})}
	} else {
		res = proposalAcceptedEvent{Round: round, Period: period, Proposal: v.R.Proposal}
	}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)

	// check staging
	req = stagingValueEvent{}
	res = stagingValueEvent{Proposal: s.staging}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)

	// check seen after
	req = voteFilterRequestEvent{RawVote: v.R}
	res = filteredEvent{T: voteFiltered, Err: makeSerErr(errProposalTrackerSenderDup{Sender: sender, Round: round, Period: period})}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)
}

func (s *proposalTrackerTestShadow) freeze() {
	var req, res event

	// check staging
	req = stagingValueEvent{}
	res = stagingValueEvent{Proposal: s.staging}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)

	// freeze
	req = proposalFrozenEvent{}
	res = proposalFrozenEvent{Proposal: s.lowest.R.Proposal}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)
	s.frozen = true
	s.leader = s.lowest.R.Proposal

	// check staging
	req = stagingValueEvent{}
	res = stagingValueEvent{Proposal: s.staging}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)
}

func (s *proposalTrackerTestShadow) stage(pv proposalValue) {
	var req, res event

	// check staging
	req = stagingValueEvent{}
	res = stagingValueEvent{}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)

	// deliver soft threshold
	req = thresholdEvent{T: softThreshold, Proposal: pv}
	res = proposalAcceptedEvent{Round: s.round, Period: s.period, Proposal: pv}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)
	s.staged = true
	s.staging = pv

	// check staging
	req = stagingValueEvent{}
	res = stagingValueEvent{Proposal: pv}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)
}

func (s *proposalTrackerTestShadow) stageWithCert(pv proposalValue) {
	var req, res event

	// check staging
	req = stagingValueEvent{}
	res = stagingValueEvent{}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)

	// deliver cert threshold
	req = thresholdEvent{T: certThreshold, Proposal: pv}
	res = proposalAcceptedEvent{Round: s.round, Period: s.period, Proposal: pv}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)
	s.staged = true
	s.staging = pv

	// check staging
	req = stagingValueEvent{}
	res = stagingValueEvent{Proposal: pv}
	s.inputs = append(s.inputs, req)
	s.outputs = append(s.outputs, res)
}

// create many proposal-votes, sorted in increasing credential-order.
func setupProposalTrackerTests(t *testing.T) (votes []vote) {
	ledger, addrs, vrfs, ots := readOnlyFixture100()
	for i := range addrs {
		prop := proposalValue{
			OriginalPeriod:   0,
			OriginalProposer: addrs[i],
			BlockDigest:      randomBlockHash(),
			EncodingDigest:   randomBlockHash(),
		}

		rv := rawVote{
			Round:    ledger.NextRound(),
			Sender:   addrs[i],
			Proposal: prop,
		}

		uv, err := makeVote(rv, ots[i], vrfs[i], ledger)
		require.NoError(t, err)

		v, err := uv.verify(ledger)
		if err == nil {
			votes = append(votes, v)
		}
	}

	sort.Slice(votes, func(i, j int) bool {
		return votes[i].Cred.Less(votes[j].Cred)
	})

	return
}

func TestProposalTrackerBasic(t *testing.T) {
	partitiontest.PartitionTest(t)

	votes := setupProposalTrackerTests(t)
	for len(votes) <= 3 {
		votes = setupProposalTrackerTests(t)
	}

	divlow := len(votes) / 3
	divhigh := 2 * divlow

	highvotes := votes[divhigh:]
	rand.Shuffle(len(highvotes), func(i, j int) {
		highvotes[i], highvotes[j] = highvotes[j], highvotes[i]
	})
	midvotes := votes[divlow:divhigh]
	rand.Shuffle(len(midvotes), func(i, j int) {
		midvotes[i], midvotes[j] = midvotes[j], midvotes[i]
	})
	lowvotes := votes[:divlow]
	rand.Shuffle(len(lowvotes), func(i, j int) {
		lowvotes[i], lowvotes[j] = lowvotes[j], lowvotes[i]
	})

	highDelivery := func(shadow *proposalTrackerTestShadow, msg string) {
		for _, v := range highvotes {
			shadow.addVote(v)
		}
		shadow.execute(t, msg)
	}
	midDelivery := func(shadow *proposalTrackerTestShadow, msg string) {
		for _, v := range midvotes {
			shadow.addVote(v)
		}
		shadow.execute(t, msg)
	}
	lowDelivery := func(shadow *proposalTrackerTestShadow, msg string) {
		for _, v := range lowvotes {
			shadow.addVote(v)
		}
		shadow.execute(t, msg)
	}

	// TODO assert more things about the state outside of using the shadow
	t.Run("Synchronous", func(t *testing.T) {
		targetCert := lowvotes[0]
		shadow := makeProposalTrackerTestShadow(votes[0].R.Round, votes[0].R.Period)

		midDelivery(shadow, "failed to track votes properly at zero state")
		highDelivery(shadow, "failed to track votes properly at zero state")
		lowDelivery(shadow, "failed to track votes properly at zero state")

		shadow.freeze()
		shadow.execute(t, "failed to freeze machine properly")

		shadow.stage(targetCert.R.Proposal)
		shadow.execute(t, "failed to deliver soft threshold properly")

	})

	t.Run("MissedLeader", func(t *testing.T) {
		targetCert := midvotes[0]
		shadow := makeProposalTrackerTestShadow(votes[0].R.Round, votes[0].R.Period)

		highDelivery(shadow, "failed to track votes properly at zero state")

		shadow.freeze()
		shadow.execute(t, "failed to freeze machine properly")

		midDelivery(shadow, "failed to track votes properly at zero state after frozen (but not staged)")

		shadow.stage(targetCert.R.Proposal)
		shadow.execute(t, "failed to deliver soft threshold properly")

		lowDelivery(shadow, "failed to track votes properly after staged")
	})

	t.Run("LateStaging", func(t *testing.T) {
		targetCert := midvotes[0]
		shadow := makeProposalTrackerTestShadow(votes[0].R.Round, votes[0].R.Period)

		highDelivery(shadow, "failed to track votes properly at zero state")

		shadow.freeze()
		shadow.execute(t, "failed to freeze machine properly")

		midDelivery(shadow, "failed to track votes properly after frozen (but not staged)")

		shadow.stage(targetCert.R.Proposal)
		shadow.execute(t, "failed to deliver soft threshold properly")

		lowDelivery(shadow, "failed to track votes properly after staged")
	})

	t.Run("EarlyStaging", func(t *testing.T) {
		targetCert := midvotes[0]
		shadow := makeProposalTrackerTestShadow(votes[0].R.Round, votes[0].R.Period)

		shadow.stage(targetCert.R.Proposal)
		shadow.execute(t, "failed to deliver soft threshold properly")

		highDelivery(shadow, "failed to track votes after staged")

		shadow.freeze()
		shadow.execute(t, "failed to freeze machine properly")

		lowDelivery(shadow, "failed to track votes properly after staged")
		midDelivery(shadow, "failed to track votes properly after staged")
	})

	t.Run("EarlyStagingCert", func(t *testing.T) {
		targetCert := midvotes[0]
		shadow := makeProposalTrackerTestShadow(votes[0].R.Round, votes[0].R.Period)

		shadow.stageWithCert(targetCert.R.Proposal)
		shadow.execute(t, "failed to deliver cert threshold properly")

		highDelivery(shadow, "failed to track votes after staged")

		shadow.freeze()
		shadow.execute(t, "failed to freeze machine properly")

		lowDelivery(shadow, "failed to track votes properly after staged")
		midDelivery(shadow, "failed to track votes properly after staged")
	})

	t.Run("LateStagingCert", func(t *testing.T) {
		targetCert := midvotes[0]
		shadow := makeProposalTrackerTestShadow(votes[0].R.Round, votes[0].R.Period)

		highDelivery(shadow, "failed to track votes properly at zero state")

		shadow.freeze()
		shadow.execute(t, "failed to freeze machine properly")

		midDelivery(shadow, "failed to track votes properly after frozen (but not staged)")

		shadow.stageWithCert(targetCert.R.Proposal)
		shadow.execute(t, "failed to deliver soft threshold properly")

		lowDelivery(shadow, "failed to track votes properly after staged")
	})

	t.Run("SynchronousCert", func(t *testing.T) {
		targetCert := lowvotes[0]
		shadow := makeProposalTrackerTestShadow(votes[0].R.Round, votes[0].R.Period)

		midDelivery(shadow, "failed to track votes properly at zero state")
		highDelivery(shadow, "failed to track votes properly at zero state")
		lowDelivery(shadow, "failed to track votes properly at zero state")

		shadow.freeze()
		shadow.execute(t, "failed to freeze machine properly")

		shadow.stageWithCert(targetCert.R.Proposal)
		shadow.execute(t, "failed to deliver cert threshold properly")

	})

}

//   func TestProposalTrackerSenderSpam(t *testing.T) {
//   	votes := setupProposalTrackerTests(t)
//   }