From 8ae260cb466d4cd0d4db378e5ce0acb8e4432f7c Mon Sep 17 00:00:00 2001 From: Ed Hennis Date: Thu, 7 Mar 2024 19:14:04 -0500 Subject: [PATCH] Format sources --- src/ValidatorKeys.cpp | 169 ++++++++------- src/ValidatorKeys.h | 67 +++--- src/ValidatorKeysTool.cpp | 291 ++++++++++++++------------ src/ValidatorKeysTool.h | 24 +-- src/test/KeyFileGuard.h | 31 ++- src/test/ValidatorKeysTool_test.cpp | 204 +++++++++--------- src/test/ValidatorKeys_test.cpp | 310 ++++++++++++++-------------- 7 files changed, 561 insertions(+), 535 deletions(-) diff --git a/src/ValidatorKeys.cpp b/src/ValidatorKeys.cpp index b6d7365..0cd8a26 100644 --- a/src/ValidatorKeys.cpp +++ b/src/ValidatorKeys.cpp @@ -19,8 +19,9 @@ //============================================================================== #include -#include + #include +#include #include #include #include @@ -33,7 +34,7 @@ namespace ripple { std::string -ValidatorToken::toString () const +ValidatorToken::toString() const { Json::Value jv; jv["validation_secret_key"] = strHex(secretKey); @@ -42,99 +43,94 @@ ValidatorToken::toString () const return ripple::base64_encode(to_string(jv)); } -ValidatorKeys::ValidatorKeys(KeyType const &keyType) +ValidatorKeys::ValidatorKeys(KeyType const& keyType) : keyType_(keyType) , tokenSequence_(0) , revoked_(false) , keys_(generateKeyPair(keyType_, randomSeed())) - { - } - +{ +} -ValidatorKeys::ValidatorKeys ( +ValidatorKeys::ValidatorKeys( KeyType const& keyType, SecretKey const& secretKey, std::uint32_t tokenSequence, bool revoked) - : keyType_ (keyType) - , tokenSequence_ (tokenSequence) - , revoked_ (revoked) - , keys_ ({derivePublicKey(keyType_, secretKey), secretKey}) + : keyType_(keyType) + , tokenSequence_(tokenSequence) + , revoked_(revoked) + , keys_({derivePublicKey(keyType_, secretKey), secretKey}) { } ValidatorKeys -ValidatorKeys::make_ValidatorKeys ( - boost::filesystem::path const& keyFile) +ValidatorKeys::make_ValidatorKeys(boost::filesystem::path const& keyFile) { - std::ifstream ifsKeys (keyFile.c_str (), std::ios::in); + std::ifstream ifsKeys(keyFile.c_str(), std::ios::in); - if (! ifsKeys) - throw std::runtime_error ( + if (!ifsKeys) + throw std::runtime_error( "Failed to open key file: " + keyFile.string()); Json::Reader reader; Json::Value jKeys; - if (! reader.parse (ifsKeys, jKeys)) + if (!reader.parse(ifsKeys, jKeys)) { - throw std::runtime_error ( + throw std::runtime_error( "Unable to parse json key file: " + keyFile.string()); } - static std::array const requiredFields {{ - "key_type", - "secret_key", - "token_sequence", - "revoked" - }}; + static std::array const requiredFields{ + {"key_type", "secret_key", "token_sequence", "revoked"}}; for (auto field : requiredFields) { - if (! jKeys.isMember(field)) + if (!jKeys.isMember(field)) { - throw std::runtime_error ( - "Key file '" + keyFile.string() + - "' is missing \"" + field + "\" field"); + throw std::runtime_error( + "Key file '" + keyFile.string() + "' is missing \"" + field + + "\" field"); } } - auto const keyType = keyTypeFromString (jKeys["key_type"].asString()); + auto const keyType = keyTypeFromString(jKeys["key_type"].asString()); if (!keyType) { - throw std::runtime_error ( + throw std::runtime_error( "Key file '" + keyFile.string() + "' contains invalid \"key_type\" field: " + jKeys["key_type"].toStyledString()); } - auto const secret = parseBase58 ( + auto const secret = parseBase58( TokenType::NodePrivate, jKeys["secret_key"].asString()); - if (! secret) + if (!secret) { - throw std::runtime_error ( + throw std::runtime_error( "Key file '" + keyFile.string() + "' contains invalid \"secret_key\" field: " + jKeys["secret_key"].toStyledString()); } std::uint32_t tokenSequence; - try { - if (! jKeys["token_sequence"].isIntegral()) - throw std::runtime_error (""); + try + { + if (!jKeys["token_sequence"].isIntegral()) + throw std::runtime_error(""); tokenSequence = jKeys["token_sequence"].asUInt(); } catch (std::runtime_error&) { - throw std::runtime_error ( + throw std::runtime_error( "Key file '" + keyFile.string() + "' contains invalid \"token_sequence\" field: " + jKeys["token_sequence"].toStyledString()); } - if (! jKeys["revoked"].isBool()) - throw std::runtime_error ( + if (!jKeys["revoked"].isBool()) + throw std::runtime_error( "Key file '" + keyFile.string() + "' contains invalid \"revoked\" field: " + jKeys["revoked"].toStyledString()); @@ -144,8 +140,8 @@ ValidatorKeys::make_ValidatorKeys ( if (jKeys.isMember("domain")) { - if (! jKeys["domain"].isString()) - throw std::runtime_error ( + if (!jKeys["domain"].isString()) + throw std::runtime_error( "Key file '" + keyFile.string() + "' contains invalid \"domain\" field: " + jKeys["domain"].toStyledString()); @@ -155,32 +151,30 @@ ValidatorKeys::make_ValidatorKeys ( if (jKeys.isMember("manifest")) { - if (! jKeys["manifest"].isString()) - throw std::runtime_error ( + if (!jKeys["manifest"].isString()) + throw std::runtime_error( "Key file '" + keyFile.string() + "' contains invalid \"manifest\" field: " + jKeys["manifest"].toStyledString()); - auto ret = strUnHex (jKeys["manifest"].asString()); + auto ret = strUnHex(jKeys["manifest"].asString()); if (!ret || ret->size() == 0) - throw std::runtime_error ( + throw std::runtime_error( "Key file '" + keyFile.string() + "' contains invalid \"manifest\" field: " + jKeys["manifest"].toStyledString()); vk.manifest_.clear(); vk.manifest_.reserve(ret->size()); - std::copy(ret->begin(), ret->end(), - std::back_inserter(vk.manifest_)); + std::copy(ret->begin(), ret->end(), std::back_inserter(vk.manifest_)); } return vk; } void -ValidatorKeys::writeToFile ( - boost::filesystem::path const& keyFile) const +ValidatorKeys::writeToFile(boost::filesystem::path const& keyFile) const { using namespace boost::filesystem; @@ -188,43 +182,41 @@ ValidatorKeys::writeToFile ( jv["key_type"] = to_string(keyType_); jv["public_key"] = toBase58(TokenType::NodePublic, keys_.publicKey); jv["secret_key"] = toBase58(TokenType::NodePrivate, keys_.secretKey); - jv["token_sequence"] = Json::UInt (tokenSequence_); + jv["token_sequence"] = Json::UInt(tokenSequence_); jv["revoked"] = revoked_; if (!domain_.empty()) jv["domain"] = domain_; if (!manifest_.empty()) jv["manifest"] = strHex(makeSlice(manifest_)); - if (! keyFile.parent_path().empty()) + if (!keyFile.parent_path().empty()) { boost::system::error_code ec; - if (! exists (keyFile.parent_path())) + if (!exists(keyFile.parent_path())) boost::filesystem::create_directories(keyFile.parent_path(), ec); - if (ec || ! is_directory (keyFile.parent_path())) - throw std::runtime_error ("Cannot create directory: " + - keyFile.parent_path().string()); + if (ec || !is_directory(keyFile.parent_path())) + throw std::runtime_error( + "Cannot create directory: " + keyFile.parent_path().string()); } - std::ofstream o (keyFile.string (), std::ios_base::trunc); + std::ofstream o(keyFile.string(), std::ios_base::trunc); if (o.fail()) - throw std::runtime_error ("Cannot open key file: " + - keyFile.string()); + throw std::runtime_error("Cannot open key file: " + keyFile.string()); o << jv.toStyledString(); } boost::optional -ValidatorKeys::createValidatorToken ( - KeyType const& keyType) +ValidatorKeys::createValidatorToken(KeyType const& keyType) { - if (revoked () || - std::numeric_limits::max () - 1 <= tokenSequence_) + if (revoked() || + std::numeric_limits::max() - 1 <= tokenSequence_) return boost::none; ++tokenSequence_; - auto const tokenSecret = generateSecretKey (keyType, randomSeed ()); + auto const tokenSecret = generateSecretKey(keyType, randomSeed()); auto const tokenPublic = derivePublicKey(keyType, tokenSecret); STObject st(sfGeneric); @@ -236,8 +228,8 @@ ValidatorKeys::createValidatorToken ( st[sfDomain] = makeSlice(domain_); ripple::sign(st, HashPrefix::manifest, keyType, tokenSecret); - ripple::sign(st, HashPrefix::manifest, keyType_, keys_.secretKey, - sfMasterSignature); + ripple::sign( + st, HashPrefix::manifest, keyType_, keys_.secretKey, sfMasterSignature); Serializer s; st.add(s); @@ -246,21 +238,21 @@ ValidatorKeys::createValidatorToken ( manifest_.reserve(s.size()); std::copy(s.begin(), s.end(), std::back_inserter(manifest_)); - return ValidatorToken { - ripple::base64_encode(manifest_.data(), manifest_.size()), tokenSecret }; + return ValidatorToken{ + ripple::base64_encode(manifest_.data(), manifest_.size()), tokenSecret}; } std::string -ValidatorKeys::revoke () +ValidatorKeys::revoke() { revoked_ = true; STObject st(sfGeneric); - st[sfSequence] = std::numeric_limits::max (); + st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = keys_.publicKey; - ripple::sign(st, HashPrefix::manifest, keyType_, keys_.secretKey, - sfMasterSignature); + ripple::sign( + st, HashPrefix::manifest, keyType_, keys_.secretKey, sfMasterSignature); Serializer s; st.add(s); @@ -273,9 +265,10 @@ ValidatorKeys::revoke () } std::string -ValidatorKeys::sign (std::string const& data) const +ValidatorKeys::sign(std::string const& data) const { - return strHex(ripple::sign(keys_.publicKey, keys_.secretKey, makeSlice(data))); + return strHex( + ripple::sign(keys_.publicKey, keys_.secretKey, makeSlice(data))); } void @@ -287,7 +280,7 @@ ValidatorKeys::domain(std::string d) // long, should contain at least one . and should not be longer // that 128 characters. if (d.size() < 4 || d.size() > 128) - throw std::runtime_error ( + throw std::runtime_error( "The domain must be between 4 and 128 characters long."); // This regular expression should do a decent job of weeding out @@ -295,23 +288,25 @@ ValidatorKeys::domain(std::string d) // really support IDNs. If this turns out to be an issue, a more // thorough regex can be used or this check can just be removed. static boost::regex const re( - "^" // Beginning of line - "(" // Hostname or domain name - "(?!-)" // - must not begin with '-' - "[a-zA-Z0-9-]{1,63}" // - only alphanumeric and '-' - "(? #include -namespace boost -{ -namespace filesystem -{ +namespace boost { +namespace filesystem { class path; } -} +} // namespace boost namespace ripple { @@ -41,7 +39,8 @@ struct ValidatorToken SecretKey const secretKey; /// Returns base64-encoded JSON object - std::string toString () const; + std::string + toString() const; }; class ValidatorKeys @@ -50,13 +49,16 @@ class ValidatorKeys KeyType keyType_; // struct used to contain both public and secret keys - struct Keys { + struct Keys + { PublicKey publicKey; SecretKey secretKey; Keys() = delete; Keys(std::pair p) - : publicKey(p.first), secretKey(p.second) {} + : publicKey(p.first), secretKey(p.second) + { + } }; std::vector manifest_; @@ -66,11 +68,9 @@ class ValidatorKeys Keys keys_; public: - explicit - ValidatorKeys ( - KeyType const& keyType); + explicit ValidatorKeys(KeyType const& keyType); - ValidatorKeys ( + ValidatorKeys( KeyType const& keyType, SecretKey const& secretKey, std::uint32_t sequence, @@ -82,18 +82,21 @@ class ValidatorKeys @throws std::runtime_error if file content is invalid */ - static ValidatorKeys make_ValidatorKeys( - boost::filesystem::path const& keyFile); + static ValidatorKeys + make_ValidatorKeys(boost::filesystem::path const& keyFile); - ~ValidatorKeys () = default; + ~ValidatorKeys() = default; ValidatorKeys(ValidatorKeys const&) = default; - ValidatorKeys& operator=(ValidatorKeys const&) = default; + ValidatorKeys& + operator=(ValidatorKeys const&) = default; - inline bool operator==(ValidatorKeys const &rhs) const { + inline bool + operator==(ValidatorKeys const& rhs) const + { return revoked_ == rhs.revoked_ && keyType_ == rhs.keyType_ && - tokenSequence_ == rhs.tokenSequence_ && - keys_.publicKey == rhs.keys_.publicKey && - keys_.secretKey == rhs.keys_.secretKey; + tokenSequence_ == rhs.tokenSequence_ && + keys_.publicKey == rhs.keys_.publicKey && + keys_.secretKey == rhs.keys_.secretKey; } /** Write keys to JSON file @@ -105,21 +108,21 @@ class ValidatorKeys @throws std::runtime_error if unable to create parent directory */ void - writeToFile (boost::filesystem::path const& keyFile) const; + writeToFile(boost::filesystem::path const& keyFile) const; /** Returns validator token for current sequence @param keyType Key type for the token keys */ boost::optional - createValidatorToken (KeyType const& keyType = KeyType::secp256k1); + createValidatorToken(KeyType const& keyType = KeyType::secp256k1); /** Revokes validator keys @return base64-encoded key revocation */ std::string - revoke (); + revoke(); /** Signs string with validator key @@ -128,17 +131,18 @@ class ValidatorKeys @return hex-encoded signature */ std::string - sign (std::string const& data) const; + sign(std::string const& data) const; /** Returns the public key. */ - PublicKey const& publicKey() const + PublicKey const& + publicKey() const { return keys_.publicKey; } /** Returns true if keys are revoked. */ bool - revoked () const + revoked() const { return revoked_; } @@ -151,19 +155,22 @@ class ValidatorKeys } /** Sets the domain associated with this key */ - void domain(std::string d); + void + domain(std::string d); /** Returns the last manifest we generated for this domain, if available. */ - std::vector manifest() const + std::vector + manifest() const { return manifest_; } /** Returns the sequence number of the last manifest generated. */ - std::uint32_t sequence() const + std::uint32_t + sequence() const { return tokenSequence_; } }; -} // ripple +} // namespace ripple diff --git a/src/ValidatorKeysTool.cpp b/src/ValidatorKeysTool.cpp index 90e103c..a12daea 100644 --- a/src/ValidatorKeysTool.cpp +++ b/src/ValidatorKeysTool.cpp @@ -19,16 +19,17 @@ //============================================================================== #include + #include -#include #include +#include #include #include #include #include -#include #include +#include #ifdef BOOST_MSVC #include @@ -38,7 +39,8 @@ // The build version number. You must edit this for each release // and follow the format described at http://semver.org/ //-------------------------------------------------------------------------- -char const* const versionString = "0.3.2" +char const* const versionString = + "0.3.2" #if defined(DEBUG) || defined(SANITIZER) "+" @@ -57,56 +59,57 @@ char const* const versionString = "0.3.2" //-------------------------------------------------------------------------- ; -static int runUnitTests () +static int +runUnitTests() { using namespace beast::unit_test; reporter r; bool const anyFailed = r.run_each(global_suites()); - if(anyFailed) - return EXIT_FAILURE; //LCOV_EXCL_LINE + if (anyFailed) + return EXIT_FAILURE; // LCOV_EXCL_LINE return EXIT_SUCCESS; } -void createKeyFile (boost::filesystem::path const& keyFile) +void +createKeyFile(boost::filesystem::path const& keyFile) { using namespace ripple; - if (exists (keyFile)) - throw std::runtime_error ( - "Refusing to overwrite existing key file: " + - keyFile.string ()); + if (exists(keyFile)) + throw std::runtime_error( + "Refusing to overwrite existing key file: " + keyFile.string()); - ValidatorKeys const keys (KeyType::ed25519); - keys.writeToFile (keyFile); + ValidatorKeys const keys(KeyType::ed25519); + keys.writeToFile(keyFile); - std::cout << "Validator keys stored in " << - keyFile.string() << - "\n\nThis file should be stored securely and not shared.\n\n"; + std::cout << "Validator keys stored in " << keyFile.string() + << "\n\nThis file should be stored securely and not shared.\n\n"; } -void createToken (boost::filesystem::path const& keyFile) +void +createToken(boost::filesystem::path const& keyFile) { using namespace ripple; - auto keys = ValidatorKeys::make_ValidatorKeys (keyFile); + auto keys = ValidatorKeys::make_ValidatorKeys(keyFile); - if (keys.revoked ()) - throw std::runtime_error ( - "Validator keys have been revoked."); + if (keys.revoked()) + throw std::runtime_error("Validator keys have been revoked."); - auto const token = keys.createValidatorToken (); + auto const token = keys.createValidatorToken(); - if (! token) - throw std::runtime_error ( + if (!token) + throw std::runtime_error( "Maximum number of tokens have already been generated.\n" "Revoke validator keys if previous token has been compromised."); // Update key file with new token sequence - keys.writeToFile (keyFile); + keys.writeToFile(keyFile); - std::cout << "Update rippled.cfg file with these values and restart rippled:\n\n"; - std::cout << "# validator public key: " << - toBase58 (TokenType::NodePublic, keys.publicKey()) << "\n\n"; + std::cout + << "Update rippled.cfg file with these values and restart rippled:\n\n"; + std::cout << "# validator public key: " + << toBase58(TokenType::NodePublic, keys.publicKey()) << "\n\n"; std::cout << "[validator_token]\n"; auto const tokenStr = token->toString(); @@ -117,25 +120,27 @@ void createToken (boost::filesystem::path const& keyFile) std::cout << std::endl; } -void createRevocation (boost::filesystem::path const& keyFile) +void +createRevocation(boost::filesystem::path const& keyFile) { using namespace ripple; - auto keys = ValidatorKeys::make_ValidatorKeys (keyFile); + auto keys = ValidatorKeys::make_ValidatorKeys(keyFile); if (keys.revoked()) std::cout << "WARNING: Validator keys have already been revoked!\n\n"; else std::cout << "WARNING: This will revoke your validator keys!\n\n"; - auto const revocation = keys.revoke (); + auto const revocation = keys.revoke(); // Update key file with new token sequence - keys.writeToFile (keyFile); + keys.writeToFile(keyFile); - std::cout << "Update rippled.cfg file with these values and restart rippled:\n\n"; - std::cout << "# validator public key: " << - toBase58 (TokenType::NodePublic, keys.publicKey()) << "\n\n"; + std::cout + << "Update rippled.cfg file with these values and restart rippled:\n\n"; + std::cout << "# validator public key: " + << toBase58(TokenType::NodePublic, keys.publicKey()) << "\n\n"; std::cout << "[validator_key_revocation]\n"; auto const len = 72; @@ -145,7 +150,8 @@ void createRevocation (boost::filesystem::path const& keyFile) std::cout << std::endl; } -void attestDomain(ripple::ValidatorKeys const& keys) +void +attestDomain(ripple::ValidatorKeys const& keys) { using namespace ripple; @@ -158,43 +164,47 @@ void attestDomain(ripple::ValidatorKeys const& keys) } std::cout << "The domain attestation for validator " - << toBase58 (TokenType::NodePublic, keys.publicKey()) << " is:\n\n"; + << toBase58(TokenType::NodePublic, keys.publicKey()) + << " is:\n\n"; - std::cout << "attestation=\"" << keys.sign ( - "[domain-attestation-blob:" + keys.domain() + ":" + - toBase58(TokenType::NodePublic, keys.publicKey()) + "]") << "\"\n\n"; + std::cout << "attestation=\"" + << keys.sign( + "[domain-attestation-blob:" + keys.domain() + ":" + + toBase58(TokenType::NodePublic, keys.publicKey()) + "]") + << "\"\n\n"; std::cout << "You should include it in your xrp-ledger.toml file in the\n"; std::cout << "section for this validator.\n"; } -void attestDomain(boost::filesystem::path const& keyFile) +void +attestDomain(boost::filesystem::path const& keyFile) { using namespace ripple; - auto keys = ValidatorKeys::make_ValidatorKeys (keyFile); + auto keys = ValidatorKeys::make_ValidatorKeys(keyFile); if (keys.revoked()) - throw std::runtime_error ( + throw std::runtime_error( "Operation error: The specified master key has been revoked!"); attestDomain(keys); } -void setDomain (std::string const& domain, - boost::filesystem::path const& keyFile) +void +setDomain(std::string const& domain, boost::filesystem::path const& keyFile) { using namespace ripple; - auto keys = ValidatorKeys::make_ValidatorKeys (keyFile); + auto keys = ValidatorKeys::make_ValidatorKeys(keyFile); if (keys.revoked()) - throw std::runtime_error ( + throw std::runtime_error( "Operation error: The specified master key has been revoked!"); if (domain == keys.domain()) { - if(domain.empty()) + if (domain.empty()) std::cout << "The domain name was already cleared!\n"; else std::cout << "The domain name was already set.\n"; @@ -203,14 +213,14 @@ void setDomain (std::string const& domain, // Set the domain and generate a new token keys.domain(domain); - auto const token = keys.createValidatorToken (); - if (! token) - throw std::runtime_error ( + auto const token = keys.createValidatorToken(); + if (!token) + throw std::runtime_error( "Maximum number of tokens have already been generated.\n" "Revoke validator keys if previous token has been compromised."); // Flush to disk - keys.writeToFile (keyFile); + keys.writeToFile(keyFile); if (domain.empty()) std::cout << "The domain name has been cleared.\n"; @@ -221,8 +231,8 @@ void setDomain (std::string const& domain, std::cout << "\n"; std::cout << "You also need to update the rippled.cfg file to add a new\n"; std::cout << "validator token and restart rippled:\n\n"; - std::cout << "# validator public key: " << - toBase58 (TokenType::NodePublic, keys.publicKey()) << "\n\n"; + std::cout << "# validator public key: " + << toBase58(TokenType::NodePublic, keys.publicKey()) << "\n\n"; std::cout << "[validator_token]\n"; auto const tokenStr = token->toString(); @@ -233,31 +243,32 @@ void setDomain (std::string const& domain, std::cout << "\n"; } -void signData (std::string const& data, - boost::filesystem::path const& keyFile) +void +signData(std::string const& data, boost::filesystem::path const& keyFile) { using namespace ripple; if (data.empty()) - throw std::runtime_error ( + throw std::runtime_error( "Syntax error: Must specify data string to sign"); - auto keys = ValidatorKeys::make_ValidatorKeys (keyFile); + auto keys = ValidatorKeys::make_ValidatorKeys(keyFile); if (keys.revoked()) std::cout << "WARNING: Validator keys have been revoked!\n\n"; - std::cout << keys.sign (data) << std::endl; + std::cout << keys.sign(data) << std::endl; std::cout << std::endl; } -void generateManifest ( +void +generateManifest( std::string const& type, boost::filesystem::path const& keyFile) { using namespace ripple; - auto keys = ValidatorKeys::make_ValidatorKeys (keyFile); + auto keys = ValidatorKeys::make_ValidatorKeys(keyFile); auto const m = keys.manifest(); @@ -285,59 +296,60 @@ void generateManifest ( std::cout << "Unknown encoding '" << type << "'\n"; } -int runCommand (std::string const& command, - std::vector const& args, +int +runCommand( + std::string const& command, + std::vector const& args, boost::filesystem::path const& keyFile) { using namespace std; static map::size_type> const commandArgs = { - { "create_keys", 0 }, - { "create_token", 0 }, - { "revoke_keys", 0 }, - { "set_domain", 1 }, - { "clear_domain", 0 }, - { "attest_domain", 0 }, - { "show_manifest", 1 }, - { "sign", 1 }, + {"create_keys", 0}, + {"create_token", 0}, + {"revoke_keys", 0}, + {"set_domain", 1}, + {"clear_domain", 0}, + {"attest_domain", 0}, + {"show_manifest", 1}, + {"sign", 1}, }; - auto const iArgs = commandArgs.find (command); + auto const iArgs = commandArgs.find(command); - if (iArgs == commandArgs.end ()) - throw std::runtime_error ("Unknown command: " + command); + if (iArgs == commandArgs.end()) + throw std::runtime_error("Unknown command: " + command); if (args.size() != iArgs->second) - throw std::runtime_error ("Syntax error: Wrong number of arguments"); + throw std::runtime_error("Syntax error: Wrong number of arguments"); if (command == "create_keys") - createKeyFile (keyFile); + createKeyFile(keyFile); else if (command == "create_token") - createToken (keyFile); + createToken(keyFile); else if (command == "revoke_keys") - createRevocation (keyFile); + createRevocation(keyFile); else if (command == "set_domain") - setDomain (args[0], keyFile); + setDomain(args[0], keyFile); else if (command == "clear_domain") - setDomain ("", keyFile); + setDomain("", keyFile); else if (command == "attest_domain") - attestDomain (keyFile); + attestDomain(keyFile); else if (command == "sign") - signData (args[0], keyFile); + signData(args[0], keyFile); else if (command == "show_manifest") - generateManifest (args[0], keyFile); + generateManifest(args[0], keyFile); return 0; } -//LCOV_EXCL_START -static -std::string -getEnvVar (char const* name) +// LCOV_EXCL_START +static std::string +getEnvVar(char const* name) { std::string value; - auto const v = getenv (name); + auto const v = getenv(name); if (v != nullptr) value = v; @@ -345,7 +357,8 @@ getEnvVar (char const* name) return value; } -void printHelp (const boost::program_options::options_description& desc) +void +printHelp(const boost::program_options::options_description& desc) { std::cerr << "validator-keys [options] [ ...]\n" @@ -354,28 +367,35 @@ void printHelp (const boost::program_options::options_description& desc) " create_keys Generate validator keys.\n" " create_token Generate validator token.\n" " revoke_keys Revoke validator keys.\n" - " sign Sign string with validator key.\n" - " show_manifest [hex|base64] Displays the last generated manifest\n" - " set_domain Associate a domain with the validator key.\n" - " clear_domain Disassociate a domain from a validator key.\n" - " attest_domain Produce the attestation string for a domain.\n"; + " sign Sign string with validator " + "key.\n" + " show_manifest [hex|base64] Displays the last generated " + "manifest\n" + " set_domain Associate a domain with the " + "validator key.\n" + " clear_domain Disassociate a domain from a " + "validator key.\n" + " attest_domain Produce the attestation string " + "for a domain.\n"; } -//LCOV_EXCL_STOP +// LCOV_EXCL_STOP std::string const& -getVersionString () +getVersionString() { static std::string const value = [] { std::string const s = versionString; beast::SemanticVersion v; - if (!v.parse (s) || v.print () != s) - throw std::logic_error (s + ": Bad version string"); //LCOV_EXCL_LINE + if (!v.parse(s) || v.print() != s) + throw std::logic_error( + s + ": Bad version string"); // LCOV_EXCL_LINE return s; }(); return value; } -int main (int argc, char** argv) +int +main(int argc, char** argv) { namespace po = boost::program_options; @@ -383,22 +403,20 @@ int main (int argc, char** argv) // Set up option parsing. // - po::options_description general ("General Options"); - general.add_options () - ("help,h", "Display this message.") - ("keyfile", po::value (), "Specify the key file.") - ("unittest,u", "Perform unit tests.") - ("version", "Display the build version.") - ; + po::options_description general("General Options"); + general.add_options()("help,h", "Display this message.")( + "keyfile", po::value(), "Specify the key file.")( + "unittest,u", "Perform unit tests.")( + "version", "Display the build version."); po::options_description hidden("Hidden options"); - hidden.add_options() - ("command", po::value< std::string > (), "Command.") - ("arguments",po::value< std::vector > ()->default_value( - std::vector (), "empty"), "Arguments.") - ; + hidden.add_options()("command", po::value(), "Command.")( + "arguments", + po::value>()->default_value( + std::vector(), "empty"), + "Arguments."); po::positional_options_description p; - p.add ("command", 1).add ("arguments", -1); + p.add("command", 1).add("arguments", -1); po::options_description cmdline_options; cmdline_options.add(general).add(hidden); @@ -406,65 +424,66 @@ int main (int argc, char** argv) // Parse options, if no error. try { - po::store (po::command_line_parser (argc, argv) - .options (cmdline_options) // Parse options. - .positional (p) - .run (), + po::store( + po::command_line_parser(argc, argv) + .options(cmdline_options) // Parse options. + .positional(p) + .run(), vm); - po::notify (vm); // Invoke option notify functions. + po::notify(vm); // Invoke option notify functions. } - //LCOV_EXCL_START + // LCOV_EXCL_START catch (std::exception const&) { - std::cerr << "validator-keys: Incorrect command line syntax." << std::endl; + std::cerr << "validator-keys: Incorrect command line syntax." + << std::endl; std::cerr << "Use '--help' for a list of options." << std::endl; return EXIT_FAILURE; } - //LCOV_EXCL_STOP + // LCOV_EXCL_STOP // Run the unit tests if requested. // The unit tests will exit the application with an appropriate return code. - if (vm.count ("unittest")) + if (vm.count("unittest")) return runUnitTests(); - //LCOV_EXCL_START - if (vm.count ("version")) + // LCOV_EXCL_START + if (vm.count("version")) { - std::cout << "validator-keys version " << - getVersionString () << std::endl; + std::cout << "validator-keys version " << getVersionString() + << std::endl; return 0; } - if (vm.count ("help") || ! vm.count ("command")) + if (vm.count("help") || !vm.count("command")) { - printHelp (general); + printHelp(general); return EXIT_SUCCESS; } - std::string const homeDir = getEnvVar ("HOME"); + std::string const homeDir = getEnvVar("HOME"); std::string const defaultKeyFile = - (homeDir.empty () ? - boost::filesystem::current_path ().string () : homeDir) + + (homeDir.empty() ? boost::filesystem::current_path().string() + : homeDir) + "/.ripple/validator-keys.json"; try { using namespace boost::filesystem; - path keyFile = vm.count ("keyfile") ? - vm["keyfile"].as () : - defaultKeyFile; + path keyFile = vm.count("keyfile") ? vm["keyfile"].as() + : defaultKeyFile; - return runCommand ( + return runCommand( vm["command"].as(), vm["arguments"].as>(), keyFile); } - catch(std::exception const& e) + catch (std::exception const& e) { std::cerr << e.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; - //LCOV_EXCL_STOP + // LCOV_EXCL_STOP } diff --git a/src/ValidatorKeysTool.h b/src/ValidatorKeysTool.h index 6e346ed..d69ff99 100644 --- a/src/ValidatorKeysTool.h +++ b/src/ValidatorKeysTool.h @@ -21,31 +21,29 @@ #include #include -namespace boost -{ -namespace filesystem -{ +namespace boost { +namespace filesystem { class path; } -} +} // namespace boost std::string const& -getVersionString (); +getVersionString(); void -createKeyFile (boost::filesystem::path const& keyFile); +createKeyFile(boost::filesystem::path const& keyFile); void -createToken (boost::filesystem::path const& keyFile); +createToken(boost::filesystem::path const& keyFile); void -createRevocation (boost::filesystem::path const& keyFile); +createRevocation(boost::filesystem::path const& keyFile); void -signData (std::string const& data, - boost::filesystem::path const& keyFile); +signData(std::string const& data, boost::filesystem::path const& keyFile); int -runCommand (std::string const& command, - std::vector const& arg, +runCommand( + std::string const& command, + std::vector const& arg, boost::filesystem::path const& keyFile); diff --git a/src/test/KeyFileGuard.h b/src/test/KeyFileGuard.h index 0a9d09a..9683dbe 100644 --- a/src/test/KeyFileGuard.h +++ b/src/test/KeyFileGuard.h @@ -33,45 +33,44 @@ class KeyFileGuard path subDir_; beast::unit_test::suite& test_; - auto rmDir (path const& toRm) + auto + rmDir(path const& toRm) { - if (is_directory (toRm)) - remove_all (toRm); + if (is_directory(toRm)) + remove_all(toRm); else - test_.log << "Expected " << toRm.string () + test_.log << "Expected " << toRm.string() << " to be an existing directory." << std::endl; }; public: - KeyFileGuard (beast::unit_test::suite& test, - std::string const& subDir) - : subDir_ (subDir) - , test_ (test) + KeyFileGuard(beast::unit_test::suite& test, std::string const& subDir) + : subDir_(subDir), test_(test) { using namespace boost::filesystem; - if (!exists (subDir_)) - create_directory (subDir_); + if (!exists(subDir_)) + create_directory(subDir_); else // Cannot run the test. Someone created a file or directory // where we want to put our directory - throw std::runtime_error ( - "Cannot create directory: " + subDir_.string ()); + throw std::runtime_error( + "Cannot create directory: " + subDir_.string()); } - ~KeyFileGuard () + ~KeyFileGuard() { try { using namespace boost::filesystem; - rmDir (subDir_); + rmDir(subDir_); } catch (std::exception& e) { // if we throw here, just let it die. - test_.log << "Error in ~KeyFileGuard: " << e.what () << std::endl; + test_.log << "Error in ~KeyFileGuard: " << e.what() << std::endl; }; } }; -} // ripple +} // namespace ripple diff --git a/src/test/ValidatorKeysTool_test.cpp b/src/test/ValidatorKeysTool_test.cpp index c1c7aaf..8ff3aa3 100644 --- a/src/test/ValidatorKeysTool_test.cpp +++ b/src/test/ValidatorKeysTool_test.cpp @@ -17,10 +17,10 @@ */ //============================================================================== -#include +#include #include +#include #include -#include namespace ripple { @@ -29,18 +29,18 @@ namespace tests { class ValidatorKeysTool_test : public beast::unit_test::suite { private: - // Allow cout to be redirected. Destructor restores old cout streambuf. class CoutRedirect { public: - CoutRedirect (std::stringstream& sStream) - : old_ (std::cout.rdbuf (sStream.rdbuf())) - { } + CoutRedirect(std::stringstream& sStream) + : old_(std::cout.rdbuf(sStream.rdbuf())) + { + } ~CoutRedirect() { - std::cout.rdbuf (old_); + std::cout.rdbuf(old_); } private: @@ -48,28 +48,28 @@ class ValidatorKeysTool_test : public beast::unit_test::suite }; void - testCreateKeyFile () + testCreateKeyFile() { - testcase ("Create Key File"); + testcase("Create Key File"); std::stringstream coutCapture; - CoutRedirect coutRedirect {coutCapture}; + CoutRedirect coutRedirect{coutCapture}; using namespace boost::filesystem; path const subdir = "test_key_file"; - KeyFileGuard const g (*this, subdir.string()); + KeyFileGuard const g(*this, subdir.string()); path const keyFile = subdir / "validator_keys.json"; - createKeyFile (keyFile); + createKeyFile(keyFile); BEAST_EXPECT(exists(keyFile)); - std::string const expectedError = "Refusing to overwrite existing key file: " + - keyFile.string(); + std::string const expectedError = + "Refusing to overwrite existing key file: " + keyFile.string(); std::string error; try { - createKeyFile (keyFile); + createKeyFile(keyFile); } catch (std::exception const& e) { @@ -79,118 +79,117 @@ class ValidatorKeysTool_test : public beast::unit_test::suite } void - testCreateToken () + testCreateToken() { - testcase ("Create Token"); + testcase("Create Token"); std::stringstream coutCapture; - CoutRedirect coutRedirect {coutCapture}; + CoutRedirect coutRedirect{coutCapture}; using namespace boost::filesystem; path const subdir = "test_key_file"; - KeyFileGuard const g (*this, subdir.string()); + KeyFileGuard const g(*this, subdir.string()); path const keyFile = subdir / "validator_keys.json"; - auto testToken = [this]( - path const& keyFile, - std::string const& expectedError) - { - try - { - createToken (keyFile); - BEAST_EXPECT(expectedError.empty()); - } - catch (std::exception const& e) - { - BEAST_EXPECT(e.what() == expectedError); - } - }; + auto testToken = + [this](path const& keyFile, std::string const& expectedError) { + try + { + createToken(keyFile); + BEAST_EXPECT(expectedError.empty()); + } + catch (std::exception const& e) + { + BEAST_EXPECT(e.what() == expectedError); + } + }; { std::string const expectedError = "Failed to open key file: " + keyFile.string(); - testToken (keyFile, expectedError); + testToken(keyFile, expectedError); } - createKeyFile (keyFile); + createKeyFile(keyFile); { std::string const expectedError = ""; - testToken (keyFile, expectedError); + testToken(keyFile, expectedError); } { auto const keyType = KeyType::ed25519; - auto const kp = generateKeyPair (keyType, randomSeed ()); + auto const kp = generateKeyPair(keyType, randomSeed()); - auto keys = ValidatorKeys ( + auto keys = ValidatorKeys( keyType, kp.second, - std::numeric_limits::max () - 1); + std::numeric_limits::max() - 1); - keys.writeToFile (keyFile); + keys.writeToFile(keyFile); std::string const expectedError = "Maximum number of tokens have already been generated.\n" "Revoke validator keys if previous token has been compromised."; - testToken (keyFile, expectedError); + testToken(keyFile, expectedError); } { - createRevocation (keyFile); + createRevocation(keyFile); std::string const expectedError = "Validator keys have been revoked."; - testToken (keyFile, expectedError); + testToken(keyFile, expectedError); } } void - testCreateRevocation () + testCreateRevocation() { - testcase ("Create Revocation"); + testcase("Create Revocation"); std::stringstream coutCapture; - CoutRedirect coutRedirect {coutCapture}; + CoutRedirect coutRedirect{coutCapture}; using namespace boost::filesystem; path const subdir = "test_key_file"; - KeyFileGuard const g (*this, subdir.string()); + KeyFileGuard const g(*this, subdir.string()); path const keyFile = subdir / "validator_keys.json"; - auto expectedError = - "Failed to open key file: " + keyFile.string(); + auto expectedError = "Failed to open key file: " + keyFile.string(); std::string error; - try { - createRevocation (keyFile); - } catch (std::runtime_error& e) { + try + { + createRevocation(keyFile); + } + catch (std::runtime_error& e) + { error = e.what(); } BEAST_EXPECT(error == expectedError); - createKeyFile (keyFile); + createKeyFile(keyFile); BEAST_EXPECT(exists(keyFile)); - createRevocation (keyFile); - createRevocation (keyFile); + createRevocation(keyFile); + createRevocation(keyFile); } void - testSign () + testSign() { - testcase ("Sign"); + testcase("Sign"); std::stringstream coutCapture; - CoutRedirect coutRedirect {coutCapture}; + CoutRedirect coutRedirect{coutCapture}; using namespace boost::filesystem; auto testSign = [this]( - std::string const& data, - path const& keyFile, - std::string const& expectedError) - { + std::string const& data, + path const& keyFile, + std::string const& expectedError) { try { - signData (data, keyFile); + signData(data, keyFile); BEAST_EXPECT(expectedError.empty()); } catch (std::exception const& e) @@ -202,53 +201,52 @@ class ValidatorKeysTool_test : public beast::unit_test::suite std::string const data = "data to sign"; path const subdir = "test_key_file"; - KeyFileGuard const g (*this, subdir.string()); + KeyFileGuard const g(*this, subdir.string()); path const keyFile = subdir / "validator_keys.json"; { std::string const expectedError = "Failed to open key file: " + keyFile.string(); - testSign (data, keyFile, expectedError); + testSign(data, keyFile, expectedError); } - createKeyFile (keyFile); + createKeyFile(keyFile); BEAST_EXPECT(exists(keyFile)); { std::string const emptyData = ""; std::string const expectedError = "Syntax error: Must specify data string to sign"; - testSign (emptyData, keyFile, expectedError); + testSign(emptyData, keyFile, expectedError); } { std::string const expectedError = ""; - testSign (data, keyFile, expectedError); + testSign(data, keyFile, expectedError); } } void - testRunCommand () + testRunCommand() { - testcase ("Run Command"); + testcase("Run Command"); std::stringstream coutCapture; - CoutRedirect coutRedirect {coutCapture}; + CoutRedirect coutRedirect{coutCapture}; using namespace boost::filesystem; path const subdir = "test_key_file"; - KeyFileGuard g (*this, subdir.string()); + KeyFileGuard g(*this, subdir.string()); path const keyFile = subdir / "validator_keys.json"; auto testCommand = [this]( - std::string const& command, - std::vector const& args, - path const& keyFile, - std::string const& expectedError) - { + std::string const& command, + std::vector const& args, + path const& keyFile, + std::string const& expectedError) { try { - runCommand (command, args, keyFile); + runCommand(command, args, keyFile); BEAST_EXPECT(expectedError.empty()); } catch (std::exception const& e) @@ -257,41 +255,41 @@ class ValidatorKeysTool_test : public beast::unit_test::suite } }; - std::vector const noArgs; - std::vector const oneArg = { "some data" }; - std::vector const twoArgs = { "data", "more data" }; + std::vector const noArgs; + std::vector const oneArg = {"some data"}; + std::vector const twoArgs = {"data", "more data"}; std::string const noError = ""; std::string const argError = "Syntax error: Wrong number of arguments"; { std::string const command = "unknown"; std::string const expectedError = "Unknown command: " + command; - testCommand (command, noArgs, keyFile, expectedError); - testCommand (command, oneArg, keyFile, expectedError); - testCommand (command, twoArgs, keyFile, expectedError); + testCommand(command, noArgs, keyFile, expectedError); + testCommand(command, oneArg, keyFile, expectedError); + testCommand(command, twoArgs, keyFile, expectedError); } { std::string const command = "create_keys"; - testCommand (command, noArgs, keyFile, noError); - testCommand (command, oneArg, keyFile, argError); - testCommand (command, twoArgs, keyFile, argError); + testCommand(command, noArgs, keyFile, noError); + testCommand(command, oneArg, keyFile, argError); + testCommand(command, twoArgs, keyFile, argError); } { std::string const command = "create_token"; - testCommand (command, noArgs, keyFile, noError); - testCommand (command, oneArg, keyFile, argError); - testCommand (command, twoArgs, keyFile, argError); + testCommand(command, noArgs, keyFile, noError); + testCommand(command, oneArg, keyFile, argError); + testCommand(command, twoArgs, keyFile, argError); } { std::string const command = "revoke_keys"; - testCommand (command, noArgs, keyFile, noError); - testCommand (command, oneArg, keyFile, argError); - testCommand (command, twoArgs, keyFile, argError); + testCommand(command, noArgs, keyFile, noError); + testCommand(command, oneArg, keyFile, argError); + testCommand(command, twoArgs, keyFile, argError); } { std::string const command = "sign"; - testCommand (command, noArgs, keyFile, argError); - testCommand (command, oneArg, keyFile, noError); - testCommand (command, twoArgs, keyFile, argError); + testCommand(command, noArgs, keyFile, argError); + testCommand(command, oneArg, keyFile, noError); + testCommand(command, twoArgs, keyFile, argError); } } @@ -301,16 +299,16 @@ class ValidatorKeysTool_test : public beast::unit_test::suite { getVersionString(); - testCreateKeyFile (); - testCreateToken (); - testCreateRevocation (); - testSign (); - testRunCommand (); + testCreateKeyFile(); + testCreateToken(); + testCreateRevocation(); + testSign(); + testRunCommand(); } }; BEAST_DEFINE_TESTSUITE(ValidatorKeysTool, keys, ripple); -} // tests +} // namespace tests -} // ripple +} // namespace ripple diff --git a/src/test/ValidatorKeys_test.cpp b/src/test/ValidatorKeys_test.cpp index 912609b..0352a7d 100644 --- a/src/test/ValidatorKeys_test.cpp +++ b/src/test/ValidatorKeys_test.cpp @@ -17,12 +17,12 @@ */ //============================================================================== -#include -#include -#include #include +#include #include #include +#include +#include namespace ripple { @@ -31,33 +31,36 @@ namespace tests { class ValidatorKeys_test : public beast::unit_test::suite { private: - void - testKeyFile (boost::filesystem::path const& keyFile, - Json::Value const& jv, std::string const& expectedError) + testKeyFile( + boost::filesystem::path const& keyFile, + Json::Value const& jv, + std::string const& expectedError) { { - std::ofstream o (keyFile.string (), std::ios_base::trunc); + std::ofstream o(keyFile.string(), std::ios_base::trunc); o << jv.toStyledString(); o.close(); } - try { - ValidatorKeys::make_ValidatorKeys (keyFile); + try + { + ValidatorKeys::make_ValidatorKeys(keyFile); BEAST_EXPECT(expectedError.empty()); - } catch (std::runtime_error& e) { + } + catch (std::runtime_error& e) + { BEAST_EXPECT(e.what() == expectedError); } } - std::array const keyTypes {{ - KeyType::ed25519, - KeyType::secp256k1 }}; + std::array const keyTypes{ + {KeyType::ed25519, KeyType::secp256k1}}; void - testMakeValidatorKeys () + testMakeValidatorKeys() { - testcase ("Make Validator Keys"); + testcase("Make Validator Keys"); using namespace boost::filesystem; @@ -66,26 +69,28 @@ class ValidatorKeys_test : public beast::unit_test::suite for (auto const keyType : keyTypes) { - ValidatorKeys const keys (keyType); + ValidatorKeys const keys(keyType); - KeyFileGuard const g (*this, subdir.string()); + KeyFileGuard const g(*this, subdir.string()); - keys.writeToFile (keyFile); - BEAST_EXPECT (exists (keyFile)); + keys.writeToFile(keyFile); + BEAST_EXPECT(exists(keyFile)); - auto const keys2 = ValidatorKeys::make_ValidatorKeys (keyFile); - BEAST_EXPECT (keys == keys2); + auto const keys2 = ValidatorKeys::make_ValidatorKeys(keyFile); + BEAST_EXPECT(keys == keys2); } { // Require expected fields - KeyFileGuard g (*this, subdir.string()); + KeyFileGuard g(*this, subdir.string()); - auto expectedError = - "Failed to open key file: " + keyFile.string(); + auto expectedError = "Failed to open key file: " + keyFile.string(); std::string error; - try { - ValidatorKeys::make_ValidatorKeys (keyFile); - } catch (std::runtime_error& e) { + try + { + ValidatorKeys::make_ValidatorKeys(keyFile); + } + catch (std::runtime_error& e) + { error = e.what(); } BEAST_EXPECT(error == expectedError); @@ -94,14 +99,17 @@ class ValidatorKeys_test : public beast::unit_test::suite "Unable to parse json key file: " + keyFile.string(); { - std::ofstream o (keyFile.string (), std::ios_base::trunc); + std::ofstream o(keyFile.string(), std::ios_base::trunc); o << "{{}"; o.close(); } - try { - ValidatorKeys::make_ValidatorKeys (keyFile); - } catch (std::runtime_error& e) { + try + { + ValidatorKeys::make_ValidatorKeys(keyFile); + } + catch (std::runtime_error& e) + { error = e.what(); } BEAST_EXPECT(error == expectedError); @@ -110,231 +118,228 @@ class ValidatorKeys_test : public beast::unit_test::suite jv["dummy"] = "field"; expectedError = "Key file '" + keyFile.string() + "' is missing \"key_type\" field"; - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); jv["key_type"] = "dummy keytype"; expectedError = "Key file '" + keyFile.string() + "' is missing \"secret_key\" field"; - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); jv["secret_key"] = "dummy secret"; expectedError = "Key file '" + keyFile.string() + "' is missing \"token_sequence\" field"; - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); jv["token_sequence"] = "dummy sequence"; expectedError = "Key file '" + keyFile.string() + "' is missing \"revoked\" field"; - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); jv["revoked"] = "dummy revoked"; expectedError = "Key file '" + keyFile.string() + "' contains invalid \"key_type\" field: " + jv["key_type"].toStyledString(); - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); auto const keyType = KeyType::ed25519; jv["key_type"] = to_string(keyType); expectedError = "Key file '" + keyFile.string() + "' contains invalid \"secret_key\" field: " + jv["secret_key"].toStyledString(); - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); - ValidatorKeys const keys (keyType); + ValidatorKeys const keys(keyType); { - auto const kp = generateKeyPair (keyType, randomSeed ()); - jv["secret_key"] = - toBase58(TokenType::NodePrivate, kp.second); + auto const kp = generateKeyPair(keyType, randomSeed()); + jv["secret_key"] = toBase58(TokenType::NodePrivate, kp.second); } expectedError = "Key file '" + keyFile.string() + "' contains invalid \"token_sequence\" field: " + jv["token_sequence"].toStyledString(); - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); jv["token_sequence"] = -1; expectedError = "Key file '" + keyFile.string() + "' contains invalid \"token_sequence\" field: " + jv["token_sequence"].toStyledString(); - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); jv["token_sequence"] = - Json::UInt(std::numeric_limits::max ()); + Json::UInt(std::numeric_limits::max()); expectedError = "Key file '" + keyFile.string() + "' contains invalid \"revoked\" field: " + jv["revoked"].toStyledString(); - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); jv["revoked"] = false; expectedError = ""; - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); jv["revoked"] = true; - testKeyFile (keyFile, jv, expectedError); + testKeyFile(keyFile, jv, expectedError); } } void - testCreateValidatorToken () + testCreateValidatorToken() { - testcase ("Create Validator Token"); + testcase("Create Validator Token"); for (auto const keyType : keyTypes) { - ValidatorKeys keys (keyType); + ValidatorKeys keys(keyType); std::uint32_t sequence = 0; for (auto const tokenKeyType : keyTypes) { - auto const token = keys.createValidatorToken (tokenKeyType); + auto const token = keys.createValidatorToken(tokenKeyType); - if(! BEAST_EXPECT(token)) + if (!BEAST_EXPECT(token)) continue; auto const tokenPublicKey = derivePublicKey(tokenKeyType, token->secretKey); - STObject st (sfGeneric); + STObject st(sfGeneric); auto const manifest = ripple::base64_decode(token->manifest); - SerialIter sit (manifest.data (), manifest.size ()); - st.set (sit); + SerialIter sit(manifest.data(), manifest.size()); + st.set(sit); - auto const seq = get (st, sfSequence); - BEAST_EXPECT (seq); - BEAST_EXPECT (*seq == ++sequence); + auto const seq = get(st, sfSequence); + BEAST_EXPECT(seq); + BEAST_EXPECT(*seq == ++sequence); auto const tpk = get(st, sfSigningPubKey); - BEAST_EXPECT (tpk); - BEAST_EXPECT (*tpk == tokenPublicKey); - BEAST_EXPECT (verify (st, HashPrefix::manifest, tokenPublicKey)); + BEAST_EXPECT(tpk); + BEAST_EXPECT(*tpk == tokenPublicKey); + BEAST_EXPECT(verify(st, HashPrefix::manifest, tokenPublicKey)); auto const pk = get(st, sfPublicKey); - BEAST_EXPECT (pk); - BEAST_EXPECT (*pk == keys.publicKey ()); - BEAST_EXPECT (verify ( - st, HashPrefix::manifest, keys.publicKey (), + BEAST_EXPECT(pk); + BEAST_EXPECT(*pk == keys.publicKey()); + BEAST_EXPECT(verify( + st, + HashPrefix::manifest, + keys.publicKey(), sfMasterSignature)); } } auto const keyType = KeyType::ed25519; - auto const kp = generateKeyPair (keyType, randomSeed ()); + auto const kp = generateKeyPair(keyType, randomSeed()); - auto keys = ValidatorKeys ( - keyType, - kp.second, - std::numeric_limits::max () - 1); + auto keys = ValidatorKeys( + keyType, kp.second, std::numeric_limits::max() - 1); - BEAST_EXPECT (! keys.createValidatorToken (keyType)); + BEAST_EXPECT(!keys.createValidatorToken(keyType)); - keys.revoke (); - BEAST_EXPECT (! keys.createValidatorToken (keyType)); + keys.revoke(); + BEAST_EXPECT(!keys.createValidatorToken(keyType)); } void - testRevoke () + testRevoke() { - testcase ("Revoke"); + testcase("Revoke"); for (auto const keyType : keyTypes) { - ValidatorKeys keys (keyType); + ValidatorKeys keys(keyType); - auto const revocation = keys.revoke (); + auto const revocation = keys.revoke(); - STObject st (sfGeneric); + STObject st(sfGeneric); auto const manifest = ripple::base64_decode(revocation); - SerialIter sit (manifest.data (), manifest.size ()); - st.set (sit); - - auto const seq = get (st, sfSequence); - BEAST_EXPECT (seq); - BEAST_EXPECT (*seq == std::numeric_limits::max ()); - - auto const pk = get (st, sfPublicKey); - BEAST_EXPECT (pk); - BEAST_EXPECT (*pk == keys.publicKey ()); - BEAST_EXPECT (verify ( - st, HashPrefix::manifest, keys.publicKey (), - sfMasterSignature)); + SerialIter sit(manifest.data(), manifest.size()); + st.set(sit); + + auto const seq = get(st, sfSequence); + BEAST_EXPECT(seq); + BEAST_EXPECT(*seq == std::numeric_limits::max()); + + auto const pk = get(st, sfPublicKey); + BEAST_EXPECT(pk); + BEAST_EXPECT(*pk == keys.publicKey()); + BEAST_EXPECT(verify( + st, HashPrefix::manifest, keys.publicKey(), sfMasterSignature)); } } void - testSign () + testSign() { - testcase ("Sign"); - - std::map expected({ - { KeyType::ed25519, "2EE541D6825791BF5454C571D2B363EAB3F01C73159B1F" - "237AC6D38663A82B9D5EAD262D5F776B916E68247A1F082090F3BAE7ABC939" - "C8F29B0DC759FD712300" }, - { KeyType::secp256k1, "3045022100F142C27BF83D8D4541C7A4E759DE64A672" - "51A388A422DFDA6F4B470A2113ABC4022002DA56695F3A805F62B55E7CC8D5" - "55438D64A229CD0B4BA2AE33402443B20409" } - }); + testcase("Sign"); + + std::map expected( + {{KeyType::ed25519, + "2EE541D6825791BF5454C571D2B363EAB3F01C73159B1F" + "237AC6D38663A82B9D5EAD262D5F776B916E68247A1F082090F3BAE7ABC939" + "C8F29B0DC759FD712300"}, + {KeyType::secp256k1, + "3045022100F142C27BF83D8D4541C7A4E759DE64A672" + "51A388A422DFDA6F4B470A2113ABC4022002DA56695F3A805F62B55E7CC8D5" + "55438D64A229CD0B4BA2AE33402443B20409"}}); std::string const data = "data to sign"; for (auto const keyType : keyTypes) { auto const sk = generateSecretKey(keyType, generateSeed("test")); - ValidatorKeys keys (keyType, sk, 1); + ValidatorKeys keys(keyType, sk, 1); - auto const signature = keys.sign (data); + auto const signature = keys.sign(data); BEAST_EXPECT(expected[keyType] == signature); - auto const ret = strUnHex (signature); - BEAST_EXPECT (ret); - BEAST_EXPECT (ret->size ()); - BEAST_EXPECT (verify ( - keys.publicKey(), - makeSlice (data), - makeSlice (*ret))); + auto const ret = strUnHex(signature); + BEAST_EXPECT(ret); + BEAST_EXPECT(ret->size()); + BEAST_EXPECT( + verify(keys.publicKey(), makeSlice(data), makeSlice(*ret))); } } void - testWriteToFile () + testWriteToFile() { - testcase ("Write to File"); + testcase("Write to File"); using namespace boost::filesystem; auto const keyType = KeyType::ed25519; - ValidatorKeys keys (keyType); + ValidatorKeys keys(keyType); { path const subdir = "test_key_file"; path const keyFile = subdir / "validator_keys.json"; - KeyFileGuard g (*this, subdir.string()); + KeyFileGuard g(*this, subdir.string()); - keys.writeToFile (keyFile); - BEAST_EXPECT(exists (keyFile)); + keys.writeToFile(keyFile); + BEAST_EXPECT(exists(keyFile)); - auto fileKeys = ValidatorKeys::make_ValidatorKeys (keyFile); - BEAST_EXPECT (keys == fileKeys); + auto fileKeys = ValidatorKeys::make_ValidatorKeys(keyFile); + BEAST_EXPECT(keys == fileKeys); // Overwrite file with new sequence - keys.createValidatorToken (KeyType::secp256k1); - keys.writeToFile (keyFile); + keys.createValidatorToken(KeyType::secp256k1); + keys.writeToFile(keyFile); - fileKeys = ValidatorKeys::make_ValidatorKeys (keyFile); - BEAST_EXPECT (keys == fileKeys); + fileKeys = ValidatorKeys::make_ValidatorKeys(keyFile); + BEAST_EXPECT(keys == fileKeys); } { // Write to key file in current relative directory path const keyFile = "test_validator_keys.json"; - if (!exists (keyFile)) + if (!exists(keyFile)) { - keys.writeToFile (keyFile); - remove (keyFile.string()); + keys.writeToFile(keyFile); + remove(keyFile.string()); } else { // Cannot run the test. Someone created a file // where we want to put our key file - Throw ( - "Cannot create key file: " + keyFile.string ()); + Throw( + "Cannot create key file: " + keyFile.string()); } } { @@ -342,39 +347,44 @@ class ValidatorKeys_test : public beast::unit_test::suite path const subdir = "test_key_file"; path const keyFile = subdir / "directories/to/create/validator_keys.json"; - KeyFileGuard g (*this, subdir.string()); + KeyFileGuard g(*this, subdir.string()); - keys.writeToFile (keyFile); - BEAST_EXPECT(exists (keyFile)); + keys.writeToFile(keyFile); + BEAST_EXPECT(exists(keyFile)); - auto const fileKeys = ValidatorKeys::make_ValidatorKeys (keyFile); - BEAST_EXPECT (keys == fileKeys); + auto const fileKeys = ValidatorKeys::make_ValidatorKeys(keyFile); + BEAST_EXPECT(keys == fileKeys); } { // Fail if file cannot be opened for write path const subdir = "test_key_file"; - KeyFileGuard g (*this, subdir.string()); + KeyFileGuard g(*this, subdir.string()); path const badKeyFile = subdir / "."; auto expectedError = "Cannot open key file: " + badKeyFile.string(); std::string error; - try { - keys.writeToFile (badKeyFile); - } catch (std::runtime_error& e) { + try + { + keys.writeToFile(badKeyFile); + } + catch (std::runtime_error& e) + { error = e.what(); } BEAST_EXPECT(error == expectedError); // Fail if parent directory is existing file path const keyFile = subdir / "validator_keys.json"; - keys.writeToFile (keyFile); - path const conflictingPath = - keyFile / "validators_keys.json"; + keys.writeToFile(keyFile); + path const conflictingPath = keyFile / "validators_keys.json"; expectedError = "Cannot create directory: " + conflictingPath.parent_path().string(); - try { - keys.writeToFile (conflictingPath); - } catch (std::runtime_error& e) { + try + { + keys.writeToFile(conflictingPath); + } + catch (std::runtime_error& e) + { error = e.what(); } BEAST_EXPECT(error == expectedError); @@ -385,16 +395,16 @@ class ValidatorKeys_test : public beast::unit_test::suite void run() override { - testMakeValidatorKeys (); - testCreateValidatorToken (); - testRevoke (); - testSign (); - testWriteToFile (); + testMakeValidatorKeys(); + testCreateValidatorToken(); + testRevoke(); + testSign(); + testWriteToFile(); } }; BEAST_DEFINE_TESTSUITE(ValidatorKeys, keys, ripple); -} // tests +} // namespace tests -} // ripple +} // namespace ripple