github.com/decred/dcrlnd@v0.7.6/neutrinocache/cache_test.go (about)

     1  package cache_test
     2  
     3  import (
     4  	"crypto/rand"
     5  	"testing"
     6  
     7  	"github.com/decred/dcrd/chaincfg/chainhash"
     8  	"github.com/decred/dcrd/dcrutil/v4"
     9  	"github.com/decred/dcrd/wire"
    10  	cache "github.com/decred/dcrlnd/neutrinocache"
    11  	"github.com/decred/dcrlnd/neutrinocache/lru"
    12  )
    13  
    14  // TestBlockFilterCaches tests that we can put and retrieve elements from all
    15  // implementations of the filter and block caches.
    16  func TestBlockFilterCaches(t *testing.T) {
    17  	t.Parallel()
    18  
    19  	// Create a cache large enough to not evict any item. We do this so we
    20  	// don't have to worry about the eviction strategy of the tested
    21  	// caches.
    22  	const numElements = 10
    23  	const cacheSize = 100000
    24  
    25  	// Initialize all types of caches we want to test, for both filters and
    26  	// blocks. Currently the LRU cache is the only implementation.
    27  	blockCaches := []cache.Cache{lru.NewCache(cacheSize)}
    28  
    29  	// Generate a list of hashes, filters and blocks that we will use as
    30  	// cache keys an values.
    31  	var (
    32  		blockHashes []chainhash.Hash
    33  		blocks      []*dcrutil.Block
    34  	)
    35  	for i := 0; i < numElements; i++ {
    36  		var blockHash chainhash.Hash
    37  		if _, err := rand.Read(blockHash[:]); err != nil {
    38  			t.Fatalf("unable to read rand: %v", err)
    39  		}
    40  
    41  		blockHashes = append(blockHashes, blockHash)
    42  
    43  		msgBlock := &wire.MsgBlock{}
    44  		block := dcrutil.NewBlock(msgBlock)
    45  		blocks = append(blocks, block)
    46  
    47  		// Add the block to the block caches, using the block INV
    48  		// vector as key.
    49  		blockKey := wire.NewInvVect(
    50  			wire.InvTypeBlock, &blockHash,
    51  		)
    52  		for _, c := range blockCaches {
    53  			c.Put(*blockKey, &cache.CacheableBlock{block})
    54  		}
    55  	}
    56  
    57  	// Now go through the list of block hashes, and make sure we can
    58  	// retrieve all elements from the caches.
    59  	for i, blockHash := range blockHashes {
    60  		// Check block caches.
    61  		blockKey := wire.NewInvVect(
    62  			wire.InvTypeBlock, &blockHash,
    63  		)
    64  		for _, c := range blockCaches {
    65  			b, err := c.Get(*blockKey)
    66  			if err != nil {
    67  				t.Fatalf("Unable to get block: %v", err)
    68  			}
    69  
    70  			// Ensure it is the same block.
    71  			block := b.(*cache.CacheableBlock).Block
    72  			if block != blocks[i] {
    73  				t.Fatalf("Not equal: %v vs %v ",
    74  					block, blocks[i])
    75  			}
    76  		}
    77  	}
    78  }