aboutsummaryrefslogtreecommitdiffstats
path: root/eth/block_pool_test.go
blob: b50a314ead9d32f764f0bcb645d4d124f41173df (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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
package eth

import (
    "fmt"
    "log"
    "math/big"
    "os"
    "sync"
    "testing"
    "time"

    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/ethutil"
    ethlogger "github.com/ethereum/go-ethereum/logger"
    "github.com/ethereum/go-ethereum/pow"
)

const waitTimeout = 60 // seconds

var logsys = ethlogger.NewStdLogSystem(os.Stdout, log.LstdFlags, ethlogger.LogLevel(ethlogger.DebugLevel))

var ini = false

func logInit() {
    if !ini {
        ethlogger.AddLogSystem(logsys)
        ini = true
    }
}

// test helpers
func arrayEq(a, b []int) bool {
    if len(a) != len(b) {
        return false
    }
    for i := range a {
        if a[i] != b[i] {
            return false
        }
    }
    return true
}

type intToHash map[int][]byte

type hashToInt map[string]int

// hashPool is a test helper, that allows random hashes to be referred to by integers
type testHashPool struct {
    intToHash
    hashToInt
    lock sync.Mutex
}

func newHash(i int) []byte {
    return crypto.Sha3([]byte(string(i)))
}

func (self *testHashPool) indexesToHashes(indexes []int) (hashes [][]byte) {
    self.lock.Lock()
    defer self.lock.Unlock()
    for _, i := range indexes {
        hash, found := self.intToHash[i]
        if !found {
            hash = newHash(i)
            self.intToHash[i] = hash
            self.hashToInt[string(hash)] = i
        }
        hashes = append(hashes, hash)
    }
    return
}

func (self *testHashPool) hashesToIndexes(hashes [][]byte) (indexes []int) {
    self.lock.Lock()
    defer self.lock.Unlock()
    for _, hash := range hashes {
        i, found := self.hashToInt[string(hash)]
        if !found {
            i = -1
        }
        indexes = append(indexes, i)
    }
    return
}

// test blockChain is an integer trie
type blockChain map[int][]int

// blockPoolTester provides the interface between tests and a blockPool
//
// refBlockChain is used to guide which blocks will be accepted as valid
// blockChain gives the current state of the blockchain and
// accumulates inserts so that we can check the resulting chain
type blockPoolTester struct {
    hashPool      *testHashPool
    lock          sync.RWMutex
    refBlockChain blockChain
    blockChain    blockChain
    blockPool     *BlockPool
    t             *testing.T
}

func newTestBlockPool(t *testing.T) (hashPool *testHashPool, blockPool *BlockPool, b *blockPoolTester) {
    hashPool = &testHashPool{intToHash: make(intToHash), hashToInt: make(hashToInt)}
    b = &blockPoolTester{
        t:             t,
        hashPool:      hashPool,
        blockChain:    make(blockChain),
        refBlockChain: make(blockChain),
    }
    b.blockPool = NewBlockPool(b.hasBlock, b.insertChain, b.verifyPoW)
    blockPool = b.blockPool
    return
}

func (self *blockPoolTester) Errorf(format string, params ...interface{}) {
    fmt.Printf(format+"\n", params...)
    self.t.Errorf(format, params...)
}

// blockPoolTester implements the 3 callbacks needed by the blockPool:
// hasBlock, insetChain, verifyPoW
func (self *blockPoolTester) hasBlock(block []byte) (ok bool) {
    self.lock.RLock()
    defer self.lock.RUnlock()
    indexes := self.hashPool.hashesToIndexes([][]byte{block})
    i := indexes[0]
    _, ok = self.blockChain[i]
    fmt.Printf("has block %v (%x...): %v\n", i, block[0:4], ok)
    return
}

func (self *blockPoolTester) insertChain(blocks types.Blocks) error {
    self.lock.RLock()
    defer self.lock.RUnlock()
    var parent, child int
    var children, refChildren []int
    var ok bool
    for _, block := range blocks {
        child = self.hashPool.hashesToIndexes([][]byte{block.Hash()})[0]
        _, ok = self.blockChain[child]
        if ok {
            fmt.Printf("block %v already in blockchain\n", child)
            continue // already in chain
        }
        parent = self.hashPool.hashesToIndexes([][]byte{block.ParentHeaderHash})[0]
        children, ok = self.blockChain[parent]
        if !ok {
            return fmt.Errorf("parent %v not in blockchain ", parent)
        }
        ok = false
        var found bool
        refChildren, found = self.refBlockChain[parent]
        if found {
            for _, c := range refChildren {
                if c == child {
                    ok = true
                }
            }
            if !ok {
                return fmt.Errorf("invalid block %v", child)
            }
        } else {
            ok = true
        }
        if ok {
            // accept any blocks if parent not in refBlockChain
            fmt.Errorf("blockchain insert %v -> %v\n", parent, child)
            self.blockChain[parent] = append(children, child)
            self.blockChain[child] = nil
        }
    }
    return nil
}

func (self *blockPoolTester) verifyPoW(pblock pow.Block) bool {
    return true
}

// test helper that compares the resulting blockChain to the desired blockChain
func (self *blockPoolTester) checkBlockChain(blockChain map[int][]int) {
    for k, v := range self.blockChain {
        fmt.Printf("got: %v -> %v\n", k, v)
    }
    for k, v := range blockChain {
        fmt.Printf("expected: %v -> %v\n", k, v)
    }
    if len(blockChain) != len(self.blockChain) {
        self.Errorf("blockchain incorrect (zlength differ)")
    }
    for k, v := range blockChain {
        vv, ok := self.blockChain[k]
        if !ok || !arrayEq(v, vv) {
            self.Errorf("blockchain incorrect on %v -> %v (!= %v)", k, vv, v)
        }
    }
}

//

// peerTester provides the peer callbacks for the blockPool
// it registers actual callbacks so that result can be compared to desired behaviour
// provides helper functions to mock the protocol calls to the blockPool
type peerTester struct {
    blockHashesRequests []int
    blocksRequests      [][]int
    blocksRequestsMap   map[int]bool
    peerErrors          []int
    blockPool           *BlockPool
    hashPool            *testHashPool
    lock                sync.RWMutex
    id                  string
    td                  int
    currentBlock        int
    t                   *testing.T
}

// peerTester constructor takes hashPool and blockPool from the blockPoolTester
func (self *blockPoolTester) newPeer(id string, td int, cb int) *peerTester {
    return &peerTester{
        id:                id,
        td:                td,
        currentBlock:      cb,
        hashPool:          self.hashPool,
        blockPool:         self.blockPool,
        t:                 self.t,
        blocksRequestsMap: make(map[int]bool),
    }
}

func (self *peerTester) Errorf(format string, params ...interface{}) {
    fmt.Printf(format+"\n", params...)
    self.t.Errorf(format, params...)
}

// helper to compare actual and expected block requests
func (self *peerTester) checkBlocksRequests(blocksRequests ...[]int) {
    if len(blocksRequests) > len(self.blocksRequests) {
        self.Errorf("blocks requests incorrect (length differ)\ngot %v\nexpected %v", self.blocksRequests, blocksRequests)
    } else {
        for i, rr := range blocksRequests {
            r := self.blocksRequests[i]
            if !arrayEq(r, rr) {
                self.Errorf("blocks requests incorrect\ngot %v\nexpected %v", self.blocksRequests, blocksRequests)
            }
        }
    }
}

// helper to compare actual and expected block hash requests
func (self *peerTester) checkBlockHashesRequests(blocksHashesRequests ...int) {
    rr := blocksHashesRequests
    self.lock.RLock()
    r := self.blockHashesRequests
    self.lock.RUnlock()
    if len(r) != len(rr) {
        self.Errorf("block hashes requests incorrect (length differ)\ngot %v\nexpected %v", r, rr)
    } else {
        if !arrayEq(r, rr) {
            self.Errorf("block hashes requests incorrect\ngot %v\nexpected %v", r, rr)
        }
    }
}

// waiter function used by peer.AddBlocks
// blocking until requests appear
// since block requests are sent to any random peers
// block request map is shared between peers
// times out after a period
func (self *peerTester) waitBlocksRequests(blocksRequest ...int) {
    timeout := time.After(waitTimeout * time.Second)
    rr := blocksRequest
    for {
        self.lock.RLock()
        r := self.blocksRequestsMap
        fmt.Printf("[%s] blocks request check %v (%v)\n", self.id, rr, r)
        i := 0
        for i = 0; i < len(rr); i++ {
            _, ok := r[rr[i]]
            if !ok {
                break
            }
        }
        self.lock.RUnlock()

        if i == len(rr) {
            return
        }
        time.Sleep(100 * time.Millisecond)
        select {
        case <-timeout:
        default:
        }
    }
}

// waiter function used by peer.AddBlockHashes
// blocking until requests appear
// times out after a period
func (self *peerTester) waitBlockHashesRequests(blocksHashesRequest int) {
    timeout := time.After(waitTimeout * time.Second)
    rr := blocksHashesRequest
    for i := 0; ; {
        self.lock.RLock()
        r := self.blockHashesRequests
        self.lock.RUnlock()
        fmt.Printf("[%s] block hash request check %v (%v)\n", self.id, rr, r)
        for ; i < len(r); i++ {
            if rr == r[i] {
                return
            }
        }
        time.Sleep(100 * time.Millisecond)
        select {
        case <-timeout:
        default:
        }
    }
}

// mocks a simple blockchain 0 (genesis) ... n (head)
func (self *blockPoolTester) initRefBlockChain(n int) {
    for i := 0; i < n; i++ {
        self.refBlockChain[i] = []int{i + 1}
    }
}

// peerTester functions that mimic protocol calls to the blockpool
//  registers the peer with the blockPool
func (self *peerTester) AddPeer() bool {
    hash := self.hashPool.indexesToHashes([]int{self.currentBlock})[0]
    return self.blockPool.AddPeer(big.NewInt(int64(self.td)), hash, self.id, self.requestBlockHashes, self.requestBlocks, self.peerError)
}

// peer sends blockhashes if and when gets a request
func (self *peerTester) AddBlockHashes(indexes ...int) {
    i := 0
    fmt.Printf("ready to add block hashes %v\n", indexes)

    self.waitBlockHashesRequests(indexes[0])
    fmt.Printf("adding block hashes %v\n", indexes)
    hashes := self.hashPool.indexesToHashes(indexes)
    next := func() (hash []byte, ok bool) {
        if i < len(hashes) {
            hash = hashes[i]
            ok = true
            i++
        }
        return
    }
    self.blockPool.AddBlockHashes(next, self.id)
}

// peer sends blocks if and when there is a request
// (in the shared request store, not necessarily to a person)
func (self *peerTester) AddBlocks(indexes ...int) {
    hashes := self.hashPool.indexesToHashes(indexes)
    fmt.Printf("ready to add blocks %v\n", indexes[1:])
    self.waitBlocksRequests(indexes[1:]...)
    fmt.Printf("adding blocks %v \n", indexes[1:])
    for i := 1; i < len(hashes); i++ {
        fmt.Printf("adding block %v %x\n", indexes[i], hashes[i][:4])
        self.blockPool.AddBlock(&types.Block{HeaderHash: ethutil.Bytes(hashes[i]), ParentHeaderHash: ethutil.Bytes(hashes[i-1])}, self.id)
    }
}

// peer callbacks
// -1 is special: not found (a hash never seen)
// records block hashes requests by the blockPool
func (self *peerTester) requestBlockHashes(hash []byte) error {
    indexes := self.hashPool.hashesToIndexes([][]byte{hash})
    fmt.Printf("[%s] blocks hash request %v %x\n", self.id, indexes[0], hash[:4])
    self.lock.Lock()
    defer self.lock.Unlock()
    self.blockHashesRequests = append(self.blockHashesRequests, indexes[0])
    return nil
}

// records block requests by the blockPool
func (self *peerTester) requestBlocks(hashes [][]byte) error {
    indexes := self.hashPool.hashesToIndexes(hashes)
    fmt.Printf("blocks request %v %x...\n", indexes, hashes[0][:4])
    self.lock.Lock()
    defer self.lock.Unlock()
    self.blocksRequests = append(self.blocksRequests, indexes)
    for _, i := range indexes {
        self.blocksRequestsMap[i] = true
    }
    return nil
}

// records the error codes of all the peerErrors found the blockPool
func (self *peerTester) peerError(code int, format string, params ...interface{}) {
    self.peerErrors = append(self.peerErrors, code)
}

// the actual tests
func TestAddPeer(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    peer0 := blockPoolTester.newPeer("peer0", 1, 0)
    peer1 := blockPoolTester.newPeer("peer1", 2, 1)
    peer2 := blockPoolTester.newPeer("peer2", 3, 2)
    var peer *peerInfo

    blockPool.Start()

    // pool
    best := peer0.AddPeer()
    if !best {
        t.Errorf("peer0 (TD=1) not accepted as best")
    }
    if blockPool.peer.id != "peer0" {
        t.Errorf("peer0 (TD=1) not set as best")
    }
    peer0.checkBlockHashesRequests(0)

    best = peer2.AddPeer()
    if !best {
        t.Errorf("peer2 (TD=3) not accepted as best")
    }
    if blockPool.peer.id != "peer2" {
        t.Errorf("peer2 (TD=3) not set as best")
    }
    peer2.checkBlockHashesRequests(2)

    best = peer1.AddPeer()
    if best {
        t.Errorf("peer1 (TD=2) accepted as best")
    }
    if blockPool.peer.id != "peer2" {
        t.Errorf("peer2 (TD=3) not set any more as best")
    }
    if blockPool.peer.td.Cmp(big.NewInt(int64(3))) != 0 {
        t.Errorf("peer1 TD not set")
    }

    peer2.td = 4
    peer2.currentBlock = 3
    best = peer2.AddPeer()
    if !best {
        t.Errorf("peer2 (TD=4) not accepted as best")
    }
    if blockPool.peer.id != "peer2" {
        t.Errorf("peer2 (TD=4) not set as best")
    }
    if blockPool.peer.td.Cmp(big.NewInt(int64(4))) != 0 {
        t.Errorf("peer2 TD not updated")
    }
    peer2.checkBlockHashesRequests(2, 3)

    peer1.td = 3
    peer1.currentBlock = 2
    best = peer1.AddPeer()
    if best {
        t.Errorf("peer1 (TD=3) should not be set as best")
    }
    if blockPool.peer.id == "peer1" {
        t.Errorf("peer1 (TD=3) should not be set as best")
    }
    peer, best = blockPool.getPeer("peer1")
    if peer.td.Cmp(big.NewInt(int64(3))) != 0 {
        t.Errorf("peer1 TD should be updated")
    }

    blockPool.RemovePeer("peer2")
    peer, best = blockPool.getPeer("peer2")
    if peer != nil {
        t.Errorf("peer2 not removed")
    }

    if blockPool.peer.id != "peer1" {
        t.Errorf("existing peer1 (TD=3) should be set as best peer")
    }
    peer1.checkBlockHashesRequests(2)

    blockPool.RemovePeer("peer1")
    peer, best = blockPool.getPeer("peer1")
    if peer != nil {
        t.Errorf("peer1 not removed")
    }

    if blockPool.peer.id != "peer0" {
        t.Errorf("existing peer0 (TD=1) should be set as best peer")
    }

    blockPool.RemovePeer("peer0")
    peer, best = blockPool.getPeer("peer0")
    if peer != nil {
        t.Errorf("peer1 not removed")
    }

    // adding back earlier peer ok
    peer0.currentBlock = 3
    best = peer0.AddPeer()
    if !best {
        t.Errorf("peer0 (TD=1) should be set as best")
    }

    if blockPool.peer.id != "peer0" {
        t.Errorf("peer0 (TD=1) should be set as best")
    }
    peer0.checkBlockHashesRequests(0, 0, 3)

    blockPool.Stop()

}

func TestPeerWithKnownBlock(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.refBlockChain[0] = nil
    blockPoolTester.blockChain[0] = nil
    // hashPool, blockPool, blockPoolTester := newTestBlockPool()
    blockPool.Start()

    peer0 := blockPoolTester.newPeer("0", 1, 0)
    peer0.AddPeer()

    blockPool.Stop()
    // no request on known block
    peer0.checkBlockHashesRequests()
}

func TestSimpleChain(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(2)

    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 2)
    peer1.AddPeer()
    go peer1.AddBlockHashes(2, 1, 0)
    peer1.AddBlocks(0, 1, 2)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[2] = []int{}
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)
}

