using Newtonsoft.Json.Linq; using System.Security.Cryptography; namespace XFEWarframe.Core.Data; // Immutable, content-addressed response files. Ordinary NPC/session/loadout saves // touch only the small references, rather than rewriting every old inventory. internal sealed class MissionReceiptArchive(string stateDirectory) { private readonly string directory = Path.Combine(Path.GetFullPath(stateDirectory), "mission-receipts"); internal byte[] Read(string hash) => File.ReadAllBytes(PathFor(hash)); internal bool Persist(JObject candidate) { var added = false; foreach (var encoded in Entries(candidate)) { if (encoded.Value("data") is not { } payload) continue; var bytes = Convert.FromBase64String(payload); var hash = Convert.ToHexStringLower(SHA256.HashData(bytes)); var path = PathFor(hash); Directory.CreateDirectory(directory); if (File.Exists(path) && !File.ReadAllBytes(path).AsSpan().SequenceEqual(bytes)) throw new InvalidDataException("Damaged existing mission replay archive."); if (!File.Exists(path)) { var temp = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536, FileOptions.SequentialScan)) { stream.Write(bytes); stream.Flush(true); } File.Move(temp, path); } finally { if (File.Exists(temp)) File.Delete(temp); } } encoded["blob"] = hash; encoded.Remove("data"); added = true; } return added; } // Called only after atomic state replacement. Keep files referenced by both // state.json and state.json.bak; a rejected transaction never deletes files. internal void Prune(JObject current, JObject previous) { var keep = Entries(current).Concat(Entries(previous)).Select(e => e.Value("blob")).OfType().ToHashSet(StringComparer.Ordinal); foreach (var file in Directory.EnumerateFiles(directory, "*.br", SearchOption.TopDirectoryOnly)) { var hash = Path.GetFileNameWithoutExtension(file); if (IsHash(hash) && !keep.Contains(hash)) File.Delete(PathFor(hash)); } } private string PathFor(string hash) => IsHash(hash) ? Path.Combine(directory, hash + ".br") : throw new InvalidDataException("Invalid mission replay archive identifier."); private static bool IsHash(string value) => value.Length == 64 && value.All(c => c is >= '0' and <= '9' or >= 'a' and <= 'f'); private static IEnumerable Entries(JObject state) => (state["accounts"] as JObject ?? new()).Properties().Select(p => p.Value).OfType() .SelectMany(a => (a["MissionReceipts"] as JArray ?? []).OfType()) .Select(r => r[MissionReceipts.EncodingKey]).OfType(); }