Back to Site
Loading...
Searching...
No Matches
peer_id.h
Go to the documentation of this file.
1#pragma once
2
16#include "core/bytes.h"
17
18#include <array>
19#include <cstdint>
20#include <optional>
21#include <string>
22#include <string_view>
23
24namespace librats {
25
26class PeerId {
27public:
28 static constexpr size_t kSize = 32;
29
30 PeerId() = default;
31
33 static PeerId from_public_key(const uint8_t* key, size_t len);
34 static PeerId from_public_key(ByteView key) { return from_public_key(key.data(), key.size()); }
35
37 static std::optional<PeerId> from_bytes(ByteView raw);
38
40 static std::optional<PeerId> from_hex(std::string_view hex);
41
42 std::string to_hex() const;
43 std::string short_hex() const;
44
45 const std::array<uint8_t, kSize>& bytes() const noexcept { return bytes_; }
46 bool is_zero() const noexcept;
47
48 bool operator==(const PeerId& o) const noexcept { return bytes_ == o.bytes_; }
49 bool operator!=(const PeerId& o) const noexcept { return bytes_ != o.bytes_; }
50 bool operator<(const PeerId& o) const noexcept { return bytes_ < o.bytes_; }
51
53 struct Hash {
54 size_t operator()(const PeerId& id) const noexcept;
55 };
56
57private:
58 std::array<uint8_t, kSize> bytes_{};
59};
60
61} // namespace librats
bool operator!=(const PeerId &o) const noexcept
Definition peer_id.h:49
const std::array< uint8_t, kSize > & bytes() const noexcept
Definition peer_id.h:45
static std::optional< PeerId > from_hex(std::string_view hex)
Parse a 64-char lowercase/uppercase hex string. nullopt if malformed.
PeerId()=default
std::string to_hex() const
static constexpr size_t kSize
SHA-256 digest length.
Definition peer_id.h:28
static std::optional< PeerId > from_bytes(ByteView raw)
Wrap raw 32 id-bytes verbatim (NOT hashed). nullopt unless exactly kSize.
static PeerId from_public_key(const uint8_t *key, size_t len)
Derive the PeerId from a raw static public key (SHA-256 of the key).
bool is_zero() const noexcept
static PeerId from_public_key(ByteView key)
Definition peer_id.h:34
std::string short_hex() const
first 8 hex chars, for logs
bool operator<(const PeerId &o) const noexcept
Definition peer_id.h:50
Definition node.h:65
Hash functor for use as an unordered_map/set key.
Definition peer_id.h:53
size_t operator()(const PeerId &id) const noexcept