func TestInvalidBlock(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(2)
    blockPoolTester.refBlockChain[2] = []int{}

    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 3)
    peer1.AddPeer()
    go peer1.AddBlockHashes(3, 2, 1, 0)
    peer1.AddBlocks(0, 1, 2, 3)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[2] = []int{}
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)
    if len(peer1.peerErrors) == 1 {
        if peer1.peerErrors[0] != ErrInvalidBlock {
            t.Errorf("wrong error, got %v, expected %v", peer1.peerErrors[0], ErrInvalidBlock)
        }
    } else {
        t.Errorf("expected invalid block error, got nothing")
    }
}

func TestVerifyPoW(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(3)
    first := false
    blockPoolTester.blockPool.verifyPoW = func(b pow.Block) bool {
        bb, _ := b.(*types.Block)
        indexes := blockPoolTester.hashPool.hashesToIndexes([][]byte{bb.Hash()})
        if indexes[0] == 1 && !first {
            first = true
            return false
        } else {
            return true
        }

    }

    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 2)
    peer1.AddPeer()
    go peer1.AddBlockHashes(2, 1, 0)
    peer1.AddBlocks(0, 1, 2)
    peer1.AddBlocks(0, 1)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[2] = []int{}
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)
    if len(peer1.peerErrors) == 1 {
        if peer1.peerErrors[0] != ErrInvalidPoW {
            t.Errorf("wrong error, got %v, expected %v", peer1.peerErrors[0], ErrInvalidPoW)
        }
    } else {
        t.Errorf("expected invalid pow error, got nothing")
    }
}

