using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json.Linq;
namespace XFEWarframe.Core.Data;
/// <summary>Exact settlement responses, without keeping dozens of expanded inventory snapshots in every transaction.</summary>
public static class MissionReceipts
{
private const int MinimumLength = 16 * 1024;
private const int MaximumLength = 128 * 1024 * 1024;
internal const string EncodingKey = "responseBrotliV1";
public static JObject Capture(string key, ApiResponse response)
{
var receipt = new JObject { ["key"] = key };
if (!Compress(receipt, response.Body)) receipt["response"] = Wire.ReadObject(response.Body);
return receipt;
}
public static ApiResponse Replay(JObject receipt, Func<string, byte[]>? archive = null)
{
if (receipt["response"] is JObject legacy) return ApiResponse.Json(legacy);
if (receipt[EncodingKey] is not JObject encoded) throw new InvalidDataException("Missing mission replay response.");
var length = encoded.Value<int>("length");
if (length is < MinimumLength or > MaximumLength) throw new InvalidDataException("Invalid mission replay length.");
var payload = encoded.Value<string>("blob") is { } blob
? archive?.Invoke(blob) ?? throw new InvalidDataException("Mission replay archive is unavailable.")
: Convert.FromBase64String(encoded.Value<string>("data") ?? "");
using var input = new MemoryStream(payload);
using var decoder = new BrotliStream(input, CompressionMode.Decompress);
var bytes = new byte[length];
decoder.ReadExactly(bytes);
if (decoder.ReadByte() != -1 || Convert.ToHexStringLower(SHA256.HashData(bytes)) != encoded.Value<string>("sha256"))
throw new InvalidDataException("Damaged mission replay response.");
return new(200, Encoding.UTF8.GetString(bytes));
}
// Runs once when opening an older store. Disk replacement still uses the normal
// atomic transaction, with the previous uncompressed file retained as .bak.
public static bool CompactLegacy(JObject state)
{
var changed = false;
foreach (var account in (state["accounts"] as JObject ?? new()).Properties().Select(p => p.Value).OfType<JObject>())
foreach (var receipt in (account["MissionReceipts"] as JArray ?? []).OfType<JObject>())
if (receipt["response"] is JObject response && Compress(receipt, ApiResponse.Json(response).Body))
{ receipt.Remove("response"); changed = true; }
return changed;
}
private static bool Compress(JObject receipt, string json)
{
if (json.Length < MinimumLength || Encoding.UTF8.GetByteCount(json) > MaximumLength) return false;
var bytes = Encoding.UTF8.GetBytes(json);
using var output = new MemoryStream();
using (var encoder = new BrotliStream(output, CompressionLevel.Optimal, leaveOpen: true)) encoder.Write(bytes);
// Leave small/incompressible responses alone; never make the store larger.
if (output.Length * 4 / 3 + 256 >= bytes.Length) return false;
receipt[EncodingKey] = new JObject { ["length"] = bytes.Length,
["sha256"] = Convert.ToHexStringLower(SHA256.HashData(bytes)), ["data"] = Convert.ToBase64String(output.GetBuffer(), 0, checked((int)output.Length)) };
return true;
}
}
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json.Linq;
namespace XFEWarframe.Core.Data;
/// <summary>Exact settlement responses, without keeping dozens of expanded inventory snapshots in every transaction.</summary>
public static class MissionReceipts
{
private const int MinimumLength = 16 * 1024;
private const int MaximumLength = 128 * 1024 * 1024;
internal const string EncodingKey = "responseBrotliV1";
public static JObject Capture(string key, ApiResponse response)
{
var receipt = new JObject { ["key"] = key };
if (!Compress(receipt, response.Body)) receipt["response"] = Wire.ReadObject(response.Body);
return receipt;
}
public static ApiResponse Replay(JObject receipt, Func<string, byte[]>? archive = null)
{
if (receipt["response"] is JObject legacy) return ApiResponse.Json(legacy);
if (receipt[EncodingKey] is not JObject encoded) throw new InvalidDataException("Missing mission replay response.");
var length = encoded.Value<int>("length");
if (length is < MinimumLength or > MaximumLength) throw new InvalidDataException("Invalid mission replay length.");
var payload = encoded.Value<string>("blob") is { } blob
? archive?.Invoke(blob) ?? throw new InvalidDataException("Mission replay archive is unavailable.")
: Convert.FromBase64String(encoded.Value<string>("data") ?? "");
using var input = new MemoryStream(payload);
using var decoder = new BrotliStream(input, CompressionMode.Decompress);
var bytes = new byte[length];
decoder.ReadExactly(bytes);
if (decoder.ReadByte() != -1 || Convert.ToHexStringLower(SHA256.HashData(bytes)) != encoded.Value<string>("sha256"))
throw new InvalidDataException("Damaged mission replay response.");
return new(200, Encoding.UTF8.GetString(bytes));
}
// Runs once when opening an older store. Disk replacement still uses the normal
// atomic transaction, with the previous uncompressed file retained as .bak.
public static bool CompactLegacy(JObject state)
{
var changed = false;
foreach (var account in (state["accounts"] as JObject ?? new()).Properties().Select(p => p.Value).OfType<JObject>())
foreach (var receipt in (account["MissionReceipts"] as JArray ?? []).OfType<JObject>())
if (receipt["response"] is JObject response && Compress(receipt, ApiResponse.Json(response).Body))
{ receipt.Remove("response"); changed = true; }
return changed;
}
private static bool Compress(JObject receipt, string json)
{
if (json.Length < MinimumLength || Encoding.UTF8.GetByteCount(json) > MaximumLength) return false;
var bytes = Encoding.UTF8.GetBytes(json);
using var output = new MemoryStream();
using (var encoder = new BrotliStream(output, CompressionLevel.Optimal, leaveOpen: true)) encoder.Write(bytes);
// Leave small/incompressible responses alone; never make the store larger.
if (output.Length * 4 / 3 + 256 >= bytes.Length) return false;
receipt[EncodingKey] = new JObject { ["length"] = bytes.Length,
["sha256"] = Convert.ToHexStringLower(SHA256.HashData(bytes)), ["data"] = Convert.ToBase64String(output.GetBuffer(), 0, checked((int)output.Length)) };
return true;
}
}