-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathcandidate_view.hpp
95 lines (79 loc) · 2.84 KB
/
candidate_view.hpp
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
/**
* Copyright Quadrivium LLC
* All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <memory>
#include <vector>
namespace kagome::parachain {
/// Tracks our impression of a single peer's view of the candidates a
/// validator has seconded for a given relay-parent.
///
/// It is expected to receive at most `VC_THRESHOLD` from us and be aware of
/// at most `VC_THRESHOLD` via other means.
struct VcPerPeerTracker {
static constexpr size_t kTrackerThreshold = 2;
VcPerPeerTracker(const log::Logger &logger) : logger_(logger) {
BOOST_ASSERT(logger_);
local_observed.reserve(kTrackerThreshold);
remote_observed.reserve(kTrackerThreshold);
}
/// Note that the remote should now be aware that a validator has seconded a
/// given candidate (by hash) based on a message that we have sent it from
/// our local pool.
void note_local(const network::CandidateHash &h) {
if (!note_hash(local_observed, h)) {
logger_->warn(
"Statement distribution is erroneously attempting to distribute "
"more than {} candidate(s) per validator index. Ignoring.",
kTrackerThreshold);
}
}
/// Note that the remote should now be aware that a validator has seconded a
/// given candidate (by hash) based on a message that it has sent us.
///
/// Returns `true` if the peer was allowed to send us such a message,
/// `false` otherwise.
bool note_remote(const network::CandidateHash &hash) {
return note_hash(remote_observed, hash);
}
/// Returns `true` if the peer is allowed to send us such a message, `false`
/// otherwise.
bool is_wanted_candidate(const network::CandidateHash &hash) {
return !contains(remote_observed, hash) && !is_full(remote_observed);
}
private:
using CandidateHashPool = std::vector<network::CandidateHash>;
bool contains(CandidateHashPool &pool, const network::CandidateHash &hash) {
for (const auto &h : pool) {
if (h == hash) {
return true;
}
}
return false;
}
bool is_full(CandidateHashPool &pool) {
return pool.size() == pool.capacity();
}
bool note_hash(CandidateHashPool &pool,
const network::CandidateHash &hash) {
std::unique_ptr<CandidateHashPool, void (*)(CandidateHashPool *)> _keeper(
&pool, [](CandidateHashPool *pool) {
BOOST_ASSERT(pool != nullptr);
BOOST_ASSERT(pool->capacity() == kTrackerThreshold);
});
if (contains(pool, hash)) {
return true;
}
if (!is_full(pool)) {
pool.push_back(hash);
return true;
}
return false;
}
CandidateHashPool local_observed;
CandidateHashPool remote_observed;
log::Logger logger_;
};
} // namespace kagome::parachain