func TestMultiSectionChain(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(5)

    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 5)

    peer1.AddPeer()
    go peer1.AddBlockHashes(5, 4, 3)
    go peer1.AddBlocks(2, 3, 4, 5)
    go peer1.AddBlockHashes(3, 2, 1, 0)
    peer1.AddBlocks(0, 1, 2)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[5] = []int{}
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)
}

func TestNewBlocksOnPartialChain(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(7)
    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 5)

    peer1.AddPeer()
    go peer1.AddBlockHashes(5, 4, 3)
    peer1.AddBlocks(2, 3) // partially complete section
    // peer1 found new blocks
    peer1.td = 2
    peer1.currentBlock = 7
    peer1.AddPeer()
    go peer1.AddBlockHashes(7, 6, 5)
    go peer1.AddBlocks(3, 4, 5, 6, 7)
    go peer1.AddBlockHashes(3, 2, 1, 0) // tests that hash request from known chain root is remembered
    peer1.AddBlocks(0, 1, 2)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[7] = []int{}
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)
}

func TestPeerSwitch(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(6)

    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 5)
    peer2 := blockPoolTester.newPeer("peer2", 2, 6)
    peer2.blocksRequestsMap = peer1.blocksRequestsMap

    peer1.AddPeer()
    go peer1.AddBlockHashes(5, 4, 3)
    peer1.AddBlocks(2, 3)               // section partially complete, block 3 will be preserved after peer demoted
    peer2.AddPeer()                     // peer2 is promoted as best peer, peer1 is demoted
    go peer2.AddBlockHashes(6, 5)       //
    go peer2.AddBlocks(4, 5, 6)         // tests that block request for earlier section is remembered
    go peer1.AddBlocks(3, 4)            // tests that connecting section by demoted peer is remembered and blocks are accepted from demoted peer
    go peer2.AddBlockHashes(3, 2, 1, 0) // tests that known chain section is activated, hash requests from 3 is remembered
    peer2.AddBlocks(0, 1, 2)            // final blocks linking to blockchain sent

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[6] = []int{}
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)
}

