aboutsummaryrefslogtreecommitdiffstats
path: root/core/consensus_test.go
blob: cd7ff02332e995e1158afbf5f9073fb5ccf52ed0 (plain) (blame)
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
// Copyright 2018 The dexon-consensus-core Authors
// This file is part of the dexon-consensus-core library.
//
// The dexon-consensus-core library 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 dexon-consensus-core library 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 dexon-consensus-core library. If not, see
// <http://www.gnu.org/licenses/>.

package core

import (
    "sort"
    "testing"
    "time"

    "github.com/dexon-foundation/dexon-consensus-core/blockdb"
    "github.com/dexon-foundation/dexon-consensus-core/common"
    "github.com/dexon-foundation/dexon-consensus-core/core/test"
    "github.com/dexon-foundation/dexon-consensus-core/core/types"
    "github.com/dexon-foundation/dexon-consensus-core/crypto/eth"
    "github.com/stretchr/testify/suite"
)

type ConsensusTestSuite struct {
    suite.Suite
}

func (s *ConsensusTestSuite) prepareGenesisBlock(
    proposerID types.ValidatorID,
    con *Consensus) *types.Block {

    block := &types.Block{
        ProposerID: proposerID,
    }
    err := con.PrepareGenesisBlock(block, time.Now().UTC())
    s.Require().Nil(err)
    return block
}

func (s *ConsensusTestSuite) prepareConsensus(
    gov *test.Governance, vID types.ValidatorID) (*Application, *Consensus) {

    app := test.NewApp()
    db, err := blockdb.NewMemBackedBlockDB()
    s.Require().Nil(err)
    prv, exist := gov.PrivateKeys[vID]
    s.Require().True(exist)
    con := NewConsensus(app, gov, db, prv, eth.SigToPub)
    return &con.app, con
}

