Kagome
Polkadot Runtime Engine in C++17
key_cache.hpp
Go to the documentation of this file.
1 
6 #ifndef KAGOME_KEY_CACHE_HPP
7 #define KAGOME_KEY_CACHE_HPP
8 
9 #include <memory>
10 #include <unordered_map>
11 #include <unordered_set>
12 
13 #include <optional>
14 
16 
17 namespace kagome::crypto {
18 
25  template <typename CryptoSuite>
26  class KeyCache {
27  public:
30  using Keypair = typename CryptoSuite::Keypair;
31  using Seed = typename CryptoSuite::Seed;
32 
33  explicit KeyCache(KeyTypeId type, std::shared_ptr<CryptoSuite> suite)
34  : type_{type}, suite_{std::move(suite)} {
35  BOOST_ASSERT(suite_ != nullptr);
36  }
37 
38  void insert(PublicKey pubkey, PrivateKey privkey) {
39  // this should be refactored in the future, the session key should be
40  // determined by either node's config or node's internal logic
41  if (not session_key_) {
42  session_key_ = suite_->composeKeypair(pubkey, privkey);
43  }
44  cache_.emplace(std::move(pubkey), std::move(privkey));
45  }
46 
50  std::optional<Keypair> const &getSessionKey() const noexcept {
51  return session_key_;
52  }
53 
54  std::unordered_set<PublicKey> getPublicKeys() const {
55  std::unordered_set<PublicKey> keys;
56  for (auto &&[k, v] : cache_) {
57  keys.emplace(k);
58  }
59  return keys;
60  }
61 
62  std::optional<Keypair> searchKeypair(const PublicKey &key) const {
63  auto it = cache_.find(key);
64  if (it != cache_.end()) {
65  return suite_->composeKeypair(it->first, it->second);
66  }
67  return std::nullopt;
68  }
69 
70  private:
72  std::optional<Keypair> session_key_;
73  std::unordered_map<PublicKey, PrivateKey> cache_;
74  std::shared_ptr<CryptoSuite> suite_;
75  };
76 } // namespace kagome::crypto
77 
78 #endif // KAGOME_KEY_CACHE_HPP
std::optional< Keypair > session_key_
Definition: key_cache.hpp:72
KeyCache(KeyTypeId type, std::shared_ptr< CryptoSuite > suite)
Definition: key_cache.hpp:33
std::unordered_map< PublicKey, PrivateKey > cache_
Definition: key_cache.hpp:73
typename kagome::crypto::Sr25519Suite::Seed Seed
Definition: key_cache.hpp:31
std::shared_ptr< CryptoSuite > suite_
Definition: key_cache.hpp:74
uint32_t KeyTypeId
Key type identifier.
Definition: key_type.hpp:21
std::optional< Keypair > const & getSessionKey() const noexcept
Definition: key_cache.hpp:50
typename kagome::crypto::Sr25519Suite::Keypair Keypair
Definition: key_cache.hpp:30
typename kagome::crypto::Sr25519Suite::PublicKey PublicKey
Definition: key_cache.hpp:28
void insert(PublicKey pubkey, PrivateKey privkey)
Definition: key_cache.hpp:38
std::optional< Keypair > searchKeypair(const PublicKey &key) const
Definition: key_cache.hpp:62
std::unordered_set< PublicKey > getPublicKeys() const
Definition: key_cache.hpp:54
typename kagome::crypto::Sr25519Suite::PrivateKey PrivateKey
Definition: key_cache.hpp:29