#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; // 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); } 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()}; } 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.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 expected = counted + static_cast(record_count) * record_size + 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}); } if (const auto valid = validate(schema, id, origin, development, parents, capabilities); !valid) { return std::unexpected{valid.error()}; } 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); // 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