1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use super::{CacheSize, LOG_TARGET};
use hash_db::Hasher;
use hashbrown::{hash_set::Entry as SetEntry, HashSet};
use lru::LruCache;
use nohash_hasher::BuildNoHashHasher;
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::{
hash::{BuildHasher, Hasher as _},
mem,
sync::Arc,
};
use trie_db::{node::NodeOwned, CachedValue};
lazy_static::lazy_static! {
static ref RANDOM_STATE: ahash::RandomState = ahash::RandomState::default();
}
type NoHashingLruCache<K, T> = lru::LruCache<K, T, BuildNoHashHasher<K>>;
pub(super) struct SharedNodeCache<H> {
pub(super) lru: LruCache<H, NodeOwned<H>>,
pub(super) size_in_bytes: usize,
maximum_cache_size: CacheSize,
}
impl<H: AsRef<[u8]> + Eq + std::hash::Hash> SharedNodeCache<H> {
fn new(cache_size: CacheSize) -> Self {
Self { lru: LruCache::unbounded(), size_in_bytes: 0, maximum_cache_size: cache_size }
}
pub fn get(&self, key: &H) -> Option<&NodeOwned<H>> {
self.lru.peek(key)
}
pub fn update(
&mut self,
added: impl IntoIterator<Item = (H, NodeOwned<H>)>,
accessed: impl IntoIterator<Item = H>,
) {
let update_size_in_bytes = |size_in_bytes: &mut usize, key: &H, node: &NodeOwned<H>| {
if let Some(new_size_in_bytes) =
size_in_bytes.checked_sub(key.as_ref().len() + node.size_in_bytes())
{
*size_in_bytes = new_size_in_bytes;
} else {
*size_in_bytes = 0;
tracing::error!(target: LOG_TARGET, "`SharedNodeCache` underflow detected!",);
}
};
accessed.into_iter().for_each(|key| {
self.lru.get(&key);
});
added.into_iter().for_each(|(key, node)| {
self.size_in_bytes += key.as_ref().len() + node.size_in_bytes();
if let Some((r_key, r_node)) = self.lru.push(key, node) {
update_size_in_bytes(&mut self.size_in_bytes, &r_key, &r_node);
}
while self.maximum_cache_size.exceeds(self.size_in_bytes) {
if let Some((key, node)) = self.lru.pop_lru() {
update_size_in_bytes(&mut self.size_in_bytes, &key, &node);
}
}
});
}
fn reset(&mut self) {
self.size_in_bytes = 0;
self.lru.clear();
}
}
#[derive(Eq, Clone, Copy)]
pub struct ValueCacheKeyHash(u64);
impl ValueCacheKeyHash {
pub fn from_hasher_and_storage_key(
mut hasher: impl std::hash::Hasher,
storage_key: &[u8],
) -> Self {
hasher.write(storage_key);
Self(hasher.finish())
}
}
impl PartialEq for ValueCacheKeyHash {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl std::hash::Hash for ValueCacheKeyHash {
fn hash<Hasher: std::hash::Hasher>(&self, state: &mut Hasher) {
state.write_u64(self.0);
}
}
impl nohash_hasher::IsEnabled for ValueCacheKeyHash {}
#[derive(Eq, PartialEq)]
pub(super) struct IReadTheDocumentation(());
#[derive(Eq)]
pub(super) enum ValueCacheKey<'a, H> {
Value {
storage_root: H,
storage_key: Arc<[u8]>,
hash: ValueCacheKeyHash,
},
Ref {
storage_root: H,
storage_key: &'a [u8],
hash: ValueCacheKeyHash,
},
Hash { hash: ValueCacheKeyHash, _i_read_the_documentation: IReadTheDocumentation },
}
impl<'a, H> ValueCacheKey<'a, H> {
pub fn new_value(storage_key: impl Into<Arc<[u8]>>, storage_root: H) -> Self
where
H: AsRef<[u8]>,
{
let storage_key = storage_key.into();
let hash = Self::hash_data(&storage_key, &storage_root);
Self::Value { storage_root, storage_key, hash }
}
pub fn new_ref(storage_key: &'a [u8], storage_root: H) -> Self
where
H: AsRef<[u8]>,
{
let storage_key = storage_key.into();
let hash = Self::hash_data(storage_key, &storage_root);
Self::Ref { storage_root, storage_key, hash }
}
pub fn hash_partial_data(storage_root: &H) -> impl std::hash::Hasher + Clone
where
H: AsRef<[u8]>,
{
let mut hasher = RANDOM_STATE.build_hasher();
hasher.write(storage_root.as_ref());
hasher
}
pub fn hash_data(key: &[u8], storage_root: &H) -> ValueCacheKeyHash
where
H: AsRef<[u8]>,
{
let hasher = Self::hash_partial_data(storage_root);
ValueCacheKeyHash::from_hasher_and_storage_key(hasher, key)
}
pub fn get_hash(&self) -> ValueCacheKeyHash {
match self {
Self::Value { hash, .. } | Self::Ref { hash, .. } | Self::Hash { hash, .. } => *hash,
}
}
pub fn storage_root(&self) -> Option<&H> {
match self {
Self::Value { storage_root, .. } | Self::Ref { storage_root, .. } => Some(storage_root),
Self::Hash { .. } => None,
}
}
pub fn storage_key(&self) -> Option<&[u8]> {
match self {
Self::Ref { storage_key, .. } => Some(&storage_key),
Self::Value { storage_key, .. } => Some(storage_key),
Self::Hash { .. } => None,
}
}
}
impl<H: std::hash::Hash> std::hash::Hash for ValueCacheKey<'_, H> {
fn hash<Hasher: std::hash::Hasher>(&self, state: &mut Hasher) {
self.get_hash().hash(state)
}
}
impl<H> nohash_hasher::IsEnabled for ValueCacheKey<'_, H> {}
impl<H: PartialEq> PartialEq for ValueCacheKey<'_, H> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Hash { hash, .. }, Self::Hash { hash: other_hash, .. }) => hash == other_hash,
(Self::Hash { hash, .. }, _) => *hash == other.get_hash(),
(_, Self::Hash { hash: other_hash, .. }) => self.get_hash() == *other_hash,
_ =>
self.get_hash() == other.get_hash() &&
self.storage_root() == other.storage_root() &&
self.storage_key() == other.storage_key(),
}
}
}
pub(super) struct SharedValueCache<H> {
pub(super) lru: NoHashingLruCache<ValueCacheKey<'static, H>, CachedValue<H>>,
pub(super) size_in_bytes: usize,
maximum_cache_size: CacheSize,
known_storage_keys: HashSet<Arc<[u8]>>,
}
impl<H: Eq + std::hash::Hash + Clone + Copy + AsRef<[u8]>> SharedValueCache<H> {
fn new(cache_size: CacheSize) -> Self {
Self {
lru: NoHashingLruCache::unbounded_with_hasher(Default::default()),
size_in_bytes: 0,
maximum_cache_size: cache_size,
known_storage_keys: Default::default(),
}
}
pub fn get<'a>(&'a self, key: &ValueCacheKey<H>) -> Option<&'a CachedValue<H>> {
debug_assert!(
!matches!(key, ValueCacheKey::Hash { .. }),
"`get` can not be called with `Hash` variant as this may returns the wrong value."
);
self.lru.peek(unsafe {
mem::transmute::<&ValueCacheKey<'_, H>, &ValueCacheKey<'static, H>>(key)
})
}
pub fn update(
&mut self,
added: impl IntoIterator<Item = (ValueCacheKey<'static, H>, CachedValue<H>)>,
accessed: impl IntoIterator<Item = ValueCacheKeyHash>,
) {
let base_size = mem::size_of::<ValueCacheKey<H>>() + mem::size_of::<CachedValue<H>>();
let known_keys_entry_size = mem::size_of::<Arc<[u8]>>();
let update_size_in_bytes =
|size_in_bytes: &mut usize, r_key: Arc<[u8]>, known_keys: &mut HashSet<Arc<[u8]>>| {
let last_instance = Arc::strong_count(&r_key) == 2;
let key_len = if last_instance {
known_keys.remove(&r_key);
r_key.len() + known_keys_entry_size
} else {
0
};
if let Some(new_size_in_bytes) = size_in_bytes.checked_sub(key_len + base_size) {
*size_in_bytes = new_size_in_bytes;
} else {
*size_in_bytes = 0;
tracing::error!(target: LOG_TARGET, "`SharedValueCache` underflow detected!",);
}
};
accessed.into_iter().for_each(|key| {
self.lru.get(&ValueCacheKey::Hash {
hash: key,
_i_read_the_documentation: IReadTheDocumentation(()),
});
});
added.into_iter().for_each(|(key, value)| {
let (storage_root, storage_key, key_hash) = match key {
ValueCacheKey::Hash { .. } => {
tracing::error!(
target: LOG_TARGET,
"`SharedValueCached::update` was called with a key to add \
that uses the `Hash` variant. This would lead to potential hash collision!",
);
return
},
ValueCacheKey::Ref { storage_key, storage_root, hash } =>
(storage_root, storage_key.into(), hash),
ValueCacheKey::Value { storage_root, storage_key, hash } =>
(storage_root, storage_key, hash),
};
let (size_update, storage_key) =
match self.known_storage_keys.entry(storage_key.clone()) {
SetEntry::Vacant(v) => {
let len = v.get().len();
v.insert();
(len + base_size + known_keys_entry_size, storage_key)
},
SetEntry::Occupied(o) => {
(base_size, o.get().clone())
},
};
self.size_in_bytes += size_update;
if let Some((r_key, _)) = self
.lru
.push(ValueCacheKey::Value { storage_key, storage_root, hash: key_hash }, value)
{
if let ValueCacheKey::Value { storage_key, .. } = r_key {
update_size_in_bytes(
&mut self.size_in_bytes,
storage_key,
&mut self.known_storage_keys,
);
}
}
while self.maximum_cache_size.exceeds(self.size_in_bytes) {
if let Some((r_key, _)) = self.lru.pop_lru() {
if let ValueCacheKey::Value { storage_key, .. } = r_key {
update_size_in_bytes(
&mut self.size_in_bytes,
storage_key,
&mut self.known_storage_keys,
);
}
}
}
});
}
fn reset(&mut self) {
self.size_in_bytes = 0;
self.lru.clear();
self.known_storage_keys.clear();
}
}
pub(super) struct SharedTrieCacheInner<H: Hasher> {
node_cache: SharedNodeCache<H::Out>,
value_cache: SharedValueCache<H::Out>,
}
impl<H: Hasher> SharedTrieCacheInner<H> {
pub(super) fn value_cache(&self) -> &SharedValueCache<H::Out> {
&self.value_cache
}
pub(super) fn value_cache_mut(&mut self) -> &mut SharedValueCache<H::Out> {
&mut self.value_cache
}
pub(super) fn node_cache(&self) -> &SharedNodeCache<H::Out> {
&self.node_cache
}
pub(super) fn node_cache_mut(&mut self) -> &mut SharedNodeCache<H::Out> {
&mut self.node_cache
}
}
pub struct SharedTrieCache<H: Hasher> {
inner: Arc<RwLock<SharedTrieCacheInner<H>>>,
}
impl<H: Hasher> Clone for SharedTrieCache<H> {
fn clone(&self) -> Self {
Self { inner: self.inner.clone() }
}
}
impl<H: Hasher> SharedTrieCache<H> {
pub fn new(cache_size: CacheSize) -> Self {
let (node_cache_size, value_cache_size) = match cache_size {
CacheSize::Maximum(max) => {
let value_cache_size_in_bytes = (max as f32 * 0.20) as usize;
(
CacheSize::Maximum(max - value_cache_size_in_bytes),
CacheSize::Maximum(value_cache_size_in_bytes),
)
},
CacheSize::Unlimited => (CacheSize::Unlimited, CacheSize::Unlimited),
};
Self {
inner: Arc::new(RwLock::new(SharedTrieCacheInner {
node_cache: SharedNodeCache::new(node_cache_size),
value_cache: SharedValueCache::new(value_cache_size),
})),
}
}
pub fn local_cache(&self) -> super::LocalTrieCache<H> {
super::LocalTrieCache {
shared: self.clone(),
node_cache: Default::default(),
value_cache: Default::default(),
shared_node_cache_access: Default::default(),
shared_value_cache_access: Default::default(),
}
}
pub fn used_memory_size(&self) -> usize {
let inner = self.inner.read();
let value_cache_size = inner.value_cache.size_in_bytes;
let node_cache_size = inner.node_cache.size_in_bytes;
node_cache_size + value_cache_size
}
pub fn reset_node_cache(&self) {
self.inner.write().node_cache.reset();
}
pub fn reset_value_cache(&self) {
self.inner.write().value_cache.reset();
}
pub fn reset(&self) {
self.reset_node_cache();
self.reset_value_cache();
}
pub(super) fn read_lock_inner(&self) -> RwLockReadGuard<'_, SharedTrieCacheInner<H>> {
self.inner.read()
}
pub(super) fn write_lock_inner(&self) -> RwLockWriteGuard<'_, SharedTrieCacheInner<H>> {
self.inner.write()
}
}
#[cfg(test)]
mod tests {
use super::*;
use sp_core::H256 as Hash;
#[test]
fn shared_value_cache_works() {
let base_size = mem::size_of::<CachedValue<Hash>>() + mem::size_of::<ValueCacheKey<Hash>>();
let arc_size = mem::size_of::<Arc<[u8]>>();
let mut cache = SharedValueCache::<sp_core::H256>::new(CacheSize::Maximum(
(base_size + arc_size + 10) * 10,
));
let key = vec![0; 10];
let root0 = Hash::repeat_byte(1);
let root1 = Hash::repeat_byte(2);
cache.update(
vec![
(ValueCacheKey::new_value(&key[..], root0), CachedValue::NonExisting),
(ValueCacheKey::new_value(&key[..], root1), CachedValue::NonExisting),
],
vec![],
);
assert_eq!(1, cache.known_storage_keys.len());
assert_eq!(3, Arc::strong_count(cache.known_storage_keys.get(&key[..]).unwrap()));
assert_eq!(base_size * 2 + key.len() + arc_size, cache.size_in_bytes);
cache.update(vec![], vec![ValueCacheKey::hash_data(&key[..], &root0)]);
assert_eq!(1, cache.known_storage_keys.len());
assert_eq!(3, Arc::strong_count(cache.known_storage_keys.get(&key[..]).unwrap()));
assert_eq!(base_size * 2 + key.len() + arc_size, cache.size_in_bytes);
cache.update(
(1..10)
.map(|i| vec![i; 10])
.map(|key| (ValueCacheKey::new_value(&key[..], root0), CachedValue::NonExisting)),
vec![],
);
assert_eq!(10, cache.known_storage_keys.len());
assert_eq!(2, Arc::strong_count(cache.known_storage_keys.get(&key[..]).unwrap()));
assert_eq!((base_size + key.len() + arc_size) * 10, cache.size_in_bytes);
assert!(matches!(
cache.get(&ValueCacheKey::new_ref(&key, root0)).unwrap(),
CachedValue::<Hash>::NonExisting
));
assert!(cache.get(&ValueCacheKey::new_ref(&key, root1)).is_none());
cache.update(
vec![(ValueCacheKey::new_value(vec![10; 10], root0), CachedValue::NonExisting)],
vec![],
);
assert!(cache.known_storage_keys.get(&key[..]).is_none());
}
#[test]
fn value_cache_key_eq_works() {
let storage_key = &b"something"[..];
let storage_key2 = &b"something2"[..];
let storage_root = Hash::random();
let value = ValueCacheKey::new_value(storage_key, storage_root);
let ref_ =
ValueCacheKey::Ref { storage_root, storage_key: storage_key2, hash: value.get_hash() };
let hash = ValueCacheKey::Hash {
hash: value.get_hash(),
_i_read_the_documentation: IReadTheDocumentation(()),
};
assert!(hash == value);
assert!(value == hash);
assert!(hash == ref_);
assert!(ref_ == hash);
assert!(hash == hash);
assert!(value != ref_);
assert!(ref_ != value);
}
}