xrpld
Loading...
Searching...
No Matches
Config_test.cpp
1#include <test/jtx/TestSuite.h>
2#include <test/unit_test/FileDirGuard.h>
3
4#include <xrpld/core/Config.h>
5
6#include <xrpl/basics/FileUtilities.h>
7#include <xrpl/beast/unit_test/suite.h>
8#include <xrpl/config/BasicConfig.h>
9#include <xrpl/config/Constants.h>
10#include <xrpl/protocol/SystemParameters.h> // IWYU pragma: keep
11#include <xrpl/protocol/XRPAmount.h>
12#include <xrpl/server/Port.h>
13
14#include <boost/lexical_cast/bad_lexical_cast.hpp>
15
16#include <array>
17#include <cstddef>
18#include <cstdint>
19#include <cstdlib>
20#include <exception>
21#include <filesystem>
22#include <format>
23#include <fstream>
24#include <optional>
25#include <ostream>
26#include <regex>
27#include <stdexcept>
28#include <string>
29#include <string_view>
30#include <typeinfo>
31#include <utility>
32#include <vector>
33
34namespace xrpl {
35namespace detail {
36std::string
37configContents(std::string const& dbPath, std::string const& validatorsFile)
38{
39 static constexpr char const* kConfigContentsTemplate = R"xrpldConfig(
40[server]
41port_rpc
42port_peer
43port_wss_admin
44
45[port_rpc]
46port = 5005
47ip = 127.0.0.1
48admin = 127.0.0.1, ::1
49protocol = https
50
51[port_peer]
52port = 51235
53ip = 0.0.0.0
54protocol = peer
55
56[port_wss_admin]
57port = 6006
58ip = 127.0.0.1
59admin = 127.0.0.1
60protocol = wss
61
62#[port_ws_public]
63#port = 5005
64#ip = 127.0.0.1
65#protocol = wss
66
67#-------------------------------------------------------------------------------
68
69[node_size]
70medium
71
72# This is primary persistent datastore for xrpld. This includes transaction
73# metadata, account states, and ledger headers. Helpful information can be
74# found on https://xrpl.org/capacity-planning.html#node-db-type
75# delete old ledgers while maintaining at least 2000. Do not require an
76# external administrative command to initiate deletion.
77[node_db]
78type=memory
79path=/Users/dummy/xrpld/config/db/rocksdb
80open_files=2000
81filter_bits=12
82cache_mb=256
83file_size_mb=8
84file_size_mult=2
85
86{}
87
88{}
89
90# This needs to be an absolute directory reference, not a relative one.
91# Modify this value as required.
92[debug_logfile]
93/Users/dummy/xrpld/config/log/debug.log
94
95[sntp_servers]
96time.windows.com
97time.apple.com
98time.nist.gov
99pool.ntp.org
100
101# Where to find some other servers speaking the XRPL protocol.
102#
103[ips]
104r.ripple.com 51235
105
106# Turn down default logging to save disk space in the long run.
107# Valid values here are trace, debug, info, warning, error, and fatal
108[rpc_startup]
109{{ "command": "log_level", "severity": "warning" }}
110
111# Defaults to 1 ("yes") so that certificates will be validated. To allow the use
112# of self-signed certificates for development or internal use, set to 0 ("no").
113[ssl_verify]
1140
115
116[sqdb]
117backend=sqlite
118)xrpldConfig";
119
120 std::string dbPathSection = dbPath.empty() ? "" : "[database_path]\n" + dbPath;
121 std::string valFileSection =
122 validatorsFile.empty() ? "" : "[validators_file]\n" + validatorsFile;
123 return std::format(kConfigContentsTemplate, dbPathSection, valFileSection);
124}
125
126// setenv and unsetenv are POSIX only, and MSVC does not have them.
127#ifndef _MSC_VER
128
137 */
138[[nodiscard]] std::optional<std::string>
139envVar(char const* name)
140{
141 if (char const* const value = std::getenv(name); value != nullptr)
142 return std::string{value};
143
144 return std::nullopt;
145}
146
150class EnvVarGuard
151{
152private:
153 std::string const name_;
154 std::optional<std::string> const saved_;
155
162 static void
163 apply(char const* name, std::optional<std::string> const& value) noexcept
164 {
165 if (value)
167 setenv(name, value->c_str(), 1);
168 }
169 else
170 {
171 unsetenv(name);
173 }
174
175public:
176
179 * @param name Name of the environment variable to set.
180 * @param value Value to set, or std::nullopt to remove the variable.
181 */
182 [[nodiscard]] EnvVarGuard(char const* name, std::optional<std::string> const& value)
183 : name_(name), saved_(envVar(name))
185 apply(name_.c_str(), value);
186 }
187
188 EnvVarGuard(EnvVarGuard const&) = delete;
189 EnvVarGuard&
190 operator=(EnvVarGuard const&) = delete;
191
195 ~EnvVarGuard()
196 {
197 apply(name_.c_str(), saved_);
198 }
199};
200
201#endif // _MSC_VER
202
203
204
207{
208private:
210
211 bool rmDataDir_{false};
212
214
215public:
218 Path subDir,
219 Path const& dbPath,
220 Path const& configFile,
221 Path const& validatorsFile,
222 bool useCounter = true,
223 std::string confContents = "")
224 : FileDirGuard(
225 test,
226 std::move(subDir),
228 confContents.empty() ? configContents(dbPath.string(), validatorsFile.string())
229 : confContents,
230 useCounter)
231 , dataDir_(dbPath)
232 {
233 if (dbPath.empty())
235
236 rmDataDir_ = !exists(dataDir_);
238 file_.string(),
239 /* bQuiet */ true,
240 /* bSilent */ false,
241 /* bStandalone */ false);
242 }
243
244 [[nodiscard]] Config const&
245 config() const
246 {
247 return config_;
248 }
249
250 [[nodiscard]] std::string
251 configFile() const
252 {
253 return file().string();
254 }
255
256 [[nodiscard]] bool
257 dataDirExists() const
258 {
260 }
261
262 [[nodiscard]] bool
263 configFileExists() const
264 {
265 return fileExists();
266 }
267
269 {
270 try
271 {
272 using namespace std::filesystem;
273 if (rmDataDir_)
275 }
276 catch (std::exception& e)
277 {
278 // if we throw here, just let it die.
279 test_.log << "Error in ~FileCfgGuard: " << e.what() << std::endl;
280 };
281 }
282};
283
284std::string
286{
287 std::string configContents(R"xrpldConfig(
288[validators]
289n949f75evCHwgyP4fPVgaHqNHxUVN15PsJEZ3B3HnXPcPjcZAoy7
290n9MD5h24qrQqiyBC8aeqqCWvpiBiYQ3jxSr91uiDvmrkyHRdYLUj
291n9L81uNCaPgtUJfaHh89gmdvXKAmSt5Gdsw2g1iPWaPkAHW5Nm4C
292n9KiYM9CgngLvtRCQHZwgC2gjpdaZcCcbt3VboxiNFcKuwFVujzS
293n9LdgEtkmGB9E2h3K4Vp7iGUaKuq23Zr32ehxiU8FWY7xoxbWTSA
294
295[validator_keys]
296nHUhG1PgAG8H8myUENypM35JgfqXAKNQvRVVAFDRzJrny5eZN8d5
297nHBu9PTL9dn2GuZtdW4U2WzBwffyX9qsQCd9CNU4Z5YG3PQfViM8
298nHUPDdcdb2Y5DZAJne4c2iabFuAP3F34xZUgYQT2NH7qfkdapgnz
299
300[validator_list_sites]
301recommended-xrpl-validators.com
302more-xrpl-validators.net
303
304[validator_list_keys]
30503E74EE14CB525AFBB9F1B7D86CD58ECC4B91452294B42AB4E78F260BD905C091D
306030775A669685BD6ABCEBD80385921C7851783D991A8055FD21D2F3966C96F1B56
307
308[validator_list_threshold]
3092
310)xrpldConfig");
311 return configContents;
312}
313
317class ValidatorsTxtGuard : public detail::FileDirGuard
318{
319public:
321 beast::unit_test::Suite& test,
322 Path subDir,
323 Path const& validatorsFileName,
324 bool useCounter = true)
325 : FileDirGuard(
326 test,
327 std::move(subDir),
328 Path(validatorsFileName.empty() ? Config::kValidatorsFileName : validatorsFileName),
330 useCounter)
331 {
332 }
333
334 [[nodiscard]] bool
336 {
337 return fileExists();
338 }
339
340 [[nodiscard]] std::string
341 validatorsFile() const
342 {
343 return absolute(file()).string();
344 }
345
346 ~ValidatorsTxtGuard() = default;
347};
348} // namespace detail
349
350class Config_test final : public TestSuite
351{
352private:
354
355public:
356 void
358 {
359 testcase("legacy");
360
361 Config c;
362
363 std::string const toLoad(R"xrpldConfig(
364[server]
365port_rpc
366port_peer
367port_wss_admin
368
369[ssl_verify]
3700
371)xrpldConfig");
372
373 c.loadFromString(toLoad);
374
375 BEAST_EXPECT(c.legacy(Sections::kSslVerify) == "0");
376 expectException([&c] {
377 [[maybe_unused]] auto const _ = c.legacy(Sections::kServer);
378 }); // not a single line
379
380 // set a legacy value
381 BEAST_EXPECT(c.legacy("not_in_file").empty());
382 c.legacy("not_in_file", "new_value");
383 BEAST_EXPECT(c.legacy("not_in_file") == "new_value");
384 }
385 void
387 {
388 testcase("config_file");
389
390 using namespace std::filesystem;
391 auto const cwd = current_path();
392
393 // Test both config file names.
395
396 // Config file in current directory.
397 for (auto const& configFile : configFiles)
398 {
399 // Use a temporary directory for testing.
400 TempDir const td;
401 current_path(td.path());
402 Path const f = td.file(std::string{configFile});
403 std::ofstream o(f.string());
404 o << detail::configContents("", "");
405 o.close();
406
407 // Load the config file from the current directory and verify it.
408 Config c;
409 c.setup("", true, false, true);
410 BEAST_EXPECT(c.section(Sections::kDebugLogfile).values().size() == 1);
411 BEAST_EXPECT(
412 c.section(Sections::kDebugLogfile).values()[0] ==
413 "/Users/dummy/xrpld/config/log/debug.log");
414 }
415
416 // Config file in HOME or XDG_CONFIG_HOME directory.
417#ifndef _MSC_VER
418 // Save the values the guards below must put back.
419 auto const home = detail::envVar("HOME");
420 auto const xdgConfigHome = detail::envVar("XDG_CONFIG_HOME");
421
422 for (auto const& configFile : configFiles)
423 {
424 // Point the current working directory to a temporary directory, so
425 // we don't pick up an actual config file from the repository root.
426 TempDir const td;
427 current_path(td.path());
428
429 // The XDG config directory is set: the config file must be in a
430 // subdirectory named after the system.
431 {
432 TempDir const tc;
433
434 // The HOME variable is not used when XDG_CONFIG_HOME is set,
435 // but must be set. Both guards are declared after tc, so they
436 // restore before it is removed.
437 detail::EnvVarGuard const homeGuard("HOME", tc.path());
438 detail::EnvVarGuard const xdgGuard("XDG_CONFIG_HOME", tc.path());
439
440 // Create the config file in '${XDG_CONFIG_HOME}/[systemName]'.
441 Path p = tc.file(systemName());
443 p = tc.file(systemName() + "/" + std::string{configFile});
444 std::ofstream o(p.string());
445 o << detail::configContents("", "");
446 o.close();
447
448 // Load the config file from the config directory and verify it.
449 Config c;
450 c.setup("", true, false, true);
451 BEAST_EXPECT(c.section(Sections::kDebugLogfile).values().size() == 1);
452 BEAST_EXPECT(
453 c.section(Sections::kDebugLogfile).values()[0] ==
454 "/Users/dummy/xrpld/config/log/debug.log");
455 }
456
457 // Both guards are gone: both variables must hold their old values.
458 BEAST_EXPECT(detail::envVar("HOME") == home);
459 BEAST_EXPECT(detail::envVar("XDG_CONFIG_HOME") == xdgConfigHome);
460
461 // The XDG config directory is not set: the config file must be in a
462 // subdirectory named .config followed by the system name.
463 {
464 TempDir const tc;
465
466 // Both guards are declared after tc, so they restore before it
467 // is removed.
468 detail::EnvVarGuard const homeGuard("HOME", tc.path());
469 detail::EnvVarGuard const xdgGuard("XDG_CONFIG_HOME", std::nullopt);
470
471 // Create the config file in '${HOME}/.config/[systemName]'.
472 std::string s = ".config";
473 Path p = tc.file(s);
475 s += "/" + systemName();
476 p = tc.file(s);
478 p = tc.file(s + "/" + std::string{configFile});
479 std::ofstream o(p.string());
480 o << detail::configContents("", "");
481 o.close();
482
483 // Load the config file from the config directory and verify it.
484 Config c;
485 c.setup("", true, false, true);
486 BEAST_EXPECT(c.section(Sections::kDebugLogfile).values().size() == 1);
487 BEAST_EXPECT(
488 c.section(Sections::kDebugLogfile).values()[0] ==
489 "/Users/dummy/xrpld/config/log/debug.log");
490 }
491
492 // Both guards are gone: both variables must hold their old values.
493 BEAST_EXPECT(detail::envVar("HOME") == home);
494 BEAST_EXPECT(detail::envVar("XDG_CONFIG_HOME") == xdgConfigHome);
495 }
496#endif // _MSC_VER
497
498 // Restore the current working directory.
499 current_path(cwd);
500 }
501 void
502 testDbPath()
503 {
504 testcase("database_path");
505
506 using namespace std::filesystem;
507 {
508 constexpr char const* cc = "[database_path]\n{}\n";
509
510 auto const cwd = current_path();
511 Path const dataDirRel("test_data_dir");
512 Path const dataDirAbs(cwd / dataDirRel);
513 {
514 // Dummy test - do we get back what we put in
515 Config c;
516 c.loadFromString(std::format(cc, dataDirAbs.string()));
517 BEAST_EXPECT(c.legacy(Sections::kDatabasePath) == dataDirAbs.string());
518 }
519 {
520 // Rel paths should convert to abs paths
521 Config c;
522 c.loadFromString(std::format(cc, dataDirRel.string()));
523 BEAST_EXPECT(c.legacy(Sections::kDatabasePath) == dataDirAbs.string());
524 }
525 {
526 // No db section.
527 // N.B. Config::setup will give database_path a default,
528 // load will not.
529 Config c;
530 c.loadFromString("");
531 BEAST_EXPECT(c.legacy(Sections::kDatabasePath).empty());
532 }
533 }
534 {
535 // read from file absolute path
536 auto const cwd = current_path();
537 detail::DirGuard const g0(*this, "test_db");
538 Path const dataDirRel("test_data_dir");
539 Path const dataDirAbs(cwd / g0.subdir() / dataDirRel);
540 detail::FileCfgGuard const g(
541 *this, g0.subdir(), dataDirAbs, Config::kConfigFileName, "", false);
542 auto const& c(g.config());
543 BEAST_EXPECT(g.dataDirExists());
544 BEAST_EXPECT(g.configFileExists());
545 BEAST_EXPECT(c.legacy(Sections::kDatabasePath) == dataDirAbs.string());
546 }
547 {
548 // read from file relative path
549 std::string const dbPath("my_db");
550 detail::FileCfgGuard const g(*this, "test_db", dbPath, Config::kConfigFileName, "");
551 auto const& c(g.config());
552 std::string const nativeDbPath = absolute(Path(dbPath)).string();
553 BEAST_EXPECT(g.dataDirExists());
554 BEAST_EXPECT(g.configFileExists());
555 BEAST_EXPECT(c.legacy(Sections::kDatabasePath) == nativeDbPath);
556 }
557 {
558 // read from file no path
559 detail::FileCfgGuard const g(*this, "test_db", "", Config::kConfigFileName, "");
560 auto const& c(g.config());
561 std::string const nativeDbPath =
562 absolute(g.subdir() / Path(Config::kDatabaseDirName)).string();
563 BEAST_EXPECT(g.dataDirExists());
564 BEAST_EXPECT(g.configFileExists());
565 BEAST_EXPECT(c.legacy(Sections::kDatabasePath) == nativeDbPath);
566 }
567 }
568
569 void
571 {
572 testcase("validator keys");
573
574 std::string const validationSeed = "spA4sh1qTvwq92X715tYyGQKmAKfa";
575
576 auto const token =
577 "eyJ2YWxpZGF0aW9uX3ByaXZhdGVfa2V5IjoiOWVkNDVmODY2MjQxY2MxOGEyNzQ3Yj"
578 "U0Mzg3YzA2MjU5MDc5NzJmNGU3MTkwMjMxZmFhOTM3NDU3ZmE5ZGFmNiIsIm1hbmlm"
579 "ZXN0IjoiSkFBQUFBRnhJZTFGdHdtaW12R3RIMmlDY01KcUM5Z1ZGS2lsR2Z3MS92Q3"
580 "hIWFhMcGxjMkduTWhBa0UxYWdxWHhCd0R3RGJJRDZPTVNZdU0wRkRBbHBBZ05rOFNL"
581 "Rm43TU8yZmRrY3dSUUloQU9uZ3U5c0FLcVhZb3VKK2wyVjBXK3NBT2tWQitaUlM2UF"
582 "NobEpBZlVzWGZBaUJzVkpHZXNhYWRPSmMvYUFab2tTMXZ5bUdtVnJsSFBLV1gzWXl3"
583 "dTZpbjhIQVNRS1B1Z0JENjdrTWFSRkd2bXBBVEhsR0tKZHZERmxXUFl5NUFxRGVkRn"
584 "Y1VEphMncwaTIxZXEzTVl5d0xWSlpuRk9yN0Mwa3cyQWlUelNDakl6ZGl0UTg9In0"
585 "=";
586
587 {
588 Config c;
589 static constexpr char const* kConfigTemplate = R"xrpldConfig(
590[validation_seed]
591{}
592
593[validator_token]
594{}
595)xrpldConfig";
596 std::string error;
597 auto const expectedError =
598 "Cannot have both [validation_seed] "
599 "and [validator_token] config sections";
600 try
601 {
602 c.loadFromString(std::format(kConfigTemplate, validationSeed, token));
603 }
604 catch (std::runtime_error const& e)
605 {
606 error = e.what();
607 }
608 BEAST_EXPECT(error == expectedError);
609 }
610 }
611
612 void
614 {
615 testcase("single-value section");
616
617 auto const load = [](Config& c, std::string const& toLoad) {
618 try
619 {
620 c.loadFromString(toLoad);
621 }
622 catch (std::runtime_error const& e)
623 {
624 return std::string(e.what());
625 }
626 return std::string();
627 };
628
629 {
630 Config c;
631 BEAST_EXPECT(load(c, "[network_id]\n10000\n").empty());
632 BEAST_EXPECT(c.networkId == 10000);
633 }
634
635 {
636 // A header above a commented-out value keeps the default.
638 BEAST_EXPECT(load(c, "[network_id]\n# 10000\n").empty());
639 BEAST_EXPECT(c.networkId == 0);
640 }
641
642 {
643 Config c;
644 BEAST_EXPECT(
645 load(c, "[network_id]\n10000\n[network_id]\n21337\n") ==
646 "[network_id] requires exactly one value, not 2");
647 }
648 }
649
650 void
652 {
653 testcase("network id");
654 std::string error;
655 Config c;
656 try
657 {
658 c.loadFromString(R"xrpldConfig(
659[network_id]
660main
661)xrpldConfig");
662 }
663 catch (std::runtime_error const& e)
664 {
665 error = e.what();
666 }
667
668 BEAST_EXPECT(error.empty());
669 BEAST_EXPECT(c.networkId == 0);
670
671 try
672 {
673 c.loadFromString(R"xrpldConfig(
674)xrpldConfig");
675 }
676 catch (std::runtime_error const& e)
677 {
678 error = e.what();
679 }
680
681 BEAST_EXPECT(error.empty());
682 BEAST_EXPECT(c.networkId == 0);
683
684 try
685 {
686 c.loadFromString(R"xrpldConfig(
687[network_id]
688255
689)xrpldConfig");
690 }
691 catch (std::runtime_error const& e)
693 error = e.what();
694 }
695
696 BEAST_EXPECT(error.empty());
697 BEAST_EXPECT(c.networkId == 255);
698
699 try
700 {
701 c.loadFromString(R"xrpldConfig(
702[network_id]
70310000
704)xrpldConfig");
705 }
706 catch (std::runtime_error const& e)
707 {
708 error = e.what();
709 }
710
711 BEAST_EXPECT(error.empty());
712 BEAST_EXPECT(c.networkId == 10000);
713 }
714
715 void
717 {
718 testcase("validators_file");
719
720 using namespace std::filesystem;
721 {
722 // load should throw for missing specified validators file
723 constexpr char const* cc = "[validators_file]\n{}\n";
724 std::string error;
725 std::string const missingPath = "/no/way/this/path/exists";
726 auto const expectedError =
727 "The file specified in [validators_file] does not exist: " + missingPath;
728 try
729 {
730 Config c;
731 c.loadFromString(std::format(cc, missingPath));
732 }
733 catch (std::runtime_error const& e)
734 {
735 error = e.what();
736 }
737 BEAST_EXPECT(error == expectedError);
738 }
739 {
740 // load should throw for invalid [validators_file]
741 detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg");
742 Path const invalidFile = current_path() / vtg.subdir();
743 constexpr char const* cc = "[validators_file]\n{}\n";
744 std::string error;
745 auto const expectedError =
746 "Invalid file specified in [validators_file]: " + invalidFile.string();
747 try
748 {
749 Config c;
750 c.loadFromString(std::format(cc, invalidFile.string()));
751 }
752 catch (std::runtime_error const& e)
753 {
754 error = e.what();
755 }
756 BEAST_EXPECT(error == expectedError);
757 }
758 {
759 // load validators from config into single section
760 Config c;
761 std::string const toLoad(R"xrpldConfig(
762[validators]
763n949f75evCHwgyP4fPVgaHqNHxUVN15PsJEZ3B3HnXPcPjcZAoy7
764n9MD5h24qrQqiyBC8aeqqCWvpiBiYQ3jxSr91uiDvmrkyHRdYLUj
765n9L81uNCaPgtUJfaHh89gmdvXKAmSt5Gdsw2g1iPWaPkAHW5Nm4C
766
767[validator_keys]
768nHUhG1PgAG8H8myUENypM35JgfqXAKNQvRVVAFDRzJrny5eZN8d5
769nHBu9PTL9dn2GuZtdW4U2WzBwffyX9qsQCd9CNU4Z5YG3PQfViM8
770)xrpldConfig");
771 c.loadFromString(toLoad);
772 BEAST_EXPECT(c.legacy(Sections::kValidatorsFile).empty());
773 BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 5);
774 BEAST_EXPECT(c.validatorListThreshold == std::nullopt);
775 }
776 {
777 // load validator list sites and keys from config
778 Config c;
779 std::string const toLoad(R"xrpldConfig(
780[validator_list_sites]
781xrpl-validators.com
782trust-these-validators.gov
783
784[validator_list_keys]
785021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566
786
787[validator_list_threshold]
7881
789)xrpldConfig");
790 c.loadFromString(toLoad);
791 BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2);
792 BEAST_EXPECT(
793 c.section(Sections::kValidatorListSites).values()[0] == "xrpl-validators.com");
794 BEAST_EXPECT(
795 c.section(Sections::kValidatorListSites).values()[1] ==
796 "trust-these-validators.gov");
797 BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 1);
798 BEAST_EXPECT(
799 c.section(Sections::kValidatorListKeys).values()[0] ==
800 "021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801"
801 "E566");
802 BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1);
803 BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values()[0] == "1");
804 BEAST_EXPECT(c.validatorListThreshold == std::size_t(1));
805 }
806 {
807 // load validator list sites and keys from config
808 Config c;
809 std::string const toLoad(R"xrpldConfig(
810[validator_list_sites]
811xrpl-validators.com
812trust-these-validators.gov
813
814[validator_list_keys]
815021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566
816
817[validator_list_threshold]
8180
819)xrpldConfig");
820 c.loadFromString(toLoad);
821 BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2);
822 BEAST_EXPECT(
823 c.section(Sections::kValidatorListSites).values()[0] == "xrpl-validators.com");
824 BEAST_EXPECT(
825 c.section(Sections::kValidatorListSites).values()[1] ==
826 "trust-these-validators.gov");
827 BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 1);
828 BEAST_EXPECT(
829 c.section(Sections::kValidatorListKeys).values()[0] ==
830 "021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801"
831 "E566");
832 BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1);
833 BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values()[0] == "0");
834 BEAST_EXPECT(c.validatorListThreshold == std::nullopt);
835 }
836 {
837 // load should throw if [validator_list_threshold] is greater than
838 // the number of [validator_list_keys]
839 Config c;
840 std::string const toLoad(R"xrpldConfig(
841[validator_list_sites]
842xrpl-validators.com
843trust-these-validators.gov
844
845[validator_list_keys]
846021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566
847
848[validator_list_threshold]
8492
850)xrpldConfig");
851 std::string error;
852 auto const expectedError =
853 "Value in config section [validator_list_threshold] exceeds "
854 "the number of configured list keys";
855 try
856 {
857 c.loadFromString(toLoad);
858 fail();
859 }
860 catch (std::runtime_error const& e)
861 {
862 error = e.what();
863 }
864 BEAST_EXPECT(error == expectedError);
865 }
866 {
867 // load should throw if [validator_list_threshold] is malformed
868 Config c;
869 std::string const toLoad(R"xrpldConfig(
870[validator_list_sites]
871xrpl-validators.com
872trust-these-validators.gov
873
874[validator_list_keys]
875021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566
876
877[validator_list_threshold]
878value = 2
879)xrpldConfig");
880 std::string error;
881 auto const expectedError =
882 "Config section [validator_list_threshold] should contain "
883 "single value only";
884 try
885 {
886 c.loadFromString(toLoad);
887 fail();
888 }
889 catch (std::runtime_error const& e)
890 {
891 error = e.what();
892 }
893 BEAST_EXPECT(error == expectedError);
894 }
895 {
896 // load should throw if [validator_list_threshold] is negative
897 Config c;
898 std::string const toLoad(R"xrpldConfig(
899[validator_list_sites]
900xrpl-validators.com
901trust-these-validators.gov
902
903[validator_list_keys]
904021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566
905
906[validator_list_threshold]
907-1
908)xrpldConfig");
909 bool error = false;
910 try
911 {
912 c.loadFromString(toLoad);
913 fail();
914 }
915 catch (std::bad_cast& e)
916 {
917 error = true;
918 }
919 BEAST_EXPECT(error);
920 }
921 {
922 // load should throw if [validator_list_sites] is configured but
923 // [validator_list_keys] is not
924 Config c;
925 std::string const toLoad(R"xrpldConfig(
926[validator_list_sites]
927xrpl-validators.com
928trust-these-validators.gov
929)xrpldConfig");
930 std::string error;
931 auto const expectedError = "[validator_list_keys] config section is missing";
932 try
933 {
934 c.loadFromString(toLoad);
935 fail();
936 }
937 catch (std::runtime_error const& e)
938 {
939 error = e.what();
940 }
941 BEAST_EXPECT(error == expectedError);
942 }
943 {
944 // load from specified [validators_file] absolute path
945 detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg");
946 BEAST_EXPECT(vtg.validatorsFileExists());
947 Config c;
948 constexpr char const* cc = "[validators_file]\n{}\n";
949 c.loadFromString(std::format(cc, vtg.validatorsFile()));
950 BEAST_EXPECT(c.legacy(Sections::kValidatorsFile) == vtg.validatorsFile());
951 BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 8);
952 BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2);
953 BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 2);
954 BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1);
955 BEAST_EXPECT(c.validatorListThreshold == 2);
956 }
957 {
958 // load from specified [validators_file] file name
959 // in config directory
960 std::string const valFileName = "validators.txt";
961 detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", valFileName);
962 detail::FileCfgGuard const rcg(
963 *this, vtg.subdir(), "", Config::kConfigFileName, valFileName, false);
964 BEAST_EXPECT(vtg.validatorsFileExists());
965 BEAST_EXPECT(rcg.configFileExists());
966 auto const& c(rcg.config());
967 BEAST_EXPECT(c.legacy(Sections::kValidatorsFile) == valFileName);
968 BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 8);
969 BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2);
970 BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 2);
971 BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1);
972 BEAST_EXPECT(c.validatorListThreshold == 2);
973 }
974 {
975 // load from specified [validators_file] relative path
976 // to config directory
977 detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.txt");
978 auto const valFilePath = ".." / vtg.subdir() / "validators.txt";
979 detail::FileCfgGuard const rcg(
980 *this, vtg.subdir(), "", Config::kConfigFileName, valFilePath, false);
981 BEAST_EXPECT(vtg.validatorsFileExists());
982 BEAST_EXPECT(rcg.configFileExists());
983 auto const& c(rcg.config());
984 BEAST_EXPECT(c.legacy(Sections::kValidatorsFile) == valFilePath);
985 BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 8);
986 BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2);
987 BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 2);
988 BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1);
989 BEAST_EXPECT(c.validatorListThreshold == 2);
990 }
991 {
992 // load from validators file in default location
993 detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.txt");
994 detail::FileCfgGuard const rcg(
995 *this, vtg.subdir(), "", Config::kConfigFileName, "", false);
996 BEAST_EXPECT(vtg.validatorsFileExists());
997 BEAST_EXPECT(rcg.configFileExists());
998 auto const& c(rcg.config());
999 BEAST_EXPECT(c.legacy(Sections::kValidatorsFile).empty());
1000 BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 8);
1001 BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2);
1002 BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 2);
1003 BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1);
1004 BEAST_EXPECT(c.validatorListThreshold == 2);
1005 }
1006 {
1007 // load from specified [validators_file] instead
1008 // of default location
1009 detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg");
1010 BEAST_EXPECT(vtg.validatorsFileExists());
1011 detail::ValidatorsTxtGuard const vtgDefault(
1012 *this, vtg.subdir(), "validators.txt", false);
1013 BEAST_EXPECT(vtgDefault.validatorsFileExists());
1014 detail::FileCfgGuard const rcg(
1015 *this, vtg.subdir(), "", Config::kConfigFileName, vtg.validatorsFile(), false);
1016 BEAST_EXPECT(rcg.configFileExists());
1017 auto const& c(rcg.config());
1018 BEAST_EXPECT(c.legacy(Sections::kValidatorsFile) == vtg.validatorsFile());
1019 BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 8);
1020 BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2);
1021 BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 2);
1022 BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1);
1023 BEAST_EXPECT(c.validatorListThreshold == 2);
1024 }
1025
1026 {
1027 // load validators from both config and validators file
1028 constexpr char const* cc = R"xrpldConfig(
1029[validators_file]
1030{}
1031
1032[validators]
1033n949f75evCHwgyP4fPVgaHqNHxUVN15PsJEZ3B3HnXPcPjcZAoy7
1034n9MD5h24qrQqiyBC8aeqqCWvpiBiYQ3jxSr91uiDvmrkyHRdYLUj
1035n9L81uNCaPgtUJfaHh89gmdvXKAmSt5Gdsw2g1iPWaPkAHW5Nm4C
1036n9KiYM9CgngLvtRCQHZwgC2gjpdaZcCcbt3VboxiNFcKuwFVujzS
1037n9LdgEtkmGB9E2h3K4Vp7iGUaKuq23Zr32ehxiU8FWY7xoxbWTSA
1038
1039[validator_keys]
1040nHB1X37qrniVugfQcuBTAjswphC1drx7QjFFojJPZwKHHnt8kU7v
1041nHUkAWDR4cB8AgPg7VXMX6et8xRTQb2KJfgv1aBEXozwrawRKgMB
1042
1043[validator_list_sites]
1044xrpl-validators.com
1045trust-these-validators.gov
1046
1047[validator_list_keys]
1048021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566
1049)xrpldConfig";
1050 detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg");
1051 BEAST_EXPECT(vtg.validatorsFileExists());
1052 Config c;
1053 c.loadFromString(std::format(cc, vtg.validatorsFile()));
1054 BEAST_EXPECT(c.legacy(Sections::kValidatorsFile) == vtg.validatorsFile());
1055 BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 15);
1056 BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 4);
1057 BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 3);
1058 BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1);
1059 BEAST_EXPECT(c.validatorListThreshold == 2);
1060 }
1061 {
1062 // load should throw if [validator_list_threshold] is present both
1063 // in xrpld.cfg and validators file
1064 constexpr char const* cc = R"xrpldConfig(
1065[validators_file]
1066{}
1067
1068[validator_list_threshold]
10691
1070)xrpldConfig";
1071 std::string error;
1072 detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg");
1073 BEAST_EXPECT(vtg.validatorsFileExists());
1074 auto const expectedError =
1075 "Config section [validator_list_threshold] should contain "
1076 "single value only";
1077 try
1078 {
1079 Config c;
1080 c.loadFromString(std::format(cc, vtg.validatorsFile()));
1081 fail();
1082 }
1083 catch (std::runtime_error const& e)
1084 {
1085 error = e.what();
1086 }
1087 BEAST_EXPECT(error == expectedError);
1088 }
1089 {
1090 // load should throw if [validators], [validator_keys] and
1091 // [validator_list_keys] are missing from xrpld.cfg and
1092 // validators file
1093 Config const c;
1094 constexpr char const* cc = "[validators_file]\n{}\n";
1095 std::string error;
1096 detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg");
1097 BEAST_EXPECT(vtg.validatorsFileExists());
1098 auto const expectedError =
1099 "The file specified in [validators_file] does not contain a "
1100 "[validators], [validator_keys] or [validator_list_keys] "
1101 "section: " +
1102 vtg.validatorsFile();
1103 std::ofstream const o(vtg.validatorsFile());
1104 try
1105 {
1106 Config c2;
1107 c2.loadFromString(std::format(cc, vtg.validatorsFile()));
1108 }
1109 catch (std::runtime_error const& e)
1110 {
1111 error = e.what();
1112 }
1113 BEAST_EXPECT(error == expectedError);
1114 }
1115 }
1116
1117 void
1118 testSetup(bool explicitPath)
1120 detail::FileCfgGuard const cfg(
1121 *this, "testSetup", explicitPath ? "test_db" : "", Config::kConfigFileName, "");
1122 /* FileCfgGuard has a Config object that gets loaded on
1123 construction, but Config::setup is not reentrant, so we
1124 need a fresh config for every test case, so ignore it.
1125 */
1126 {
1127 Config config;
1128 config.setup(
1129 cfg.configFile(),
1130 /*bQuiet*/ false,
1131 /* bSilent */ false,
1132 /* bStandalone */ false);
1133 BEAST_EXPECT(!config.quiet());
1134 BEAST_EXPECT(!config.silent());
1135 BEAST_EXPECT(!config.standalone());
1136 BEAST_EXPECT(config.ledgerHistory == 256);
1137 BEAST_EXPECT(!config.legacy(Sections::kDatabasePath).empty());
1139 {
1140 Config config;
1141 config.setup(
1142 cfg.configFile(),
1143 /*bQuiet*/ true,
1144 /* bSilent */ false,
1145 /* bStandalone */ false);
1146 BEAST_EXPECT(config.quiet());
1147 BEAST_EXPECT(!config.silent());
1148 BEAST_EXPECT(!config.standalone());
1149 BEAST_EXPECT(config.ledgerHistory == 256);
1150 BEAST_EXPECT(!config.legacy(Sections::kDatabasePath).empty());
1151 }
1152 {
1153 Config config;
1154 config.setup(
1155 cfg.configFile(),
1156 /*bQuiet*/ false,
1157 /* bSilent */ true,
1158 /* bStandalone */ false);
1159 BEAST_EXPECT(config.quiet());
1160 BEAST_EXPECT(config.silent());
1161 BEAST_EXPECT(!config.standalone());
1162 BEAST_EXPECT(config.ledgerHistory == 256);
1163 BEAST_EXPECT(!config.legacy(Sections::kDatabasePath).empty());
1164 }
1165 {
1166 Config config;
1167 config.setup(
1168 cfg.configFile(),
1169 /*bQuiet*/ true,
1170 /* bSilent */ true,
1171 /* bStandalone */ false);
1172 BEAST_EXPECT(config.quiet());
1173 BEAST_EXPECT(config.silent());
1174 BEAST_EXPECT(!config.standalone());
1175 BEAST_EXPECT(config.ledgerHistory == 256);
1176 BEAST_EXPECT(!config.legacy(Sections::kDatabasePath).empty());
1177 }
1178 {
1179 Config config;
1180 config.setup(
1181 cfg.configFile(),
1182 /*bQuiet*/ false,
1183 /* bSilent */ false,
1184 /* bStandalone */ true);
1185 BEAST_EXPECT(!config.quiet());
1186 BEAST_EXPECT(!config.silent());
1187 BEAST_EXPECT(config.standalone());
1188 BEAST_EXPECT(config.ledgerHistory == 0);
1189 BEAST_EXPECT(config.legacy(Sections::kDatabasePath).empty() == !explicitPath);
1190 }
1191 {
1192 Config config;
1193 config.setup(
1194 cfg.configFile(),
1195 /*bQuiet*/ true,
1196 /* bSilent */ false,
1197 /* bStandalone */ true);
1198 BEAST_EXPECT(config.quiet());
1199 BEAST_EXPECT(!config.silent());
1200 BEAST_EXPECT(config.standalone());
1201 BEAST_EXPECT(config.ledgerHistory == 0);
1202 BEAST_EXPECT(config.legacy(Sections::kDatabasePath).empty() == !explicitPath);
1203 }
1204 {
1205 Config config;
1206 config.setup(
1207 cfg.configFile(),
1208 /*bQuiet*/ false,
1209 /* bSilent */ true,
1210 /* bStandalone */ true);
1211 BEAST_EXPECT(config.quiet());
1212 BEAST_EXPECT(config.silent());
1213 BEAST_EXPECT(config.standalone());
1214 BEAST_EXPECT(config.ledgerHistory == 0);
1215 BEAST_EXPECT(config.legacy(Sections::kDatabasePath).empty() == !explicitPath);
1216 }
1217 {
1218 Config config;
1219 config.setup(
1220 cfg.configFile(),
1221 /*bQuiet*/ true,
1222 /* bSilent */ true,
1223 /* bStandalone */ true);
1224 BEAST_EXPECT(config.quiet());
1225 BEAST_EXPECT(config.silent());
1226 BEAST_EXPECT(config.standalone());
1227 BEAST_EXPECT(config.ledgerHistory == 0);
1228 BEAST_EXPECT(config.legacy(Sections::kDatabasePath).empty() == !explicitPath);
1229 }
1230 }
1231
1232 void
1233 testPort()
1235 detail::FileCfgGuard const cfg(*this, "testPort", "", Config::kConfigFileName, "");
1236 auto const& conf = cfg.config();
1237 if (!BEAST_EXPECT(conf.exists(Sections::kPortRpc)))
1238 return;
1239 if (!BEAST_EXPECT(conf.exists(Sections::kPortWssAdmin)))
1240 return;
1242 if (!unexcept([&] { parsePort(rpc, conf[Sections::kPortRpc], log); }))
1243 return;
1244 BEAST_EXPECT(rpc.adminNetsV4.size() + rpc.adminNetsV6.size() == 2);
1245 ParsedPort wss;
1246 if (!unexcept([&] { parsePort(wss, conf[Sections::kPortWssAdmin], log); }))
1247 return;
1248 BEAST_EXPECT(wss.adminNetsV4.size() + wss.adminNetsV6.size() == 1);
1249 }
1250
1251 void
1252 testZeroPort()
1253 {
1254 auto const contents = std::regex_replace(
1255 detail::configContents("", ""), std::regex(R"(port\s*=\s*\d+)"), "port = 0");
1256
1257 try
1258 {
1259 detail::FileCfgGuard const cfg(
1260 *this, "testPort", "", Config::kConfigFileName, "", true, contents);
1261 BEAST_EXPECT(false);
1262 }
1263 catch (std::exception const& ex)
1264 {
1265 BEAST_EXPECT(
1266 std::string_view(ex.what()).starts_with("Invalid value '0' for key 'port'"));
1267 }
1268 }
1269
1270 void
1272 {
1273 Config cfg;
1274 /* NOTE: this string includes some explicit
1275 * space chars in order to verify proper trimming */
1276 std::string const toLoad(
1277 R"(
1278[port_rpc])"
1279 "\x20"
1280 R"(
1281# comment
1282 # indented comment
1283)"
1284 "\x20\x20"
1285 R"(
1286[ips])"
1287 "\x20"
1288 R"(
1289r.ripple.com 51235
1290
1291 [ips_fixed])"
1292 "\x20\x20"
1293 R"(
1294 # COMMENT
1295 s1.ripple.com 51235
1296 s2.ripple.com 51235
1297
1298)");
1299 cfg.loadFromString(toLoad);
1300 BEAST_EXPECT(
1301 cfg.exists(Sections::kPortRpc) && cfg.section(Sections::kPortRpc).lines().empty() &&
1302 cfg.section(Sections::kPortRpc).values().empty());
1303 BEAST_EXPECT(
1304 cfg.exists(Sections::kIps) && cfg.section(Sections::kIps).lines().size() == 1 &&
1305 cfg.section(Sections::kIps).values().size() == 1);
1306 BEAST_EXPECT(
1307 cfg.exists(Sections::kIpsFixed) &&
1308 cfg.section(Sections::kIpsFixed).lines().size() == 2 &&
1309 cfg.section(Sections::kIpsFixed).values().size() == 2);
1310 }
1311
1312 void
1313 testColons()
1314 {
1315 Config cfg;
1316 /* NOTE: this string includes some explicit
1317 * space chars in order to verify proper trimming */
1318 std::string const toLoad(
1319 R"(
1320[port_rpc])"
1321 "\x20"
1322 R"(
1323# comment
1324 # indented comment
1325)"
1326 "\x20\x20"
1327 R"(
1328[ips])"
1329 "\x20"
1330 R"(
1331r.ripple.com:51235
1332
1333 [ips_fixed])"
1334 "\x20\x20"
1335 R"(
1336 # COMMENT
1337 s1.ripple.com:51235
1338 s2.ripple.com 51235
1339 anotherserversansport
1340 anotherserverwithport:12
1341 1.1.1.1:1
1342 1.1.1.1 1
1343 12.34.12.123:12345
1344 12.34.12.123 12345
1345 ::
1346 2001:db8::
1347 ::1
1348 ::1:12345
1349 [::1]:12345
1350 2001:db8:3333:4444:5555:6666:7777:8888:12345
1351 [2001:db8:3333:4444:5555:6666:7777:8888]:1
1352
1353
1354)");
1355 cfg.loadFromString(toLoad);
1356 BEAST_EXPECT(
1357 cfg.exists(Sections::kPortRpc) && cfg.section(Sections::kPortRpc).lines().empty() &&
1358 cfg.section(Sections::kPortRpc).values().empty());
1359 BEAST_EXPECT(
1360 cfg.exists(Sections::kIps) && cfg.section(Sections::kIps).lines().size() == 1 &&
1361 cfg.section(Sections::kIps).values().size() == 1);
1362 BEAST_EXPECT(
1363 cfg.exists(Sections::kIpsFixed) &&
1364 cfg.section(Sections::kIpsFixed).lines().size() == 15 &&
1365 cfg.section(Sections::kIpsFixed).values().size() == 15);
1366 BEAST_EXPECT(cfg.ips[0] == "r.ripple.com 51235");
1367
1368 BEAST_EXPECT(cfg.ipsFixed[0] == "s1.ripple.com 51235");
1369 BEAST_EXPECT(cfg.ipsFixed[1] == "s2.ripple.com 51235");
1370 BEAST_EXPECT(cfg.ipsFixed[2] == "anotherserversansport");
1371 BEAST_EXPECT(cfg.ipsFixed[3] == "anotherserverwithport 12");
1372 BEAST_EXPECT(cfg.ipsFixed[4] == "1.1.1.1 1");
1373 BEAST_EXPECT(cfg.ipsFixed[5] == "1.1.1.1 1");
1374 BEAST_EXPECT(cfg.ipsFixed[6] == "12.34.12.123 12345");
1375 BEAST_EXPECT(cfg.ipsFixed[7] == "12.34.12.123 12345");
1376
1377 // all ipv6 should be ignored by colon replacer, howsoever formatted
1378 BEAST_EXPECT(cfg.ipsFixed[8] == "::");
1379 BEAST_EXPECT(cfg.ipsFixed[9] == "2001:db8::");
1380 BEAST_EXPECT(cfg.ipsFixed[10] == "::1");
1381 BEAST_EXPECT(cfg.ipsFixed[11] == "::1:12345");
1382 BEAST_EXPECT(cfg.ipsFixed[12] == "[::1]:12345");
1383 BEAST_EXPECT(cfg.ipsFixed[13] == "2001:db8:3333:4444:5555:6666:7777:8888:12345");
1384 BEAST_EXPECT(cfg.ipsFixed[14] == "[2001:db8:3333:4444:5555:6666:7777:8888]:1");
1385 }
1386
1387 void
1388 testComments()
1389 {
1390 struct TestCommentData
1391 {
1392 std::string_view line;
1393 std::string_view field;
1394 std::string_view expect;
1395 bool hadComment;
1396 };
1397
1398 std::array<TestCommentData, 13> const tests = {
1399 {
1400 {
1401 .line = "password = aaaa\\#bbbb",
1402 .field = "password",
1403 .expect = "aaaa#bbbb",
1404 .hadComment = false,
1405 },
1406 {
1407 .line = "password = aaaa#bbbb",
1408 .field = "password",
1409 .expect = "aaaa",
1410 .hadComment = true,
1411 },
1412 {
1413 .line = "password = aaaa #bbbb",
1414 .field = "password",
1415 .expect = "aaaa",
1416 .hadComment = true,
1417 },
1418 // since the value is all comment, this doesn't parse as k=v :
1419 {
1420 .line = "password = #aaaa #bbbb",
1421 .field = "",
1422 .expect = "password =",
1423 .hadComment = true,
1424 },
1425 {
1426 .line = "password = aaaa\\# #bbbb",
1427 .field = "password",
1428 .expect = "aaaa#",
1429 .hadComment = true,
1430 },
1431 {
1432 .line = "password = aaaa\\##bbbb",
1433 .field = "password",
1434 .expect = "aaaa#",
1435 .hadComment = true,
1436 },
1437 {.line = "aaaa#bbbb", .field = "", .expect = "aaaa", .hadComment = true},
1438 {.line = "aaaa\\#bbbb", .field = "", .expect = "aaaa#bbbb", .hadComment = false},
1439 {.line = "aaaa\\##bbbb", .field = "", .expect = "aaaa#", .hadComment = true},
1440 {.line = "aaaa #bbbb", .field = "", .expect = "aaaa", .hadComment = true},
1441 {.line = "1 #comment", .field = "", .expect = "1", .hadComment = true},
1442 {.line = "#whole thing is comment", .field = "", .expect = "", .hadComment = false},
1443 {
1444 .line = " #whole comment with space",
1445 .field = "",
1446 .expect = "",
1447 .hadComment = false,
1448 },
1449 },
1450 };
1451
1452 for (auto const& t : tests)
1453 {
1454 Section s;
1455 s.append(std::string(t.line));
1456 BEAST_EXPECT(s.hadTrailingComments() == t.hadComment);
1457 if (t.field.empty())
1458 {
1459 BEAST_EXPECTS(s.legacy() == t.expect, s.legacy());
1460 }
1461 else
1462 {
1463 std::string field;
1464 BEAST_EXPECTS(set(field, std::string(t.field), s), t.line);
1465 BEAST_EXPECTS(field == t.expect, t.line);
1466 }
1467 }
1468
1469 {
1470 Section s;
1471 s.append("online_delete = 3000");
1472 std::uint32_t od = 0;
1473 BEAST_EXPECT(set(od, Keys::kOnlineDelete, s));
1474 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
1475 BEAST_EXPECTS(od == 3000, *(s.get<std::string>(Keys::kOnlineDelete)));
1476 }
1477
1478 {
1479 Section s;
1480 s.append("online_delete = 2000 #my comment on this");
1481 std::uint32_t od = 0;
1482 BEAST_EXPECT(set(od, Keys::kOnlineDelete, s));
1483 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
1484 BEAST_EXPECTS(od == 2000, *(s.get<std::string>(Keys::kOnlineDelete)));
1485 }
1486 }
1488 void
1489 testGetters()
1490 {
1491 using namespace std::string_literals;
1492 Section s{"MySection"};
1493 s.append("a_string = mystring");
1494 s.append("positive_int = 2");
1495 s.append("negative_int = -3");
1496 s.append("bool_ish = 1");
1497
1498 {
1499 auto val1 = "value 1"s;
1500 BEAST_EXPECT(set(val1, "a_string", s));
1501 BEAST_EXPECT(val1 == "mystring");
1502
1503 auto val2 = "value 2"s;
1504 BEAST_EXPECT(!set(val2, "not_a_key", s));
1505 BEAST_EXPECT(val2 == "value 2");
1506 BEAST_EXPECT(!set(val2, "default"s, "not_a_key", s));
1507 BEAST_EXPECT(val2 == "default");
1508
1509 auto const val3 = get<std::string>(s, "a_string");
1510 BEAST_EXPECT(val3 == "mystring");
1511 auto const val4 = get<std::string>(s, "not_a_key");
1512 BEAST_EXPECT(val4.empty());
1513 auto const val5 = get<std::string>(s, "not_a_key", "default");
1514 BEAST_EXPECT(val5 == "default");
1515
1516 auto val6 = "value 6"s;
1517 BEAST_EXPECT(getIfExists(s, "a_string", val6));
1518 BEAST_EXPECT(val6 == "mystring");
1519
1520 auto val7 = "value 7"s;
1521 BEAST_EXPECT(!getIfExists(s, "not_a_key", val7));
1522 BEAST_EXPECT(val7 == "value 7");
1523 }
1524
1525 {
1526 int val1 = 1;
1527 BEAST_EXPECT(set(val1, "positive_int", s));
1528 BEAST_EXPECT(val1 == 2);
1529
1530 int val2 = 2;
1531 BEAST_EXPECT(set(val2, "negative_int", s));
1532 BEAST_EXPECT(val2 == -3);
1533
1534 int val3 = 3;
1535 BEAST_EXPECT(!set(val3, "a_string", s));
1536 BEAST_EXPECT(val3 == 3);
1537
1538 auto const val4 = get<int>(s, "positive_int");
1539 BEAST_EXPECT(val4 == 2);
1540 auto const val5 = get<int>(s, "not_a_key");
1541 BEAST_EXPECT(val5 == 0);
1542 auto const val6 = get<int>(s, "not_a_key", 5);
1543 BEAST_EXPECT(val6 == 5);
1544 auto const val7 = get<int>(s, "a_string", 6);
1545 BEAST_EXPECT(val7 == 6);
1546
1547 int val8 = 8;
1548 BEAST_EXPECT(getIfExists(s, "positive_int", val8));
1549 BEAST_EXPECT(val8 == 2);
1550
1551 auto val9 = 9;
1552 BEAST_EXPECT(!getIfExists(s, "not_a_key", val9));
1553 BEAST_EXPECT(val9 == 9);
1554
1555 auto val10 = 10;
1556 BEAST_EXPECT(!getIfExists(s, "a_string", val10));
1557 BEAST_EXPECT(val10 == 10);
1558
1559 BEAST_EXPECT(s.get<int>("not_a_key") == std::nullopt);
1560 try
1561 {
1562 [[maybe_unused]] auto const _ = s.get<int>("a_string");
1563 fail();
1564 }
1565 catch (boost::bad_lexical_cast&)
1566 {
1567 pass();
1568 }
1569 }
1570
1571 {
1572 bool flag1 = false;
1573 BEAST_EXPECT(getIfExists(s, "bool_ish", flag1));
1574 BEAST_EXPECT(flag1 == true);
1575
1576 bool flag2 = false;
1577 BEAST_EXPECT(!getIfExists(s, "not_a_key", flag2));
1578 BEAST_EXPECT(flag2 == false);
1579 }
1580 }
1581
1582 void
1584 {
1585 testcase("amendment");
1586 struct ConfigUnit
1587 {
1589 std::uint32_t numSeconds;
1590 std::uint32_t configVal;
1591 bool shouldPass;
1592 };
1593
1594 std::vector<ConfigUnit> const units = {
1595 {.unit = "seconds", .numSeconds = 1, .configVal = 15 * 60, .shouldPass = false},
1596 {.unit = "minutes", .numSeconds = 60, .configVal = 14, .shouldPass = false},
1597 {.unit = "minutes", .numSeconds = 60, .configVal = 15, .shouldPass = true},
1598 {.unit = "hours", .numSeconds = 3600, .configVal = 10, .shouldPass = true},
1599 {.unit = "days", .numSeconds = 86400, .configVal = 10, .shouldPass = true},
1600 {.unit = "weeks", .numSeconds = 604800, .configVal = 2, .shouldPass = true},
1601 {.unit = "months", .numSeconds = 2592000, .configVal = 1, .shouldPass = false},
1602 {.unit = "years", .numSeconds = 31536000, .configVal = 1, .shouldPass = false},
1603 };
1604
1605 std::string space;
1606 for (auto& [unit, sec, val, shouldPass] : units)
1607 {
1608 Config c;
1609 std::string toLoad(R"xrpldConfig(
1610[amendment_majority_time]
1611)xrpldConfig");
1612 // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
1613 toLoad += std::to_string(val) + space + unit;
1614 space = space.empty() ? " " : "";
1615
1616 try
1617 {
1618 c.loadFromString(toLoad);
1619 if (shouldPass)
1620 {
1621 BEAST_EXPECT(c.amendmentMajorityTime.count() == val * sec);
1622 }
1623 else
1624 {
1625 fail();
1626 }
1627 }
1628 catch (std::runtime_error const&)
1629 {
1630 if (!shouldPass)
1631 {
1632 pass();
1633 }
1634 else
1635 {
1636 fail();
1637 }
1638 }
1639 }
1641
1642 void
1643 testOverlay()
1644 {
1645 testcase("overlay: unknown time");
1646
1647 auto const testUnknown = [](std::string value) -> std::optional<std::chrono::seconds> {
1648 try
1649 {
1650 Config c;
1651 c.loadFromString("[overlay]\nmax_unknown_time=" + value);
1652 return c.maxUnknownTime;
1653 }
1654 catch (std::runtime_error const&)
1655 {
1656 return {};
1657 }
1658 };
1659
1660 // Failures
1661 BEAST_EXPECT(!testUnknown("none"));
1662 BEAST_EXPECT(!testUnknown("0.5"));
1663 BEAST_EXPECT(!testUnknown("180 seconds"));
1664 BEAST_EXPECT(!testUnknown("9 minutes"));
1665
1666 // Below lower bound
1667 BEAST_EXPECT(!testUnknown("299"));
1668
1669 // In bounds
1670 BEAST_EXPECT(testUnknown("300") == std::chrono::seconds{300});
1671 BEAST_EXPECT(testUnknown("301") == std::chrono::seconds{301});
1672 BEAST_EXPECT(testUnknown("1799") == std::chrono::seconds{1799});
1673 BEAST_EXPECT(testUnknown("1800") == std::chrono::seconds{1800});
1674
1675 // Above upper bound
1676 BEAST_EXPECT(!testUnknown("1801"));
1677
1678 testcase("overlay: diverged time");
1679
1680 // In bounds:
1681 auto const testDiverged = [](std::string value) -> std::optional<std::chrono::seconds> {
1682 try
1683 {
1684 Config c;
1685 c.loadFromString("[overlay]\nmax_diverged_time=" + value);
1686 return c.maxDivergedTime;
1687 }
1688 catch (std::runtime_error const&)
1689 {
1690 return {};
1691 }
1692 };
1693
1694 // Failures
1695 BEAST_EXPECT(!testDiverged("none"));
1696 BEAST_EXPECT(!testDiverged("0.5"));
1697 BEAST_EXPECT(!testDiverged("180 seconds"));
1698 BEAST_EXPECT(!testDiverged("9 minutes"));
1699
1700 // Below lower bound
1701 BEAST_EXPECT(!testDiverged("0"));
1702 BEAST_EXPECT(!testDiverged("59"));
1703
1704 // In bounds
1705 BEAST_EXPECT(testDiverged("60") == std::chrono::seconds{60});
1706 BEAST_EXPECT(testDiverged("61") == std::chrono::seconds{61});
1707 BEAST_EXPECT(testDiverged("899") == std::chrono::seconds{899});
1708 BEAST_EXPECT(testDiverged("900") == std::chrono::seconds{900});
1709
1710 // Above upper bound
1711 BEAST_EXPECT(!testDiverged("901"));
1712
1713 testcase("overlay: manifest counts");
1714
1715 // Both keys share one range and one parse path, so exercise each
1716 // through the same helper.
1717 auto const testCount = [](std::string const& key,
1718 std::string const& value) -> std::optional<std::size_t> {
1719 try
1720 {
1721 Config c;
1722 c.loadFromString("[overlay]\n" + key + "=" + value);
1723 return key == "max_trusted_count" ? c.maxTrustedCount : c.maxUntrustedCount;
1724 }
1725 catch (std::runtime_error const&)
1726 {
1727 return {};
1728 }
1729 };
1730
1731 for (auto const* key : {"max_untrusted_count", "max_trusted_count"})
1732 {
1733 // Failures. A bad value must surface as std::runtime_error, not
1734 // the std::bad_cast that the underlying parse throws.
1735 BEAST_EXPECT(!testCount(key, "none"));
1736 BEAST_EXPECT(!testCount(key, "0.5"));
1737 BEAST_EXPECT(!testCount(key, "400 manifests"));
1738 BEAST_EXPECT(!testCount(key, "-1"));
1739
1740 // Below lower bound
1741 BEAST_EXPECT(!testCount(key, "0"));
1742 BEAST_EXPECT(!testCount(key, "49"));
1743
1744 // In bounds
1745 BEAST_EXPECT(testCount(key, "50") == 50);
1746 BEAST_EXPECT(testCount(key, "51") == 51);
1747 BEAST_EXPECT(testCount(key, "300") == 300);
1748 BEAST_EXPECT(testCount(key, "400") == 400);
1749 BEAST_EXPECT(testCount(key, "999") == 999);
1750 BEAST_EXPECT(testCount(key, "1000") == 1000);
1751
1752 // Above upper bound
1753 BEAST_EXPECT(!testCount(key, "1001"));
1754 }
1755
1756 // Each key is independent: setting one leaves the other unset.
1757 {
1758 Config c;
1759 c.loadFromString("[overlay]\nmax_untrusted_count=500");
1760 BEAST_EXPECT(c.maxUntrustedCount == 500);
1761 BEAST_EXPECT(!c.maxTrustedCount);
1762 }
1763 {
1764 Config c;
1765 c.loadFromString("[overlay]\nmax_trusted_count=500");
1766 BEAST_EXPECT(c.maxTrustedCount == 500);
1767 BEAST_EXPECT(!c.maxUntrustedCount);
1768 }
1769
1770 // Both can be set together.
1771 {
1772 Config c;
1773 c.loadFromString("[overlay]\nmax_untrusted_count=250\nmax_trusted_count=750");
1774 BEAST_EXPECT(c.maxUntrustedCount == 250);
1775 BEAST_EXPECT(c.maxTrustedCount == 750);
1776 }
1777
1778 // Unset leaves no override, so the use sites fall back to the defaults.
1779 {
1780 Config c;
1781 c.loadFromString("[overlay]\nip_limit=64");
1782 BEAST_EXPECT(!c.maxUntrustedCount);
1783 BEAST_EXPECT(!c.maxTrustedCount);
1784 }
1785
1786 // No [overlay] section at all leaves both unset too.
1787 {
1788 Config c;
1789 c.loadFromString("");
1790 BEAST_EXPECT(!c.maxUntrustedCount);
1791 BEAST_EXPECT(!c.maxTrustedCount);
1792 }
1793 }
1794
1795 void
1796 testToFees()
1797 {
1798 testcase("toFees");
1799
1800 FeeSetup setup;
1801
1802 setup.referenceFee = XRPAmount{17};
1803 setup.accountReserve = XRPAmount{3'000'017};
1804 setup.ownerReserve = XRPAmount{700'017};
1805 setup.gasLimit = 123'457;
1806 setup.bytecodeSizeLimit = 23'457;
1807 setup.gasPrice = 7'654'321;
1808
1809 auto const fees = setup.toFees();
1810
1811 BEAST_EXPECT(fees.base == setup.referenceFee);
1812 BEAST_EXPECT(fees.reserve == setup.accountReserve);
1813 BEAST_EXPECT(fees.increment == setup.ownerReserve);
1814 BEAST_EXPECT(fees.gasLimit == setup.gasLimit);
1815 BEAST_EXPECT(fees.bytecodeSizeLimit == setup.bytecodeSizeLimit);
1816 BEAST_EXPECT(fees.gasPrice == setup.gasPrice);
1817 }
1818
1819 void
1820 run() override
1821 {
1822 testLegacy();
1824 testDbPath();
1827 testSetup(false);
1828 testSetup(true);
1829 testPort();
1830 testZeroPort();
1832 testColons();
1833 testComments();
1834 testGetters();
1835 testAmendment();
1836 testOverlay();
1837 testNetworkID();
1839 testToFees();
1840 }
1841};
1842
1844
1845} // namespace xrpl
T append(T... args)
T c_str(T... args)
A testsuite class.
Definition suite.h:52
bool unexcept(F &&f, String const &reason)
Definition suite.h:499
void pass()
Record a successful test condition.
Definition suite.h:532
void fail(String const &reason, char const *file, int line)
Record a failure.
Definition suite.h:554
LogOs< char > log
Logging output stream.
Definition suite.h:150
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
void legacy(std::string const &section, std::string value)
Set a value that is not a key/value pair.
void testSetup(bool explicitPath)
void run() override
Runs the suite.
std::filesystem::path Path
static constexpr std::string_view kConfigLegacyName
bool standalone() const
static constexpr std::string_view kDatabaseDirName
static constexpr std::string_view kConfigFileName
void setup(std::string const &strConf, bool bQuiet, bool bSilent, bool bStandalone)
Set up the configuration and determine the config and data directories.
std::chrono::seconds maxUnknownTime
void loadFromString(std::string const &fileContents)
Load the config from the contents of the string.
std::uint32_t ledgerHistory
Holds a collection of configuration values.
Definition BasicConfig.h:28
std::optional< T > get(std::string const &name) const
void append(std::vector< std::string > const &lines)
Append a set of lines to this section.
bool expectException(Functor f, std::string const &message="")
Definition TestSuite.h:77
auto rmDir(Path const &toRm)
beast::unit_test::Suite & test_
Path const & subdir() const
std::filesystem::path Path
Write an xrpld config file and remove when done.
Config const & config() const
std::string configFile() const
FileCfgGuard(beast::unit_test::Suite &test, Path subDir, Path const &dbPath, Path const &configFile, Path const &validatorsFile, bool useCounter=true, std::string confContents="")
Write a file in a directory and remove when done.
Path const & file() const
FileDirGuard(beast::unit_test::Suite &test, Path subDir, Path file, std::string const &contents, bool useCounter=true, bool create=true)
Write a validators.txt file and remove when done.
std::string validatorsFile() const
ValidatorsTxtGuard(beast::unit_test::Suite &test, Path subDir, Path const &validatorsFileName, bool useCounter=true)
T current_path(T... args)
T empty(T... args)
T endl(T... args)
T format(T... args)
T getenv(T... args)
T is_directory(T... args)
T move(T... args)
STL namespace.
std::string valFileContents()
std::string configContents(std::string const &dbPath, std::string const &validatorsFile)
The api_version numbers this server serves.
Definition ApiVersion.h:26
constexpr XRPAmount
Convert XRP to drops (integral types).
Definition TxTest.h:53
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
bool set(T &target, std::string const &name, Section const &section)
Set a value from a configuration Section If the named value is not found or doesn't parse as a T,...
ApplyResult apply(ServiceRegistry &registry, OpenView &view, STTx const &tx, ApplyFlags flags, beast::Journal journal)
Apply a transaction to an OpenView.
Definition apply.cpp:181
void parsePort(ParsedPort &port, Section const &section, std::ostream &log)
Definition Port.cpp:195
T get(Section const &section, std::string const &name, T const &defaultValue=T{})
Retrieve a key/value pair from a section.
bool getIfExists(Section const &section, std::string const &name, T &v)
static std::string const & systemName()
BEAST_DEFINE_TESTSUITE(AccountTxPaging, app, xrpl)
static std::optional< Seed > validationSeed(json::Value const &params)
T regex_replace(T... args)
T size(T... args)
T starts_with(T... args)
static constexpr auto kOnlineDelete
Definition Constants.h:140
std::vector< boost::asio::ip::network_v4 > adminNetsV4
Definition Port.h:96
std::vector< boost::asio::ip::network_v6 > adminNetsV6
Definition Port.h:97
static constexpr auto kIps
Definition Constants.h:23
static constexpr auto kPortWssAdmin
Definition Constants.h:49
static constexpr auto kValidatorListThreshold
Definition Constants.h:72
static constexpr auto kValidators
Definition Constants.h:74
static constexpr auto kValidatorListKeys
Definition Constants.h:70
static constexpr auto kServer
Definition Constants.h:56
static constexpr auto kPortRpc
Definition Constants.h:47
static constexpr auto kSslVerify
Definition Constants.h:62
static constexpr auto kValidatorsFile
Definition Constants.h:75
static constexpr auto kIpsFixed
Definition Constants.h:24
static constexpr auto kDatabasePath
Definition Constants.h:13
static constexpr auto kDebugLogfile
Definition Constants.h:14
static constexpr auto kValidatorListSites
Definition Constants.h:71
T to_string(T... args)
T what(T... args)