From 607a5de3408758b0d2b6f7e0a75ff9df2be45448 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Tue, 4 Mar 2014 11:46:26 -0600 Subject: [PATCH] Repotted Common.h. --- alethzero/MainWin.cpp | 14 +- alethzero/MainWin.h | 2 +- eth/main.cpp | 16 +- libethereum/BlockChain.cpp | 2 +- libethereum/BlockChain.h | 3 +- libethereum/Common.cpp | 280 -------------- libethereum/Common.h | 611 +------------------------------ libethereum/CommonData.cpp | 96 +++++ libethereum/CommonEth.cpp | 200 ++++++++++ libethereum/CommonIO.cpp | 48 +++ libethereum/Dagger.h | 3 +- libethereum/Exceptions.h | 12 +- libethereum/FixedHash.cpp | 25 ++ libethereum/Instruction.cpp | 3 +- libethereum/Log.cpp | 41 +++ libethereum/MemTrie.cpp | 12 +- libethereum/PeerNetwork.h | 1 + libethereum/PeerServer.cpp | 4 +- libethereum/PeerSession.cpp | 8 +- libethereum/State.cpp | 8 +- libethereum/State.h | 4 +- libethereum/Transaction.cpp | 2 +- libethereum/Transaction.h | 2 +- libethereum/TransactionQueue.cpp | 1 + libethereum/TrieDB.h | 6 +- libethereum/TrieHash.cpp | 12 +- libethereum/TrieHash.h | 1 + libethereum/UPnP.cpp | 1 + test/crypto.cpp | 37 +- test/dagger.cpp | 1 + test/hexPrefix.cpp | 5 +- test/main.cpp | 2 +- test/rlp.cpp | 5 +- test/trie.cpp | 6 +- test/vm.cpp | 1 + 35 files changed, 507 insertions(+), 968 deletions(-) create mode 100644 libethereum/CommonData.cpp create mode 100644 libethereum/CommonEth.cpp create mode 100644 libethereum/CommonIO.cpp create mode 100644 libethereum/FixedHash.cpp create mode 100644 libethereum/Log.cpp diff --git a/alethzero/MainWin.cpp b/alethzero/MainWin.cpp index 5fd9b5509..e0415ca8b 100644 --- a/alethzero/MainWin.cpp +++ b/alethzero/MainWin.cpp @@ -31,12 +31,12 @@ using eth::Secret; using eth::Transaction; // functions -using eth::asHex; +using eth::toHex; using eth::assemble; using eth::compileLisp; using eth::disassemble; using eth::formatBalance; -using eth::fromUserHex; +using eth::fromHex; using eth::right160; using eth::simpleDebugOut; using eth::toLog2; @@ -180,7 +180,7 @@ Address Main::fromString(QString const& _a) const if (h256 a = state().contractMemory(m_nameReg, n)) return right160(a); if (_a.size() == 40) - return Address(fromUserHex(_a.toStdString())); + return Address(fromHex(_a.toStdString())); else return Address(); } @@ -258,7 +258,7 @@ void Main::on_nameReg_textChanged() string s = ui->nameReg->text().toStdString(); if (s.size() == 40) { - m_nameReg = Address(fromUserHex(s)); + m_nameReg = Address(fromHex(s)); refresh(true); } } @@ -512,7 +512,7 @@ void Main::on_ourAccounts_doubleClicked() { auto hba = ui->ourAccounts->currentItem()->data(Qt::UserRole).toByteArray(); auto h = Address((byte const*)hba.data(), Address::ConstructFromPointer); - qApp->clipboard()->setText(QString::fromStdString(asHex(h.asArray()))); + qApp->clipboard()->setText(QString::fromStdString(toHex(h.asArray()))); } void Main::on_log_doubleClicked() @@ -524,14 +524,14 @@ void Main::on_accounts_doubleClicked() { auto hba = ui->accounts->currentItem()->data(Qt::UserRole).toByteArray(); auto h = Address((byte const*)hba.data(), Address::ConstructFromPointer); - qApp->clipboard()->setText(QString::fromStdString(asHex(h.asArray()))); + qApp->clipboard()->setText(QString::fromStdString(toHex(h.asArray()))); } void Main::on_contracts_doubleClicked() { auto hba = ui->contracts->currentItem()->data(Qt::UserRole).toByteArray(); auto h = Address((byte const*)hba.data(), Address::ConstructFromPointer); - qApp->clipboard()->setText(QString::fromStdString(asHex(h.asArray()))); + qApp->clipboard()->setText(QString::fromStdString(toHex(h.asArray()))); } void Main::on_destination_textChanged() diff --git a/alethzero/MainWin.h b/alethzero/MainWin.h index 70b2d051c..9f8f781f6 100644 --- a/alethzero/MainWin.h +++ b/alethzero/MainWin.h @@ -5,7 +5,7 @@ #include #include #include -#include +#include namespace Ui { class Main; diff --git a/eth/main.cpp b/eth/main.cpp index b8e26aefb..955721f05 100644 --- a/eth/main.cpp +++ b/eth/main.cpp @@ -138,9 +138,9 @@ int main(int argc, char** argv) else if ((arg == "-c" || arg == "--client-name") && i + 1 < argc) clientName = argv[++i]; else if ((arg == "-a" || arg == "--address" || arg == "--coinbase-address") && i + 1 < argc) - coinbase = h160(fromUserHex(argv[++i])); + coinbase = h160(fromHex(argv[++i])); else if ((arg == "-s" || arg == "--secret") && i + 1 < argc) - us = KeyPair(h256(fromUserHex(argv[++i]))); + us = KeyPair(h256(fromHex(argv[++i]))); else if (arg == "-i" || arg == "--interactive") interactive = true; else if ((arg == "-d" || arg == "--path" || arg == "--db-path") && i + 1 < argc) @@ -228,13 +228,13 @@ int main(int argc, char** argv) else if (cmd == "address") { cout << endl; - cout << "Current address: " + asHex(us.address().asArray()) << endl; + cout << "Current address: " + toHex(us.address().asArray()) << endl; cout << "===" << endl; } else if (cmd == "secret") { cout << endl; - cout << "Current secret: " + asHex(us.secret().asArray()) << endl; + cout << "Current secret: " + toHex(us.secret().asArray()) << endl; cout << "===" << endl; } else if (cmd == "balance") @@ -251,8 +251,8 @@ int main(int argc, char** argv) string rechex; u256 amount; cin >> sechex >> rechex >> amount; - Secret secret = h256(fromUserHex(sechex)); - Address dest = h160(fromUserHex(rechex)); + Secret secret = h256(fromHex(sechex)); + Address dest = h160(fromHex(rechex)); c.transact(secret, dest, amount); } else if (cmd == "send") @@ -260,7 +260,7 @@ int main(int argc, char** argv) string rechex; u256 amount; cin >> rechex >> amount; - Address dest = h160(fromUserHex(rechex)); + Address dest = h160(fromHex(rechex)); c.transact(us.secret(), dest, amount); } else if (cmd == "exit") @@ -271,7 +271,7 @@ int main(int argc, char** argv) } else { - cout << "Address: " << endl << asHex(us.address().asArray()) << endl; + cout << "Address: " << endl << toHex(us.address().asArray()) << endl; c.startNetwork(listenPort, remoteHost, remotePort, mode, peers, publicIP, upnp); eth::uint n = c.blockChain().details().number; if (mining) diff --git a/libethereum/BlockChain.cpp b/libethereum/BlockChain.cpp index 7bf7606da..644c5e2d9 100644 --- a/libethereum/BlockChain.cpp +++ b/libethereum/BlockChain.cpp @@ -45,7 +45,7 @@ std::ostream& operator<<(std::ostream& _out, BlockChain const& _bc) if (it->key().ToString() != "best") { BlockDetails d(RLP(it->value().ToString())); - _out << asHex(it->key().ToString()) << ": " << d.number << " @ " << d.parent << (cmp == it->key().ToString() ? " BEST" : "") << std::endl; + _out << toHex(it->key().ToString()) << ": " << d.number << " @ " << d.parent << (cmp == it->key().ToString() ? " BEST" : "") << std::endl; } delete it; return _out; diff --git a/libethereum/BlockChain.h b/libethereum/BlockChain.h index ee208e508..b295253c7 100644 --- a/libethereum/BlockChain.h +++ b/libethereum/BlockChain.h @@ -22,7 +22,8 @@ #pragma once #include -#include "Common.h" +#include "CommonEth.h" +#include "Log.h" #include "AddressState.h" namespace ldb = leveldb; diff --git a/libethereum/Common.cpp b/libethereum/Common.cpp index 2b08c84fd..7c1d80ff2 100644 --- a/libethereum/Common.cpp +++ b/libethereum/Common.cpp @@ -21,285 +21,5 @@ #include "Common.h" -#include -#include -#if WIN32 -#pragma warning(push) -#pragma warning(disable:4244) -#else -#pragma GCC diagnostic ignored "-Wunused-function" -#endif -#include -#include -#if WIN32 -#pragma warning(pop) -#else -#endif -#include "Exceptions.h" using namespace std; using namespace eth; - -//#define ETH_ADDRESS_DEBUG 1 - -// Logging -int eth::g_logVerbosity = 8; -map eth::g_logOverride; - -ThreadLocalLogName eth::t_logThreadName("main"); - -void eth::simpleDebugOut(std::string const& _s, char const*) -{ - cout << _s << endl << flush; -} - -std::function eth::g_logPost = simpleDebugOut; - -std::string eth::escaped(std::string const& _s, bool _all) -{ - std::string ret; - ret.reserve(_s.size()); - ret.push_back('"'); - for (auto i: _s) - if (i == '"' && !_all) - ret += "\\\""; - else if (i == '\\' && !_all) - ret += "\\\\"; - else if (i < ' ' || i > 127 || _all) - { - ret += "\\x"; - ret.push_back("0123456789abcdef"[(uint8_t)i / 16]); - ret.push_back("0123456789abcdef"[(uint8_t)i % 16]); - } - else - ret.push_back(i); - ret.push_back('"'); - return ret; -} - -std::string eth::randomWord() -{ - static std::mt19937_64 s_eng(0); - std::string ret(std::uniform_int_distribution(4, 10)(s_eng), ' '); - char const n[] = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"; - std::uniform_int_distribution d(0, sizeof(n) - 2); - for (char& c: ret) - c = n[d(s_eng)]; - return ret; -} - -int eth::fromHex(char _i) -{ - if (_i >= '0' && _i <= '9') - return _i - '0'; - if (_i >= 'a' && _i <= 'f') - return _i - 'a' + 10; - if (_i >= 'A' && _i <= 'F') - return _i - 'A' + 10; - throw BadHexCharacter(); -} - -bytes eth::fromUserHex(std::string const& _s) -{ - assert(_s.size() % 2 == 0); - if (_s.size() < 2) - return bytes(); - uint s = (_s[0] == '0' && _s[1] == 'x') ? 2 : 0; - std::vector ret; - ret.reserve((_s.size() - s) / 2); - for (uint i = s; i < _s.size(); i += 2) - ret.push_back((byte)(fromHex(_s[i]) * 16 + fromHex(_s[i + 1]))); - return ret; -} - -bytes eth::toHex(std::string const& _s) -{ - std::vector ret; - ret.reserve(_s.size() * 2); - for (auto i: _s) - { - ret.push_back(i / 16); - ret.push_back(i % 16); - } - return ret; -} - -std::string eth::sha3(std::string const& _input, bool _hex) -{ - if (!_hex) - { - string ret(32, '\0'); - sha3(bytesConstRef((byte const*)_input.data(), _input.size()), bytesRef((byte*)ret.data(), 32)); - return ret; - } - - uint8_t buf[32]; - sha3(bytesConstRef((byte const*)_input.data(), _input.size()), bytesRef((byte*)&(buf[0]), 32)); - std::string ret(64, '\0'); - for (unsigned int i = 0; i < 32; i++) - sprintf((char*)(ret.data())+i*2, "%02x", buf[i]); - return ret; -} - -void eth::sha3(bytesConstRef _input, bytesRef _output) -{ - CryptoPP::SHA3_256 ctx; - ctx.Update((byte*)_input.data(), _input.size()); - assert(_output.size() >= 32); - ctx.Final(_output.data()); -} - -bytes eth::sha3Bytes(bytesConstRef _input) -{ - bytes ret(32); - sha3(_input, &ret); - return ret; -} - -h256 eth::sha3(bytesConstRef _input) -{ - h256 ret; - sha3(_input, bytesRef(&ret[0], 32)); - return ret; -} - -Address eth::toAddress(Secret _private) -{ - secp256k1_start(); - - byte pubkey[65]; - int pubkeylen = 65; - int ok = secp256k1_ecdsa_seckey_verify(_private.data()); - if (!ok) - return Address(); - ok = secp256k1_ecdsa_pubkey_create(pubkey, &pubkeylen, _private.data(), 0); - assert(pubkeylen == 65); - if (!ok) - return Address(); - ok = secp256k1_ecdsa_pubkey_verify(pubkey, 65); - if (!ok) - return Address(); - auto ret = right160(eth::sha3(bytesConstRef(&(pubkey[1]), 64))); -#if ETH_ADDRESS_DEBUG - cout << "---- ADDRESS -------------------------------" << endl; - cout << "SEC: " << _private << endl; - cout << "PUB: " << asHex(bytesConstRef(&(pubkey[1]), 64)) << endl; - cout << "ADR: " << ret << endl; -#endif - return ret; -} - -KeyPair KeyPair::create() -{ - secp256k1_start(); - static std::mt19937_64 s_eng(time(0)); - std::uniform_int_distribution d(0, 255); - - for (int i = 0; i < 100; ++i) - { - h256 sec; - for (unsigned i = 0; i < 32; ++i) - sec[i] = (byte)d(s_eng); - - KeyPair ret(sec); - if (ret.address()) - return ret; - } - return KeyPair(); -} - -KeyPair::KeyPair(h256 _sec): - m_secret(_sec) -{ - int ok = secp256k1_ecdsa_seckey_verify(m_secret.data()); - if (!ok) - return; - - byte pubkey[65]; - int pubkeylen = 65; - ok = secp256k1_ecdsa_pubkey_create(pubkey, &pubkeylen, m_secret.data(), 0); - if (!ok || pubkeylen != 65) - return; - - ok = secp256k1_ecdsa_pubkey_verify(pubkey, 65); - if (!ok) - return; - - m_secret = m_secret; - memcpy(m_public.data(), &(pubkey[1]), 64); - m_address = right160(eth::sha3(bytesConstRef(&(pubkey[1]), 64))); - -#if ETH_ADDRESS_DEBUG - cout << "---- ADDRESS -------------------------------" << endl; - cout << "SEC: " << m_secret << endl; - cout << "PUB: " << m_public << endl; - cout << "ADR: " << m_address << endl; -#endif -} - -static const vector> g_units = -{ - {((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000, "Uether"}, - {((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000, "Vether"}, - {((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000, "Dether"}, - {(((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000, "Nether"}, - {(((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000, "Yether"}, - {(((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000, "Zether"}, - {((u256(1000000000) * 1000000000) * 1000000000) * 1000000000, "Eether"}, - {((u256(1000000000) * 1000000000) * 1000000000) * 1000000, "Pether"}, - {((u256(1000000000) * 1000000000) * 1000000000) * 1000, "Tether"}, - {(u256(1000000000) * 1000000000) * 1000000000, "Gether"}, - {(u256(1000000000) * 1000000000) * 1000000, "Mether"}, - {(u256(1000000000) * 1000000000) * 1000, "Kether"}, - {u256(1000000000) * 1000000000, "ether"}, - {u256(1000000000) * 1000000, "finney"}, - {u256(1000000000) * 1000, "szabo"}, - {u256(1000000000), "Gwei"}, - {u256(1000000), "Mwei"}, - {u256(1000), "Kwei"}, - {u256(1), "wei"} -}; - -vector> const& eth::units() -{ - return g_units; -} - -std::string eth::formatBalance(u256 _b) -{ - ostringstream ret; - if (_b > g_units[0].first * 10000) - { - ret << (_b / g_units[0].first) << " " << g_units[0].second; - return ret.str(); - } - ret << setprecision(5); - for (auto const& i: g_units) - if (i.first != 1 && _b >= i.first * 100) - { - ret << (double(_b / (i.first / 1000)) / 1000.0) << " " << i.second; - return ret.str(); - } - ret << _b << " wei"; - return ret.str(); -} - -bytes eth::contents(std::string const& _file) -{ - std::ifstream is(_file, std::ifstream::binary); - if (!is) - return bytes(); - // get length of file: - is.seekg (0, is.end); - streamoff length = is.tellg(); - is.seekg (0, is.beg); - bytes ret(length); - is.read((char*)ret.data(), length); - is.close(); - return ret; -} - -void eth::writeFile(std::string const& _file, bytes const& _data) -{ - ofstream(_file, ios::trunc).write((char const*)_data.data(), _data.size()); -} - diff --git a/libethereum/Common.h b/libethereum/Common.h index df1d8569e..7d38e2cf7 100644 --- a/libethereum/Common.h +++ b/libethereum/Common.h @@ -18,7 +18,7 @@ * @author Gav Wood * @date 2014 * - * Shared algorithms and data types. + * Very common stuff (i.e. that every other header needs except vector_ref.h). */ #pragma once @@ -36,22 +36,10 @@ #define noexcept throw() #endif -#include -#include -#include #include -#include +#include #include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include #include "vector_ref.h" // CryptoPP defines byte in the global namespace, so so must we. @@ -81,132 +69,8 @@ using u160s = std::vector; using u256Set = std::set; using u160Set = std::set; -template inline void toBigEndian(T _val, Out& o_out); -template inline T fromBigEndian(In const& _bytes); - -/// Convert a series of bytes to the corresponding string of hex duplets. -/// @param _w specifies the width of each of the elements. Defaults to two - enough to represent a byte. -/// @example asHex("A\x69") == "4169" -template -std::string asHex(_T const& _data, int _w = 2) -{ - std::ostringstream ret; - for (auto i: _data) - ret << std::hex << std::setfill('0') << std::setw(_w) << (int)(typename std::make_unsigned::type)i; - return ret.str(); -} - -/// Converts a (printable) ASCII hex string into the corresponding byte stream. -/// @example fromUserHex("41626261") == asBytes("Abba") -bytes fromUserHex(std::string const& _s); - template class UnitTest {}; -template -class FixedHash -{ - using Arith = boost::multiprecision::number>; - -public: - enum { size = N }; - enum ConstructFromPointerType { ConstructFromPointer }; - - FixedHash() { m_data.fill(0); } - FixedHash(Arith const& _arith) { toBigEndian(_arith, m_data); } - explicit FixedHash(bytes const& _b) { if (_b.size() == N) memcpy(m_data.data(), _b.data(), std::min(_b.size(), N)); } - explicit FixedHash(byte const* _bs, ConstructFromPointerType) { memcpy(m_data.data(), _bs, N); } - explicit FixedHash(std::string const& _user): FixedHash(fromUserHex(_user)) {} - - operator Arith() const { return fromBigEndian(m_data); } - - operator bool() const { return ((Arith)*this) != 0; } - - bool operator==(FixedHash const& _c) const { return m_data == _c.m_data; } - bool operator!=(FixedHash const& _c) const { return m_data != _c.m_data; } - bool operator<(FixedHash const& _c) const { return m_data < _c.m_data; } - - FixedHash& operator^=(FixedHash const& _c) { for (auto i = 0; i < N; ++i) m_data[i] ^= _c.m_data[i]; return *this; } - FixedHash operator^(FixedHash const& _c) const { return FixedHash(*this) ^= _c; } - FixedHash& operator|=(FixedHash const& _c) { for (auto i = 0; i < N; ++i) m_data[i] |= _c.m_data[i]; return *this; } - FixedHash operator|(FixedHash const& _c) const { return FixedHash(*this) |= _c; } - FixedHash& operator&=(FixedHash const& _c) { for (auto i = 0; i < N; ++i) m_data[i] &= _c.m_data[i]; return *this; } - FixedHash operator&(FixedHash const& _c) const { return FixedHash(*this) &= _c; } - FixedHash& operator~() { for (auto i = 0; i < N; ++i) m_data[i] = ~m_data[i]; return *this; } - - std::string abridged() const { return asHex(ref().cropped(0, 4)) + ".."; } - - byte& operator[](unsigned _i) { return m_data[_i]; } - byte operator[](unsigned _i) const { return m_data[_i]; } - - bytesRef ref() { return bytesRef(m_data.data(), N); } - bytesConstRef ref() const { return bytesConstRef(m_data.data(), N); } - - byte* data() { return m_data.data(); } - byte const* data() const { return m_data.data(); } - - bytes asBytes() const { return bytes(data(), data() + N); } - std::array& asArray() { return m_data; } - std::array const& asArray() const { return m_data; } - - // generic std::hash compatible function object - struct hash - { - size_t operator()(FixedHash const& value) const - { - size_t h = 0; - for (auto i: value.m_data) - h = (h << 5 - h) + i; - return h; - } - }; - -private: - std::array m_data; -}; - - -// fast equality for h256 -template<> inline bool FixedHash<32>::operator==(FixedHash<32> const& _other) const -{ - const uint64_t* hash1 = (const uint64_t*)this->data(); - const uint64_t* hash2 = (const uint64_t*)_other.data(); - return (hash1[0] == hash2[0]) && (hash1[1] == hash2[1]) && (hash1[2] == hash2[2]) && (hash1[3] == hash2[3]); -} - -// fast std::hash compatible hash function object for h256 -template<> inline size_t FixedHash<32>::hash::operator()(FixedHash<32> const& value) const -{ - const uint64_t*data = (const uint64_t*)value.data(); - uint64_t hash = data[0]; - hash ^= data[1]; - hash ^= data[2]; - hash ^= data[3]; - return (size_t)hash; -} - -template -inline std::ostream& operator<<(std::ostream& _out, FixedHash const& _h) -{ - _out << std::noshowbase << std::hex << std::setfill('0'); - for (unsigned i = 0; i < N; ++i) - _out << std::setw(2) << (int)_h[i]; - _out << std::dec; - return _out; -} - -using h512 = FixedHash<64>; -using h256 = FixedHash<32>; -using h160 = FixedHash<20>; -using h256s = std::vector; -using h160s = std::vector; -using h256Set = std::set; -using h160Set = std::set; - -using Secret = h256; -using Public = h512; -using Address = h160; -using Addresses = h160s; - // Map types. using StringMap = std::map; using u256Map = std::map; @@ -216,475 +80,4 @@ using HexMap = std::map; static const u256 Invalid256 = ~(u256)0; static const bytes NullBytes; -/// Logging -class NullOutputStream -{ -public: - template NullOutputStream& operator<<(T const&) { return *this; } -}; - -extern std::map g_logOverride; - -struct ThreadLocalLogName -{ - ThreadLocalLogName(std::string _name) { m_name.reset(new std::string(_name)); }; - boost::thread_specific_ptr m_name; -}; - -extern ThreadLocalLogName t_logThreadName; -inline void setThreadName(char const* _n) { t_logThreadName.m_name.reset(new std::string(_n)); } - -struct LogChannel { static const char* name() { return " "; } static const int verbosity = 1; }; -struct LeftChannel: public LogChannel { static const char* name() { return "<<<"; } }; -struct RightChannel: public LogChannel { static const char* name() { return ">>>"; } }; -struct WarnChannel: public LogChannel { static const char* name() { return "!!!"; } static const int verbosity = 0; }; -struct NoteChannel: public LogChannel { static const char* name() { return "***"; } }; -struct DebugChannel: public LogChannel { static const char* name() { return "---"; } static const int verbosity = 0; }; - -extern int g_logVerbosity; -extern std::function g_logPost; - -void simpleDebugOut(std::string const&, char const* ); - -template -class LogOutputStream -{ -public: - LogOutputStream(bool _term = true) - { - std::type_info const* i = &typeid(Id); - auto it = g_logOverride.find(i); - if ((it != g_logOverride.end() && it->second == true) || (it == g_logOverride.end() && Id::verbosity <= g_logVerbosity)) - { - time_t rawTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); - char buf[24]; - if (strftime(buf, 24, "%X", localtime(&rawTime)) == 0) - buf[0] = '\0'; // empty if case strftime fails - sstr << Id::name() << " [ " << buf << " | " << *(t_logThreadName.m_name.get()) << (_term ? " ] " : ""); - } - } - ~LogOutputStream() { if (Id::verbosity <= g_logVerbosity) g_logPost(sstr.str(), Id::name()); } - template LogOutputStream& operator<<(T const& _t) { if (Id::verbosity <= g_logVerbosity) { if (_AutoSpacing && sstr.str().size() && sstr.str().back() != ' ') sstr << " "; sstr << _t; } return *this; } - std::stringstream sstr; -}; - -// Dirties the global namespace, but oh so convenient... -#define cnote eth::LogOutputStream() -#define cwarn eth::LogOutputStream() - -#define ndebug if (true) {} else eth::NullOutputStream() -#define nlog(X) if (true) {} else eth::NullOutputStream() -#define nslog(X) if (true) {} else eth::NullOutputStream() - -#if NDEBUG -#define cdebug ndebug -#else -#define cdebug eth::LogOutputStream() -#endif - -#if NLOG -#define clog(X) nlog(X) -#define cslog(X) nslog(X) -#else -#define clog(X) eth::LogOutputStream() -#define cslog(X) eth::LogOutputStream() -#endif - - - - - - - -/// User-friendly string representation of the amount _b in wei. -std::string formatBalance(u256 _b); - -/// Converts arbitrary value to string representation using std::stringstream. -template -std::string toString(_T const& _t) -{ - std::ostringstream o; - o << _t; - return o.str(); -} - -/// Converts byte array to a string containing the same (binary) data. Unless -/// the byte array happens to contain ASCII data, this won't be printable. -inline std::string asString(bytes const& _b) -{ - return std::string((char const*)_b.data(), (char const*)(_b.data() + _b.size())); -} - -/// Converts a string to a byte array containing the string's (byte) data. -inline bytes asBytes(std::string const& _b) -{ - return bytes((byte const*)_b.data(), (byte const*)(_b.data() + _b.size())); -} - -/// Trims a given number of elements from the front of a collection. -/// Only works for POD element types. -template -void trimFront(_T& _t, uint _elements) -{ - static_assert(std::is_pod::value, ""); - memmove(_t.data(), _t.data() + _elements, (_t.size() - _elements) * sizeof(_t[0])); - _t.resize(_t.size() - _elements); -} - -/// Pushes an element on to the front of a collection. -/// Only works for POD element types. -template -void pushFront(_T& _t, _U _e) -{ - static_assert(std::is_pod::value, ""); - _t.push_back(_e); - memmove(_t.data() + 1, _t.data(), (_t.size() - 1) * sizeof(_e)); - _t[0] = _e; -} - -/// Creates a random, printable, word. -std::string randomWord(); - -/// Escapes a string into the C-string representation. -/// @p _all if true will escape all characters, not just the unprintable ones. -std::string escaped(std::string const& _s, bool _all = true); - -/// Converts a (printable) ASCII hex character into the correspnding integer value. -/// @example fromHex('A') == 10 && fromHex('f') == 15 && fromHex('5') == 5 -int fromHex(char _i); - -/// Converts a string into the big-endian base-16 stream of integers (NOT ASCII). -/// @example toHex("A")[0] == 4 && toHex("A")[1] == 1 -bytes toHex(std::string const& _s); - -/// Converts a templated integer value to the big-endian byte-stream represented on a templated collection. -/// The size of the collection object will be unchanged. If it is too small, it will not represent the -/// value properly, if too big then the additional elements will be zeroed out. -/// @a _Out will typically be either std::string or bytes. -/// @a _T will typically by uint, u160, u256 or bigint. -template -inline void toBigEndian(_T _val, _Out& o_out) -{ - for (auto i = o_out.size(); i-- != 0; _val >>= 8) - o_out[i] = (typename _Out::value_type)(uint8_t)_val; -} - -/// Converts a big-endian byte-stream represented on a templated collection to a templated integer value. -/// @a _In will typically be either std::string or bytes. -/// @a _T will typically by uint, u160, u256 or bigint. -template -inline _T fromBigEndian(_In const& _bytes) -{ - _T ret = 0; - for (auto i: _bytes) - ret = (ret << 8) | (byte)(typename std::make_unsigned::type)i; - return ret; -} - -/// Convenience functions for toBigEndian -inline std::string toBigEndianString(u256 _val) { std::string ret(32, '\0'); toBigEndian(_val, ret); return ret; } -inline std::string toBigEndianString(u160 _val) { std::string ret(20, '\0'); toBigEndian(_val, ret); return ret; } -inline bytes toBigEndian(u256 _val) { bytes ret(32); toBigEndian(_val, ret); return ret; } -inline bytes toBigEndian(u160 _val) { bytes ret(20); toBigEndian(_val, ret); return ret; } - -/// Convenience function for toBigEndian. -/// @returns a string just big enough to represent @a _val. -template -inline std::string toCompactBigEndianString(_T _val) -{ - int i = 0; - for (_T v = _val; v; ++i, v >>= 8) {} - std::string ret(i, '\0'); - toBigEndian(_val, ret); - return ret; -} - -/// Determines the length of the common prefix of the two collections given. -/// @returns the number of elements both @a _t and @a _u share, in order, at the beginning. -/// @example commonPrefix("Hello world!", "Hello, world!") == 5 -template -uint commonPrefix(_T const& _t, _U const& _u) -{ - uint s = std::min(_t.size(), _u.size()); - for (uint i = 0;; ++i) - if (i == s || _t[i] != _u[i]) - return i; - return s; -} - -/// Convert the given value into h160 (160-bit unsigned integer) using the right 20 bytes. -inline h160 right160(h256 const& _t) -{ - h160 ret; - memcpy(ret.data(), _t.data() + 12, 20); - return ret; -} - -/// Convert the given value into h160 (160-bit unsigned integer) using the left 20 bytes. -inline h160 left160(h256 const& _t) -{ - h160 ret; - memcpy(&ret[0], _t.data(), 20); - return ret; -} - -/// Convert the given value into u160 (160-bit unsigned integer) by taking the lowest order 160-bits and discarding the rest. -inline u160 low160(u256 const& _t) -{ - return (u160)(_t & ((((u256)1) << 160) - 1)); -} - -inline u160 low160(bigint const& _t) -{ - return (u160)(_t & ((((bigint)1) << 160) - 1)); -} - -/// Convert the given value into u160 (160-bit unsigned integer) by taking the lowest order 160-bits and discarding the rest. -inline u160 high160(u256 const& _t) -{ - return (u160)(_t >> 96); -} - - -/// Concatenate two vectors of elements. _T must be POD. -template -inline std::vector<_T>& operator+=(std::vector::value, _T>::type>& _a, std::vector<_T> const& _b) -{ - auto s = _a.size(); - _a.resize(_a.size() + _b.size()); - memcpy(_a.data() + s, _b.data(), _b.size() * sizeof(_T)); - return _a; - -} - -/// Concatenate two vectors of elements. _T must be POD. -template -inline std::vector<_T> operator+(std::vector::value, _T>::type> const& _a, std::vector<_T> const& _b) -{ - std::vector<_T> ret(_a); - return ret += _b; -} - -/// SHA-3 convenience routines. -void sha3(bytesConstRef _input, bytesRef _output); -std::string sha3(std::string const& _input, bool _hex); -bytes sha3Bytes(bytesConstRef _input); -inline bytes sha3Bytes(std::string const& _input) { return sha3Bytes((std::string*)&_input); } -inline bytes sha3Bytes(bytes const& _input) { return sha3Bytes((bytes*)&_input); } -h256 sha3(bytesConstRef _input); -inline h256 sha3(bytes const& _input) { return sha3(bytesConstRef((bytes*)&_input)); } -inline h256 sha3(std::string const& _input) { return sha3(bytesConstRef(_input)); } - -/// Get information concerning the currency denominations. -std::vector> const& units(); - -/// Convert a private key into the public key equivalent. -/// @returns 0 if it's not a valid private key. -Address toAddress(h256 _private); - -class KeyPair -{ -public: - KeyPair() {} - KeyPair(Secret _k); - - static KeyPair create(); - - Secret const& secret() const { return m_secret; } - Secret const& sec() const { return m_secret; } - Public const& pub() const { return m_public; } - - Address const& address() const { return m_address; } - -private: - Secret m_secret; - Public m_public; - Address m_address; -}; - - -static const u256 Uether = ((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000; -static const u256 Vether = ((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000; -static const u256 Dether = ((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000; -static const u256 Nether = (((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000; -static const u256 Yether = (((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000; -static const u256 Zether = (((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000; -static const u256 Eether = ((u256(1000000000) * 1000000000) * 1000000000) * 1000000000; -static const u256 Pether = ((u256(1000000000) * 1000000000) * 1000000000) * 1000000; -static const u256 Tether = ((u256(1000000000) * 1000000000) * 1000000000) * 1000; -static const u256 Gether = (u256(1000000000) * 1000000000) * 1000000000; -static const u256 Mether = (u256(1000000000) * 1000000000) * 1000000; -static const u256 Kether = (u256(1000000000) * 1000000000) * 1000; -static const u256 ether = u256(1000000000) * 1000000000; -static const u256 finney = u256(1000000000) * 1000000; -static const u256 szabo = u256(1000000000) * 1000; -static const u256 Gwei = u256(1000000000); -static const u256 Mwei = u256(1000000); -static const u256 Kwei = u256(1000); -static const u256 wei = u256(1); - - -// Stream IO - - - -template struct StreamOut { static S& bypass(S& _out, T const& _t) { _out << _t; return _out; } }; -template struct StreamOut { static S& bypass(S& _out, uint8_t const& _t) { _out << (int)_t; return _out; } }; - -template -inline S& streamout(S& _out, std::vector const& _e) -{ - _out << "["; - if (!_e.empty()) - { - StreamOut::bypass(_out, _e.front()); - for (auto i = ++_e.begin(); i != _e.end(); ++i) - StreamOut::bypass(_out << ",", *i); - } - _out << "]"; - return _out; -} - -template inline std::ostream& operator<<(std::ostream& _out, std::vector const& _e) { streamout(_out, _e); return _out; } - -template -inline S& streamout(S& _out, std::array const& _e) -{ - _out << "["; - if (!_e.empty()) - { - StreamOut::bypass(_out, _e.front()); - auto i = _e.begin(); - for (++i; i != _e.end(); ++i) - StreamOut::bypass(_out << ",", *i); - } - _out << "]"; - return _out; -} -template inline std::ostream& operator<<(std::ostream& _out, std::array const& _e) { streamout(_out, _e); return _out; } - -template -inline S& streamout(S& _out, std::array const& _e) -{ - _out << "["; - if (!_e.empty()) - { - StreamOut::bypass(_out, _e.front()); - auto i = _e.begin(); - for (++i; i != _e.end(); ++i) - StreamOut::bypass(_out << ",", *i); - } - _out << "]"; - return _out; -} -template inline std::ostream& operator<<(std::ostream& _out, std::array const& _e) { streamout(_out, _e); return _out; } - -template -inline S& streamout(S& _out, std::list const& _e) -{ - _out << "["; - if (!_e.empty()) - { - _out << _e.front(); - for (auto i = ++_e.begin(); i != _e.end(); ++i) - _out << "," << *i; - } - _out << "]"; - return _out; -} -template inline std::ostream& operator<<(std::ostream& _out, std::list const& _e) { streamout(_out, _e); return _out; } - -template -inline S& streamout(S& _out, std::pair const& _e) -{ - _out << "(" << _e.first << "," << _e.second << ")"; - return _out; -} -template inline std::ostream& operator<<(std::ostream& _out, std::pair const& _e) { streamout(_out, _e); return _out; } - -template -inline S& streamout(S& _out, std::tuple const& _t) -{ - _out << "(" << std::get<0>(_t) << "," << std::get<1>(_t) << "," << std::get<2>(_t) << ")"; - return _out; -} -template inline std::ostream& operator<<(std::ostream& _out, std::tuple const& _e) { streamout(_out, _e); return _out; } - -template -S& streamout(S& _out, std::map const& _v) -{ - if (_v.empty()) - return _out << "{}"; - int i = 0; - for (auto p: _v) - _out << (!(i++) ? "{ " : "; ") << p.first << " => " << p.second; - return _out << " }"; -} -template inline std::ostream& operator<<(std::ostream& _out, std::map const& _e) { streamout(_out, _e); return _out; } - -template -S& streamout(S& _out, std::unordered_map const& _v) -{ - if (_v.empty()) - return _out << "{}"; - int i = 0; - for (auto p: _v) - _out << (!(i++) ? "{ " : "; ") << p.first << " => " << p.second; - return _out << " }"; -} -template inline std::ostream& operator<<(std::ostream& _out, std::unordered_map const& _e) { streamout(_out, _e); return _out; } - -template -S& streamout(S& _out, std::set const& _v) -{ - if (_v.empty()) - return _out << "{}"; - int i = 0; - for (auto p: _v) - _out << (!(i++) ? "{ " : ", ") << p; - return _out << " }"; -} -template inline std::ostream& operator<<(std::ostream& _out, std::set const& _e) { streamout(_out, _e); return _out; } - -template -S& streamout(S& _out, std::multiset const& _v) -{ - if (_v.empty()) - return _out << "{}"; - int i = 0; - for (auto p: _v) - _out << (!(i++) ? "{ " : ", ") << p; - return _out << " }"; -} -template inline std::ostream& operator<<(std::ostream& _out, std::multiset const& _e) { streamout(_out, _e); return _out; } - -template -S& streamout(S& _out, std::multimap const& _v) -{ - if (_v.empty()) - return _out << "{}"; - T l; - int i = 0; - for (auto p: _v) - if (!(i++)) - _out << "{ " << (l = p.first) << " => " << p.second; - else if (l == p.first) - _out << ", " << p.second; - else - _out << "; " << (l = p.first) << " => " << p.second; - return _out << " }"; -} -template inline std::ostream& operator<<(std::ostream& _out, std::multimap const& _e) { streamout(_out, _e); return _out; } - -template _S& operator<<(_S& _out, std::shared_ptr<_T> const& _p) { if (_p) _out << "@" << (*_p); else _out << "nullptr"; return _out; } - -bytes contents(std::string const& _file); -void writeFile(std::string const& _file, bytes const& _data); - -} - -namespace std -{ - // forward std::hash to eth::h256::hash - template<> struct hash: eth::h256::hash {}; } diff --git a/libethereum/CommonData.cpp b/libethereum/CommonData.cpp new file mode 100644 index 000000000..261d110c1 --- /dev/null +++ b/libethereum/CommonData.cpp @@ -0,0 +1,96 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file Common.cpp + * @author Gav Wood + * @date 2014 + */ + +#include "CommonData.h" + +#include +#include "Exceptions.h" +using namespace std; +using namespace eth; + +std::string eth::escaped(std::string const& _s, bool _all) +{ + std::string ret; + ret.reserve(_s.size()); + ret.push_back('"'); + for (auto i: _s) + if (i == '"' && !_all) + ret += "\\\""; + else if (i == '\\' && !_all) + ret += "\\\\"; + else if (i < ' ' || i > 127 || _all) + { + ret += "\\x"; + ret.push_back("0123456789abcdef"[(uint8_t)i / 16]); + ret.push_back("0123456789abcdef"[(uint8_t)i % 16]); + } + else + ret.push_back(i); + ret.push_back('"'); + return ret; +} + +std::string eth::randomWord() +{ + static std::mt19937_64 s_eng(0); + std::string ret(std::uniform_int_distribution(4, 10)(s_eng), ' '); + char const n[] = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"; + std::uniform_int_distribution d(0, sizeof(n) - 2); + for (char& c: ret) + c = n[d(s_eng)]; + return ret; +} + +int eth::fromHex(char _i) +{ + if (_i >= '0' && _i <= '9') + return _i - '0'; + if (_i >= 'a' && _i <= 'f') + return _i - 'a' + 10; + if (_i >= 'A' && _i <= 'F') + return _i - 'A' + 10; + throw BadHexCharacter(); +} + +bytes eth::fromHex(std::string const& _s) +{ + assert(_s.size() % 2 == 0); + if (_s.size() < 2) + return bytes(); + uint s = (_s[0] == '0' && _s[1] == 'x') ? 2 : 0; + std::vector ret; + ret.reserve((_s.size() - s) / 2); + for (uint i = s; i < _s.size(); i += 2) + ret.push_back((byte)(fromHex(_s[i]) * 16 + fromHex(_s[i + 1]))); + return ret; +} + +bytes eth::asNibbles(std::string const& _s) +{ + std::vector ret; + ret.reserve(_s.size() * 2); + for (auto i: _s) + { + ret.push_back(i / 16); + ret.push_back(i % 16); + } + return ret; +} diff --git a/libethereum/CommonEth.cpp b/libethereum/CommonEth.cpp new file mode 100644 index 000000000..93d484a6a --- /dev/null +++ b/libethereum/CommonEth.cpp @@ -0,0 +1,200 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file CommonEth.cpp + * @author Gav Wood + * @date 2014 + */ + +#include "CommonEth.h" + +#if WIN32 +#pragma warning(push) +#pragma warning(disable:4244) +#else +#pragma GCC diagnostic ignored "-Wunused-function" +#endif +#include +#include +#if WIN32 +#pragma warning(pop) +#else +#endif +#include "Exceptions.h" +using namespace std; +using namespace eth; + +//#define ETH_ADDRESS_DEBUG 1 + +static const vector> g_units = +{ + {((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000, "Uether"}, + {((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000, "Vether"}, + {((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000, "Dether"}, + {(((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000, "Nether"}, + {(((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000, "Yether"}, + {(((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000, "Zether"}, + {((u256(1000000000) * 1000000000) * 1000000000) * 1000000000, "Eether"}, + {((u256(1000000000) * 1000000000) * 1000000000) * 1000000, "Pether"}, + {((u256(1000000000) * 1000000000) * 1000000000) * 1000, "Tether"}, + {(u256(1000000000) * 1000000000) * 1000000000, "Gether"}, + {(u256(1000000000) * 1000000000) * 1000000, "Mether"}, + {(u256(1000000000) * 1000000000) * 1000, "Kether"}, + {u256(1000000000) * 1000000000, "ether"}, + {u256(1000000000) * 1000000, "finney"}, + {u256(1000000000) * 1000, "szabo"}, + {u256(1000000000), "Gwei"}, + {u256(1000000), "Mwei"}, + {u256(1000), "Kwei"}, + {u256(1), "wei"} +}; + +vector> const& eth::units() +{ + return g_units; +} + +std::string eth::formatBalance(u256 _b) +{ + ostringstream ret; + if (_b > g_units[0].first * 10000) + { + ret << (_b / g_units[0].first) << " " << g_units[0].second; + return ret.str(); + } + ret << setprecision(5); + for (auto const& i: g_units) + if (i.first != 1 && _b >= i.first * 100) + { + ret << (double(_b / (i.first / 1000)) / 1000.0) << " " << i.second; + return ret.str(); + } + ret << _b << " wei"; + return ret.str(); +} + +Address eth::toAddress(Secret _private) +{ + secp256k1_start(); + + byte pubkey[65]; + int pubkeylen = 65; + int ok = secp256k1_ecdsa_seckey_verify(_private.data()); + if (!ok) + return Address(); + ok = secp256k1_ecdsa_pubkey_create(pubkey, &pubkeylen, _private.data(), 0); + assert(pubkeylen == 65); + if (!ok) + return Address(); + ok = secp256k1_ecdsa_pubkey_verify(pubkey, 65); + if (!ok) + return Address(); + auto ret = right160(eth::sha3(bytesConstRef(&(pubkey[1]), 64))); +#if ETH_ADDRESS_DEBUG + cout << "---- ADDRESS -------------------------------" << endl; + cout << "SEC: " << _private << endl; + cout << "PUB: " << toHex(bytesConstRef(&(pubkey[1]), 64)) << endl; + cout << "ADR: " << ret << endl; +#endif + return ret; +} + +KeyPair KeyPair::create() +{ + secp256k1_start(); + static std::mt19937_64 s_eng(time(0)); + std::uniform_int_distribution d(0, 255); + + for (int i = 0; i < 100; ++i) + { + h256 sec; + for (unsigned i = 0; i < 32; ++i) + sec[i] = (byte)d(s_eng); + + KeyPair ret(sec); + if (ret.address()) + return ret; + } + return KeyPair(); +} + +KeyPair::KeyPair(h256 _sec): + m_secret(_sec) +{ + int ok = secp256k1_ecdsa_seckey_verify(m_secret.data()); + if (!ok) + return; + + byte pubkey[65]; + int pubkeylen = 65; + ok = secp256k1_ecdsa_pubkey_create(pubkey, &pubkeylen, m_secret.data(), 0); + if (!ok || pubkeylen != 65) + return; + + ok = secp256k1_ecdsa_pubkey_verify(pubkey, 65); + if (!ok) + return; + + m_secret = m_secret; + memcpy(m_public.data(), &(pubkey[1]), 64); + m_address = right160(eth::sha3(bytesConstRef(&(pubkey[1]), 64))); + +#if ETH_ADDRESS_DEBUG + cout << "---- ADDRESS -------------------------------" << endl; + cout << "SEC: " << m_secret << endl; + cout << "PUB: " << m_public << endl; + cout << "ADR: " << m_address << endl; +#endif +} + +std::string eth::sha3(std::string const& _input, bool _hex) +{ + if (!_hex) + { + string ret(32, '\0'); + sha3(bytesConstRef((byte const*)_input.data(), _input.size()), bytesRef((byte*)ret.data(), 32)); + return ret; + } + + uint8_t buf[32]; + sha3(bytesConstRef((byte const*)_input.data(), _input.size()), bytesRef((byte*)&(buf[0]), 32)); + std::string ret(64, '\0'); + for (unsigned int i = 0; i < 32; i++) + sprintf((char*)(ret.data())+i*2, "%02x", buf[i]); + return ret; +} + +void eth::sha3(bytesConstRef _input, bytesRef _output) +{ + CryptoPP::SHA3_256 ctx; + ctx.Update((byte*)_input.data(), _input.size()); + assert(_output.size() >= 32); + ctx.Final(_output.data()); +} + +bytes eth::sha3Bytes(bytesConstRef _input) +{ + bytes ret(32); + sha3(_input, &ret); + return ret; +} + +h256 eth::sha3(bytesConstRef _input) +{ + h256 ret; + sha3(_input, bytesRef(&ret[0], 32)); + return ret; +} diff --git a/libethereum/CommonIO.cpp b/libethereum/CommonIO.cpp new file mode 100644 index 000000000..9def88b2a --- /dev/null +++ b/libethereum/CommonIO.cpp @@ -0,0 +1,48 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file CommonIO.cpp + * @author Gav Wood + * @date 2014 + */ + +#include "Common.h" + +#include +#include "Exceptions.h" +using namespace std; +using namespace eth; + +bytes eth::contents(std::string const& _file) +{ + std::ifstream is(_file, std::ifstream::binary); + if (!is) + return bytes(); + // get length of file: + is.seekg (0, is.end); + streamoff length = is.tellg(); + is.seekg (0, is.beg); + bytes ret(length); + is.read((char*)ret.data(), length); + is.close(); + return ret; +} + +void eth::writeFile(std::string const& _file, bytes const& _data) +{ + ofstream(_file, ios::trunc).write((char const*)_data.data(), _data.size()); +} + diff --git a/libethereum/Dagger.h b/libethereum/Dagger.h index 3f89b293b..ec12ae193 100644 --- a/libethereum/Dagger.h +++ b/libethereum/Dagger.h @@ -23,7 +23,8 @@ #pragma once -#include "Common.h" +#include "FixedHash.h" +#include "CommonEth.h" #define FAKE_DAGGER 1 diff --git a/libethereum/Exceptions.h b/libethereum/Exceptions.h index e55530dfe..e390ec3bb 100644 --- a/libethereum/Exceptions.h +++ b/libethereum/Exceptions.h @@ -1,7 +1,9 @@ #pragma once #include -#include "Common.h" +#include "CommonIO.h" +#include "CommonData.h" +#include "FixedHash.h" namespace eth { @@ -31,13 +33,13 @@ class NoSuchContract: public Exception {}; class ContractAddressCollision: public Exception {}; class FeeTooSmall: public Exception {}; class InvalidSignature: public Exception {}; -class InvalidTransactionFormat: public Exception { public: InvalidTransactionFormat(int _f, bytesConstRef _d): m_f(_f), m_d(_d.toBytes()) {} int m_f; bytes m_d; virtual std::string description() const { return "Invalid transaction format: Bad field " + toString(m_f) + " (" + asHex(m_d) + ")"; } }; -class InvalidBlockFormat: public Exception { public: InvalidBlockFormat(int _f, bytesConstRef _d): m_f(_f), m_d(_d.toBytes()) {} int m_f; bytes m_d; virtual std::string description() const { return "Invalid block format: Bad field " + toString(m_f) + " (" + asHex(m_d) + ")"; } }; -class InvalidBlockHeaderFormat: public Exception { public: InvalidBlockHeaderFormat(int _f, bytesConstRef _d): m_f(_f), m_d(_d.toBytes()) {} int m_f; bytes m_d; virtual std::string description() const { return "Invalid block header format: Bad field " + toString(m_f) + " (" + asHex(m_d) + ")"; } }; +class InvalidTransactionFormat: public Exception { public: InvalidTransactionFormat(int _f, bytesConstRef _d): m_f(_f), m_d(_d.toBytes()) {} int m_f; bytes m_d; virtual std::string description() const { return "Invalid transaction format: Bad field " + toString(m_f) + " (" + toHex(m_d) + ")"; } }; +class InvalidBlockFormat: public Exception { public: InvalidBlockFormat(int _f, bytesConstRef _d): m_f(_f), m_d(_d.toBytes()) {} int m_f; bytes m_d; virtual std::string description() const { return "Invalid block format: Bad field " + toString(m_f) + " (" + toHex(m_d) + ")"; } }; +class InvalidBlockHeaderFormat: public Exception { public: InvalidBlockHeaderFormat(int _f, bytesConstRef _d): m_f(_f), m_d(_d.toBytes()) {} int m_f; bytes m_d; virtual std::string description() const { return "Invalid block header format: Bad field " + toString(m_f) + " (" + toHex(m_d) + ")"; } }; class InvalidUnclesHash: public Exception {}; class InvalidUncle: public Exception {}; class InvalidStateRoot: public Exception {}; -class InvalidTransactionsHash: public Exception { public: InvalidTransactionsHash(h256 _head, h256 _real): m_head(_head), m_real(_real) {} h256 m_head; h256 m_real; virtual std::string description() const { return "Invalid transactions hash: header says: " + asHex(m_head.ref()) + " block is:" + asHex(m_real.ref()); } }; +class InvalidTransactionsHash: public Exception { public: InvalidTransactionsHash(h256 _head, h256 _real): m_head(_head), m_real(_real) {} h256 m_head; h256 m_real; virtual std::string description() const { return "Invalid transactions hash: header says: " + toHex(m_head.ref()) + " block is:" + toHex(m_real.ref()); } }; class InvalidTransaction: public Exception {}; class InvalidDifficulty: public Exception {}; class InvalidTimestamp: public Exception {}; diff --git a/libethereum/FixedHash.cpp b/libethereum/FixedHash.cpp new file mode 100644 index 000000000..9d16cacb2 --- /dev/null +++ b/libethereum/FixedHash.cpp @@ -0,0 +1,25 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file FixedHash.cpp + * @author Gav Wood + * @date 2014 + */ + +#include "FixedHash.h" + +using namespace std; +using namespace eth; diff --git a/libethereum/Instruction.cpp b/libethereum/Instruction.cpp index 660747cfe..9e412ee3f 100644 --- a/libethereum/Instruction.cpp +++ b/libethereum/Instruction.cpp @@ -22,7 +22,8 @@ #include "Instruction.h" #include -#include "Common.h" +#include "CommonEth.h" +#include "Log.h" using namespace std; using namespace eth; diff --git a/libethereum/Log.cpp b/libethereum/Log.cpp new file mode 100644 index 000000000..0ead148f0 --- /dev/null +++ b/libethereum/Log.cpp @@ -0,0 +1,41 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file Log.cpp + * @author Gav Wood + * @date 2014 + */ + +#include "Log.h" + +#include +#include +using namespace std; +using namespace eth; + +// Logging +int eth::g_logVerbosity = 8; +map eth::g_logOverride; + +ThreadLocalLogName eth::t_logThreadName("main"); + +void eth::simpleDebugOut(std::string const& _s, char const*) +{ + cout << _s << endl << flush; +} + +std::function eth::g_logPost = simpleDebugOut; + diff --git a/libethereum/MemTrie.cpp b/libethereum/MemTrie.cpp index 7d2f9f54c..c9d257c05 100644 --- a/libethereum/MemTrie.cpp +++ b/libethereum/MemTrie.cpp @@ -19,7 +19,7 @@ * @date 2014 */ -#include "Common.h" +#include "CommonEth.h" #include "TrieCommon.h" #include "MemTrie.h" using namespace std; @@ -147,7 +147,7 @@ public: assert(m_value.size()); std::cerr << _indent; if (m_ext.size()) - std::cerr << asHex(m_ext, 1) << ": "; + std::cerr << toHex(m_ext, 1) << ": "; else std::cerr << "@: "; std::cerr << m_value << std::endl; @@ -174,7 +174,7 @@ public: #if ENABLE_DEBUG_PRINT virtual void debugPrintBody(std::string const& _indent) const { - std::cerr << _indent << asHex(m_ext, 1) << ": "; + std::cerr << _indent << toHex(m_ext, 1) << ": "; m_next->debugPrint(_indent + " "); } #endif @@ -454,7 +454,7 @@ std::string const& MemTrie::at(std::string const& _key) const { if (!m_root) return c_nullString; - auto h = toHex(_key); + auto h = asNibbles(_key); return m_root->at(bytesConstRef(&h)); } @@ -462,7 +462,7 @@ void MemTrie::insert(std::string const& _key, std::string const& _value) { if (_value.empty()) remove(_key); - auto h = toHex(_key); + auto h = asNibbles(_key); m_root = m_root ? m_root->insert(&h, _value) : new TrieLeafNode(bytesConstRef(&h), _value); } @@ -470,7 +470,7 @@ void MemTrie::remove(std::string const& _key) { if (m_root) { - auto h = toHex(_key); + auto h = asNibbles(_key); m_root = m_root->remove(&h); } } diff --git a/libethereum/PeerNetwork.h b/libethereum/PeerNetwork.h index 955a4c86e..8f5dc1463 100644 --- a/libethereum/PeerNetwork.h +++ b/libethereum/PeerNetwork.h @@ -28,6 +28,7 @@ #include #include #include "Common.h" +#include "Log.h" namespace ba = boost::asio; namespace bi = boost::asio::ip; diff --git a/libethereum/PeerServer.cpp b/libethereum/PeerServer.cpp index 408835ca3..f4f630f86 100644 --- a/libethereum/PeerServer.cpp +++ b/libethereum/PeerServer.cpp @@ -68,7 +68,7 @@ PeerServer::PeerServer(std::string const& _clientVersion, BlockChain const& _ch, populateAddresses(); determinePublic(_publicAddress, _upnp); ensureAccepting(); - clog(NetNote) << "Id:" << asHex(m_key.address().ref().cropped(0, 4)) << "Mode: " << (_m == NodeMode::PeerServer ? "PeerServer" : "Full"); + clog(NetNote) << "Id:" << toHex(m_key.address().ref().cropped(0, 4)) << "Mode: " << (_m == NodeMode::PeerServer ? "PeerServer" : "Full"); } PeerServer::PeerServer(std::string const& _clientVersion, uint _networkId, NodeMode _m): @@ -82,7 +82,7 @@ PeerServer::PeerServer(std::string const& _clientVersion, uint _networkId, NodeM { // populate addresses. populateAddresses(); - clog(NetNote) << "Id:" << asHex(m_key.address().ref().cropped(0, 4)) << "Mode: " << (m_mode == NodeMode::PeerServer ? "PeerServer" : "Full"); + clog(NetNote) << "Id:" << toHex(m_key.address().ref().cropped(0, 4)) << "Mode: " << (m_mode == NodeMode::PeerServer ? "PeerServer" : "Full"); } PeerServer::~PeerServer() diff --git a/libethereum/PeerSession.cpp b/libethereum/PeerSession.cpp index 0c8699829..0bd7f53a9 100644 --- a/libethereum/PeerSession.cpp +++ b/libethereum/PeerSession.cpp @@ -163,7 +163,7 @@ bool PeerSession::interpret(RLP const& _r) s << PeersPacket; for (auto i: peers) { - clogS(NetMessageDetail) << "Sending peer " << asHex(i.first.ref().cropped(0, 4)) << i.second; + clogS(NetMessageDetail) << "Sending peer " << toHex(i.first.ref().cropped(0, 4)) << i.second; s.appendList(3) << i.second.address().to_v4().to_bytes() << i.second.port() << i.first; } sealAndSend(s); @@ -179,7 +179,7 @@ bool PeerSession::interpret(RLP const& _r) if (isPrivateAddress(peerAddress)) goto CONTINUE; - clogS(NetAllDetail) << "Checking: " << ep << "(" << asHex(id.ref().cropped(0, 4)) << ")"; + clogS(NetAllDetail) << "Checking: " << ep << "(" << toHex(id.ref().cropped(0, 4)) << ")"; // check that it's not us or one we already know: if (id && (m_server->m_key.pub() == id || m_server->m_peers.count(id) || m_server->m_incomingPeers.count(id))) @@ -545,11 +545,11 @@ void PeerSession::doRead() break; // enough has come in. -// cerr << "Received " << len << ": " << asHex(bytesConstRef(m_incoming.data() + 8, len)) << endl; +// cerr << "Received " << len << ": " << toHex(bytesConstRef(m_incoming.data() + 8, len)) << endl; auto data = bytesConstRef(m_incoming.data(), tlen); if (!checkPacket(data)) { - cerr << "Received " << len << ": " << asHex(bytesConstRef(m_incoming.data() + 8, len)) << endl; + cerr << "Received " << len << ": " << toHex(bytesConstRef(m_incoming.data() + 8, len)) << endl; cwarn << "INVALID MESSAGE RECEIVED"; disconnect(BadProtocol); return; diff --git a/libethereum/State.cpp b/libethereum/State.cpp index c06453c6f..8a88a0a98 100644 --- a/libethereum/State.cpp +++ b/libethereum/State.cpp @@ -42,10 +42,10 @@ std::map const& eth::genesisState() if (s_ret.empty()) { // Initialise. - s_ret[Address(fromUserHex("8a40bfaa73256b60764c1bf40675a99083efb075"))] = AddressState(u256(1) << 200, 0, AddressType::Normal); - s_ret[Address(fromUserHex("e6716f9544a56c530d868e4bfbacb172315bdead"))] = AddressState(u256(1) << 200, 0, AddressType::Normal); - s_ret[Address(fromUserHex("1e12515ce3e0f817a4ddef9ca55788a1d66bd2df"))] = AddressState(u256(1) << 200, 0, AddressType::Normal); - s_ret[Address(fromUserHex("1a26338f0d905e295fccb71fa9ea849ffa12aaf4"))] = AddressState(u256(1) << 200, 0, AddressType::Normal); + s_ret[Address(fromHex("8a40bfaa73256b60764c1bf40675a99083efb075"))] = AddressState(u256(1) << 200, 0, AddressType::Normal); + s_ret[Address(fromHex("e6716f9544a56c530d868e4bfbacb172315bdead"))] = AddressState(u256(1) << 200, 0, AddressType::Normal); + s_ret[Address(fromHex("1e12515ce3e0f817a4ddef9ca55788a1d66bd2df"))] = AddressState(u256(1) << 200, 0, AddressType::Normal); + s_ret[Address(fromHex("1a26338f0d905e295fccb71fa9ea849ffa12aaf4"))] = AddressState(u256(1) << 200, 0, AddressType::Normal); } return s_ret; } diff --git a/libethereum/State.h b/libethereum/State.h index e3670fe98..be53c2b9c 100644 --- a/libethereum/State.h +++ b/libethereum/State.h @@ -322,7 +322,7 @@ inline std::ostream& operator<<(std::ostream& _out, State const& _s) std::map mem; for (auto const& j: memdb) { - _out << std::endl << " [" << j.first << ":" << asHex(j.second) << "]"; + _out << std::endl << " [" << j.first << ":" << toHex(j.second) << "]"; #ifdef __clang__ auto mFinder = mem.find(j.first); if (mFinder == mem.end()) @@ -359,7 +359,7 @@ inline std::ostream& operator<<(std::ostream& _out, State const& _s) std::map mem; for (auto const& j: memdb) { - _out << std::endl << " [" << j.first << ":" << asHex(j.second) << "]"; + _out << std::endl << " [" << j.first << ":" << toHex(j.second) << "]"; #ifdef __clang__ auto mFinder = mem.find(j.first); if (mFinder == mem.end()) diff --git a/libethereum/Transaction.cpp b/libethereum/Transaction.cpp index e751815af..f7c5431d3 100644 --- a/libethereum/Transaction.cpp +++ b/libethereum/Transaction.cpp @@ -79,7 +79,7 @@ Address Transaction::sender() const cout << "---- RECOVER -------------------------------" << endl; cout << "MSG: " << msg << endl; cout << "R S V: " << sig[0] << " " << sig[1] << " " << (int)(vrs.v - 27) << "+27" << endl; - cout << "PUB: " << asHex(bytesConstRef(&(pubkey[1]), 64)) << endl; + cout << "PUB: " << toHex(bytesConstRef(&(pubkey[1]), 64)) << endl; cout << "ADR: " << ret << endl; #endif return ret; diff --git a/libethereum/Transaction.h b/libethereum/Transaction.h index aca8a125c..ea034ac9f 100644 --- a/libethereum/Transaction.h +++ b/libethereum/Transaction.h @@ -21,7 +21,7 @@ #pragma once -#include "Common.h" +#include "CommonEth.h" #include "RLP.h" namespace eth diff --git a/libethereum/TransactionQueue.cpp b/libethereum/TransactionQueue.cpp index 55d225273..3d50e069f 100644 --- a/libethereum/TransactionQueue.cpp +++ b/libethereum/TransactionQueue.cpp @@ -19,6 +19,7 @@ * @date 2014 */ +#include "Log.h" #include "Transaction.h" #include "TransactionQueue.h" using namespace std; diff --git a/libethereum/TrieDB.h b/libethereum/TrieDB.h index 36fede58b..fbd0b238c 100644 --- a/libethereum/TrieDB.h +++ b/libethereum/TrieDB.h @@ -25,6 +25,8 @@ #include #include #include "Exceptions.h" +#include "CommonEth.h" +#include "Log.h" #include "TrieCommon.h" namespace ldb = leveldb; @@ -54,7 +56,7 @@ inline std::ostream& operator<<(std::ostream& _out, BasicMap const& _m) { _out << i.first << ": "; _out << RLP(i.second); - _out << " " << asHex(i.second); + _out << " " << toHex(i.second); _out << std::endl; } return _out; @@ -177,7 +179,7 @@ public: } if (!(rlp.isList() && (rlp.itemCount() == 2 || rlp.itemCount() == 17))) { - cdebug << b.rlp.size() << asHex(b.rlp); + cdebug << b.rlp.size() << toHex(b.rlp); cdebug << rlp; auto c = rlp.itemCount(); cdebug << c; diff --git a/libethereum/TrieHash.cpp b/libethereum/TrieHash.cpp index bbe5c1fe7..b4e3a7eb4 100644 --- a/libethereum/TrieHash.cpp +++ b/libethereum/TrieHash.cpp @@ -19,7 +19,7 @@ * @date 2014 */ -#include "Common.h" +#include "CommonEth.h" #include "TrieCommon.h" #include "TrieHash.h" using namespace std; @@ -58,7 +58,7 @@ void hash256rlp(HexMap const& _s, HexMap::const_iterator _begin, HexMap::const_i _rlp.appendList(2) << hexPrefixEncode(_begin->first, true, _preLen) << _begin->second; #if ENABLE_DEBUG_PRINT if (g_hashDebug) - std::cerr << s_indent << asHex(bytesConstRef(_begin->first.data() + _preLen, _begin->first.size() - _preLen), 1) << ": " << _begin->second << " = " << sha3(_rlp.out()) << std::endl; + std::cerr << s_indent << toHex(bytesConstRef(_begin->first.data() + _preLen, _begin->first.size() - _preLen), 1) << ": " << _begin->second << " = " << sha3(_rlp.out()) << std::endl; #endif } else @@ -79,7 +79,7 @@ void hash256rlp(HexMap const& _s, HexMap::const_iterator _begin, HexMap::const_i // if they all have the same next nibble, we also want a pair. #if ENABLE_DEBUG_PRINT if (g_hashDebug) - std::cerr << s_indent << asHex(bytesConstRef(_begin->first.data() + _preLen, sharedPre), 1) << ": " << std::endl; + std::cerr << s_indent << toHex(bytesConstRef(_begin->first.data() + _preLen, sharedPre), 1) << ": " << std::endl; #endif _rlp.appendList(2) << hexPrefixEncode(_begin->first, false, _preLen, (int)sharedPre); hash256aux(_s, _begin, _end, (unsigned)sharedPre, _rlp); @@ -162,7 +162,7 @@ h256 hash256(StringMap const& _s) return h256(); HexMap hexMap; for (auto i = _s.rbegin(); i != _s.rend(); ++i) - hexMap[toHex(i->first)] = i->second; + hexMap[asNibbles(i->first)] = i->second; RLPStream s; hash256rlp(hexMap, hexMap.cbegin(), hexMap.cend(), 0, s); return sha3(s.out()); @@ -175,7 +175,7 @@ bytes rlp256(StringMap const& _s) return bytes(); HexMap hexMap; for (auto i = _s.rbegin(); i != _s.rend(); ++i) - hexMap[toHex(i->first)] = i->second; + hexMap[asNibbles(i->first)] = i->second; RLPStream s; hash256aux(hexMap, hexMap.cbegin(), hexMap.cend(), 0, s); return s.out(); @@ -188,7 +188,7 @@ h256 hash256(u256Map const& _s) return h256(); HexMap hexMap; for (auto i = _s.rbegin(); i != _s.rend(); ++i) - hexMap[toHex(toBigEndianString(i->first))] = asString(rlp(i->second)); + hexMap[asNibbles(toBigEndianString(i->first))] = asString(rlp(i->second)); RLPStream s; hash256rlp(hexMap, hexMap.cbegin(), hexMap.cend(), 0, s); return sha3(s.out()); diff --git a/libethereum/TrieHash.h b/libethereum/TrieHash.h index bf3b557f2..dcdcfd86a 100644 --- a/libethereum/TrieHash.h +++ b/libethereum/TrieHash.h @@ -22,6 +22,7 @@ #pragma once #include "Common.h" +#include "FixedHash.h" namespace eth { diff --git a/libethereum/UPnP.cpp b/libethereum/UPnP.cpp index 6008bc7de..bcf769c0a 100644 --- a/libethereum/UPnP.cpp +++ b/libethereum/UPnP.cpp @@ -26,6 +26,7 @@ #include #include #include "Common.h" +#include "Log.h" #include "Exceptions.h" #include "UPnP.h" using namespace std; diff --git a/test/crypto.cpp b/test/crypto.cpp index 8a57e1d57..93d4d2571 100644 --- a/test/crypto.cpp +++ b/test/crypto.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include using namespace std; using namespace eth; @@ -33,21 +34,21 @@ int cryptoTest() cnote << "Testing Crypto..."; secp256k1_start(); - KeyPair p(Secret(fromUserHex("3ecb44df2159c26e0f995712d4f39b6f6e499b40749b1cf1246c37f9516cb6a4"))); - assert(p.pub() == Public(fromUserHex("97466f2b32bc3bb76d4741ae51cd1d8578b48d3f1e68da206d47321aec267ce78549b514e4453d74ef11b0cd5e4e4c364effddac8b51bcfc8de80682f952896f"))); - assert(p.address() == Address(fromUserHex("8a40bfaa73256b60764c1bf40675a99083efb075"))); + KeyPair p(Secret(fromHex("3ecb44df2159c26e0f995712d4f39b6f6e499b40749b1cf1246c37f9516cb6a4"))); + assert(p.pub() == Public(fromHex("97466f2b32bc3bb76d4741ae51cd1d8578b48d3f1e68da206d47321aec267ce78549b514e4453d74ef11b0cd5e4e4c364effddac8b51bcfc8de80682f952896f"))); + assert(p.address() == Address(fromHex("8a40bfaa73256b60764c1bf40675a99083efb075"))); { Transaction t; t.nonce = 0; - t.receiveAddress = h160(fromUserHex("944400f4b88ac9589a0f17ed4671da26bddb668b")); + t.receiveAddress = h160(fromHex("944400f4b88ac9589a0f17ed4671da26bddb668b")); t.value = 1000; t.data = u256s(); cnote << RLP(t.rlp(false)); - cnote << asHex(t.rlp(false)); + cnote << toHex(t.rlp(false)); cnote << t.sha3(false); t.sign(p.secret()); cnote << RLP(t.rlp(true)); - cnote << asHex(t.rlp(true)); + cnote << toHex(t.rlp(true)); cnote << t.sha3(true); assert(t.sender() == p.address()); } @@ -55,7 +56,7 @@ int cryptoTest() #if 0 // Test transaction. - bytes tx = fromUserHex("88005401010101010101010101010101010101010101011f0de0b6b3a76400001ce8d4a5100080181c373130a009ba1f10285d4e659568bfcfec85067855c5a3c150100815dad4ef98fd37cf0593828c89db94bd6c64e210a32ef8956eaa81ea9307194996a3b879441f5d"); + bytes tx = fromHex("88005401010101010101010101010101010101010101011f0de0b6b3a76400001ce8d4a5100080181c373130a009ba1f10285d4e659568bfcfec85067855c5a3c150100815dad4ef98fd37cf0593828c89db94bd6c64e210a32ef8956eaa81ea9307194996a3b879441f5d"); cout << "TX: " << RLP(tx) << endl; Transaction t2(tx); @@ -69,13 +70,13 @@ int cryptoTest() t.receiveAddress = toAddress(sha3("123")); bytes sig64 = toBigEndian(t.vrs.r) + toBigEndian(t.vrs.s); - cout << "SIG: " << sig64.size() << " " << asHex(sig64) << " " << t.vrs.v << endl; + cout << "SIG: " << sig64.size() << " " << toHex(sig64) << " " << t.vrs.v << endl; auto msg = t.rlp(false); cout << "TX w/o SIG: " << RLP(msg) << endl; - cout << "RLP(TX w/o SIG): " << asHex(t.rlpString(false)) << endl; + cout << "RLP(TX w/o SIG): " << toHex(t.rlpString(false)) << endl; std::string hmsg = sha3(t.rlpString(false), false); - cout << "SHA256(RLP(TX w/o SIG)): 0x" << asHex(hmsg) << endl; + cout << "SHA256(RLP(TX w/o SIG)): 0x" << toHex(hmsg) << endl; bytes privkey = sha3Bytes("123"); @@ -84,12 +85,12 @@ int cryptoTest() int pubkeylen = 65; int ret = secp256k1_ecdsa_seckey_verify(privkey.data()); - cout << "SEC: " << dec << ret << " " << asHex(privkey) << endl; + cout << "SEC: " << dec << ret << " " << toHex(privkey) << endl; ret = secp256k1_ecdsa_pubkey_create(pubkey.data(), &pubkeylen, privkey.data(), 1); pubkey.resize(pubkeylen); int good = secp256k1_ecdsa_pubkey_verify(pubkey.data(), (int)pubkey.size()); - cout << "PUB: " << dec << ret << " " << pubkeylen << " " << asHex(pubkey) << (good ? " GOOD" : " BAD") << endl; + cout << "PUB: " << dec << ret << " " << pubkeylen << " " << toHex(pubkey) << (good ? " GOOD" : " BAD") << endl; } // Test roundtrip... @@ -97,17 +98,17 @@ int cryptoTest() bytes sig(64); u256 nonce = 0; int v = 0; - cout << asHex(hmsg) << endl; - cout << asHex(privkey) << endl; + cout << toHex(hmsg) << endl; + cout << toHex(privkey) << endl; cout << hex << nonce << dec << endl; int ret = secp256k1_ecdsa_sign_compact((byte const*)hmsg.data(), (int)hmsg.size(), sig.data(), privkey.data(), (byte const*)&nonce, &v); - cout << "MYSIG: " << dec << ret << " " << sig.size() << " " << asHex(sig) << " " << v << endl; + cout << "MYSIG: " << dec << ret << " " << sig.size() << " " << toHex(sig) << " " << v << endl; bytes pubkey(65); int pubkeylen = 65; ret = secp256k1_ecdsa_recover_compact((byte const*)hmsg.data(), (int)hmsg.size(), (byte const*)sig.data(), pubkey.data(), &pubkeylen, 0, v); pubkey.resize(pubkeylen); - cout << "MYREC: " << dec << ret << " " << pubkeylen << " " << asHex(pubkey) << endl; + cout << "MYREC: " << dec << ret << " " << pubkeylen << " " << toHex(pubkey) << endl; } { @@ -115,8 +116,8 @@ int cryptoTest() int pubkeylen = 65; int ret = secp256k1_ecdsa_recover_compact((byte const*)hmsg.data(), (int)hmsg.size(), (byte const*)sig64.data(), pubkey.data(), &pubkeylen, 0, (int)t.vrs.v - 27); pubkey.resize(pubkeylen); - cout << "RECPUB: " << dec << ret << " " << pubkeylen << " " << asHex(pubkey) << endl; - cout << "SENDER: " << hex << low160(eth::sha3(bytesConstRef(&pubkey).cropped(1))) << dec << endl; + cout << "RECPUB: " << dec << ret << " " << pubkeylen << " " << toHex(pubkey) << endl; + cout << "SENDER: " << hex << toAddress(eth::sha3(bytesConstRef(&pubkey).cropped(1))) << dec << endl; } #endif return 0; diff --git a/test/dagger.cpp b/test/dagger.cpp index 8f7df77d3..728c8382a 100644 --- a/test/dagger.cpp +++ b/test/dagger.cpp @@ -21,6 +21,7 @@ */ #include +#include "Log.h" #include "Dagger.h" using namespace std; using namespace std::chrono; diff --git a/test/hexPrefix.cpp b/test/hexPrefix.cpp index b8bc1f48c..62f4d4916 100644 --- a/test/hexPrefix.cpp +++ b/test/hexPrefix.cpp @@ -24,6 +24,7 @@ #include "../json_spirit/json_spirit_reader_template.h" #include "../json_spirit/json_spirit_writer_template.h" #include "TrieCommon.h" +#include "Log.h" using namespace std; using namespace eth; namespace js = json_spirit; @@ -48,11 +49,11 @@ public: for (auto& i: o["seq"].get_array()) v.push_back((byte)i.get_int()); auto e = hexPrefixEncode(v, o["term"].get_bool()); - if (!o["out"].is_null() && o["out"].get_str() != asHex(e)) + if (!o["out"].is_null() && o["out"].get_str() != toHex(e)) { cwarn << "Test failed."; cwarn << "Test says:" << o["out"].get_str(); - cwarn << "Impl says:" << asHex(e); + cwarn << "Impl says:" << toHex(e); passed = false; } } diff --git a/test/main.cpp b/test/main.cpp index 311a43701..c5d750204 100644 --- a/test/main.cpp +++ b/test/main.cpp @@ -39,7 +39,7 @@ int main(int, char**) /* RLPStream s; BlockInfo::genesis().fillStream(s, false); std::cout << RLP(s.out()) << std::endl; - std::cout << asHex(s.out()) << std::endl; + std::cout << toHex(s.out()) << std::endl; std::cout << sha3(s.out()) << std::endl;*/ int r = 0; diff --git a/test/rlp.cpp b/test/rlp.cpp index bc8fb6031..f82af521f 100644 --- a/test/rlp.cpp +++ b/test/rlp.cpp @@ -23,6 +23,7 @@ #include #include "../json_spirit/json_spirit_reader_template.h" #include "../json_spirit/json_spirit_writer_template.h" +#include #include using namespace std; using namespace eth; @@ -67,11 +68,11 @@ public: cnote << i.first; RLPStream s; buildRLP(o["in"], s); - if (!o["out"].is_null() && o["out"].get_str() != asHex(s.out())) + if (!o["out"].is_null() && o["out"].get_str() != toHex(s.out())) { cwarn << "Test failed."; cwarn << "Test says:" << o["out"].get_str(); - cwarn << "Impl says:" << asHex(s.out()); + cwarn << "Impl says:" << toHex(s.out()); passed = false; } } diff --git a/test/trie.cpp b/test/trie.cpp index 3092238ce..419602d62 100644 --- a/test/trie.cpp +++ b/test/trie.cpp @@ -61,11 +61,11 @@ public: t.init(); for (auto const& k: ss) t.insert(k.first, k.second); - if (!o["root"].is_null() && o["root"].get_str() != asHex(t.root().asArray())) + if (!o["root"].is_null() && o["root"].get_str() != toHex(t.root().asArray())) { cwarn << "Test failed on permutation " << j; cwarn << "Test says:" << o["root"].get_str(); - cwarn << "Impl says:" << asHex(t.root().asArray()); + cwarn << "Impl says:" << toHex(t.root().asArray()); passed = false; } } @@ -154,7 +154,7 @@ int trieTest() t.insert("doe", "reindeer"); cout << hex << t.hash256() << endl; cout << RLP(t.rlp()) << endl; - cout << asHex(t.rlp()) << endl; + cout << toHex(t.rlp()) << endl; } { BasicMap m; diff --git a/test/vm.cpp b/test/vm.cpp index 55299f906..03893525c 100644 --- a/test/vm.cpp +++ b/test/vm.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include using namespace std; using namespace json_spirit;