From f0405c6a1decc41a878708b0f80e4b6fd6ebbcd5 Mon Sep 17 00:00:00 2001 From: Jimmy Hu Date: Thu, 27 Dec 2018 09:17:28 +0800 Subject: dex: add pull randomness (#105) * vendor: sync to latest core * dex: Add PullRandomness --- dex/cache.go | 62 +++++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 11 deletions(-) (limited to 'dex/cache.go') diff --git a/dex/cache.go b/dex/cache.go index 89bbbe3be..bdc22e114 100644 --- a/dex/cache.go +++ b/dex/cache.go @@ -44,21 +44,23 @@ func voteToKey(vote *coreTypes.Vote) voteKey { } type cache struct { - lock sync.RWMutex - blockCache map[coreCommon.Hash]*coreTypes.Block - voteCache map[coreTypes.Position]map[voteKey]*coreTypes.Vote - votePosition []coreTypes.Position - db coreDb.Database - voteSize int - size int + lock sync.RWMutex + blockCache map[coreCommon.Hash]*coreTypes.Block + voteCache map[coreTypes.Position]map[voteKey]*coreTypes.Vote + randomnessCache map[coreCommon.Hash]*coreTypes.BlockRandomnessResult + votePosition []coreTypes.Position + db coreDb.Database + voteSize int + size int } func newCache(size int, db coreDb.Database) *cache { return &cache{ - blockCache: make(map[coreCommon.Hash]*coreTypes.Block), - voteCache: make(map[coreTypes.Position]map[voteKey]*coreTypes.Vote), - db: db, - size: size, + blockCache: make(map[coreCommon.Hash]*coreTypes.Block), + voteCache: make(map[coreTypes.Position]map[voteKey]*coreTypes.Vote), + randomnessCache: make(map[coreCommon.Hash]*coreTypes.BlockRandomnessResult), + db: db, + size: size, } } @@ -126,3 +128,41 @@ func (c *cache) blocks(hashes coreCommon.Hashes) []*coreTypes.Block { } return cacheBlocks } + +func (c *cache) addRandomness(rand *coreTypes.BlockRandomnessResult) { + c.lock.Lock() + defer c.lock.Unlock() + if len(c.randomnessCache) >= c.size { + // Randomly delete one entry. + for k := range c.randomnessCache { + delete(c.randomnessCache, k) + break + } + } + c.randomnessCache[rand.BlockHash] = rand +} + +func (c *cache) randomness(hashes coreCommon.Hashes) []*coreTypes.BlockRandomnessResult { + c.lock.RLock() + defer c.lock.RUnlock() + cacheRandomnesss := make([]*coreTypes.BlockRandomnessResult, 0, len(hashes)) + for _, hash := range hashes { + if block, exist := c.randomnessCache[hash]; exist { + cacheRandomnesss = append(cacheRandomnesss, block) + } else { + block, err := c.db.GetBlock(hash) + if err != nil { + continue + } + if len(block.Finalization.Randomness) == 0 { + continue + } + cacheRandomnesss = append(cacheRandomnesss, &coreTypes.BlockRandomnessResult{ + BlockHash: block.Hash, + Position: block.Position, + Randomness: block.Finalization.Randomness, + }) + } + } + return cacheRandomnesss +} -- cgit v1.2.3