refactor: encapsulate vector/array keys into Obfuscation

This commit is contained in:
Lőrinc
2025-07-05 14:39:19 +02:00
parent 377aab8e5a
commit 478d40afc6
13 changed files with 136 additions and 85 deletions

View File

@@ -7,19 +7,32 @@
#include <cstdint>
#include <span.h>
#include <tinyformat.h>
#include <util/strencodings.h>
#include <ios>
class Obfuscation
{
public:
static constexpr size_t KEY_SIZE{sizeof(uint64_t)};
using KeyType = uint64_t;
static constexpr size_t KEY_SIZE{sizeof(KeyType)};
void Xor(std::span<std::byte> write, std::span<const std::byte> key, size_t key_offset = 0)
Obfuscation() : m_key{KEY_SIZE, std::byte{0}} {}
explicit Obfuscation(std::span<const std::byte, KEY_SIZE> key_bytes)
{
assert(key.size() == KEY_SIZE);
m_key = {key_bytes.begin(), key_bytes.end()};
}
operator bool() const { return ToKey() != 0; }
void operator()(std::span<std::byte> write, size_t key_offset = 0) const
{
assert(m_key.size() == KEY_SIZE);
key_offset %= KEY_SIZE;
for (size_t i = 0, j = key_offset; i != write.size(); i++) {
write[i] ^= key[j++];
write[i] ^= m_key[j++];
// This potentially acts on very many bytes of data, so it's
// important that we calculate `j`, i.e. the `key` index in this
@@ -29,6 +42,34 @@ public:
j = 0;
}
}
template <typename Stream>
void Serialize(Stream& s) const
{
s << m_key;
}
template <typename Stream>
void Unserialize(Stream& s)
{
s >> m_key;
if (m_key.size() != KEY_SIZE) throw std::ios_base::failure(strprintf("Obfuscation key size should be exactly %s bytes long", KEY_SIZE));
}
std::string HexKey() const
{
return HexStr(m_key);
}
private:
std::vector<std::byte> m_key;
KeyType ToKey() const
{
KeyType key{};
std::memcpy(&key, m_key.data(), KEY_SIZE);
return key;
}
};
#endif // BITCOIN_UTIL_OBFUSCATION_H