block hash lru cache

This commit is contained in:
Jack Robison 2020-02-25 14:17:52 -05:00
parent 31c141e757
commit 5ec4a88c35
No known key found for this signature in database
GPG key ID: DF25C68FE0239BB2

View file

@ -3,6 +3,7 @@ import itertools
import json import json
import time import time
from functools import wraps from functools import wraps
from pylru import lrucache
import aiohttp import aiohttp
@ -42,6 +43,7 @@ class Daemon:
self._height = None self._height = None
self.available_rpcs = {} self.available_rpcs = {}
self.connector = aiohttp.TCPConnector() self.connector = aiohttp.TCPConnector()
self._block_hash_cache = lrucache(1000000)
async def close(self): async def close(self):
if self.connector: if self.connector:
@ -219,9 +221,20 @@ class Daemon:
async def block_hex_hashes(self, first, count): async def block_hex_hashes(self, first, count):
"""Return the hex hashes of count block starting at height first.""" """Return the hex hashes of count block starting at height first."""
if first + count < (self.cached_height() or 0) - 200:
return await self._cached_block_hex_hashes(first, count)
params_iterable = ((h, ) for h in range(first, first + count)) params_iterable = ((h, ) for h in range(first, first + count))
return await self._send_vector('getblockhash', params_iterable) return await self._send_vector('getblockhash', params_iterable)
async def _cached_block_hex_hashes(self, first, count):
"""Return the hex hashes of count block starting at height first."""
cached = self._block_hash_cache.get((first, count))
if cached:
return cached
params_iterable = ((h, ) for h in range(first, first + count))
self._block_hash_cache[(first, count)] = await self._send_vector('getblockhash', params_iterable)
return self._block_hash_cache[(first, count)]
async def deserialised_block(self, hex_hash): async def deserialised_block(self, hex_hash):
"""Return the deserialised block with the given hex hash.""" """Return the deserialised block with the given hex hash."""
return await self._send_single('getblock', (hex_hash, True)) return await self._send_single('getblock', (hex_hash, True))