forked from bitcoin/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathsaltedhasher.h
76 lines (63 loc) · 1.81 KB
/
saltedhasher.h
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
// Copyright (c) 2019-2023 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_SALTEDHASHER_H
#define BITCOIN_SALTEDHASHER_H
#include <hash.h>
#include <uint256.h>
#include <crypto/siphash.h>
/** Helper classes for std::unordered_map and std::unordered_set hashing */
template<typename T> struct SaltedHasherImpl;
template<typename N>
struct SaltedHasherImpl<std::pair<uint256, N>>
{
static std::size_t CalcHash(const std::pair<uint256, N>& v, uint64_t k0, uint64_t k1)
{
return SipHashUint256Extra(k0, k1, v.first, (uint32_t) v.second);
}
};
template<typename N>
struct SaltedHasherImpl<std::pair<N, uint256>>
{
static std::size_t CalcHash(const std::pair<N, uint256>& v, uint64_t k0, uint64_t k1)
{
return SipHashUint256Extra(k0, k1, v.second, (uint32_t) v.first);
}
};
template<>
struct SaltedHasherImpl<uint256>
{
static std::size_t CalcHash(const uint256& v, uint64_t k0, uint64_t k1)
{
return SipHashUint256(k0, k1, v);
}
};
struct SaltedHasherBase
{
/** Salt */
const uint64_t k0, k1;
SaltedHasherBase();
};
/* Allows each instance of unordered maps/sest to have their own salt */
template<typename T, typename S>
struct SaltedHasher
{
S s;
std::size_t operator()(const T& v) const
{
return SaltedHasherImpl<T>::CalcHash(v, s.k0, s.k1);
}
};
/* Allows to use a static salt for all instances. The salt is a random value set at startup
* (through static initialization)
*/
struct StaticSaltedHasher
{
static SaltedHasherBase s;
template<typename T>
std::size_t operator()(const T& v) const
{
return SaltedHasherImpl<T>::CalcHash(v, s.k0, s.k1);
}
};
#endif // BITCOIN_SALTEDHASHER_H