func (s *ConsensusTestSuite) TestSimpleDeliverBlock() {
    // This test scenario:
    // o o o o <- this layer makes older blocks strongly acked.
    // |x|x|x| <- lots of acks.
    // o | o o <- this layer would be sent to total ordering.
    // |\|/|-|
    // | o | | <- the only block which is acked by all other blocks
    // |/|\|\|    at the same height.
    // o o o o <- genesis blocks
    // 0 1 2 3 <- index of validator ID
    //
    // This test case only works for Total Ordering with K=0.
    var (
        minInterval = 50 * time.Millisecond
        gov, err    = test.NewGovernance(4, 1000)
        req         = s.Require()
        validators  []types.ValidatorID
    )
    s.Require().Nil(err)

    for vID := range gov.GetValidatorSet() {
        validators = append(validators, vID)
    }

    // Setup core.Consensus and test.App.
    objs := map[types.ValidatorID]*struct {
        app *Application
        con *Consensus
    }{}
    for _, vID := range validators {
        app, con := s.prepareConsensus(gov, vID)
        objs[vID] = &struct {
            app *Application
            con *Consensus
        }{app, con}
    }
    // It's a helper function to emit one block
    // to all core.Consensus objects.
    broadcast := func(b *types.Block) {
        for _, obj := range objs {
            req.Nil(obj.con.ProcessBlock(b))
        }
    }
    // Genesis blocks
    b00 := s.prepareGenesisBlock(validators[0], objs[validators[0]].con)
    time.Sleep(minInterval)
    b10 := s.prepareGenesisBlock(validators[1], objs[validators[1]].con)
    time.Sleep(minInterval)
    b20 := s.prepareGenesisBlock(validators[2], objs[validators[2]].con)
    time.Sleep(minInterval)
    b30 := s.prepareGenesisBlock(validators[3], objs[validators[3]].con)
    broadcast(b00)
    broadcast(b10)
    broadcast(b20)
    broadcast(b30)
    // Setup b11.
    time.Sleep(minInterval)
    b11 := &types.Block{
        ProposerID: validators[1],
    }
    b11.Hash, err = hashBlock(b11)
    s.Require().Nil(err)
    req.Nil(objs[validators[1]].con.PrepareBlock(b11, time.Now().UTC()))
    req.Len(b11.Acks, 4)
    req.Contains(b11.Acks, b00.Hash)
    req.Contains(b11.Acks, b10.Hash)
    req.Contains(b11.Acks, b20.Hash)
    req.Contains(b11.Acks, b30.Hash)
    broadcast(b11)
    // Setup b01.
    time.Sleep(minInterval)
    b01 := &types.Block{
        ProposerID: validators[0],
        Hash:       common.NewRandomHash(),
    }
    req.Nil(objs[validators[0]].con.PrepareBlock(b01, time.Now().UTC()))
    req.Len(b01.Acks, 4)
    req.Contains(b01.Acks, b11.Hash)
    // Setup b21.
    time.Sleep(minInterval)
    b21 := &types.Block{
        ProposerID: validators[2],
        Hash:       common.NewRandomHash(),
    }
    req.Nil(objs[validators[2]].con.PrepareBlock(b21, time.Now().UTC()))
    req.Len(b21.Acks, 4)
    req.Contains(b21.Acks, b11.Hash)
    // Setup b31.
    time.Sleep(minInterval)
    b31 := &types.Block{
        ProposerID: validators[3],
        Hash:       common.NewRandomHash(),
    }
    req.Nil(objs[validators[3]].con.PrepareBlock(b31, time.Now().UTC()))
    req.Len(b31.Acks, 4)
    req.Contains(b31.Acks, b11.Hash)
    // Broadcast other height=1 blocks.
    broadcast(b01)
    broadcast(b21)
    broadcast(b31)
    // Setup height=2 blocks.
    // Setup b02.
    time.Sleep(minInterval)
    b02 := &types.Block{
        ProposerID: validators[0],
        Hash:       common.NewRandomHash(),
    }
    req.Nil(objs[validators[0]].con.PrepareBlock(b02, time.Now().UTC()))
    req.Len(b02.Acks, 3)
    req.Contains(b02.Acks, b01.Hash)
    req.Contains(b02.Acks, b21.Hash)
    req.Contains(b02.Acks, b31.Hash)
    // Setup b12.
    time.Sleep(minInterval)
    b12 := &types.Block{
        ProposerID: validators[1],
        Hash:       common.NewRandomHash(),
    }
    req.Nil(objs[validators[1]].con.PrepareBlock(b12, time.Now().UTC()))
    req.Len(b12.Acks, 4)
    req.Contains(b12.Acks, b01.Hash)
    req.Contains(b12.Acks, b11.Hash)
    req.Contains(b12.Acks, b21.Hash)
    req.Contains(b12.Acks, b31.Hash)
    // Setup b22.
    time.Sleep(minInterval)
    b22 := &types.Block{
        ProposerID: validators[2],
        Hash:       common.NewRandomHash(),
    }
    req.Nil(objs[validators[2]].con.PrepareBlock(b22, time.Now().UTC()))
    req.Len(b22.Acks, 3)
    req.Contains(b22.Acks, b01.Hash)
    req.Contains(b22.Acks, b21.Hash)
    req.Contains(b22.Acks, b31.Hash)
    // Setup b32.
    time.Sleep(minInterval)
    b32 := &types.Block{
        ProposerID: validators[3],
        Hash:       common.NewRandomHash(),
    }
    req.Nil(objs[validators[3]].con.PrepareBlock(b32, time.Now().UTC()))
    req.Len(b32.Acks, 3)
    req.Contains(b32.Acks, b01.Hash)
    req.Contains(b32.Acks, b21.Hash)
    req.Contains(b32.Acks, b31.Hash)
    // Broadcast blocks at height=2.
    broadcast(b02)
    broadcast(b12)
    broadcast(b22)
    broadcast(b32)

    // Verify the cached status of each app.
    verify := func(app *test.App) {
        // Check blocks that are strongly acked.
        req.Contains(app.Acked, b00.Hash)
        req.Contains(app.Acked, b10.Hash)
        req.Contains(app.Acked, b20.Hash)
        req.Contains(app.Acked, b30.Hash)
        req.Contains(app.Acked, b01.Hash)
        req.Contains(app.Acked, b11.Hash)
        req.Contains(app.Acked, b21.Hash)
        req.Contains(app.Acked, b31.Hash)
        // Genesis blocks are delivered by total ordering as a set.
        delivered0 := common.Hashes{b00.Hash, b10.Hash, b20.Hash, b30.Hash}
        sort.Sort(delivered0)
        req.Len(app.TotalOrdered, 2)
        req.Equal(app.TotalOrdered[0].BlockHashes, delivered0)
        req.False(app.TotalOrdered[0].Early)
        // b11 is the sencond set delivered by total ordering.
        delivered1 := common.Hashes{b11.Hash}
        sort.Sort(delivered1)
        req.Equal(app.TotalOrdered[1].BlockHashes, delivered1)
        req.False(app.TotalOrdered[1].Early)
        // Check generated timestamps.
        req.Contains(app.Delivered, b00.Hash)
        req.Contains(app.Delivered, b10.Hash)
        req.Contains(app.Delivered, b20.Hash)
        req.Contains(app.Delivered, b30.Hash)
        req.Contains(app.Delivered, b11.Hash)
        // Check timestamps, there is no direct way to know which block is
        // selected as main chain, we can only detect it by making sure
        // its ConsensusTimestamp is not interpolated.
        t, err := getMedianTime(b11)
        req.Nil(err)
        req.Equal(t, app.Delivered[b11.Hash].ConsensusTime)
    }
    for _, obj := range objs {
        app := *obj.app
        if nbapp, ok := app.(*nonBlockingApplication); ok {
            nbapp.wait()
            app = nbapp.app
        }
        testApp, ok := app.(*test.App)
        s.Require().True(ok)
        verify(testApp)
    }
}