func TestPeerDownSwitch(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(6)
    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 4)
    peer2 := blockPoolTester.newPeer("peer2", 2, 6)
    peer2.blocksRequestsMap = peer1.blocksRequestsMap

    peer2.AddPeer()
    go peer2.AddBlockHashes(6, 5, 4)
    peer2.AddBlocks(5, 6)                  // partially complete, section will be preserved
    blockPool.RemovePeer("peer2")          // peer2 disconnects
    peer1.AddPeer()                        // inferior peer1 is promoted as best peer
    go peer1.AddBlockHashes(4, 3, 2, 1, 0) //
    go peer1.AddBlocks(3, 4, 5)            // tests that section set by demoted peer is remembered and blocks are accepted
    peer1.AddBlocks(0, 1, 2, 3)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[6] = []int{}
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)
}

func TestPeerSwitchBack(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(8)

    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 2, 11)
    peer2 := blockPoolTester.newPeer("peer2", 1, 8)
    peer2.blocksRequestsMap = peer1.blocksRequestsMap

    peer2.AddPeer()
    go peer2.AddBlockHashes(8, 7, 6)
    go peer2.AddBlockHashes(6, 5, 4)
    peer2.AddBlocks(4, 5)                  // section partially complete
    peer1.AddPeer()                        // peer1 is promoted as best peer
    go peer1.AddBlockHashes(11, 10)        // only gives useless results
    blockPool.RemovePeer("peer1")          // peer1 disconnects
    go peer2.AddBlockHashes(4, 3, 2, 1, 0) // tests that asking for hashes from 4 is remembered
    go peer2.AddBlocks(3, 4, 5, 6, 7, 8)   // tests that section 4, 5, 6 and 7, 8 are remembered for missing blocks
    peer2.AddBlocks(0, 1, 2, 3)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[8] = []int{}
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)
}

