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

package test

import (
    "sort"
    "testing"
    "time"

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

type BlocksGeneratorTestSuite struct {
    suite.Suite
}

func (s *BlocksGeneratorTestSuite) TestGenerate() {
    // This test case is to make sure the generated blocks are legimate.
    var (
        config = &BlocksGeneratorConfig{
            NumChains:            19,
            MinBlockTimeInterval: 200 * time.Millisecond,
        }
        gen       = NewBlocksGenerator(config, nil, stableRandomHash)
        req       = s.Require()
        beginTime = time.Now().UTC()
        endTime   = beginTime.Add(time.Minute)
    )
    db, err := blockdb.NewMemBackedBlockDB()
    req.NoError(err)
    req.NoError(gen.Generate(1, beginTime, endTime, db))
    // Load all blocks in that database for further checking.
    iter, err := db.GetAll()
    req.NoError(err)
    blocksByChain := make(map[uint32][]*types.Block)
    blocksByHash := make(map[common.Hash]*types.Block)
    for {
        block, err := iter.Next()
        if err == blockdb.ErrIterationFinished {
            break
        }
        req.NoError(err)
        // TODO(mission): Make sure each block is correctly signed once
        //                we have a way to access core.hashBlock.
        req.NotEqual(block.Hash, common.Hash{})
        if !block.IsEmpty() {
            req.NotEmpty(block.Signature)
        }
        req.Equal(block.Position.Round, uint64(1))
        blocksByChain[block.Position.ChainID] =
            append(blocksByChain[block.Position.ChainID], &block)
        sort.Sort(types.ByPosition(blocksByChain[block.Position.ChainID]))
        blocksByHash[block.Hash] = &block
    }
    // Make sure these two rules are hold for these blocks:
    //  - No backward acking: the later block should only ack new blocks
    //                        compared to its parent block.
    //  - Parent Ack: always ack its parent block.
    //  - Timestamp: timestamp are increasing, and with valid interval to
    //               previous block.
    //  - The last block of each chain should pass endTime.
    //  - No Acks in genesis bloc
    for _, blocks := range blocksByChain {
        lastAckingHeights := map[uint32]uint64{}
        req.NotEmpty(blocks)
        // Check genesis block.
        genesisBlock := blocks[0]
        req.Equal(genesisBlock.ParentHash, common.Hash{})
        req.Equal(genesisBlock.Position.Height, uint64(0))
        req.Empty(genesisBlock.Acks)
        // Check normal blocks.
        for index, block := range blocks[1:] {
            parentAcked := false
            for _, ack := range block.Acks {
                if ack == block.ParentHash {
                    parentAcked = true
                }
                ackedBlock := blocksByHash[ack]
                req.NotNil(ackedBlock)
                prevAckingHeight, exists :=
                    lastAckingHeights[ackedBlock.Position.ChainID]
                if exists {
                    s.True(prevAckingHeight < ackedBlock.Position.Height)
                }
                lastAckingHeights[ackedBlock.Position.ChainID] =
                    ackedBlock.Position.Height
                // Block Height should always incremental by 1.
                //
                // Because we iterate blocks slice from 1,
                // we need to add 1 to the index.
                req.Equal(block.Position.Height, uint64(index+1))
            }
            req.True(parentAcked)
        }
        // The block time of the last block should be after end time.
        req.True(blocks[len(blocks)-1].Timestamp.After(endTime))
    }
}

func (s *BlocksGeneratorTestSuite) TestGenerateWithMaxAckCount() {
    var (
        config = &BlocksGeneratorConfig{
            NumChains:            13,
            MinBlockTimeInterval: 250 * time.Millisecond,
        }
        req              = s.Require()
        totalAckingCount = 0
        totalBlockCount  = 0
        genesisTime      = time.Now().UTC()
    )
    // Generate with 0 acks.
    db, err := blockdb.NewMemBackedBlockDB()
    req.NoError(err)
    gen := NewBlocksGenerator(
        config, MaxAckingCountGenerator(0), stableRandomHash)
    req.NoError(gen.Generate(
        0,
        genesisTime,
        genesisTime.Add(50*time.Second),
        db))
    // Load blocks to check their acking count.
    iter, err := db.GetAll()
    req.NoError(err)
    for {
        block, err := iter.Next()
        if err == blockdb.ErrIterationFinished {
            break
        }
        req.NoError(err)
        if block.IsGenesis() {
            continue
        }
        req.Len(block.Acks, 1)
    }
    // Generate with acks as many as possible.
    db, err = blockdb.NewMemBackedBlockDB()
    req.NoError(err)
    gen = NewBlocksGenerator(
        config, MaxAckingCountGenerator(config.NumChains), stableRandomHash)
    req.NoError(gen.Generate(
        0,
        genesisTime,
        genesisTime.Add(50*time.Second),
        db))
    // Load blocks to verify the average acking count.
    iter, err = db.GetAll()
    req.NoError(err)
    for {
        block, err := iter.Next()
        if err == blockdb.ErrIterationFinished {
            break
        }
        req.NoError(err)
        if block.IsGenesis() {
            continue
        }
        totalAckingCount += len(block.Acks)
        totalBlockCount++
    }
    req.NotZero(totalBlockCount)
    req.True((totalAckingCount / totalBlockCount) >= int(config.NumChains/2))
}

// TestFindTips make sure findTips works as expected.
func (s *BlocksGeneratorTestSuite) TestFindTips() {
    var (
        config = &BlocksGeneratorConfig{
            NumChains:            10,
            MinBlockTimeInterval: 250 * time.Millisecond,
        }
        req         = s.Require()
        genesisTime = time.Now().UTC()
        endTime     = genesisTime.Add(100 * time.Second)
    )
    gen := NewBlocksGenerator(config, nil, stableRandomHash)
    db, err := blockdb.NewMemBackedBlockDB()
    req.NoError(err)
    req.NoError(gen.Generate(
        0,
        genesisTime,
        endTime,
        db))
    tips, err := gen.findTips(0, db)
    req.NoError(err)
    req.Len(tips, int(config.NumChains))
    for _, b := range tips {
        req.True(b.Timestamp.After(endTime))
    }
}

func (s *BlocksGeneratorTestSuite) TestConcateBlocksFromRounds() {
    // This test case run these steps:
    //  - generate blocks by round but sharing one blockdb.
    //  - if those rounds are continuous, they should be concated.
    var (
        req         = s.Require()
        genesisTime = time.Now().UTC()
    )
    db, err := blockdb.NewMemBackedBlockDB()
    req.NoError(err)
    // Generate round 0 blocks.
    gen := NewBlocksGenerator(&BlocksGeneratorConfig{
        NumChains:            4,
        MinBlockTimeInterval: 250 * time.Millisecond,
    }, nil, stableRandomHash)
    req.NoError(gen.Generate(
        0,
        genesisTime,
        genesisTime.Add(10*time.Second),
        db))
    tips0, err := gen.findTips(0, db)
    req.NoError(err)
    req.Len(tips0, 4)
    // Generate round 1 blocks.
    gen = NewBlocksGenerator(&BlocksGeneratorConfig{
        NumChains:            10,
        MinBlockTimeInterval: 250 * time.Millisecond,
    }, nil, stableRandomHash)
    req.NoError(gen.Generate(
        1,
        genesisTime.Add(10*time.Second),
        genesisTime.Add(20*time.Second),
        db))
    tips1, err := gen.findTips(1, db)
    req.NoError(err)
    req.Len(tips1, 10)
    // Generate round 2 blocks.
    gen = NewBlocksGenerator(&BlocksGeneratorConfig{
        NumChains:            7,
        MinBlockTimeInterval: 250 * time.Millisecond,
    }, nil, stableRandomHash)
    req.NoError(gen.Generate(
        2,
        genesisTime.Add(20*time.Second),
        genesisTime.Add(30*time.Second),
        db))
    tips2, err := gen.findTips(2, db)
    req.NoError(err)
    req.Len(tips2, 7)
    // Check results, make sure tips0, tips1 are acked by correct blocks.
    iter, err := db.GetAll()
    req.NoError(err)
    revealer, err := NewRandomRevealer(iter)
    req.NoError(err)
    removeTip := func(tips map[uint32]*types.Block, b *types.Block) {
        toRemove := []uint32{}
        for chainID, tip := range tips {
            if b.ParentHash == tip.Hash {
                req.Equal(b.Position.Height, tip.Position.Height+1)
                req.Equal(b.Position.Round, tip.Position.Round+1)
                req.True(b.IsAcking(tip.Hash))
                toRemove = append(toRemove, chainID)
            }
        }
        for _, ID := range toRemove {
            delete(tips, ID)
        }
    }
    // Make sure all tips are acked by loading blocks from db
    // and check them one by one.
    for {
        b, err := revealer.Next()
        if err != nil {
            if err == blockdb.ErrIterationFinished {
                err = nil
                break
            }
            req.NoError(err)
        }
        switch b.Position.Round {
        case 1:
            removeTip(tips0, &b)
        case 2:
            removeTip(tips1, &b)
        }
    }
    req.Empty(tips0)
    req.Len(tips1, 3)
    req.Contains(tips1, uint32(7))
    req.Contains(tips1, uint32(8))
    req.Contains(tips1, uint32(9))
    // Check the acking frequency of last round, it might be wrong.
    totalBlockCount := 0
    totalAckCount := 0
    revealer.Reset()
    for {
        b, err := revealer.Next()
        if err != nil {
            if err == blockdb.ErrIterationFinished {
                err = nil
                break
            }
            req.NoError(err)
        }
        if b.Position.Round != 2 {
            continue
        }
        totalBlockCount++
        totalAckCount += len(b.Acks)
    }
    // At least all blocks can ack some non-parent block.
    req.True(totalAckCount/totalBlockCount >= 2)
}

func TestBlocksGenerator(t *testing.T) {
    suite.Run(t, new(BlocksGeneratorTestSuite))
}