#include "evo/biology/genome.hpp" #include "evo/accounting/rates.hpp" #include namespace evo::biology { namespace { constexpr std::array magic{'A', 'E', 'V', 'O', 'G', 'E', 'N', '1'}; // Magic, versions, identity, origin and parent count. constexpr std::size_t fixed_prefix = 36; constexpr std::size_t parent_size = 8; constexpr std::size_t record_size = 9; constexpr std::size_t digest_size = 8; constexpr std::size_t checksum_size = 8; // Schema 6: nine 16-bit movement indices after the capability records. constexpr std::size_t arrangement_count = 9; constexpr std::size_t arrangement_size = arrangement_count * 2; // Schema 7: twenty 16-bit cellular traits after the arrangement. constexpr std::size_t trait_count = 20; constexpr std::size_t traits_size = trait_count * 2; bool has_arrangement(std::uint32_t schema) noexcept { return schema >= genome_schema_v6; } bool has_traits(std::uint32_t schema) noexcept { return schema >= genome_schema_v7; } std::array trait_values(const CellularTraits& t) noexcept { return {t.density, t.upkeep_efficiency, t.growth_speed, t.collection[0], t.collection[1], t.collection[2], t.collection[3], t.collection[4], t.burn[0], t.burn[1], t.burn[2], t.burn[3], t.engulf_capacity, t.kill_absorption, t.litter, t.recipe[0], t.recipe[1], t.recipe[2], t.recipe[3], t.adhesion}; } CellularTraits traits_from(const std::array& v) noexcept { return {v[0], v[1], v[2], {v[3], v[4], v[5], v[6], v[7]}, {v[8], v[9], v[10], v[11]}, v[12], v[13], v[14], {v[15], v[16], v[17], v[18]}, v[19]}; } // Required from schema 7 and refused before it. Every index is 1 to 1,000 points; litter // is bounded; each recipe share is at least 1 and they sum to 1000; adhesion is a flag. bool valid_traits(std::uint32_t schema, const std::optional& traits) noexcept { if (!has_traits(schema)) return !traits.has_value(); if (!traits) return false; const auto& t = *traits; const auto index = [](std::uint16_t value) { return value >= 1 && value <= max_trait_points; }; if (!index(t.density) || !index(t.upkeep_efficiency) || !index(t.growth_speed) || !index(t.engulf_capacity) || !index(t.kill_absorption)) return false; for (const auto value : t.collection) if (!index(value)) return false; for (const auto value : t.burn) if (!index(value)) return false; if (t.litter > max_litter || t.adhesion > 1) return false; std::uint32_t recipe{}; for (const auto share : t.recipe) { if (share == 0) return false; recipe += share; } return recipe == 1000; } std::array indices(const MovementArrangement& a) noexcept { return {a.output, a.efficiency, a.burst, a.steering, a.streamlining, a.braking, a.anchor, a.coasting, a.colony_drive}; } // Required from schema 6 and refused before it. Parts a body cannot lack (efficiency, // steering, streamlining, braking, coasting) are at least 1; acquired modules and shed // output may be 0. bool valid_arrangement(std::uint32_t schema, const std::optional& arrangement) noexcept { if (!has_arrangement(schema)) return !arrangement.has_value(); if (!arrangement) return false; const auto& a = *arrangement; for (const auto value : indices(a)) if (value > max_movement_points) return false; return a.efficiency != 0 && a.steering != 0 && a.streamlining != 0 && a.braking != 0 && a.coasting != 0; } // Accidental-corruption detection only, per ADR-0008. Not authenticity. std::uint64_t checksum(std::span bytes) noexcept { std::uint64_t hash = 14695981039346656037ULL; for (const auto byte : bytes) { hash = (hash ^ byte) * 1099511628211ULL; } return hash; } // Record digest, deliberately a different function from the checksum: the two // answer different questions and neither is a cryptographic claim. std::uint64_t digest_of(std::span bytes) noexcept { std::uint64_t hash = 0x9e3779b97f4a7c15ULL; for (const auto byte : bytes) { hash ^= byte; hash *= 0xff51afd7ed558ccdULL; hash ^= hash >> 29U; } return hash; } void append(std::vector& bytes, std::uint64_t value, std::size_t width) { for (std::size_t index = 0; index < width; ++index) { bytes.push_back(static_cast(value & 0xffU)); value >>= 8U; } } // Private reader: callers validate the whole bounded region before reading. // Widths below are constants, not input-controlled values. class Reader { public: explicit Reader(std::span bytes) noexcept : bytes_{bytes} {} std::uint64_t read(std::size_t width) noexcept { std::uint64_t value{}; for (std::size_t index = 0; index < width; ++index) { value |= static_cast(bytes_[offset_++]) << (8U * index); } return value; } private: std::span bytes_; std::size_t offset_{}; }; constexpr std::uint32_t every_capability = (1U << capability_count) - 1U; std::expected validate(std::uint32_t schema, std::uint64_t id, std::uint64_t origin, std::uint32_t development, std::span parents, std::span capabilities) { const auto* table = capability_schema_for(schema); if (table == nullptr) { return std::unexpected{GenomeError::unsupported_version}; } const auto spec = [table](Capability kind) -> const CapabilitySpec& { return (*table)[static_cast(kind)]; }; if (id == 0 || origin == 0) { return std::unexpected{GenomeError::invalid_identity}; } if (development == 0) { return std::unexpected{GenomeError::unsupported_version}; } // The format reserves room for recombination; schema 1 admits one parent. if (parents.size() > 1) { return std::unexpected{GenomeError::invalid_ancestry}; } for (std::size_t index = 0; index < parents.size(); ++index) { if (parents[index] == 0 || parents[index] == id) { return std::unexpected{GenomeError::invalid_ancestry}; } for (std::size_t other = index + 1; other < parents.size(); ++other) { if (parents[index] == parents[other]) { return std::unexpected{GenomeError::invalid_ancestry}; } } } if (capabilities.empty()) { return std::unexpected{GenomeError::missing_capability}; } if (capabilities.size() > capability_count) { return std::unexpected{GenomeError::duplicate_capability}; } std::uint32_t present{}; for (std::size_t index = 0; index < capabilities.size(); ++index) { const auto& record = capabilities[index]; if (static_cast(record.kind) >= capability_count) { return std::unexpected{GenomeError::unknown_capability}; } // Strictly ascending order is canonical and rejects duplicates at once. if (index > 0 && !(capabilities[index - 1].kind < record.kind)) { return std::unexpected{GenomeError::duplicate_capability}; } if ((record.prerequisites & ~every_capability) != 0) { return std::unexpected{GenomeError::unknown_capability}; } const auto& limits = spec(record.kind); if (record.parameter < limits.minimum || record.parameter > limits.maximum) { return std::unexpected{GenomeError::parameter_out_of_range}; } present |= capability_bit(record.kind); } for (std::size_t index = 0; index < capability_count; ++index) { const auto kind = static_cast(index); if ((*table)[index].required && (present & capability_bit(kind)) == 0) { return std::unexpected{GenomeError::missing_capability}; } } std::array edges{}; for (const auto& record : capabilities) { // In schema 1 every mandated capability is also a required one, so this // presence check fires only for declared prerequisites. Mandated edges // still take part in the cycle closure below, and a later schema may // mandate a capability that is not required. const auto required = record.prerequisites | spec(record.kind).mandates; if ((required & ~present) != 0) { return std::unexpected{GenomeError::missing_prerequisite}; } edges[static_cast(record.kind)] = required; } // Seven nodes make the transitive closure exact and bounded. for (std::size_t round = 0; round < capability_count; ++round) { for (std::size_t node = 0; node < capability_count; ++node) { std::uint32_t reached = edges[node]; for (std::size_t other = 0; other < capability_count; ++other) { if ((edges[node] & (1U << other)) != 0) { reached |= edges[other]; } } edges[node] = reached; } } for (std::size_t node = 0; node < capability_count; ++node) { if ((edges[node] & (1U << node)) != 0) { return std::unexpected{GenomeError::cyclic_development}; } } return {}; } } // namespace std::vector Genome::body() const { std::vector bytes; bytes.reserve(max_genome_bytes); bytes.insert(bytes.end(), magic.begin(), magic.end()); append(bytes, schema_version_, 4); append(bytes, development_version_, 4); append(bytes, id_, 8); append(bytes, origin_event_, 8); append(bytes, parents_.size(), 4); for (const auto parent : parents_) { append(bytes, parent, 8); } append(bytes, capabilities_.size(), 4); for (const auto& record : capabilities_) { append(bytes, static_cast(record.kind), 1); append(bytes, record.parameter, 4); append(bytes, record.prerequisites, 4); } if (movement_arrangement_) for (const auto value : indices(*movement_arrangement_)) append(bytes, value, 2); if (cellular_traits_) for (const auto value : trait_values(*cellular_traits_)) append(bytes, value, 2); return bytes; } std::vector Genome::encode() const { auto bytes = body(); append(bytes, digest_, digest_size); append(bytes, checksum(bytes), checksum_size); return bytes; } std::expected Genome::create(const GenomeDraft& draft) { // A draft is unordered input; the stored record is canonical. std::vector ordered{draft.capabilities.begin(), draft.capabilities.end()}; std::ranges::sort(ordered, {}, &CapabilityRecord::kind); if (draft.parents.size() > max_parents) { return std::unexpected{GenomeError::invalid_ancestry}; } if (const auto valid = validate(draft.schema_version, draft.id, draft.origin_event, draft.development_version, draft.parents, ordered); !valid) { return std::unexpected{valid.error()}; } if (!valid_arrangement(draft.schema_version, draft.movement_arrangement) || !valid_traits(draft.schema_version, draft.cellular_traits)) { return std::unexpected{GenomeError::parameter_out_of_range}; } Genome genome; genome.schema_version_ = draft.schema_version; genome.id_ = draft.id; genome.origin_event_ = draft.origin_event; genome.development_version_ = draft.development_version; genome.parents_ = draft.parents; genome.capabilities_ = std::move(ordered); genome.movement_arrangement_ = draft.movement_arrangement; genome.cellular_traits_ = draft.cellular_traits; genome.digest_ = digest_of(genome.body()); return genome; } std::expected Genome::decode(std::span bytes) { if (bytes.size() < fixed_prefix + 4 + digest_size + checksum_size || bytes.size() > max_genome_bytes) { return std::unexpected{GenomeError::invalid_encoding}; } if (!std::equal(magic.begin(), magic.end(), bytes.begin())) { return std::unexpected{GenomeError::invalid_encoding}; } Reader reader{bytes}; static_cast(reader.read(magic.size())); const auto schema = static_cast(reader.read(4)); if (capability_schema_for(schema) == nullptr) { return std::unexpected{GenomeError::unsupported_version}; } const auto development = static_cast(reader.read(4)); const auto id = reader.read(8); const auto origin = reader.read(8); const auto parent_count = reader.read(4); if (parent_count > max_parents) { return std::unexpected{GenomeError::invalid_ancestry}; } // Bound the record region before reading any of it. const auto counted = fixed_prefix + static_cast(parent_count) * parent_size + 4; if (bytes.size() < counted + digest_size + checksum_size) { return std::unexpected{GenomeError::invalid_encoding}; } std::vector parents; parents.reserve(static_cast(parent_count)); for (std::uint64_t index = 0; index < parent_count; ++index) { parents.push_back(reader.read(parent_size)); } const auto record_count = reader.read(4); if (record_count > capability_count) { return std::unexpected{GenomeError::duplicate_capability}; } // An exact length match rejects trailing bytes rather than ignoring them. const auto arrangement_bytes = has_arrangement(schema) ? arrangement_size : 0; const auto trait_bytes = has_traits(schema) ? traits_size : 0; const auto expected = counted + static_cast(record_count) * record_size + arrangement_bytes + trait_bytes + digest_size + checksum_size; if (bytes.size() != expected) { return std::unexpected{GenomeError::invalid_encoding}; } const auto stored = Reader{bytes.subspan(expected - checksum_size)}.read(checksum_size); if (stored != checksum(bytes.first(expected - checksum_size))) { return std::unexpected{GenomeError::invalid_encoding}; } std::vector capabilities; capabilities.reserve(static_cast(record_count)); for (std::uint64_t index = 0; index < record_count; ++index) { const auto kind = reader.read(1); if (kind >= capability_count) { return std::unexpected{GenomeError::unknown_capability}; } const auto parameter = static_cast(reader.read(4)); const auto prerequisites = static_cast(reader.read(4)); capabilities.push_back({static_cast(kind), parameter, prerequisites}); } std::optional arrangement; if (has_arrangement(schema)) { std::array read{}; for (auto& value : read) value = static_cast(reader.read(2)); arrangement = MovementArrangement{read[0], read[1], read[2], read[3], read[4], read[5], read[6], read[7], read[8]}; } std::optional traits; if (has_traits(schema)) { std::array read{}; for (auto& value : read) value = static_cast(reader.read(2)); traits = traits_from(read); } if (const auto valid = validate(schema, id, origin, development, parents, capabilities); !valid) { return std::unexpected{valid.error()}; } if (!valid_arrangement(schema, arrangement) || !valid_traits(schema, traits)) { return std::unexpected{GenomeError::parameter_out_of_range}; } Genome genome; genome.schema_version_ = schema; genome.id_ = id; genome.origin_event_ = origin; genome.development_version_ = development; genome.parents_ = std::move(parents); genome.capabilities_ = std::move(capabilities); genome.movement_arrangement_ = arrangement; genome.cellular_traits_ = traits; // The body must reproduce exactly, so a rewritten record is rejected. const auto digest = digest_of(genome.body()); if (digest != reader.read(digest_size)) { return std::unexpected{GenomeError::digest_mismatch}; } genome.digest_ = digest; return genome; } bool Genome::carries(Capability kind) const noexcept { return std::ranges::any_of(capabilities_, [kind](const auto& record) { return record.kind == kind; }); } std::expected Genome::parameter(Capability kind) const noexcept { for (const auto& record : capabilities_) { if (record.kind == kind) { return record.parameter; } } return std::unexpected{GenomeError::missing_capability}; } std::expected Genome::per_second(Capability kind) const noexcept { const auto stored = parameter(kind); if (!stored) { return std::unexpected{stored.error()}; } const auto unit = capability_schema_v1[static_cast(kind)].unit; const bool per_tick = unit == Unit::micrometres_per_tick || unit == Unit::femtograms_per_tick; if (schema_version_ == genome_schema_v1 && per_tick) { // Exact: a 50 ms tick is a twentieth of a second (ADR-0099). const auto rate = accounting::per_second_from_per_tick(*stored, schema_v1_tick_microseconds); if (!rate) { return std::unexpected{GenomeError::parameter_out_of_range}; } return *rate; } return std::uint64_t{*stored}; } } // namespace evo::biology