diff --git a/beacon-chain/db/block.go b/beacon-chain/db/block.go index 1ce493281f..92b7ecb608 100644 --- a/beacon-chain/db/block.go +++ b/beacon-chain/db/block.go @@ -50,7 +50,7 @@ func (db *BeaconDB) Block(root [32]byte) (*pb.BeaconBlock, error) { db.blocksLock.RLock() // Return block from cache if it exists - if _, exists := db.blocks[root]; exists { + if blk, exists := db.blocks[root]; exists && blk != nil { db.blocksLock.RUnlock() blockCacheHit.Inc() return db.blocks[root], nil @@ -141,7 +141,7 @@ func (db *BeaconDB) SaveBlock(block *pb.BeaconBlock) error { } // Skip saving block to DB if it exists in the cache. - if _, exists := db.blocks[root]; exists { + if blk, exists := db.blocks[root]; exists && blk != nil { return nil } // Save it to the cache if it's not in the cache. diff --git a/beacon-chain/db/block_test.go b/beacon-chain/db/block_test.go index 8ac047dfe3..3db81b1df7 100644 --- a/beacon-chain/db/block_test.go +++ b/beacon-chain/db/block_test.go @@ -82,6 +82,34 @@ func TestSaveBlock_OK(t *testing.T) { } } +func TestSaveBlock_NilBlkInCache(t *testing.T) { + db := setupDB(t) + defer teardownDB(t, db) + + block := &pb.BeaconBlock{Slot: 999} + h1, _ := hashutil.HashBeaconBlock(block) + + // Save a nil block to with block root. + db.blocks[h1] = nil + + if err := db.SaveBlock(block); err != nil { + t.Fatalf("save block failed: %v", err) + } + + savedBlock, err := db.Block(h1) + if err != nil { + t.Fatal(err) + } + if !proto.Equal(block, savedBlock) { + t.Error("Could not save block in DB") + } + + // Verify we have the correct cached block + if !proto.Equal(db.blocks[h1], savedBlock) { + t.Error("Could not save block in cache") + } +} + func TestSaveBlockInCache_OK(t *testing.T) { db := setupDB(t) defer teardownDB(t, db)