func TestForkSimple(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(9)
    blockPoolTester.refBlockChain[3] = []int{4, 7}
    delete(blockPoolTester.refBlockChain, 6)

    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 9)
    peer2 := blockPoolTester.newPeer("peer2", 2, 6)
    peer2.blocksRequestsMap = peer1.blocksRequestsMap

    peer1.AddPeer()
    go peer1.AddBlockHashes(9, 8, 7, 3, 2)
    peer1.AddBlocks(1, 2, 3, 7, 8, 9)
    peer2.AddPeer()                        // peer2 is promoted as best peer
    go peer2.AddBlockHashes(6, 5, 4, 3, 2) // fork on 3 -> 4 (earlier child: 7)
    go peer2.AddBlocks(1, 2, 3, 4, 5, 6)
    go peer2.AddBlockHashes(2, 1, 0)
    peer2.AddBlocks(0, 1, 2)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[6] = []int{}
    blockPoolTester.refBlockChain[3] = []int{4}
    delete(blockPoolTester.refBlockChain, 7)
    delete(blockPoolTester.refBlockChain, 8)
    delete(blockPoolTester.refBlockChain, 9)
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)

}

func TestForkSwitchBackByNewBlocks(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(11)
    blockPoolTester.refBlockChain[3] = []int{4, 7}
    delete(blockPoolTester.refBlockChain, 6)

    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 9)
    peer2 := blockPoolTester.newPeer("peer2", 2, 6)
    peer2.blocksRequestsMap = peer1.blocksRequestsMap

    peer1.AddPeer()
    go peer1.AddBlockHashes(9, 8, 7, 3, 2)
    peer1.AddBlocks(8, 9)                  // partial section
    peer2.AddPeer()                        //
    go peer2.AddBlockHashes(6, 5, 4, 3, 2) // peer2 forks on block 3
    peer2.AddBlocks(1, 2, 3, 4, 5, 6)      //

    // peer1 finds new blocks
    peer1.td = 3
    peer1.currentBlock = 11
    peer1.AddPeer()
    go peer1.AddBlockHashes(11, 10, 9)
    peer1.AddBlocks(7, 8, 9, 10, 11)
    go peer1.AddBlockHashes(7, 3) // tests that hash request from fork root is remembered
    go peer1.AddBlocks(3, 7)      // tests that block requests on earlier fork are remembered
    // go peer1.AddBlockHashes(1, 0) // tests that hash request from root of connecting chain section (added by demoted peer) is remembered
    go peer1.AddBlockHashes(2, 1, 0) // tests that hash request from root of connecting chain section (added by demoted peer) is remembered
    peer1.AddBlocks(0, 1, 2, 3)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[11] = []int{}
    blockPoolTester.refBlockChain[3] = []int{7}
    delete(blockPoolTester.refBlockChain, 6)
    delete(blockPoolTester.refBlockChain, 5)
    delete(blockPoolTester.refBlockChain, 4)
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)

}

