Store compactBlocks

This commit is contained in:
Aditya Kulkarni
2019-09-25 17:18:27 -07:00
parent d503752588
commit 6f56b8b8e9
3 changed files with 22 additions and 20 deletions

View File

@@ -3,7 +3,7 @@ package common
import (
"bytes"
"github.com/adityapk00/lightwalletd/parser"
"github.com/adityapk00/lightwalletd/walletrpc"
"github.com/pkg/errors"
)
@@ -13,7 +13,7 @@ type BlockCache struct {
FirstBlock int
LastBlock int
m map[int]*parser.Block
m map[int]*walletrpc.CompactBlock
}
func New(maxEntries int) *BlockCache {
@@ -21,12 +21,12 @@ func New(maxEntries int) *BlockCache {
MaxEntries: maxEntries,
FirstBlock: -1,
LastBlock: -1,
m: make(map[int]*parser.Block),
m: make(map[int]*walletrpc.CompactBlock),
}
}
func (c *BlockCache) Add(height int, block *parser.Block) error {
println("Cache add", height)
func (c *BlockCache) Add(height int, block *walletrpc.CompactBlock) error {
//println("Cache add", height)
if c.FirstBlock == -1 && c.LastBlock == -1 {
// If this is the first block, prep the data structure
c.FirstBlock = height
@@ -35,6 +35,7 @@ func (c *BlockCache) Add(height int, block *parser.Block) error {
// Overwriting an existing entry. If so, then remove all
// subsequent blocks, since this might be a reorg
for i := height; i <= c.LastBlock; i++ {
//println("Deleteing at height", i)
delete(c.m, i)
}
c.LastBlock = height - 1
@@ -44,7 +45,7 @@ func (c *BlockCache) Add(height int, block *parser.Block) error {
return errors.New("Blocks need to be added sequentially")
}
if c.m[height-1] != nil && !bytes.Equal(block.GetPrevHash(), c.m[height-1].GetEncodableHash()) {
if c.m[height-1] != nil && !bytes.Equal(block.PrevHash, c.m[height-1].Hash) {
return errors.New("Prev hash of the block didn't match")
}
@@ -55,23 +56,26 @@ func (c *BlockCache) Add(height int, block *parser.Block) error {
// If the cache is full, remove the oldest block
if c.LastBlock-c.FirstBlock+1 > c.MaxEntries {
//println("Deleteing at height", c.FirstBlock)
delete(c.m, c.FirstBlock)
c.FirstBlock = c.FirstBlock + 1
}
//println("Cache size is ", len(c.m))
return nil
}
func (c *BlockCache) Get(height int) *parser.Block {
println("Cache get", height)
func (c *BlockCache) Get(height int) *walletrpc.CompactBlock {
//println("Cache get", height)
if c.LastBlock == -1 || c.FirstBlock == -1 {
return nil
}
if height < c.FirstBlock || height > c.LastBlock {
//println("Cache miss: index out of range")
return nil
}
println("Cache returned")
//println("Cache returned")
return c.m[height]
}