github.com/aergoio/aergo@v1.3.1/chain/orphanpool_test.go (about) 1 package chain 2 3 import ( 4 "github.com/aergoio/aergo/types" 5 "github.com/stretchr/testify/assert" 6 "testing" 7 ) 8 9 func checkExist(t *testing.T, orp *OrphanPool, blk *types.Block) { 10 var orphan *types.Block 11 orphan = orp.getOrphan(blk.Header.GetPrevBlockHash()) 12 13 assert.NotNil(t, orphan) 14 assert.Equal(t, orphan.BlockHash(), blk.BlockHash()) 15 } 16 17 func TestOrphanPool(t *testing.T) { 18 // measure time to add block 19 var stubChain *StubBlockChain 20 var orp *OrphanPool 21 var orphan *types.Block 22 23 orp = NewOrphanPool(5) 24 25 _, stubChain = testAddBlockNoTest(10) 26 27 start := 1 28 for i := start; i <= 5; i++ { 29 blk := stubChain.GetBlockByNo(uint64(i)) 30 31 err := orp.addOrphan(blk) 32 assert.NoError(t, err) 33 34 checkExist(t, orp, blk) 35 } 36 37 // check pool is full 38 assert.True(t, orp.isFull()) 39 40 // remove oldest and put new one 41 blk := stubChain.GetBlockByNo(6) 42 err := orp.addOrphan(blk) 43 assert.NoError(t, err) 44 45 checkExist(t, orp, blk) 46 47 // first block is removed 48 startBlock := stubChain.GetBlockByNo(uint64(start)) 49 orphan = orp.getOrphan(startBlock.Header.GetPrevBlockHash()) 50 assert.Nil(t, orphan) 51 52 assert.True(t, orp.isFull()) 53 } 54 55 func TestOrphanSamePrev(t *testing.T) { 56 var orp *OrphanPool 57 58 mainChainBest := 3 59 _, mainChain := testAddBlock(t, mainChainBest) 60 61 // make branch 62 sideChain := InitStubBlockChain(mainChain.Blocks[0:mainChainBest+1], 1) 63 64 // make fork 65 mainChain.GenAddBlock() 66 67 mBest := mainChain.BestBlock 68 sBest := sideChain.BestBlock 69 70 assert.Equal(t, mBest.PrevBlockID(), sBest.PrevBlockID()) 71 72 // No.4 blocks of mainchain and sidechain have same previous hash 73 orp = NewOrphanPool(5) 74 75 err := orp.addOrphan(mBest) 76 assert.NoError(t, err) 77 78 err = orp.addOrphan(sBest) 79 assert.NoError(t, err) 80 81 checkExist(t, orp, mBest) 82 83 orphan := orp.getOrphan(sBest.Header.GetPrevBlockHash()) 84 assert.Equal(t, orphan.BlockHash(), mBest.BlockHash()) 85 } 86 87 func BenchmarkOrphanPoolWhenPool(b *testing.B) { 88 b.ResetTimer() 89 90 // measure time to add block 91 start := 1001 92 93 var stubChain *StubBlockChain 94 var orp *OrphanPool 95 96 b.StopTimer() 97 98 orp = NewOrphanPool(300) 99 _, stubChain = testAddBlockNoTest(11000) 100 // make pool to be full 101 for i := 1; i <= 1000; i++ { 102 blk := stubChain.GetBlockByNo(uint64(i)) 103 104 orp.addOrphan(blk) 105 } 106 107 b.StartTimer() 108 109 for i := 0; i < b.N; i++ { 110 111 idx := start + (i % 10000) 112 113 blk := stubChain.GetBlockByNo(uint64(idx)) 114 115 orp.addOrphan(blk) 116 } 117 }