func TestForkSwitchBackByPeerSwitchBack(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(9)
    blockPoolTester.refBlockChain[3] = []int{4, 7}
    delete(blockPoolTester.refBlockChain, 6)

    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 9)
    peer2 := blockPoolTester.newPeer("peer2", 2, 6)
    peer2.blocksRequestsMap = peer1.blocksRequestsMap

    peer1.AddPeer()
    go peer1.AddBlockHashes(9, 8, 7, 3, 2)
    peer1.AddBlocks(8, 9)
    peer2.AddPeer()                        //
    go peer2.AddBlockHashes(6, 5, 4, 3, 2) // peer2 forks on block 3
    peer2.AddBlocks(2, 3, 4, 5, 6)         //
    blockPool.RemovePeer("peer2")          // peer2 disconnects, peer1 is promoted again as best peer
    peer1.AddBlockHashes(7, 3)             // tests that hash request from fork root is remembered
    go peer1.AddBlocks(3, 7, 8)            // tests that block requests on earlier fork are remembered
    go peer1.AddBlockHashes(2, 1, 0)       //
    peer1.AddBlocks(0, 1, 2, 3)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[9] = []int{}
    blockPoolTester.refBlockChain[3] = []int{7}
    delete(blockPoolTester.refBlockChain, 6)
    delete(blockPoolTester.refBlockChain, 5)
    delete(blockPoolTester.refBlockChain, 4)
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)

}

