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
use polkadot_node_subsystem::{SubsystemError, SubsystemResult};
use polkadot_node_subsystem_util::database::{DBTransaction, Database};
use polkadot_primitives::v2::{
CandidateHash, CandidateReceipt, Hash, InvalidDisputeStatementKind, SessionIndex,
ValidDisputeStatementKind, ValidatorIndex, ValidatorSignature,
};
use std::sync::Arc;
use parity_scale_codec::{Decode, Encode};
use crate::{
backend::{Backend, BackendWriteOp, OverlayedBackend},
error::{FatalError, FatalResult},
metrics::Metrics,
status::DisputeStatus,
DISPUTE_WINDOW, LOG_TARGET,
};
const RECENT_DISPUTES_KEY: &[u8; 15] = b"recent-disputes";
const EARLIEST_SESSION_KEY: &[u8; 16] = b"earliest-session";
const CANDIDATE_VOTES_SUBKEY: &[u8; 15] = b"candidate-votes";
const CLEANED_VOTES_WATERMARK_KEY: &[u8; 23] = b"cleaned-votes-watermark";
#[cfg(test)]
const MAX_CLEAN_BATCH_SIZE: u32 = 10;
#[cfg(not(test))]
const MAX_CLEAN_BATCH_SIZE: u32 = 300;
pub struct DbBackend {
inner: Arc<dyn Database>,
config: ColumnConfiguration,
metrics: Metrics,
}
impl DbBackend {
pub fn new(db: Arc<dyn Database>, config: ColumnConfiguration, metrics: Metrics) -> Self {
Self { inner: db, config, metrics }
}
fn add_vote_cleanup_tx(
&mut self,
tx: &mut DBTransaction,
earliest_session: SessionIndex,
) -> FatalResult<()> {
let watermark = load_cleaned_votes_watermark(&*self.inner, &self.config)?.unwrap_or(0);
let clean_until = if earliest_session.saturating_sub(watermark) > MAX_CLEAN_BATCH_SIZE {
watermark + MAX_CLEAN_BATCH_SIZE
} else {
earliest_session
};
gum::trace!(
target: LOG_TARGET,
?watermark,
?clean_until,
?earliest_session,
?MAX_CLEAN_BATCH_SIZE,
"WriteEarliestSession"
);
for index in watermark..clean_until {
gum::trace!(
target: LOG_TARGET,
?index,
encoded = ?candidate_votes_session_prefix(index),
"Cleaning votes for session index"
);
tx.delete_prefix(self.config.col_data, &candidate_votes_session_prefix(index));
}
tx.put_vec(self.config.col_data, CLEANED_VOTES_WATERMARK_KEY, clean_until.encode());
Ok(())
}
}
impl Backend for DbBackend {
fn load_earliest_session(&self) -> SubsystemResult<Option<SessionIndex>> {
load_earliest_session(&*self.inner, &self.config)
}
fn load_recent_disputes(&self) -> SubsystemResult<Option<RecentDisputes>> {
load_recent_disputes(&*self.inner, &self.config)
}
fn load_candidate_votes(
&self,
session: SessionIndex,
candidate_hash: &CandidateHash,
) -> SubsystemResult<Option<CandidateVotes>> {
load_candidate_votes(&*self.inner, &self.config, session, candidate_hash)
}
fn write<I>(&mut self, ops: I) -> FatalResult<()>
where
I: IntoIterator<Item = BackendWriteOp>,
{
let mut tx = DBTransaction::new();
let mut cleanup_timer = None;
for op in ops {
match op {
BackendWriteOp::WriteEarliestSession(session) => {
cleanup_timer = match cleanup_timer.take() {
None => Some(self.metrics.time_vote_cleanup()),
Some(t) => Some(t),
};
self.add_vote_cleanup_tx(&mut tx, session)?;
tx.put_vec(self.config.col_data, EARLIEST_SESSION_KEY, session.encode());
},
BackendWriteOp::WriteRecentDisputes(recent_disputes) => {
tx.put_vec(self.config.col_data, RECENT_DISPUTES_KEY, recent_disputes.encode());
},
BackendWriteOp::WriteCandidateVotes(session, candidate_hash, votes) => {
gum::trace!(target: LOG_TARGET, ?session, "Writing candidate votes");
tx.put_vec(
self.config.col_data,
&candidate_votes_key(session, &candidate_hash),
votes.encode(),
);
},
BackendWriteOp::DeleteCandidateVotes(session, candidate_hash) => {
tx.delete(self.config.col_data, &candidate_votes_key(session, &candidate_hash));
},
}
}
self.inner.write(tx).map_err(FatalError::DbWriteFailed)
}
}
fn candidate_votes_key(session: SessionIndex, candidate_hash: &CandidateHash) -> [u8; 15 + 4 + 32] {
let mut buf = [0u8; 15 + 4 + 32];
buf[..15].copy_from_slice(CANDIDATE_VOTES_SUBKEY);
buf[15..][..4].copy_from_slice(&session.to_be_bytes());
candidate_hash.using_encoded(|s| buf[(15 + 4)..].copy_from_slice(s));
buf
}
fn candidate_votes_session_prefix(session: SessionIndex) -> [u8; 15 + 4] {
let mut buf = [0u8; 15 + 4];
buf[..15].copy_from_slice(CANDIDATE_VOTES_SUBKEY);
buf[15..][..4].copy_from_slice(&session.to_be_bytes());
buf
}
#[derive(Debug, Clone)]
pub struct ColumnConfiguration {
pub col_data: u32,
}
#[derive(Debug, Clone, Encode, Decode)]
pub struct CandidateVotes {
pub candidate_receipt: CandidateReceipt,
pub valid: Vec<(ValidDisputeStatementKind, ValidatorIndex, ValidatorSignature)>,
pub invalid: Vec<(InvalidDisputeStatementKind, ValidatorIndex, ValidatorSignature)>,
}
impl From<CandidateVotes> for polkadot_node_primitives::CandidateVotes {
fn from(db_votes: CandidateVotes) -> polkadot_node_primitives::CandidateVotes {
polkadot_node_primitives::CandidateVotes {
candidate_receipt: db_votes.candidate_receipt,
valid: db_votes.valid.into_iter().map(|(kind, i, sig)| (i, (kind, sig))).collect(),
invalid: db_votes.invalid.into_iter().map(|(kind, i, sig)| (i, (kind, sig))).collect(),
}
}
}
impl From<polkadot_node_primitives::CandidateVotes> for CandidateVotes {
fn from(primitive_votes: polkadot_node_primitives::CandidateVotes) -> CandidateVotes {
CandidateVotes {
candidate_receipt: primitive_votes.candidate_receipt,
valid: primitive_votes
.valid
.into_iter()
.map(|(i, (kind, sig))| (kind, i, sig))
.collect(),
invalid: primitive_votes.invalid.into_iter().map(|(i, (k, sig))| (k, i, sig)).collect(),
}
}
}
pub type RecentDisputes = std::collections::BTreeMap<(SessionIndex, CandidateHash), DisputeStatus>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
Codec(#[from] parity_scale_codec::Error),
}
impl From<Error> for crate::error::Error {
fn from(err: Error) -> Self {
match err {
Error::Io(io) => Self::Io(io),
Error::Codec(e) => Self::Codec(e),
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
fn load_decode<D: Decode>(db: &dyn Database, col_data: u32, key: &[u8]) -> Result<Option<D>> {
match db.get(col_data, key)? {
None => Ok(None),
Some(raw) => D::decode(&mut &raw[..]).map(Some).map_err(Into::into),
}
}
pub(crate) fn load_candidate_votes(
db: &dyn Database,
config: &ColumnConfiguration,
session: SessionIndex,
candidate_hash: &CandidateHash,
) -> SubsystemResult<Option<CandidateVotes>> {
load_decode(db, config.col_data, &candidate_votes_key(session, candidate_hash))
.map_err(|e| SubsystemError::with_origin("dispute-coordinator", e))
}
pub(crate) fn load_earliest_session(
db: &dyn Database,
config: &ColumnConfiguration,
) -> SubsystemResult<Option<SessionIndex>> {
load_decode(db, config.col_data, EARLIEST_SESSION_KEY)
.map_err(|e| SubsystemError::with_origin("dispute-coordinator", e))
}
pub(crate) fn load_recent_disputes(
db: &dyn Database,
config: &ColumnConfiguration,
) -> SubsystemResult<Option<RecentDisputes>> {
load_decode(db, config.col_data, RECENT_DISPUTES_KEY)
.map_err(|e| SubsystemError::with_origin("dispute-coordinator", e))
}
pub(crate) fn note_current_session(
overlay_db: &mut OverlayedBackend<'_, impl Backend>,
current_session: SessionIndex,
) -> SubsystemResult<()> {
let new_earliest = current_session.saturating_sub(DISPUTE_WINDOW.get());
match overlay_db.load_earliest_session()? {
None => {
overlay_db.write_earliest_session(new_earliest);
},
Some(prev_earliest) if new_earliest > prev_earliest => {
overlay_db.write_earliest_session(new_earliest);
{
let mut recent_disputes = overlay_db.load_recent_disputes()?.unwrap_or_default();
let lower_bound = (new_earliest, CandidateHash(Hash::repeat_byte(0x00)));
let new_recent_disputes = recent_disputes.split_off(&lower_bound);
let pruned_disputes = recent_disputes;
if pruned_disputes.len() != 0 {
overlay_db.write_recent_disputes(new_recent_disputes);
}
}
},
Some(_) => {
},
}
Ok(())
}
fn load_cleaned_votes_watermark(
db: &dyn Database,
config: &ColumnConfiguration,
) -> FatalResult<Option<SessionIndex>> {
load_decode(db, config.col_data, CLEANED_VOTES_WATERMARK_KEY)
.map_err(|e| FatalError::DbReadFailed(e))
}
#[cfg(test)]
mod tests {
use super::*;
use ::test_helpers::{dummy_candidate_receipt, dummy_hash};
use polkadot_primitives::v2::{Hash, Id as ParaId};
fn make_db() -> DbBackend {
let db = kvdb_memorydb::create(1);
let db = polkadot_node_subsystem_util::database::kvdb_impl::DbAdapter::new(db, &[0]);
let store = Arc::new(db);
let config = ColumnConfiguration { col_data: 0 };
DbBackend::new(store, config, Metrics::default())
}
#[test]
fn max_clean_batch_size_is_honored() {
let mut backend = make_db();
let mut overlay_db = OverlayedBackend::new(&backend);
let current_session = MAX_CLEAN_BATCH_SIZE + DISPUTE_WINDOW.get() + 3;
let earliest_session = current_session - DISPUTE_WINDOW.get();
overlay_db.write_earliest_session(0);
let candidate_hash = CandidateHash(Hash::repeat_byte(1));
for session in 0..current_session + 1 {
overlay_db.write_candidate_votes(
session,
candidate_hash,
CandidateVotes {
candidate_receipt: dummy_candidate_receipt(dummy_hash()),
valid: Vec::new(),
invalid: Vec::new(),
},
);
}
assert!(overlay_db.load_candidate_votes(0, &candidate_hash).unwrap().is_some());
assert!(overlay_db
.load_candidate_votes(MAX_CLEAN_BATCH_SIZE - 1, &candidate_hash)
.unwrap()
.is_some());
assert!(overlay_db
.load_candidate_votes(MAX_CLEAN_BATCH_SIZE, &candidate_hash)
.unwrap()
.is_some());
let write_ops = overlay_db.into_write_ops();
backend.write(write_ops).unwrap();
let mut overlay_db = OverlayedBackend::new(&backend);
gum::trace!(target: LOG_TARGET, ?current_session, "Noting current session");
note_current_session(&mut overlay_db, current_session).unwrap();
let write_ops = overlay_db.into_write_ops();
backend.write(write_ops).unwrap();
let mut overlay_db = OverlayedBackend::new(&backend);
assert!(overlay_db
.load_candidate_votes(MAX_CLEAN_BATCH_SIZE - 1, &candidate_hash)
.unwrap()
.is_none());
assert!(overlay_db
.load_candidate_votes(MAX_CLEAN_BATCH_SIZE, &candidate_hash)
.unwrap()
.is_some());
let current_session = current_session + 1;
let earliest_session = earliest_session + 1;
note_current_session(&mut overlay_db, current_session).unwrap();
let write_ops = overlay_db.into_write_ops();
backend.write(write_ops).unwrap();
let overlay_db = OverlayedBackend::new(&backend);
assert!(overlay_db
.load_candidate_votes(earliest_session - 1, &candidate_hash)
.unwrap()
.is_none());
assert!(overlay_db
.load_candidate_votes(earliest_session, &candidate_hash)
.unwrap()
.is_some());
assert!(overlay_db
.load_candidate_votes(current_session - 1, &candidate_hash)
.unwrap()
.is_some());
}
#[test]
fn overlay_pre_and_post_commit_consistency() {
let mut backend = make_db();
let mut overlay_db = OverlayedBackend::new(&backend);
overlay_db.write_earliest_session(0);
overlay_db.write_earliest_session(1);
overlay_db.write_recent_disputes(
vec![((0, CandidateHash(Hash::repeat_byte(0))), DisputeStatus::Active)]
.into_iter()
.collect(),
);
overlay_db.write_recent_disputes(
vec![((1, CandidateHash(Hash::repeat_byte(1))), DisputeStatus::Active)]
.into_iter()
.collect(),
);
overlay_db.write_candidate_votes(
1,
CandidateHash(Hash::repeat_byte(1)),
CandidateVotes {
candidate_receipt: dummy_candidate_receipt(dummy_hash()),
valid: Vec::new(),
invalid: Vec::new(),
},
);
overlay_db.write_candidate_votes(
1,
CandidateHash(Hash::repeat_byte(1)),
CandidateVotes {
candidate_receipt: {
let mut receipt = dummy_candidate_receipt(dummy_hash());
receipt.descriptor.para_id = ParaId::from(5_u32);
receipt
},
valid: Vec::new(),
invalid: Vec::new(),
},
);
assert_eq!(overlay_db.load_earliest_session().unwrap().unwrap(), 1);
assert_eq!(
overlay_db.load_recent_disputes().unwrap().unwrap(),
vec![((1, CandidateHash(Hash::repeat_byte(1))), DisputeStatus::Active),]
.into_iter()
.collect()
);
assert_eq!(
overlay_db
.load_candidate_votes(1, &CandidateHash(Hash::repeat_byte(1)))
.unwrap()
.unwrap()
.candidate_receipt
.descriptor
.para_id,
ParaId::from(5),
);
let write_ops = overlay_db.into_write_ops();
backend.write(write_ops).unwrap();
assert_eq!(backend.load_earliest_session().unwrap().unwrap(), 1);
assert_eq!(
backend.load_recent_disputes().unwrap().unwrap(),
vec![((1, CandidateHash(Hash::repeat_byte(1))), DisputeStatus::Active),]
.into_iter()
.collect()
);
assert_eq!(
backend
.load_candidate_votes(1, &CandidateHash(Hash::repeat_byte(1)))
.unwrap()
.unwrap()
.candidate_receipt
.descriptor
.para_id,
ParaId::from(5),
);
}
#[test]
fn overlay_preserves_candidate_votes_operation_order() {
let mut backend = make_db();
let mut overlay_db = OverlayedBackend::new(&backend);
overlay_db.write_candidate_votes(
1,
CandidateHash(Hash::repeat_byte(1)),
CandidateVotes {
candidate_receipt: dummy_candidate_receipt(Hash::random()),
valid: Vec::new(),
invalid: Vec::new(),
},
);
let receipt = dummy_candidate_receipt(dummy_hash());
overlay_db.write_candidate_votes(
1,
CandidateHash(Hash::repeat_byte(1)),
CandidateVotes {
candidate_receipt: receipt.clone(),
valid: Vec::new(),
invalid: Vec::new(),
},
);
let write_ops = overlay_db.into_write_ops();
backend.write(write_ops).unwrap();
assert_eq!(
backend
.load_candidate_votes(1, &CandidateHash(Hash::repeat_byte(1)))
.unwrap()
.unwrap()
.candidate_receipt,
receipt,
);
}
#[test]
fn note_current_session_prunes_old() {
let mut backend = make_db();
let hash_a = CandidateHash(Hash::repeat_byte(0x0a));
let hash_b = CandidateHash(Hash::repeat_byte(0x0b));
let hash_c = CandidateHash(Hash::repeat_byte(0x0c));
let hash_d = CandidateHash(Hash::repeat_byte(0x0d));
let prev_earliest_session = 0;
let new_earliest_session = 5;
let current_session = 5 + DISPUTE_WINDOW.get();
let super_old_no_dispute = 1;
let very_old = 3;
let slightly_old = 4;
let very_recent = current_session - 1;
let blank_candidate_votes = || CandidateVotes {
candidate_receipt: dummy_candidate_receipt(dummy_hash()),
valid: Vec::new(),
invalid: Vec::new(),
};
let mut overlay_db = OverlayedBackend::new(&backend);
overlay_db.write_earliest_session(prev_earliest_session);
overlay_db.write_recent_disputes(
vec![
((very_old, hash_a), DisputeStatus::Active),
((slightly_old, hash_b), DisputeStatus::Active),
((new_earliest_session, hash_c), DisputeStatus::Active),
((very_recent, hash_d), DisputeStatus::Active),
]
.into_iter()
.collect(),
);
overlay_db.write_candidate_votes(super_old_no_dispute, hash_a, blank_candidate_votes());
overlay_db.write_candidate_votes(very_old, hash_a, blank_candidate_votes());
overlay_db.write_candidate_votes(slightly_old, hash_b, blank_candidate_votes());
overlay_db.write_candidate_votes(new_earliest_session, hash_c, blank_candidate_votes());
overlay_db.write_candidate_votes(very_recent, hash_d, blank_candidate_votes());
let write_ops = overlay_db.into_write_ops();
backend.write(write_ops).unwrap();
let mut overlay_db = OverlayedBackend::new(&backend);
note_current_session(&mut overlay_db, current_session).unwrap();
assert_eq!(overlay_db.load_earliest_session().unwrap(), Some(new_earliest_session));
assert_eq!(
overlay_db.load_recent_disputes().unwrap().unwrap(),
vec![
((new_earliest_session, hash_c), DisputeStatus::Active),
((very_recent, hash_d), DisputeStatus::Active),
]
.into_iter()
.collect(),
);
let write_ops = overlay_db.into_write_ops();
backend.write(write_ops).unwrap();
let overlay_db = OverlayedBackend::new(&backend);
assert!(overlay_db
.load_candidate_votes(super_old_no_dispute, &hash_a)
.unwrap()
.is_none());
assert!(overlay_db.load_candidate_votes(very_old, &hash_a).unwrap().is_none());
assert!(overlay_db.load_candidate_votes(slightly_old, &hash_b).unwrap().is_none());
assert!(overlay_db
.load_candidate_votes(new_earliest_session, &hash_c)
.unwrap()
.is_some());
assert!(overlay_db.load_candidate_votes(very_recent, &hash_d).unwrap().is_some());
}
}