#ifndef BITCOIN_UINT256_H
#define BITCOIN_UINT256_H
#include <array>
#include <assert.h>
#include <cstring>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <vector>
template<unsigned int BITS>
class base_blob
{
protected:
enum { WIDTH=BITS/8 };
alignas(uint32_t) uint8_t data[WIDTH];
public:
base_blob()
{
memset(data, 0, sizeof(data));
}
explicit base_blob(const std::vector<unsigned char>& vch);
bool IsNull() const
{
for (int i = 0; i < WIDTH; i++)
if (data[i] != 0)
return false;
return true;
}
void SetNull()
{
memset(data, 0, sizeof(data));
}
friend inline bool operator==(const base_blob& a, const base_blob& b) { return memcmp(a.data, b.data, sizeof(a.data)) == 0; }
friend inline bool operator!=(const base_blob& a, const base_blob& b) { return memcmp(a.data, b.data, sizeof(a.data)) != 0; }
friend inline bool operator<(const base_blob& a, const base_blob& b) { return memcmp(a.data, b.data, sizeof(a.data)) < 0; }
std::string GetHex() const;
void SetHex(const char* psz);
void SetHex(const std::string& str);
std::string ToString() const;
unsigned char* begin()
{
return &data[0];
}
unsigned char* end()
{
return &data[WIDTH];
}
const unsigned char* begin() const
{
return &data[0];
}
const unsigned char* end() const
{
return &data[WIDTH];
}
unsigned int size() const
{
return sizeof(data);
}
uint64_t GetUint64(int pos) const
{
const uint8_t* ptr = data + pos * 8;
return ((uint64_t)ptr[0]) | \
((uint64_t)ptr[1]) << 8 | \
((uint64_t)ptr[2]) << 16 | \
((uint64_t)ptr[3]) << 24 | \
((uint64_t)ptr[4]) << 32 | \
((uint64_t)ptr[5]) << 40 | \
((uint64_t)ptr[6]) << 48 | \
((uint64_t)ptr[7]) << 56;
}
std::array<uint8_t, WIDTH> GetRawBytes() const
{
std::array<uint8_t, WIDTH> buf = {};
std::memcpy(buf.data(), this->begin(), WIDTH);
return buf;
}
template<typename Stream>
void Serialize(Stream& s) const
{
s.write((char*)data, sizeof(data));
}
template<typename Stream>
void Unserialize(Stream& s)
{
s.read((char*)data, sizeof(data));
}
};
class uint160 : public base_blob<160> {
public:
uint160() {}
explicit uint160(const std::vector<unsigned char>& vch) : base_blob<160>(vch) {}
};
class uint256 : public base_blob<256> {
public:
uint256() {}
explicit uint256(const std::vector<unsigned char>& vch) : base_blob<256>(vch) {}
static uint256 FromRawBytes(std::array<uint8_t, 32> bytes)
{
uint256 buf;
std::memcpy(buf.begin(), bytes.data(), 32);
return buf;
}
std::array<uint8_t, 32> ToRawBytes() const
{
std::array<uint8_t, 32> buf;
std::memcpy(buf.data(), begin(), 32);
return buf;
}
uint64_t GetCheapHash() const
{
uint64_t result;
memcpy((void*)&result, (void*)data, 8);
return result;
}
};
inline uint256 uint256S(const char *str)
{
uint256 rv;
rv.SetHex(str);
return rv;
}
inline uint256 uint256S(const std::string& str)
{
uint256 rv;
rv.SetHex(str);
return rv;
}
static const uint256 LEGACY_TX_AUTH_DIGEST =
uint256S("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
#endif