#include "chain.hpp" #include namespace chain { namespace { bool decimal_character(char value) { return value >= '0' && value <= '9'; } int nibble(char value) { if (value >= '0' && value <= '9') { return value - '0'; } if (value >= 'a' && value <= 'f') { return value - 'a' + 10; } if (value >= 'A' && value <= 'F') { return value - 'A' + 10; } return -1; } char digit(unsigned value) { static const char alphabet[] = "0123456789abcdef"; return alphabet[value]; } Amount bad_amount() { Amount result; result.code = AMOUNT; result.value = 0; return result; } Text bad_text() { Text result; result.code = PAYLOAD; result.value.clear(); return result; } Bytes bad_bytes() { Bytes result; result.code = PAYLOAD; result.value.clear(); return result; } } std::string code_name(int code) { switch (code) { case OK: return "ok"; case SLOT: return "slot"; case LINK: return "link"; case PAYLOAD: return "payload"; case AMOUNT: return "amount"; case INACTIVE: return "inactive"; case CYCLE: return "cycle"; case DOMAIN: return "domain"; case DEVICE: return "device"; default: return "unknown"; } } Amount parse_amount(const std::string &text, std::size_t ceiling) { if (text.empty()) { return bad_amount(); } for (char character : text) { if (!decimal_character(character)) { return bad_amount(); } } Amount result; bool capped = false; for (char character : text) { unsigned value = static_cast(character - '0'); if (capped) { continue; } if (result.value > ceiling / 10) { result.value = ceiling; capped = true; continue; } if (result.value == ceiling / 10 && value > ceiling % 10) { result.value = ceiling; capped = true; continue; } result.value = result.value * 10 + value; } return result; } Text encode_bytes(const std::vector &bytes) { if (bytes.size() > 32) { return bad_text(); } for (unsigned value : bytes) { if (value > 255) { return bad_text(); } } Text result; result.value.reserve(bytes.size() * 2); for (unsigned value : bytes) { unsigned high = value / 16; unsigned low = value % 16; result.value.push_back(digit(high)); result.value.push_back(digit(low)); } return result; } Bytes decode_bytes(const std::string &text) { if (text.size() > 64) { return bad_bytes(); } if (text.size() % 2 != 0) { return bad_bytes(); } Bytes result; result.value.reserve(text.size() / 2); for (std::size_t offset = 0; offset < text.size(); offset += 2) { int high = nibble(text[offset]); int low = nibble(text[offset + 1]); if (high < 0) { return bad_bytes(); } if (low < 0) { return bad_bytes(); } unsigned value = static_cast(high * 16 + low); result.value.push_back(value); } return result; } }