Bitcoin ABC 0.30.7
P2P Digital Currency
hash.cpp
Go to the documentation of this file.
1// Copyright (c) 2013-2016 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <hash.h>
6
8#include <span.h>
9
10inline uint32_t ROTL32(uint32_t x, int8_t r) {
11 return (x << r) | (x >> (32 - r));
12}
13
14uint32_t MurmurHash3(uint32_t nHashSeed, Span<const uint8_t> vDataToHash) {
15 // The following is MurmurHash3 (x86_32), see
16 // http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
17 uint32_t h1 = nHashSeed;
18 const uint32_t c1 = 0xcc9e2d51;
19 const uint32_t c2 = 0x1b873593;
20
21 const int nblocks = vDataToHash.size() / 4;
22
23 //----------
24 // body
25 const uint8_t *blocks = vDataToHash.data();
26
27 for (int i = 0; i < nblocks; ++i) {
28 uint32_t k1 = ReadLE32(blocks + i * 4);
29
30 k1 *= c1;
31 k1 = ROTL32(k1, 15);
32 k1 *= c2;
33
34 h1 ^= k1;
35 h1 = ROTL32(h1, 13);
36 h1 = h1 * 5 + 0xe6546b64;
37 }
38
39 //----------
40 // tail
41 const uint8_t *tail = vDataToHash.data() + nblocks * 4;
42
43 uint32_t k1 = 0;
44
45 switch (vDataToHash.size() & 3) {
46 case 3:
47 k1 ^= tail[2] << 16;
48 // FALLTHROUGH
49 case 2:
50 k1 ^= tail[1] << 8;
51 // FALLTHROUGH
52 case 1:
53 k1 ^= tail[0];
54 k1 *= c1;
55 k1 = ROTL32(k1, 15);
56 k1 *= c2;
57 h1 ^= k1;
58 }
59
60 //----------
61 // finalization
62 h1 ^= vDataToHash.size();
63 h1 ^= h1 >> 16;
64 h1 *= 0x85ebca6b;
65 h1 ^= h1 >> 13;
66 h1 *= 0xc2b2ae35;
67 h1 ^= h1 >> 16;
68
69 return h1;
70}
71
72void BIP32Hash(const ChainCode &chainCode, uint32_t nChild, uint8_t header,
73 const uint8_t data[32], uint8_t output[64]) {
74 uint8_t num[4];
75 num[0] = (nChild >> 24) & 0xFF;
76 num[1] = (nChild >> 16) & 0xFF;
77 num[2] = (nChild >> 8) & 0xFF;
78 num[3] = (nChild >> 0) & 0xFF;
79 CHMAC_SHA512(chainCode.begin(), chainCode.size())
80 .Write(&header, 1)
81 .Write(data, 32)
82 .Write(num, 4)
83 .Finalize(output);
84}
static const uint8_t k1[32]
A hasher class for HMAC-SHA-512.
Definition: hmac_sha512.h:14
CHMAC_SHA512 & Write(const uint8_t *data, size_t len)
Definition: hmac_sha512.h:23
void Finalize(uint8_t hash[OUTPUT_SIZE])
Definition: hmac_sha512.cpp:30
constexpr std::size_t size() const noexcept
Definition: span.h:209
constexpr C * data() const noexcept
Definition: span.h:198
unsigned int size() const
Definition: uint256.h:93
uint8_t * begin()
Definition: uint256.h:85
256-bit opaque blob.
Definition: uint256.h:129
static uint32_t ReadLE32(const uint8_t *ptr)
Definition: common.h:23
uint32_t MurmurHash3(uint32_t nHashSeed, Span< const uint8_t > vDataToHash)
Definition: hash.cpp:14
void BIP32Hash(const ChainCode &chainCode, uint32_t nChild, uint8_t header, const uint8_t data[32], uint8_t output[64])
Definition: hash.cpp:72
uint32_t ROTL32(uint32_t x, int8_t r)
Definition: hash.cpp:10