func TestForkCompleteSectionSwitchBackByPeerSwitchBack(t *testing.T) {
    logInit()
    _, blockPool, blockPoolTester := newTestBlockPool(t)
    blockPoolTester.blockChain[0] = nil
    blockPoolTester.initRefBlockChain(9)
    blockPoolTester.refBlockChain[3] = []int{4, 7}
    delete(blockPoolTester.refBlockChain, 6)

    blockPool.Start()

    peer1 := blockPoolTester.newPeer("peer1", 1, 9)
    peer2 := blockPoolTester.newPeer("peer2", 2, 6)
    peer2.blocksRequestsMap = peer1.blocksRequestsMap

    peer1.AddPeer()
    go peer1.AddBlockHashes(9, 8, 7)
    peer1.AddBlocks(3, 7, 8, 9) // make sure this section is complete
    time.Sleep(1 * time.Second)
    go peer1.AddBlockHashes(7, 3, 2)       // block 3/7 is section boundary
    peer1.AddBlocks(2, 3)                  // partially complete sections
    peer2.AddPeer()                        //
    go peer2.AddBlockHashes(6, 5, 4, 3, 2) // peer2 forks on block 3
    peer2.AddBlocks(2, 3, 4, 5, 6)         // block 2 still missing.
    blockPool.RemovePeer("peer2")          // peer2 disconnects, peer1 is promoted again as best peer
    peer1.AddBlockHashes(7, 3)             // tests that hash request from fork root is remembered even though section process completed
    go peer1.AddBlockHashes(2, 1, 0)       //
    peer1.AddBlocks(0, 1, 2)

    blockPool.Wait(waitTimeout * time.Second)
    blockPool.Stop()
    blockPoolTester.refBlockChain[9] = []int{}
    blockPoolTester.refBlockChain[3] = []int{7}
    delete(blockPoolTester.refBlockChain, 6)
    delete(blockPoolTester.refBlockChain, 5)
    delete(blockPoolTester.refBlockChain, 4)
    blockPoolTester.checkBlockChain(blockPoolTester.refBlockChain)

}