Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate hashes with random keys to avoid collisions #212

Draft
wants to merge 1 commit into
base: trunk
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 7 additions & 12 deletions src/util/common/hashmap.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,22 @@
#include "buffer.hpp"
#include "crypto/siphash.h"
#include "hash.hpp"
#include "random_source.hpp"

#include <array>
#include <cstring>

namespace cbdc::hashing {
/// \brief SipHash function to generate STL data structure hash keys for
/// system IDs.
///
/// [TODO: Uses randomly generated initialization keys to insure that
/// colliding values will differ from run to run.] For transaction data
/// that comes from users, it is important to key data in sets and hashmaps
/// non-deterministically. Otherwise, malicious actors might pre-calculate
/// colliding values and spam the system with them to cripple performance.
/// \tparam T hash-like type to hash.
template<class T>
struct const_sip_hash {
static_assert(std::is_trivial_v<T>);
auto operator()(T const& tx) const noexcept -> size_t {
// TODO: pick the initialization key at random.
static constexpr std::array<uint64_t, 2> siphash_key{0x1337,
0x1337};
auto generator = random_source("/dev/urandom");
std::array<uint64_t, 2> siphash_key{generator(),
generator()};
CSipHasher hasher(siphash_key[0], siphash_key[1]);
std::array<unsigned char, sizeof(tx)> tx_arr{};
std::memcpy(tx_arr.data(), &tx, sizeof(tx));
Expand All @@ -41,9 +36,9 @@ namespace cbdc::hashing {
template<>
struct const_sip_hash<buffer> {
auto operator()(const buffer& buf) const noexcept -> size_t {
// TODO: pick the initialization key at random.
static constexpr std::array<uint64_t, 2> siphash_key{0x1337,
0x1337};
auto generator = random_source("/dev/urandom");
std::array<uint64_t, 2> siphash_key{generator(),
generator()};
CSipHasher hasher(siphash_key[0], siphash_key[1]);
std::vector<unsigned char> arr(buf.size());
std::memcpy(arr.data(), buf.data(), buf.size());
Expand Down