2022-11-23 16:11:38 +00:00
|
|
|
# nimbus_verified_proxy
|
2024-02-15 13:50:25 +00:00
|
|
|
# Copyright (c) 2022-2024 Status Research & Development GmbH
|
2022-09-28 08:01:32 +00:00
|
|
|
# Licensed and distributed under either of
|
|
|
|
# * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT).
|
|
|
|
# * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0).
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
|
|
|
|
2023-01-31 12:38:08 +00:00
|
|
|
{.push raises: [].}
|
2022-09-28 08:01:32 +00:00
|
|
|
|
2024-10-21 03:10:41 +00:00
|
|
|
import eth/common/hashes, web3/eth_api_types, minilru, results
|
2022-09-28 08:01:32 +00:00
|
|
|
|
2022-11-23 16:11:38 +00:00
|
|
|
## Cache for payloads received through block gossip and validated by the
|
|
|
|
## consensus light client.
|
|
|
|
## The payloads are stored in order of arrival. When the cache is full, the
|
|
|
|
## oldest payload is deleted first.
|
2022-09-28 08:01:32 +00:00
|
|
|
type BlockCache* = ref object
|
2024-10-21 03:10:41 +00:00
|
|
|
blocks: LruCache[Hash32, BlockObject]
|
2022-09-28 08:01:32 +00:00
|
|
|
|
|
|
|
proc new*(T: type BlockCache, max: uint32): T =
|
|
|
|
let maxAsInt = int(max)
|
2024-10-21 03:10:41 +00:00
|
|
|
BlockCache(blocks: LruCache[Hash32, BlockObject].init(maxAsInt))
|
2022-09-28 08:01:32 +00:00
|
|
|
|
|
|
|
func len*(self: BlockCache): int =
|
2024-10-21 03:10:41 +00:00
|
|
|
len(self.blocks)
|
2022-09-28 08:01:32 +00:00
|
|
|
|
|
|
|
func isEmpty*(self: BlockCache): bool =
|
2024-10-21 03:10:41 +00:00
|
|
|
len(self.blocks) == 0
|
2022-09-28 08:01:32 +00:00
|
|
|
|
2024-10-21 03:10:41 +00:00
|
|
|
proc add*(self: BlockCache, payload: BlockObject) =
|
|
|
|
# Only add if it didn't exist before - the implementation of `latest` relies
|
|
|
|
# on this..
|
|
|
|
if payload.hash notin self.blocks:
|
|
|
|
self.blocks.put(payload.hash, payload)
|
2022-09-28 08:01:32 +00:00
|
|
|
|
2024-10-21 03:10:41 +00:00
|
|
|
proc latest*(self: BlockCache): Opt[BlockObject] =
|
|
|
|
for b in self.blocks.values:
|
|
|
|
return Opt.some(b)
|
|
|
|
Opt.none(BlockObject)
|
2022-09-28 08:01:32 +00:00
|
|
|
|
2024-10-21 03:10:41 +00:00
|
|
|
proc getByNumber*(self: BlockCache, number: Quantity): Opt[BlockObject] =
|
|
|
|
for b in self.blocks.values:
|
|
|
|
if b.number == number:
|
|
|
|
return Opt.some(b)
|
2022-09-28 08:01:32 +00:00
|
|
|
|
2024-10-21 03:10:41 +00:00
|
|
|
Opt.none(BlockObject)
|
2022-11-23 11:46:09 +00:00
|
|
|
|
2024-10-21 03:10:41 +00:00
|
|
|
proc getPayloadByHash*(self: BlockCache, hash: Hash32): Opt[BlockObject] =
|
|
|
|
self.blocks.get(hash)
|