A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
fix(sim): saves are immutable, hostile-input safe and encoding-independent; budget summed in key order
eyalgolanbe0661213370
diff --git a/sim/Statecraft.Sim.Tests/SaveGameTests.cs b/sim/Statecraft.Sim.Tests/SaveGameTests.csindex 8df6e56bf..f9006f335 100644--- a/sim/Statecraft.Sim.Tests/SaveGameTests.cs+++ b/sim/Statecraft.Sim.Tests/SaveGameTests.cs@@ -7,7 +7,14 @@ using Statecraft.Sim;/// <summary>Saves: seed + command log + content hash + schema version; loading replays to the same state hash.</summary>public class SaveGameTests{- static Content Fixture1() => ContentLoader.Load(Fixture.Write(events: new Dictionary<string, string> { ["drought.yaml"] = ValidationTests.Event }));+ /// <summary>The fixture with a two-office budget, so a saved AllocateBudget has more than one share.</summary>+ static string Rules(string treasury = "100") =>+ Fixture.Files["rules.yaml"].Replace("budget_start: { finance_minister: 1.0 }", "budget_start: { finance_minister: 0.6, defense_minister: 0.4 }")+ .Replace("treasury_start: 100", "treasury_start: " + treasury);++ static Content Fixture1(string treasury = "100") => ContentLoader.Load(Fixture.Write(+ new Dictionary<string, string> { ["rules.yaml"] = Rules(treasury) },+ new Dictionary<string, string> { ["drought.yaml"] = ValidationTests.Event }));/// <summary>Ten turns using every command kind, including ones the sim rejects.</summary>static GameSession Played(Content c)@@ -17,7 +24,7 @@ public class SaveGameTests{new Command[] { new SetMobilization(0.9), new SecurityOrder(-2) },new Command[] { new ChooseEventOption("drought", "ration"), new SetPolicy("rationing", 1.0 / 3) },- new Command[] { new AllocateBudget(new Dictionary<string, double> { ["finance_minister"] = 1.0 }) },+ new Command[] { new AllocateBudget(new Dictionary<string, double> { ["finance_minister"] = 0.75, ["defense_minister"] = 0.25 }) },new Command[] { new Appoint("finance_minister", "pm_one"), new MapAction("housing", 2, 0) },new Command[] { new SetPolicy("odd id with spaces%", 0.5), new MapAction("transit_camp", 4, 0) },new Command[0], new Command[0], new Command[] { new SecurityOrder(1) }, new Command[0], new Command[0],@@ -52,7 +59,7 @@ public class SaveGameTestsAssert.Equal("mode Historical", lines[3]);Assert.Contains("policy rationing 3FD5555555555555", lines); // 1/3, bit for bitAssert.Contains("policy odd%20id%20with%20spaces%25 3FE0000000000000", lines);- Assert.Contains("budget finance_minister=3FF0000000000000", lines);+ Assert.Contains("budget defense_minister=3FD0000000000000,finance_minister=3FE8000000000000", lines);Assert.Contains("map housing 2 0", lines);Assert.Contains("security -2", lines);Assert.StartsWith("end ", lines[lines.Length - 2]);@@ -74,9 +81,7 @@ public class SaveGameTestspublic void OtherContentLoadsWithAWarning(){var text = Played(Fixture1()).Save.Write();- var other = ContentLoader.Load(Fixture.Write(- new Dictionary<string, string> { ["rules.yaml"] = Fixture.Files["rules.yaml"].Replace("treasury_start: 100", "treasury_start: 90") },- new Dictionary<string, string> { ["drought.yaml"] = ValidationTests.Event }));+ var other = Fixture1("90");GameSession.Load(other, text, out var warnings);Assert.Equal(new[] { "This save was made with different game content; the replayed game may differ.", "The replayed game differs from the saved one." }, warnings);}@@ -89,7 +94,7 @@ public class SaveGameTestsvar lines = text.Split('\n');lines[2] = "seed 100"; // same content, different gamevar ex = Assert.Throws<SaveException>(() => GameSession.Load(c, string.Join("\n", lines), out _));- Assert.Contains("did not reproduce the saved game", ex.Message);+ Assert.Contains("The replay does not match the saved game", ex.Message);}[Theory]@@ -149,4 +154,225 @@ public class SaveGameTestsvar used = Played(Fixture1()).Save.Turns.SelectMany(x => x).Select(x => x.GetType().Name).Distinct().OrderBy(x => x).ToList();Assert.Equal(all, used);}++ // ---- fix round 1: immutability, null/surrogate ids, hostile input, damaged saves, encoding ----++ static string Lines(GameSession g, Func<string[], string[]> edit) => string.Join("\n", edit(g.Save.Write().Split('\n')));+ static string Hex64(char c) => new string(c, 64);++ [Fact]+ public void ARecordedTurnDoesNotChangeWhenTheCallerMutatesItsOrders()+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ var shares = c.Rules.BudgetStart.ToDictionary(kv => kv.Key, kv => kv.Value);+ var g = GameSession.New(c, 5, Mode.Historical);+ g.Step(new Command[] { new AllocateBudget(shares) });+ g.Step(new Command[0]);+ var before = g.Save.Write();+ shares.Remove(shares.Keys.First()); // the caller reuses its own dictionary afterwards+ shares["prime_minister"] = 99;+ Assert.Equal(before, g.Save.Write());+ var loaded = GameSession.Load(c, g.Save.Write(), out var warnings);+ Assert.Empty(warnings);+ Assert.Equal(g.State.Hash(), loaded.State.Hash());+ }++ [Fact]+ public void ANullIdIsRefusedAtStepSoTheSaveStaysWritable()+ {+ var g = GameSession.New(Fixture1(), 1, Mode.Historical);+ Assert.Throws<ArgumentNullException>(() => g.Step(new Command[] { new SetPolicy(null!, 1) }));+ Assert.Throws<ArgumentNullException>(() => g.Step(new Command[] { new ChooseEventOption("drought", null!) }));+ Assert.Throws<ArgumentNullException>(() => g.Step(new Command[] { new Appoint(null!, "pm_one") }));+ Assert.Throws<ArgumentNullException>(() => g.Step(new Command[] { new MapAction(null!, 1, 1) }));+ Assert.Empty(g.Save.Turns); // nothing half-recorded+ Assert.StartsWith("statecraft-save 1", g.Save.Write());+ }++ [Fact]+ public void ALoneSurrogateIsRefusedAtStep()+ {+ var g = GameSession.New(Fixture1(), 1, Mode.Historical);+ Assert.Throws<ArgumentException>(() => g.Step(new Command[] { new SetPolicy("bad\uD800id", 1) }));+ g.Step(new Command[] { new SetPolicy("fine\uD83D\uDE00id", 1) }); // a valid pair is fine and round-trips+ var loaded = GameSession.Load(Fixture1(), g.Save.Write(), out _);+ Assert.Equal(g.State.Hash(), loaded.State.Hash());+ }++ [Fact]+ public void ANullBudgetReplaysWithTheSameRejectionReason()+ {+ var c = Fixture1();+ var g = GameSession.New(c, 1, Mode.Historical);+ g.Step(new Command[] { new AllocateBudget(null!) });+ var live = g.Last!.Rejected.Single().Reason;+ var loaded = GameSession.Load(c, g.Save.Write(), out _);+ Assert.Equal(live, loaded.Last!.Rejected.Single().Reason);+ Assert.Equal("Budget shares are required", live);+ var empty = GameSession.New(c, 1, Mode.Historical);+ empty.Step(new Command[] { new AllocateBudget(new Dictionary<string, double>()) });+ Assert.NotEqual(live, empty.Last!.Rejected.Single().Reason); // an empty map is a different mistake+ Assert.Equal(empty.Last.Rejected.Single().Reason, GameSession.Load(c, empty.Save.Write(), out _).Last!.Rejected.Single().Reason);+ }++ [Theory]+ [InlineData("mode Open", 4, "mode Open is not supported")]+ [InlineData("mode 0", 4, "bad mode")]+ [InlineData("mode Foo", 4, "bad mode")]+ [InlineData("mode ", 4, "bad mode")]+ public void ModesMustBeNamesTheGameCanStart(string mode, int line, string message)+ {+ var g = Played(Fixture1());+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(Fixture1(), Lines(g, l => { l[3] = mode; return l; }), out _));+ Assert.Equal((line, "line 4: " + message), (ex.Line, ex.Message));+ }++ [Fact]+ public void AHugeTurnCountIsRefusedBeforeReplay()+ {+ var text = "statecraft-save 1\ncontent " + Hex64('a') + "\nseed 1\nmode Historical\n" + string.Concat(Enumerable.Repeat("turn\n", 400000)) + "end " + Hex64('b') + "\n";+ var ex = Assert.Throws<SaveException>(() => SaveGame.Parse(text));+ Assert.Equal("save has 400000 turns; the most this game plays is 2000", ex.Message);+ var ok = "statecraft-save 1\ncontent " + Hex64('a') + "\nseed 1\nmode Historical\n" + string.Concat(Enumerable.Repeat("turn\n", 2000)) + "end " + Hex64('b') + "\n";+ Assert.Equal(2000, SaveGame.Parse(ok).Turns.Count);+ }++ /// <summary>The replay runs under content whose step throws (a MapAction with no attention cost line): the exception+ /// must surface as a SaveException that names the turn.</summary>+ [Fact]+ public void AReplayThatThrowsIsASaveExceptionNamingTheTurn()+ {+ var text = Played(Fixture1()).Save.Write();+ var broken = Fixture1();+ broken.Rules.AttentionCost.Remove("map_action");+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(broken, text, out _));+ Assert.StartsWith("turn 4: ", ex.Message);+ }++ [Theory]+ [InlineData("content xyz", 2, "bad content hash")]+ [InlineData("end 12", -1, "bad end hash")]+ [InlineData("end ZZZZ", -1, "bad end hash")]+ public void DamagedHashesAreNamedAsSuch(string replacement, int lineIndex, string message)+ {+ var g = Played(Fixture1());+ var lines = g.Save.Write().Split('\n');+ var idx = lineIndex < 0 ? lines.Length - 2 : lineIndex - 1;+ lines[idx] = replacement;+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(Fixture1(), string.Join("\n", lines), out _));+ Assert.Equal("line " + (idx + 1) + ": " + message, ex.Message);+ }++ [Fact]+ public void AnEditedCommandWithTheSameContentSaysTheSaveIsDamagedNotThatTheGameHasABug()+ {+ var c = Fixture1();+ var lines = Played(c).Save.Write().Split('\n');+ var i = Array.FindIndex(lines, l => l.StartsWith("policy rationing "));+ lines[i] = "policy rationing 3FE0000000000000";+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(c, string.Join("\n", lines), out _));+ Assert.Equal("The replay does not match the saved game: the save is damaged or was edited, or the game has a bug.", ex.Message);+ }++ [Theory]+ [InlineData("policy bad%ZZ 3FE0000000000000", "bad text 'bad%ZZ'")]+ [InlineData("policy bad%4 3FE0000000000000", "bad text 'bad%4'")]+ [InlineData("policy bad%FF 3FE0000000000000", "bad text 'bad%FF'")]+ public void MalformedEscapesAreSaveExceptionsWithALine(string command, string message)+ {+ var c = Fixture1();+ var lines = Played(c).Save.Write().Split('\n').ToList();+ lines.Insert(5, command);+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(c, string.Join("\n", lines), out _));+ Assert.Equal("line 6: " + message, ex.Message);+ }++ [Fact]+ public void TheEscapingIsOurOwnAndMatchesRfc3986()+ {+ var g = GameSession.New(Fixture1(), 1, Mode.Historical);+ g.Step(new Command[] { new SetPolicy("A-z_0.9~ \u00E9\u20AC\uD83D\uDE00/", 1) });+ Assert.Contains("policy A-z_0.9~%20%C3%A9%E2%82%AC%F0%9F%98%80%2F 3FF0000000000000", g.Save.Write().Split('\n'));+ }++ [Fact]+ public void ABudgetSummedInAnyInsertionOrderIsJudgedAlike()+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ var v = new[] { 0.37466668006693443, 0.1119292744233292, 0.016696259782142436, 0.014296586668015622, 0.010296855346174184, 0.19600249013696078, 0.12343932175585436, 0.152673531820589 };+ var keys = c.Rules.BudgetStart.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList();+ var forward = new Dictionary<string, double>(); var backward = new Dictionary<string, double>();+ for (int i = 0; i < keys.Count; i++) forward[keys[i]] = v[i];+ for (int i = keys.Count - 1; i >= 0; i--) backward[keys[i]] = v[i];+ var s1 = Simulation.NewGame(c, 1, Mode.Historical); var s2 = Simulation.NewGame(c, 1, Mode.Historical);+ var r1 = Simulation.Step(c, s1, new Command[] { new AllocateBudget(forward) });+ var r2 = Simulation.Step(c, s2, new Command[] { new AllocateBudget(backward) });+ Assert.Equal(r1.Rejected.Select(x => x.Reason), r2.Rejected.Select(x => x.Reason));+ Assert.Equal(r1.State.Hash(), r2.State.Hash());+ }++ [Fact]+ public void ABomOnContentOrOnASaveChangesNothing()+ {+ var plain = ContentLoader.Load(Fixture.Write());+ var dir = Fixture.Write();+ var withBom = ContentLoader.Load(rel =>+ {+ var path = Path.Combine(dir, rel);+ return File.Exists(path) ? "\uFEFF" + File.ReadAllText(path) : null;+ }, new string[0]);+ Assert.Equal(plain.Hash, withBom.Hash);+ var c = Fixture1();+ var text = Played(c).Save.Write();+ var loaded = GameSession.Load(c, "\uFEFF" + text, out var warnings);+ Assert.Empty(warnings);+ Assert.Equal(Played(c).State.Hash(), loaded.State.Hash());+ }++ [Fact]+ public void TheContentHashChangesWithEventsAndSettlements()+ {+ var a = ContentLoader.Load(Fixture.Write(events: new Dictionary<string, string> { ["drought.yaml"] = ValidationTests.Event }));+ var b = ContentLoader.Load(Fixture.Write(events: new Dictionary<string, string> { ["drought.yaml"] = ValidationTests.Event + "# edited\n" }));+ Assert.NotEqual(a.Hash, b.Hash);+ var c = ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["map/settlements_1948.yaml"] = Fixture.Files["map/settlements_1948.yaml"] + "# note\n" }));+ Assert.NotEqual(ContentLoader.Load(Fixture.Write()).Hash, c.Hash);+ }++ [Theory]+ [InlineData("")]+ [InlineData("statecraft-save 1\ncontent x\n")]+ [InlineData("statecraft-save 0")]+ public void ShortInputsAreSaveExceptions(string text) => Assert.Throws<SaveException>(() => SaveGame.Parse(text));++ [Fact]+ public void AMissingOrShortEndLineIsReportedAsDamage()+ {+ var c = Fixture1();+ var lines = Played(c).Save.Write().Split('\n').ToList();+ lines.RemoveAt(lines.Count - 2); // drop "end <hash>"+ Assert.Throws<SaveException>(() => GameSession.Load(c, string.Join("\n", lines), out _));+ }++ [Theory]+ [InlineData("statecraft-save 0", "unknown save schema version 0")]+ [InlineData("statecraft-save 2", "save schema version 2 is newer than this game (1)")]+ [InlineData("statecraft-save -1", "bad schema version")]+ public void SchemaVersionsOutsideOneAreRefused(string first, string message)+ {+ var lines = Played(Fixture1()).Save.Write().Split('\n');+ lines[0] = first;+ var ex = Assert.Throws<SaveException>(() => SaveGame.Parse(string.Join("\n", lines)));+ Assert.Equal("line 1: " + message, ex.Message);+ }++ [Fact]+ public void CrLfLoadsAndALoneCrIsNotASave()+ {+ var c = Fixture1();+ var text = Played(c).Save.Write();+ GameSession.Load(c, text.Replace("\n", "\r\n"), out var warnings);+ Assert.Empty(warnings);+ Assert.Throws<SaveException>(() => SaveGame.Parse(text.Replace("\n", "\r")));+ }}diff --git a/sim/Statecraft.Sim/Commands.cs b/sim/Statecraft.Sim/Commands.csindex d6aac43c2..81e2087ef 100644--- a/sim/Statecraft.Sim/Commands.cs+++ b/sim/Statecraft.Sim/Commands.cs@@ -1,3 +1,4 @@+using System;using System.Collections.Generic;namespace Statecraft.Sim@@ -70,4 +71,28 @@ namespace Statecraft.Simpublic IReadOnlyList<Rejection> Rejected { get; }public StepResult(GameState state, IReadOnlyList<Cause> why, IReadOnlyList<Rejection> rejected) { State = state; Why = why; Rejected = rejected; }}++ /// <summary>Checks that every text an order carries can be saved: a null id or a lone surrogate would make the save+ /// unwritable or lossy, so Step refuses the whole batch before anything happens (a programmer error, like a null Command).</summary>+ static class CommandText+ {+ public static void Validate(IReadOnlyList<Command> commands)+ {+ foreach (var cmd in commands)+ switch (cmd)+ {+ case SetPolicy p: Text(p.Policy, "Policy"); break;+ case AllocateBudget b: if (b.Shares != null) foreach (var k in b.Shares.Keys) Text(k, "Shares key"); break;+ case ChooseEventOption e: Text(e.EventId, "EventId"); Text(e.OptionId, "OptionId"); break;+ case Appoint a: Text(a.Office, "Office"); Text(a.Person, "Person"); break;+ case MapAction m: Text(m.Action, "Action"); break;+ }+ }++ static void Text(string? s, string field)+ {+ if (s == null) throw new ArgumentNullException("commands", $"{field} cannot be null.");+ if (!SaveText.IsEncodable(s)) throw new ArgumentException($"{field} is not valid text (a lone surrogate).", "commands");+ }+ }}diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex b7b382838..378c3937f 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -130,6 +130,7 @@ namespace Statecraft.SimreadFile = rel =>{var text = inner(rel);+ if (text != null && text.Length > 0 && text[0] == '\uFEFF') text = text.Substring(1); // a byte-order mark is not contentif (text != null) read.Add((rel, text));return text;};diff --git a/sim/Statecraft.Sim/EconomySystem.cs b/sim/Statecraft.Sim/EconomySystem.csindex c11f0e46c..fdf7db99b 100644--- a/sim/Statecraft.Sim/EconomySystem.cs+++ b/sim/Statecraft.Sim/EconomySystem.cs@@ -60,7 +60,8 @@ namespace Statecraft.Simif (shares.Values.Any(v => double.IsNaN(v) || double.IsInfinity(v))) return "Budget shares must be finite numbers";if (!new HashSet<string>(shares.Keys).SetEquals(c.Rules.BudgetStart.Keys))return "Budget shares must cover exactly: " + string.Join(", ", c.Rules.BudgetStart.Keys.OrderBy(k => k, StringComparer.Ordinal));- if (Math.Abs(shares.Values.Sum() - 1.0) > 1e-6) return "Budget shares must sum to 1";+ // Summed in key order, not dictionary order, so play and replay agree to the bit whatever order the caller built the map in.+ if (Math.Abs(shares.OrderBy(kv => kv.Key, StringComparer.Ordinal).Sum(kv => kv.Value) - 1.0) > 1e-6) return "Budget shares must sum to 1";if (shares.Values.Any(v => v < 0)) return "Budget shares cannot be negative";s.Budget = new Dictionary<string, double>(shares);return null;diff --git a/sim/Statecraft.Sim/GameSession.cs b/sim/Statecraft.Sim/GameSession.csindex 22df748b5..b5116fa6a 100644--- a/sim/Statecraft.Sim/GameSession.cs+++ b/sim/Statecraft.Sim/GameSession.cs@@ -44,10 +44,13 @@ namespace Statecraft.Simbool sameContent = saved.ContentHash == c.Hash;if (!sameContent) list.Add("This save was made with different game content; the replayed game may differ.");var session = New(c, saved.Seed, saved.Mode);- foreach (var turn in saved.Turns) session.Step(turn);+ int turnNo = 0;+ try { foreach (var turn in saved.Turns) { session.Step(turn); turnNo++; } }+ catch (SaveException) { throw; }+ catch (Exception e) { throw new SaveException(0, $"turn {turnNo + 1}: {e.Message}"); }if (session.State.Hash() != saved.FinalHash){- if (sameContent) throw new SaveException(0, "The replay did not reproduce the saved game (determinism bug): please report it with the save file.");+ if (sameContent) throw new SaveException(0, "The replay does not match the saved game: the save is damaged or was edited, or the game has a bug.");list.Add("The replayed game differs from the saved one.");}warnings = list;diff --git a/sim/Statecraft.Sim/SaveGame.cs b/sim/Statecraft.Sim/SaveGame.csindex b7905ea05..61fe95d38 100644--- a/sim/Statecraft.Sim/SaveGame.cs+++ b/sim/Statecraft.Sim/SaveGame.cs@@ -28,6 +28,8 @@ namespace Statecraft.Simpublic sealed class SaveGame{public const int SchemaVersion = 1;+ /// <summary>Turns are at least a week long, so 2000 turns is 38 years, far past any content; a save with more is hostile or damaged.</summary>+ public const int MaxTurns = 2000;const string Magic = "statecraft-save";readonly List<IReadOnlyList<Command>> turns = new List<IReadOnlyList<Command>>();@@ -47,11 +49,12 @@ namespace Statecraft.Sim}/// <summary>Appends one turn: the commands passed to Simulation.Step and the state it returned.</summary>- public void Record(IReadOnlyList<Command> commands, GameState after)+ internal void Record(IReadOnlyList<Command> commands, GameState after){if (commands == null) throw new ArgumentNullException(nameof(commands));if (after == null) throw new ArgumentNullException(nameof(after));- turns.Add(commands.ToList());+ // A recorded turn is immutable: the caller keeps its own objects (an AllocateBudget's dictionary is theirs to reuse).+ turns.Add(commands.Select(Snapshot).ToList());FinalHash = after.Hash();}@@ -71,14 +74,17 @@ namespace Statecraft.Simreturn sb.ToString();}- static string Esc(string s) => Uri.EscapeDataString(s);+ static Command Snapshot(Command cmd) =>+ cmd is AllocateBudget b && b.Shares != null ? new AllocateBudget(new Dictionary<string, double>(b.Shares)) : cmd;++ static string Esc(string s) => SaveText.Escape(s);static string Num(double v) => BitConverter.DoubleToInt64Bits(v).ToString("X16", CultureInfo.InvariantCulture);static string Int(int v) => v.ToString(CultureInfo.InvariantCulture);static string Format(Command cmd) => cmd switch{SetPolicy p => $"policy {Esc(p.Policy)} {Num(p.Level)}",- AllocateBudget b => "budget " + (b.Shares == null || b.Shares.Count == 0 ? "-" :+ AllocateBudget b => "budget " + (b.Shares == null ? "~" : b.Shares.Count == 0 ? "-" :string.Join(",", b.Shares.OrderBy(kv => kv.Key, StringComparer.Ordinal).Select(kv => Esc(kv.Key) + "=" + Num(kv.Value)))),ChooseEventOption e => $"event {Esc(e.EventId)} {Esc(e.OptionId)}",SetMobilization m => $"mobilize {Num(m.Level)}",@@ -92,10 +98,13 @@ namespace Statecraft.Simpublic static SaveGame Parse(string text){if (text == null) throw new ArgumentNullException(nameof(text));+ if (text.Length > 0 && text[0] == '\uFEFF') text = text.Substring(1); // a byte-order mark is not part of the savevar lines = text.Replace("\r\n", "\n").Split('\n');int n = lines.Length;while (n > 0 && lines[n - 1] == "") n--;if (n < 5) throw new SaveException(0, "Not a Statecraft save (too short)");+ if (lines.Take(n).Count(l => l == "turn") > MaxTurns)+ throw new SaveException(0, FormattableString.Invariant($"save has {lines.Take(n).Count(l => l == "turn")} turns; the most this game plays is {MaxTurns}"));string[] Head(int i, string key, int parts){var f = lines[i].Split(' ');@@ -107,9 +116,14 @@ namespace Statecraft.Simif (version > SchemaVersion) throw new SaveException(1, FormattableString.Invariant($"save schema version {version} is newer than this game ({SchemaVersion})"));if (version < 1) throw new SaveException(1, FormattableString.Invariant($"unknown save schema version {version}"));var content = Head(1, "content", 2)[1];+ if (!IsHash(content)) throw new SaveException(2, "bad content hash");if (!ulong.TryParse(Head(2, "seed", 2)[1], NumberStyles.None, CultureInfo.InvariantCulture, out var seed)) throw new SaveException(3, "bad seed");- if (!Enum.TryParse<Mode>(Head(3, "mode", 2)[1], false, out var mode) || !Enum.IsDefined(typeof(Mode), mode)) throw new SaveException(4, "bad mode");+ var modeName = Head(3, "mode", 2)[1];+ if (!Enum.GetNames(typeof(Mode)).Contains(modeName)) throw new SaveException(4, "bad mode"); // names only: Enum.TryParse would accept "0"+ var mode = (Mode)Enum.Parse(typeof(Mode), modeName);+ if (mode == Mode.Open) throw new SaveException(4, "mode Open is not supported"); // Simulation.NewGame cannot start it before M4var end = Head(n - 1, "end", 2)[1];+ if (!IsHash(end)) throw new SaveException(n, "bad end hash");var save = new SaveGame(content, seed, mode, end);List<Command>? current = null;for (int i = 4; i < n - 1; i++)@@ -121,14 +135,15 @@ namespace Statecraft.Simreturn save;}+ static bool IsHash(string s) => s.Length == 64 && s.All(ch => (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f'));+static Command ParseCommand(int line, string text){var f = text.Split(' ');void Arity(int count) { if (f.Length != count) throw new SaveException(line, $"'{f[0]}' needs {count - 1} values"); }string Str(string s){- try { return Uri.UnescapeDataString(s); }- catch (UriFormatException) { throw new SaveException(line, $"bad text '{s}'"); }+ return SaveText.Unescape(s) ?? throw new SaveException(line, $"bad text '{s}'");}double Dbl(string s) => long.TryParse(s, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var bits) && s.Length == 16? BitConverter.Int64BitsToDouble(bits) : throw new SaveException(line, $"bad number '{s}'");@@ -138,6 +153,7 @@ namespace Statecraft.Simcase "policy": Arity(3); return new SetPolicy(Str(f[1]), Dbl(f[2]));case "budget":Arity(2);+ if (f[1] == "~") return new AllocateBudget(null!); // a null budget: replays with the same rejection reasonvar shares = new Dictionary<string, double>();if (f[1] != "-")foreach (var pair in f[1].Split(','))@@ -156,4 +172,50 @@ namespace Statecraft.Sim}}}++ /// <summary>The save format's own percent-encoding (RFC 3986: unreserved characters stay, everything else is %XX of its+ /// UTF-8 bytes), so a save does not depend on the runtime's Uri class (Mono and .NET differ).</summary>+ internal static class SaveText+ {+ static readonly System.Text.UTF8Encoding Strict = new System.Text.UTF8Encoding(false, true);++ static bool Unreserved(byte b) => (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') || b == '-' || b == '.' || b == '_' || b == '~';++ /// <summary>False for a string that is not valid Unicode text (a lone surrogate), which cannot be saved losslessly.</summary>+ public static bool IsEncodable(string s)+ {+ try { Strict.GetBytes(s); return true; }+ catch (System.Text.EncoderFallbackException) { return false; }+ }++ public static string Escape(string s)+ {+ var sb = new StringBuilder();+ foreach (var b in Strict.GetBytes(s))+ {+ if (Unreserved(b)) sb.Append((char)b);+ else sb.Append('%').Append("0123456789ABCDEF"[b >> 4]).Append("0123456789ABCDEF"[b & 15]);+ }+ return sb.ToString();+ }++ /// <summary>Null when the text has a malformed escape or is not valid UTF-8.</summary>+ public static string? Unescape(string s)+ {+ var bytes = new List<byte>();+ for (int i = 0; i < s.Length; i++)+ {+ if (s[i] != '%') { if (s[i] > 127) return null; bytes.Add((byte)s[i]); continue; }+ if (i + 2 >= s.Length) return null;+ int hi = HexVal(s[i + 1]), lo = HexVal(s[i + 2]);+ if (hi < 0 || lo < 0) return null;+ bytes.Add((byte)(hi * 16 + lo));+ i += 2;+ }+ try { return Strict.GetString(bytes.ToArray()); }+ catch (System.Text.DecoderFallbackException) { return null; }+ }++ static int HexVal(char c) => c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1;+ }}diff --git a/sim/Statecraft.Sim/Simulation.cs b/sim/Statecraft.Sim/Simulation.csindex a615170d2..f67099a08 100644--- a/sim/Statecraft.Sim/Simulation.cs+++ b/sim/Statecraft.Sim/Simulation.cs@@ -31,6 +31,7 @@ namespace Statecraft.Simif (state == null) throw new ArgumentNullException(nameof(state));if (commands == null) throw new ArgumentNullException(nameof(commands));if (commands.Any(x => x == null)) throw new ArgumentException("Commands cannot contain null.", nameof(commands));+ CommandText.Validate(commands);var s = state.Clone();var why = new List<Cause>();