Kagome
Polkadot Runtime Engine in C++17
grandpa_context.hpp
Go to the documentation of this file.
1 
6 #ifndef KAGOME_CONSENSUS_GRANDPACONTEXT
7 #define KAGOME_CONSENSUS_GRANDPACONTEXT
8 
11 
12 #include <libp2p/peer/peer_id.hpp>
13 
15 
16  class GrandpaContext final {
17  public:
18  // RAII holder of context on the stack
19  class Guard {
20  // Avoid creation of guard in the heap
21  void *operator new(size_t) = delete;
22  void *operator new(size_t, void *) = delete;
23  void *operator new[](size_t) = delete;
24  void *operator new[](size_t, void *) = delete;
25 
26  public:
27  Guard() {
28  // Create context in ctor
29  create();
30  }
31 
32  ~Guard() {
33  // Release context in the out of scope
34  release();
35  }
36  };
37 
38  // Payload
39  std::optional<const libp2p::peer::PeerId> peer_id{};
40  std::optional<const network::VoteMessage> vote{};
41  std::optional<const network::CatchUpResponse> catch_up_response{};
42  std::optional<const network::FullCommitMessage> commit{};
43  std::set<primitives::BlockInfo, std::greater<primitives::BlockInfo>>
48 
49  static void set(std::shared_ptr<GrandpaContext> context) {
50  auto &opt = instance();
51  if (opt.has_value()) {
52  throw std::runtime_error(
53  "Attempt to set GrandpaContext in thread, "
54  "which has already have it set");
55  }
56  opt.emplace(std::move(context));
57  }
58 
59  static std::optional<std::shared_ptr<GrandpaContext>> get() {
60  auto opt = instance();
61  return opt;
62  }
63 
64  private:
65  static std::optional<std::shared_ptr<GrandpaContext>> &instance() {
66  static thread_local std::optional<std::shared_ptr<GrandpaContext>> inst;
67  return inst;
68  }
69 
70  static void create() {
71  auto &opt = instance();
72  if (not opt.has_value()) {
73  opt.emplace(std::make_shared<GrandpaContext>());
74  }
75  }
76 
77  static std::shared_ptr<GrandpaContext> release() {
78  auto &opt = instance();
79  auto ptr = std::move(opt.value());
80  opt.reset();
81  return ptr;
82  }
83  };
84 
85 } // namespace kagome::consensus::grandpa
86 
87 #endif // KAGOME_CONSENSUS_GRANDPACONTEXT
std::optional< const libp2p::peer::PeerId > peer_id
std::optional< const network::FullCommitMessage > commit
std::set< primitives::BlockInfo, std::greater< primitives::BlockInfo > > missing_blocks
static std::shared_ptr< GrandpaContext > release()
std::optional< const network::VoteMessage > vote
std::optional< const network::CatchUpResponse > catch_up_response
static std::optional< std::shared_ptr< GrandpaContext > > & instance()