func (s *ConsensusTestSuite) TestPrepareBlock() {
    // This test case would test these steps:
    //  - Add all genesis blocks into lattice.
    //  - Make sure Consensus.PrepareBlock would attempt to ack
    //    all genesis blocks.
    //  - Add the prepared block into lattice.
    //  - Make sure Consensus.PrepareBlock would only attempt to
    //    ack the prepared block.
    var (
        gov, err   = test.NewGovernance(4, 1000)
        req        = s.Require()
        validators []types.ValidatorID
    )
    s.Require().Nil(err)
    for vID := range gov.GetValidatorSet() {
        validators = append(validators, vID)
    }
    // Setup core.Consensus and test.App.
    objs := map[types.ValidatorID]*struct {
        app *Application
        con *Consensus
    }{}
    for _, vID := range validators {
        app, con := s.prepareConsensus(gov, vID)
        objs[vID] = &struct {
            app *Application
            con *Consensus
        }{app, con}
    }
    b00 := s.prepareGenesisBlock(validators[0], objs[validators[0]].con)
    b10 := s.prepareGenesisBlock(validators[1], objs[validators[1]].con)
    b20 := s.prepareGenesisBlock(validators[2], objs[validators[2]].con)
    b30 := s.prepareGenesisBlock(validators[3], objs[validators[3]].con)
    for _, obj := range objs {
        con := obj.con
        req.Nil(con.ProcessBlock(b00))
        req.Nil(con.ProcessBlock(b10))
        req.Nil(con.ProcessBlock(b20))
        req.Nil(con.ProcessBlock(b30))
    }
    b11 := &types.Block{
        ProposerID: validators[1],
    }
    // Sleep to make sure 'now' is slower than b10's timestamp.
    time.Sleep(100 * time.Millisecond)
    req.Nil(objs[validators[1]].con.PrepareBlock(b11, time.Now().UTC()))
    // Make sure we would assign 'now' to the timestamp belongs to
    // the proposer.
    req.True(
        b11.Timestamps[validators[1]].Sub(
            b10.Timestamps[validators[1]]) > 100*time.Millisecond)
    for _, obj := range objs {
        con := obj.con
        req.Nil(con.ProcessBlock(b11))
    }
    b12 := &types.Block{
        ProposerID: validators[1],
    }
    req.Nil(objs[validators[1]].con.PrepareBlock(b12, time.Now().UTC()))
    req.Len(b12.Acks, 1)
    req.Contains(b12.Acks, b11.Hash)
}

func (s *ConsensusTestSuite) TestPrepareGenesisBlock() {
    var (
        gov, err   = test.NewGovernance(4, 1000)
        validators []types.ValidatorID
    )
    s.Require().Nil(err)
    for vID := range gov.GetValidatorSet() {
        validators = append(validators, vID)
    }
    _, con := s.prepareConsensus(gov, validators[0])
    block := &types.Block{
        ProposerID: validators[0],
    }
    con.PrepareGenesisBlock(block, time.Now().UTC())
    s.True(block.IsGenesis())
    s.Nil(con.sanityCheck(block))
}

func TestConsensus(t *testing.T) {
    suite.Run(t, new(ConsensusTestSuite))
}