#include "settlement/core/checkpoint.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { using namespace settlement; using Void::Testing::Test; constexpr Void::Uuid::Uuid world_id{{0x91, 2, 3, 4, 5, 6, 0x47, 8, 0x89, 10, 11, 12, 13, 14, 15, 16}}; void require(bool condition, std::string_view message) { if (!condition) throw std::runtime_error(std::string(message)); } template T checked(std::expected result) { if (!result) throw std::runtime_error(result.error().message); return std::move(*result); } std::string saved_state(const World& world) { std::ostringstream stream(std::ios::binary); world.write_save(stream); return std::move(stream).str(); } std::string encoded(const World& world, const RulesManifest& rules) { return checked(encode_checkpoint(world, world_id, 7, rules)); } WorldCheckpoint decoded(std::string_view bytes, std::span catalog) { return checked(decode_checkpoint(bytes, catalog, 1, ExecutionMode::SerialReference)); } void rejected(std::string_view bytes, std::span catalog, CheckpointError code, std::string_view field = {}, std::string_view package = {}) { const auto result = decode_checkpoint(bytes, catalog, 1, ExecutionMode::SerialReference); require(!result, "invalid checkpoint was accepted"); require(result.error().code == code && !result.error().message.empty(), "checkpoint error lost its code or message"); require(result.error().field.find(field) != std::string::npos, "checkpoint error named the wrong field"); require(result.error().package.find(package) != std::string::npos, "checkpoint error lost its package"); } template void change(std::string& bytes, std::size_t offset, T value) { Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}).subspan(offset)); require(writer.writeLittle(value).has_value(), "fixture field write failed"); } void rehash(std::string& bytes) { auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256); require(hasher.has_value(), "fixture hasher creation failed"); require(hasher->update(std::string_view(bytes).substr(0, bytes.size() - 32)).has_value(), "fixture hash failed"); const auto checksum = hasher->finalize(); require(checksum.has_value() && checksum->size() == 32, "fixture hash finalization failed"); std::memcpy(bytes.data() + bytes.size() - 32, checksum->data(), checksum->size()); } struct PackageLocation { std::size_t begin; std::size_t version_length; std::size_t end; }; struct FrameLayout { std::uint32_t metadata_size; std::uint64_t body_size; std::size_t body_begin; std::vector packages; }; FrameLayout layout(std::string_view bytes) { Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(), bytes.size()})); require(reader.skip(12).has_value(), "fixture header skip failed"); FrameLayout result{}; result.metadata_size = reader.readLittle().value(); result.body_size = reader.readLittle().value(); result.body_begin = 24 + result.metadata_size; require(reader.skip(64).has_value(), "fixture metadata skip failed"); const auto count = reader.readLittle().value(); for (std::uint32_t i = 0; i < count; ++i) { const auto begin = reader.position(); const auto id_size = reader.readLittle().value(); require(reader.skip(id_size).has_value(), "fixture ID skip failed"); const auto version_length = reader.position(); const auto version_size = reader.readLittle().value(); require(reader.skip(version_size + 32).has_value(), "fixture identity skip failed"); result.packages.push_back({begin, version_length, reader.position()}); } return result; } std::string package_json(std::string_view id, std::string_view version = "1.0.0", std::string_view dependencies = "[]") { return "{\"schema\":1,\"id\":\"" + std::string(id) + "\",\"version\":\"" + std::string(version) + "\",\"dependencies\":" + std::string(dependencies) + ",\"exclusive_capabilities\":[],\"definitions\":[]}"; } RulePackage load(std::string_view json) { return checked(load_rule_package("checkpoint-fixture.json", json)); } struct [[= Void::Testing::name("CheckpointTests")]] CheckpointTests : Void::Testing::Suite { [[= Void::Testing::tag("checkpoint")]] Test test_round_trip_preserves_identity_and_legacy_world_bytes(); [[= Void::Testing::tag("checkpoint")]] Test test_mid_carry_round_trip_continues_the_same_world(); [[= Void::Testing::tag("checkpoint")]] Test test_selected_rules_survive_catalog_reordering(); [[= Void::Testing::tag("checkpoint")]] Test test_missing_changed_and_duplicate_installed_packages(); [[= Void::Testing::tag("checkpoint")]] Test test_integrity_covers_the_entire_frame_and_rejects_truncation(); [[= Void::Testing::tag("checkpoint")]] Test test_bounded_metadata_and_complete_dependency_closure(); [[= Void::Testing::tag("checkpoint")]] Test test_valid_checksum_still_requires_valid_identity_and_world(); [[= Void::Testing::tag("checkpoint")]] Test test_world_body_larger_than_one_shot_hash_limit(); }; Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes() { const auto catalog = checked(builtin_rule_packages()); const auto rules = checked(default_rules_manifest()); World world(43, 8, 9, 1, ExecutionMode::SerialReference); static_cast(world.spawn_agent({1, 1})); static_cast(world.add_job({6, 6}, 4)); for (int i = 0; i < 4; ++i) world.step(); const auto before = saved_state(world); const auto bytes = encoded(world, rules); auto restored = decoded(bytes, catalog); require(restored.world_id == world_id && restored.city == 7 && restored.rules == rules, "checkpoint lost stable world identity, city or rules"); require(saved_state(*restored.world) == before && saved_state(world) == before, "checkpoint changed the original or restored canonical state"); require(bytes.substr(layout(bytes).body_begin, before.size()) == before, "checkpoint did not use the existing world serialization"); require(before.substr(0, 8) == "SETTLERS" && static_cast(before[8]) == 13, "canonical serialization version changed"); require(encoded(*restored.world, restored.rules) == bytes, "re-encoding changed the checkpoint frame"); auto parallel = checked(decode_checkpoint(bytes, catalog, 6)); require(parallel.world->worker_count() == 6 && saved_state(*parallel.world) == before, "checkpoint did not honor requested execution configuration"); auto nil = encode_checkpoint(world, {}, 7, rules); auto no_city = encode_checkpoint(world, world_id, 0, rules); require(!nil && nil.error().code == CheckpointError::InvalidIdentity && !no_city && no_city.error().code == CheckpointError::InvalidIdentity, "encode accepted an invalid world or city identity"); } Test CheckpointTests::test_mid_carry_round_trip_continues_the_same_world() { const auto catalog = checked(builtin_rule_packages()); const auto rules = checked(default_rules_manifest()); auto world = make_first_colony(2); require(world->apply_command({1, 1, CommandKind::PlaceBed, {16, 18}}).status == CommandStatus::Accepted, "fixture bed placement failed"); bool carrying = false; for (int i = 0; i < 300 && !carrying; ++i) { world->step(); carrying = std::any_of(world->agents().begin(), world->agents().end(), [](const Agent& agent) { return agent.inventory.item_count(ItemType::Wood) > 0 || agent.inventory.item_count(ItemType::Stone) > 0 || agent.inventory.item_count(ItemType::Cloth) > 0; }); } require(carrying, "fixture never carried construction material"); const auto before = saved_state(*world); auto restored = decoded(encoded(*world, rules), catalog); require(saved_state(*restored.world) == before, "mid-carry checkpoint changed reservations or inventory"); for (int i = 0; i < 300; ++i) { world->step(); restored.world->step(); require(saved_state(*world) == saved_state(*restored.world), "checkpoint continuation diverged"); } require(world->scenario_progress().assigned_beds >= 1, "checkpoint fixture never completed its bed"); } Test CheckpointTests::test_selected_rules_survive_catalog_reordering() { std::vector catalog{ load(package_json("game.core")), load(package_json("game.water", "1.0.0", R"([{"id":"game.core","version":"1.0.0"}])")), load(package_json("game.unselected"))}; const std::array dry_selection{std::string{"game.core"}}; const std::array wet_selection{std::string{"game.water"}}; const auto dry = checked(resolve_rules(catalog, dry_selection)); const auto wet = checked(resolve_rules(catalog, wet_selection)); World world(12, 5, 5, 1, ExecutionMode::SerialReference); const auto dry_frame = encoded(world, dry); const auto wet_frame = encoded(world, wet); std::reverse(catalog.begin(), catalog.end()); require(decoded(dry_frame, catalog).rules == dry && decoded(wet_frame, catalog).rules == wet && dry != wet, "installed discovery order changed selected world rules"); require(decoded(wet_frame, catalog).rules.packages().size() == 2, "unselected installed package entered the saved rules"); } Test CheckpointTests::test_missing_changed_and_duplicate_installed_packages() { World world(1, 5, 5, 1, ExecutionMode::SerialReference); std::vector catalog{load(package_json("game.core"))}; const std::array selected{std::string{"game.core"}}; const auto rules = checked(resolve_rules(catalog, selected)); const auto bytes = encoded(world, rules); rejected(bytes, {}, CheckpointError::RulesMismatch, "packages", "game.core"); for (std::string_view version : {"1.0.1", "1.0.0+build2"}) { const std::array changed{load(package_json("game.core", version))}; rejected(bytes, changed, CheckpointError::RulesMismatch, "version", "game.core"); } const std::array changed_content{load(R"({"schema":1,"id":"game.core","version":"1.0.0","dependencies":[],"exclusive_capabilities":["game.core:changed"],"definitions":[]})")}; rejected(bytes, changed_content, CheckpointError::RulesMismatch, "sha256", "game.core"); catalog.push_back(catalog.front()); rejected(bytes, catalog, CheckpointError::RulesMismatch, "id", "game.core"); } Test CheckpointTests::test_integrity_covers_the_entire_frame_and_rejects_truncation() { World world(1, 5, 5, 1, ExecutionMode::SerialReference); const auto catalog = checked(builtin_rule_packages()); const auto bytes = encoded(world, checked(default_rules_manifest())); for (std::size_t length = 0; length < bytes.size(); ++length) { require(!decode_checkpoint(std::string_view(bytes).substr(0, length), catalog), "truncated frame was accepted"); } rejected(bytes + "x", catalog, CheckpointError::InvalidFrame, "lengths"); for (std::size_t offset : {std::size_t{24}, std::size_t{40}, std::size_t{48}, std::size_t{56}, layout(bytes).packages.front().begin + 2, layout(bytes).body_begin, bytes.size() - 1}) { auto corrupt = bytes; corrupt[offset] ^= 1; rejected(corrupt, catalog, CheckpointError::IntegrityMismatch, "sha256"); } auto unsupported = bytes; change(unsupported, 8, checkpoint_version + 1); rejected(unsupported, catalog, CheckpointError::UnsupportedVersion, "version"); auto wrong_magic = bytes; wrong_magic[0] = 'X'; rejected(wrong_magic, catalog, CheckpointError::InvalidFrame, "magic"); } Test CheckpointTests::test_bounded_metadata_and_complete_dependency_closure() { World world(1, 5, 5, 1, ExecutionMode::SerialReference); const auto catalog = checked(builtin_rule_packages()); const auto bytes = encoded(world, checked(default_rules_manifest())); const auto wire = layout(bytes); auto huge_body = bytes; change(huge_body, 16, std::numeric_limits::max()); rejected(huge_body, catalog, CheckpointError::LimitExceeded, "lengths"); auto huge_metadata = bytes; change(huge_metadata, 12, static_cast(max_checkpoint_metadata_bytes + 1)); rejected(huge_metadata, catalog, CheckpointError::LimitExceeded, "lengths"); for (std::uint32_t count : {0U, 129U}) { auto invalid = bytes; change(invalid, 88, count); rehash(invalid); rejected(invalid, catalog, CheckpointError::LimitExceeded, "rules.packages"); } for (std::uint16_t count : {std::uint16_t{0}, std::uint16_t{129}}) { auto invalid = bytes; change(invalid, wire.packages.front().begin, count); rehash(invalid); rejected(invalid, catalog, CheckpointError::LimitExceeded, "rules.id"); } auto long_version = bytes; change(long_version, wire.packages.front().version_length, std::uint16_t{257}); rehash(long_version); rejected(long_version, catalog, CheckpointError::LimitExceeded, "rules.version"); const auto first = wire.packages.front(); const auto last = wire.packages.back(); auto duplicate = bytes; const auto record = bytes.substr(first.begin, first.end - first.begin); duplicate.replace(last.begin, last.end - last.begin, record); change(duplicate, 12, static_cast(wire.metadata_size + record.size() - (last.end - last.begin))); rehash(duplicate); rejected(duplicate, catalog, CheckpointError::RulesMismatch, "rules.packages", "settlement.colony"); auto missing_dependency = bytes; missing_dependency.erase(last.begin, last.end - last.begin); change(missing_dependency, 12, static_cast(wire.metadata_size - (last.end - last.begin))); change(missing_dependency, 88, std::uint32_t{1}); rehash(missing_dependency); rejected(missing_dependency, catalog, CheckpointError::RulesMismatch, "rules.packages", "settlement.core"); auto bad_fingerprint = bytes; bad_fingerprint[56] ^= 1; rehash(bad_fingerprint); rejected(bad_fingerprint, catalog, CheckpointError::RulesMismatch, "rules.fingerprint"); } Test CheckpointTests::test_valid_checksum_still_requires_valid_identity_and_world() { World world(4, 5, 5, 1, ExecutionMode::SerialReference); const auto before = saved_state(world); const auto catalog = checked(builtin_rule_packages()); const auto bytes = encoded(world, checked(default_rules_manifest())); const auto wire = layout(bytes); auto nil = bytes; std::fill_n(nil.begin() + 24, 16, '\0'); rehash(nil); rejected(nil, catalog, CheckpointError::InvalidIdentity, "world_id"); auto no_city = bytes; change(no_city, 40, std::uint64_t{0}); rehash(no_city); rejected(no_city, catalog, CheckpointError::InvalidIdentity, "city"); auto wrong_tick = bytes; change(wrong_tick, 48, std::uint64_t{1}); rehash(wrong_tick); rejected(wrong_tick, catalog, CheckpointError::InvalidWorld, "tick"); auto invalid_dimensions = bytes; change(invalid_dimensions, wire.body_begin + 20, std::int32_t{0}); rehash(invalid_dimensions); rejected(invalid_dimensions, catalog, CheckpointError::InvalidWorld, "world"); auto invalid_counter = bytes; // The existing save13 header places next_agent_id after tick, four counters and hunger. change(invalid_counter, wire.body_begin + 69, std::uint64_t{0}); rehash(invalid_counter); rejected(invalid_counter, catalog, CheckpointError::InvalidWorld, "world"); auto inner_trailing = bytes; inner_trailing.insert(wire.body_begin + static_cast(wire.body_size), 1, 'x'); change(inner_trailing, 16, wire.body_size + 1); rehash(inner_trailing); rejected(inner_trailing, catalog, CheckpointError::InvalidWorld, "world"); require(saved_state(world) == before, "failed checkpoint preparation changed the live world"); } Test CheckpointTests::test_world_body_larger_than_one_shot_hash_limit() { World world(1, 5, 5, 1, ExecutionMode::SerialReference); for (int i = 0; i < 700'000; ++i) static_cast(world.add_job({1, 1}, 1)); const auto rules = checked(default_rules_manifest()); const auto catalog = checked(builtin_rule_packages()); const auto bytes = encoded(world, rules); require(layout(bytes).body_size > 16 * 1024 * 1024, "fixture did not exceed the one-shot hash limit"); auto restored = decoded(bytes, catalog); require(restored.world->jobs().size() == world.jobs().size() && restored.world->jobs().back().id == world.jobs().back().id && saved_state(*restored.world) == saved_state(world), "incremental checkpoint hash lost a large supported world"); } } // namespace