github.com/klaytn/klaytn@v1.12.1/reward/staking_info_cache.go (about) 1 // Copyright 2019 The klaytn Authors 2 // This file is part of the klaytn library. 3 // 4 // The klaytn library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The klaytn library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the klaytn library. If not, see <http://www.gnu.org/licenses/>. 16 17 package reward 18 19 import "sync" 20 21 const ( 22 maxStakingCache = 4 23 ) 24 25 type stakingInfoCache struct { 26 cells map[uint64]*StakingInfo 27 minBlockNum uint64 28 lock sync.RWMutex 29 } 30 31 func newStakingInfoCache() *stakingInfoCache { 32 stakingCache := new(stakingInfoCache) 33 stakingCache.cells = make(map[uint64]*StakingInfo) 34 return stakingCache 35 } 36 37 func (sc *stakingInfoCache) get(blockNum uint64) *StakingInfo { 38 sc.lock.RLock() 39 defer sc.lock.RUnlock() 40 41 if s, ok := sc.cells[blockNum]; ok { 42 return s 43 } 44 return nil 45 } 46 47 func (sc *stakingInfoCache) add(stakingInfo *StakingInfo) { 48 sc.lock.Lock() 49 defer sc.lock.Unlock() 50 51 // Assumption: stakingInfo is not nil. 52 53 if _, ok := sc.cells[stakingInfo.BlockNum]; ok { 54 return 55 } 56 57 if len(sc.cells) >= maxStakingCache { 58 delete(sc.cells, sc.minBlockNum) 59 } 60 sc.minBlockNum = stakingInfo.BlockNum 61 for _, s := range sc.cells { 62 if s.BlockNum < sc.minBlockNum { 63 sc.minBlockNum = s.BlockNum 64 } 65 } 66 sc.cells[stakingInfo.BlockNum] = stakingInfo 67 logger.Debug("Add a new stakingInfo to stakingInfoCache", "blockNum", stakingInfo.BlockNum) 68 } 69 70 func (sc *stakingInfoCache) purge() { 71 sc.lock.Lock() 72 defer sc.lock.Unlock() 73 74 sc.minBlockNum = 0 75 sc.cells = make(map[uint64]*StakingInfo) 76 logger.Debug("Initialized staking info cache") 77 }