// Chainvara server SDK for .NET 6+ — https://www.chainvara.com/docs // // One file, no package beyond the base library (HttpClient, System.Text.Json). Server side only: never ship a secret // API key to a browser or an app. // // var cv = new Chainvara(Environment.GetEnvironmentVariable("CHAINVARA_API_KEY")!); // var wallet = await cv.Wallets.CreateAsync(new { network = "base-sepolia", label = "Treasury" }); // var t = await cv.Transfers.CreateAsync(new { wallet_id = (string)wallet["id"]!, asset = "ETH", amount = "0.01", destination = "0x…" }); // await cv.Transfers.WaitAsync((string)t["id"]!); // // // Webhooks: pass the RAW body, exactly as received. // var evt = Chainvara.VerifyWebhook(rawBody, request.Headers["fos-signature"], webhookSecret); // // Every POST carries an Idempotency-Key, so a retry never acts twice. Responses are System.Text.Json.Nodes.JsonNode. #nullable enable using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net.Http; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace ChainvaraSdk { /// API or transport error: Status 0 for network errors, a stable machine Code, the RequestId for support. public sealed class ChainvaraException : Exception { public int Status { get; } public string Type { get; } public string Code { get; } public string? RequestId { get; } public ChainvaraException(string message, int status, string type, string code, string? requestId) : base(message) { Status = status; Type = type; Code = code; RequestId = requestId; } } /// Client for the Chainvara REST API (/api/v1). public sealed class Chainvara { public const string Version = "0.1.0"; public static readonly IReadOnlyList FinalTransferStatuses = new[] { "confirmed", "failed", "rejected", "blocked", "canceled", "expired" }; private static readonly Regex KeyPattern = new Regex("^fos_(test|live)_[0-9a-f]{12}_[0-9a-f]{64}$", RegexOptions.CultureInvariant); private readonly string _key; private readonly string _base; private readonly int _maxRetries; private readonly HttpClient _http; /// "test" or "live", from the key. public string Mode { get; } public WalletsApi Wallets { get; } public TransfersApi Transfers { get; } public OperationsApi Operations { get; } public PayoutsApi Payouts { get; } public EventsApi Events { get; } public VaultsApi Vaults { get; } public PolicyApi Policy { get; } public AddressesApi Addresses { get; } public ReportsApi Reports { get; } public AuditApi Audit { get; } public DepositAddressesApi DepositAddresses { get; } public EmbeddedApi Embedded { get; } public NetworkApi Network { get; } public NetworksApi Networks { get; } public ListApi Payees { get; } public ListApi Prices { get; } public ListApi Tokens { get; } public SwapApi Swap { get; } public ScreeningApi Screening { get; } public SecurityApi Security { get; } public AddressProofsApi AddressProofs { get; } public TravelRuleApi TravelRule { get; } public ReservesApi Reserves { get; } public Chainvara(string apiKey, string baseUrl = "https://www.chainvara.com", int maxRetries = 2, TimeSpan? timeout = null, HttpMessageHandler? handler = null) { var m = KeyPattern.Match(apiKey ?? ""); if (!m.Success) throw new ArgumentException("Chainvara: invalid API key. Expected fos_test_… or fos_live_… (create one in Developers)."); Mode = m.Groups[1].Value; _key = apiKey!; _base = baseUrl.TrimEnd('/') + "/api/v1"; _maxRetries = maxRetries; _http = new HttpClient(handler ?? new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = timeout ?? TimeSpan.FromSeconds(30) }; Wallets = new WalletsApi(this); Transfers = new TransfersApi(this); Operations = new OperationsApi(this); Payouts = new PayoutsApi(this); Events = new EventsApi(this); Vaults = new VaultsApi(this); Policy = new PolicyApi(this); Addresses = new AddressesApi(this); Reports = new ReportsApi(this); Audit = new AuditApi(this); DepositAddresses = new DepositAddressesApi(this); Embedded = new EmbeddedApi(this); Network = new NetworkApi(this); Networks = new NetworksApi(this); Payees = new ListApi(this, "/payees"); Prices = new ListApi(this, "/prices"); Tokens = new ListApi(this, "/tokens"); Swap = new SwapApi(this); Screening = new ScreeningApi(this); Security = new SecurityApi(this); AddressProofs = new AddressProofsApi(this); TravelRule = new TravelRuleApi(this); Reserves = new ReservesApi(this); } public override string ToString() => $"Chainvara(mode={Mode})"; // never the key internal static string Seg(string s) => Uri.EscapeDataString(s); /// Any endpoint: GET or POST /api/v1 + path. body: an anonymous object, a dictionary or a JsonNode. public async Task RequestAsync(string method, string path, object? body = null, IDictionary? query = null, string? idempotencyKey = null, CancellationToken ct = default) { var url = new StringBuilder(_base).Append(path); if (query != null) { var sep = "?"; foreach (var kv in query) { if (kv.Value == null) continue; var v = kv.Value is bool b ? (b ? "true" : "false") : Convert.ToString(kv.Value, CultureInfo.InvariantCulture) ?? ""; url.Append(sep).Append(Uri.EscapeDataString(kv.Key)).Append('=').Append(Uri.EscapeDataString(v)); sep = "&"; } } var idem = method == "POST" ? (idempotencyKey ?? "sdk_" + Guid.NewGuid()) : null; var payload = method == "POST" ? JsonSerializer.Serialize(body ?? new Dictionary()) : null; for (var attempt = 0; ; attempt++) { using var req = new HttpRequestMessage(new HttpMethod(method), url.ToString()); req.Headers.TryAddWithoutValidation("authorization", "Bearer " + _key); req.Headers.TryAddWithoutValidation("accept", "application/json"); req.Headers.TryAddWithoutValidation("user-agent", "chainvara-dotnet/" + Version); if (payload != null) { req.Headers.TryAddWithoutValidation("idempotency-key", idem); req.Content = new StringContent(payload, Encoding.UTF8, "application/json"); } HttpResponseMessage? res = null; Exception? netErr = null; try { res = await _http.SendAsync(req, ct).ConfigureAwait(false); } catch (HttpRequestException e) { netErr = e; } catch (TaskCanceledException e) when (!ct.IsCancellationRequested) { netErr = e; } using (res) { var status = res == null ? 0 : (int)res.StatusCode; if ((netErr != null || status == 429 || status >= 500) && attempt < _maxRetries) { var ra = res?.Headers.RetryAfter?.Delta; var wait = ra.HasValue ? (ra.Value > TimeSpan.FromSeconds(60) ? TimeSpan.FromSeconds(60) : ra.Value) : TimeSpan.FromMilliseconds(500 * Math.Pow(2, attempt) + Random.Shared.Next(250)); await Task.Delay(wait, ct).ConfigureAwait(false); continue; } if (netErr != null) throw new ChainvaraException("Network error: " + netErr.Message, 0, "connection_error", "network_error", null); var text = await res!.Content.ReadAsStringAsync(ct).ConfigureAwait(false); var requestId = res.Headers.TryGetValues("request-id", out var ids) ? ids.FirstOrDefault() : null; JsonNode? json = null; try { json = string.IsNullOrEmpty(text) ? null : JsonNode.Parse(text); } catch (JsonException) { json = null; } if (status >= 400) { var err = json?["error"] as JsonObject; string Str(string k, string? fallback) => err?[k] is JsonValue v && v.TryGetValue(out var s) && s.Length > 0 ? s : fallback ?? ""; throw new ChainvaraException(Str("message", "HTTP " + status), status, Str("type", "api_error"), Str("code", "http_error"), err?["request_id"] is JsonValue r && r.TryGetValue(out var rid) ? rid : requestId); } return json; } } } internal async Task ObjAsync(string method, string path, object? body = null, IDictionary? query = null, string? idem = null, CancellationToken ct = default) => await RequestAsync(method, path, body, query, idem, ct).ConfigureAwait(false) as JsonObject ?? new JsonObject(); /// A query without null values: Q(("limit", 50), ("tag", null)). public static Dictionary Q(params (string Key, object? Value)[] kv) => kv.Where(x => x.Value != null).ToDictionary(x => x.Key, x => x.Value); // ---------------------------------------------------------------------------------------------- resources public sealed class WalletsApi { private readonly Chainvara _c; internal WalletsApi(Chainvara c) => _c = c; /// { network, label?, external_user_id?, kind?, key_mode? (single | split | mpc | mpc_backup) }. public Task CreateAsync(object p, string? idempotencyKey = null) => _c.ObjAsync("POST", "/wallets", p, null, idempotencyKey); public Task ListAsync(IDictionary? query = null) => _c.ObjAsync("GET", "/wallets", null, query); public Task GetAsync(string id) => _c.ObjAsync("GET", "/wallets/" + Seg(id)); public Task BalancesAsync(string id, bool refresh = false) => _c.ObjAsync("GET", $"/wallets/{Seg(id)}/balances", null, refresh ? Q(("refresh", true)) : null); public Task TransactionsAsync(string id, int? limit = null) => _c.ObjAsync("GET", $"/wallets/{Seg(id)}/transactions", null, Q(("limit", limit))); /// Token approvals of an EVM wallet that can still be used (ERC-20, NFT operators, Permit2), riskiest first. public Task AllowancesAsync(string id) => _c.ObjAsync("GET", $"/wallets/{Seg(id)}/allowances"); /// Requests the revocation of one approval (kind: erc20 | nft_operator | permit2). public Task RevokeAllowanceAsync(string id, string kind, string token, string spender, string? idempotencyKey = null) => _c.ObjAsync("POST", $"/wallets/{Seg(id)}/allowances", new { kind, token, spender }, null, idempotencyKey); /// One wallet per end user and network: created on first call, returned afterwards (the server deduplicates). public Task ForUserAsync(string externalUserId, string network, string? label = null) => _c.ObjAsync("POST", "/wallets", Q(("network", network), ("external_user_id", externalUserId), ("label", label))); /// Renews both shares of an MPC wallet with your co-signer (same address; older shares stop working). public Task RefreshKeysAsync(string id) => _c.ObjAsync("POST", $"/wallets/{Seg(id)}/refresh-keys", new { }); } public sealed class TransfersApi { private readonly Chainvara _c; internal TransfersApi(Chainvara c) => _c = c; /// { wallet_id, asset, amount, destination, note?, fee_level?, external_id?, tags?, travel_rule? }. public Task CreateAsync(object p, string? idempotencyKey = null) => _c.ObjAsync("POST", "/transfers", p, null, idempotencyKey); /// The policy decision a transfer would get, without creating it. public Task PreviewAsync(object p) => _c.ObjAsync("POST", "/transfers/preview", p); /// Newest first; when has_more, pass next_cursor as starting_after. Filters: status, wallet_id, external_id, tag, limit. public Task ListAsync(IDictionary? query = null) => _c.ObjAsync("GET", "/transfers", null, query); public Task GetAsync(string id) => _c.ObjAsync("GET", "/transfers/" + Seg(id)); public Task CancelAsync(string id) => _c.ObjAsync("POST", $"/transfers/{Seg(id)}/cancel"); public Task SpeedUpAsync(string id) => _c.ObjAsync("POST", $"/transfers/{Seg(id)}/speed-up"); public Task CancelOnchainAsync(string id) => _c.ObjAsync("POST", $"/transfers/{Seg(id)}/cancel-onchain"); /// Replaces the accounting tags (never part of what was approved or signed). public Task SetTagsAsync(string id, IEnumerable tags) => _c.ObjAsync("POST", $"/transfers/{Seg(id)}/tags", new { tags = tags.ToArray() }); /// Every transfer matching the filters, newest first, page after page. public async IAsyncEnumerable IterateAsync(IDictionary? filters = null, [EnumeratorCancellation] CancellationToken ct = default) { string? after = null; while (true) { var q = new Dictionary(filters ?? new Dictionary()) { ["limit"] = 200 }; if (after != null) q["starting_after"] = after; var page = await _c.ObjAsync("GET", "/transfers", null, q, null, ct).ConfigureAwait(false); if (page["data"] is JsonArray data) foreach (var x in data) if (x is JsonObject o) yield return o; after = page["next_cursor"] is JsonValue v && v.TryGetValue(out var s) ? s : null; if (!(page["has_more"] is JsonValue hm && hm.TryGetValue(out var more) && more) || after == null) yield break; } } /// Polls until the transfer reaches a final status (or until(t) is true). public async Task WaitAsync(string id, TimeSpan? interval = null, TimeSpan? timeout = null, Func? until = null, CancellationToken ct = default) { var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromMinutes(10)); while (true) { var t = await _c.ObjAsync("GET", "/transfers/" + Seg(id), null, null, null, ct).ConfigureAwait(false); var status = t["status"] is JsonValue sv && sv.TryGetValue(out var st) ? st : ""; if (until != null ? until(t) : FinalTransferStatuses.Contains(status)) return t; if (DateTime.UtcNow > deadline) throw new ChainvaraException($"Transfer {id} still {status} after timeout.", 408, "timeout", "wait_timeout", null); await Task.Delay(interval ?? TimeSpan.FromSeconds(5), ct).ConfigureAwait(false); } } } public sealed class OperationsApi { private readonly Chainvara _c; internal OperationsApi(Chainvara c) => _c = c; /// { wallet_id, type, … }: tokens, swaps, staking, CCTP, contract calls (contracts:write) — same policy and signing as transfers. public Task CreateAsync(object p, string? idempotencyKey = null) => _c.ObjAsync("POST", "/operations", p, null, idempotencyKey); public Task ListAsync(int? limit = null) => _c.ObjAsync("GET", "/operations", null, Q(("limit", limit))); } public sealed class PayoutsApi { private readonly Chainvara _c; internal PayoutsApi(Chainvara c) => _c = c; /// { wallet_id, asset, items: [{ destination, amount, reference? }], reference? } — up to 500 lines. public Task CreateAsync(object p, string? idempotencyKey = null) => _c.ObjAsync("POST", "/payouts", p, null, idempotencyKey); public Task GetAsync(string id) => _c.ObjAsync("GET", "/payouts/" + Seg(id)); public Task ListAsync(int? limit = null) => _c.ObjAsync("GET", "/payouts", null, Q(("limit", limit))); } public sealed class EventsApi { private readonly Chainvara _c; internal EventsApi(Chainvara c) => _c = c; /// after: every event after this seq, oldest first, without gaps (next_after for the next call). public Task ListAsync(long? after = null, string? type = null, int? limit = null) => _c.ObjAsync("GET", "/events", null, Q(("after", after), ("type", type), ("limit", limit))); } public sealed class VaultsApi { private readonly Chainvara _c; internal VaultsApi(Chainvara c) => _c = c; public Task ListAsync() => _c.ObjAsync("GET", "/vaults"); public Task CreateAsync(string name, string? description = null) => _c.ObjAsync("POST", "/vaults", description == null ? new { name } : (object)new { name, description }); /// Stops every outflow of the vault until it is unfrozen in the console (never by API). public Task FreezeAsync(string id, string reason) => _c.ObjAsync("POST", $"/vaults/{Seg(id)}/freeze", new { reason }); /// Moves a wallet into a vault; null takes it out of its vault. public Task AssignWalletAsync(string walletId, string? vaultId) => _c.ObjAsync("POST", $"/wallets/{Seg(walletId)}/vault", new Dictionary { ["vault_id"] = vaultId }); } public sealed class PolicyApi { private readonly Chainvara _c; internal PolicyApi(Chainvara c) => _c = c; public Task GetAsync() => _c.ObjAsync("GET", "/policy"); /// What a candidate policy would change on the last 200 requests (nothing is published). public Task ImpactAsync(object candidate) => _c.ObjAsync("POST", "/policy/impact", new { policy = candidate }); } public sealed class AddressesApi { private readonly Chainvara _c; internal AddressesApi(Chainvara c) => _c = c; public Task ListAsync() => _c.ObjAsync("GET", "/addresses"); /// { network, address, label, note?, beneficiary? } (scope addresses:write; screened, cooldown applies). public Task AddAsync(object p) => _c.ObjAsync("POST", "/addresses", p); public Task RevokeAsync(string id) => _c.ObjAsync("POST", $"/addresses/{Seg(id)}/revoke"); } public sealed class ReportsApi { private readonly Chainvara _c; internal ReportsApi(Chainvara c) => _c = c; public Task LedgerAsync(string? from = null, string? to = null) => _c.ObjAsync("GET", "/reports/ledger", null, Q(("from", from), ("to", to))); /// Realized and unrealized gains (method: fifo | average). public Task GainsAsync(string? from = null, string? to = null, string? method = null) => _c.ObjAsync("GET", "/reports/gains", null, Q(("from", from), ("to", to), ("method", method))); } /// Audit trail for a SIEM (scope audit:read): poll with after = the last seq received; VerifyAsync recomputes the chain. public sealed class AuditApi { private readonly Chainvara _c; internal AuditApi(Chainvara c) => _c = c; public Task ListAsync(long? after = null, string? since = null, string? action = null, int? limit = null) => _c.ObjAsync("GET", "/audit", null, Q(("after", after), ("since", since), ("action", action), ("limit", limit))); public Task VerifyAsync() => _c.ObjAsync("GET", "/audit/verify"); } public sealed class DepositAddressesApi { private readonly Chainvara _c; internal DepositAddressesApi(Chainvara c) => _c = c; /// Every deposit address of one of your users (one wallet per network); calling again returns the same ones. networks null: defaults. public Task CreateAsync(string externalUserId, IEnumerable? networks = null, string? label = null) => _c.ObjAsync("POST", "/deposit-addresses", Q(("external_user_id", externalUserId), ("networks", networks?.ToArray()), ("label", label))); } /// Embedded wallets: relay the device SDK's calls from your backend, with external_user_id from your own session. public sealed class EmbeddedApi { private static readonly string[] Paths = { "/embedded/wallets", "/embedded/sign", "/embedded/backup" }; private readonly Chainvara _c; internal EmbeddedApi(Chainvara c) => _c = c; public Task RelayAsync(string path, object body) { if (!Paths.Contains(path)) throw new ArgumentException("Unknown embedded path."); return _c.ObjAsync("POST", path, body); } } /// Chainvara network: payment requests and bilateral net settlement with connected organizations. public sealed class NetworkApi { private static readonly string[] Answers = { "confirm", "dispute", "cancel" }; private readonly Chainvara _c; internal NetworkApi(Chainvara c) => _c = c; /// { to: "@handle", network, asset, amount, reference, note?, ttl_days? }. public Task RequestPaymentAsync(object p, string? idempotencyKey = null) => _c.ObjAsync("POST", "/network/requests", p, null, idempotencyKey); public Task RequestsAsync(string? direction = null, string? status = null) => _c.ObjAsync("GET", "/network/requests", null, Q(("direction", direction), ("status", status))); /// Pays an incoming request from one of your wallets: a normal transfer under your policy and approvals. public Task PayRequestAsync(string requestId, string walletId, string? idempotencyKey = null) => _c.ObjAsync("POST", $"/network/requests/{Seg(requestId)}/pay", new { wallet_id = walletId }, null, idempotencyKey); public Task CloseRequestAsync(string requestId) => _c.ObjAsync("POST", $"/network/requests/{Seg(requestId)}/close", new { }); /// { counterparty, direction: they_owe | we_owe, network, asset, amount, reference }: counts once the counterparty confirms. public Task RecordObligationAsync(object p, string? idempotencyKey = null) => _c.ObjAsync("POST", "/network/obligations", p, null, idempotencyKey); public Task ObligationsAsync() => _c.ObjAsync("GET", "/network/obligations"); /// action: confirm, dispute or cancel. public Task AnswerObligationAsync(string obligationId, string action) { if (!Answers.Contains(action)) throw new ArgumentException("action must be confirm, dispute or cancel."); return _c.ObjAsync("POST", $"/network/obligations/{Seg(obligationId)}/{action}", new { }); } /// Net of confirmed obligations per counterparty and asset. public Task PositionsAsync() => _c.ObjAsync("GET", "/network/positions"); /// The net debtor settles the whole position with one transfer. public Task SettleAsync(string counterparty, string assetId, string walletId, string? idempotencyKey = null) => _c.ObjAsync("POST", "/network/settlements", new { counterparty, asset_id = assetId, wallet_id = walletId }, null, idempotencyKey); public Task SettlementsAsync() => _c.ObjAsync("GET", "/network/settlements"); } public sealed class NetworksApi { private readonly Chainvara _c; internal NetworksApi(Chainvara c) => _c = c; public Task ListAsync() => _c.ObjAsync("GET", "/networks"); /// Current fee estimates for a typical transfer at each fee_level (low, medium, high). public Task FeesAsync(string network) => _c.ObjAsync("GET", $"/networks/{Seg(network)}/fees"); } /// A plain list: payees (connected organizations you pay with "@handle"), prices, issued tokens. public sealed class ListApi { private readonly Chainvara _c; private readonly string _path; internal ListApi(Chainvara c, string path) { _c = c; _path = path; } public Task ListAsync() => _c.ObjAsync("GET", _path); } public sealed class SwapApi { private readonly Chainvara _c; internal SwapApi(Chainvara c) => _c = c; /// Informational quote; an operation of type "swap" swaps with a guaranteed minimum. public Task QuoteAsync(string walletId, string sell, string buy, string amount, int? slippageBps = null) => _c.ObjAsync("GET", "/swap/quote", null, Q(("wallet_id", walletId), ("sell", sell), ("buy", buy), ("amount", amount), ("slippage_bps", slippageBps))); } public sealed class ScreeningApi { private readonly Chainvara _c; internal ScreeningApi(Chainvara c) => _c = c; /// Sanctions screening (OFAC SDN) of any address. public Task CheckAsync(string network, string address) => _c.ObjAsync("GET", "/screening", null, Q(("network", network), ("address", address))); /// Screening of the senders of your deposits (status: clear, flagged, released, reported; null for all). public Task InboundAsync(string? status = null, int? limit = null) => _c.ObjAsync("GET", "/screening/inbound", null, Q(("status", status), ("limit", limit))); } public sealed class SecurityApi { private readonly Chainvara _c; internal SecurityApi(Chainvara c) => _c = c; /// Score 0-100 and every check with its fix. public Task PostureAsync() => _c.ObjAsync("GET", "/security"); } /// Self-hosted wallet ownership proofs: CreateAsync returns the message and the link (url) to send the owner. public sealed class AddressProofsApi { private readonly Chainvara _c; internal AddressProofsApi(Chainvara c) => _c = c; public Task CreateAsync(string network, string address, string label) => _c.ObjAsync("POST", "/address-proofs", new { network, address, label }); public Task ListAsync() => _c.ObjAsync("GET", "/address-proofs"); public Task SubmitSignatureAsync(string id, string signature) => _c.ObjAsync("POST", $"/address-proofs/{Seg(id)}/signature", new { signature }); } public sealed class TravelRuleApi { private readonly Chainvara _c; internal TravelRuleApi(Chainvara c) => _c = c; /// Messages exchanged with organizations on the Chainvara network (direction: incoming, outgoing or null). public Task MessagesAsync(string? direction = null) => _c.ObjAsync("GET", "/travel-rule/messages", null, Q(("direction", direction))); /// As beneficiary: confirm you received the originator information. public Task AcknowledgeAsync(string messageId) => _c.ObjAsync("POST", $"/travel-rule/messages/{Seg(messageId)}/acknowledge", new { }); } /// Proof of reserves (scope reserves:write). public sealed class ReservesApi { private readonly Chainvara _c; internal ReservesApi(Chainvara c) => _c = c; /// customers: [{ user_id, balances: { "BTC": "0.25" } }]; commits them in a Merkle sum tree and reads your reserves. public Task CreateSnapshotAsync(object customers, string? idempotencyKey = null) => _c.ObjAsync("POST", "/reserves/snapshots", new { customers }, null, idempotencyKey); /// One customer's inclusion proof, to give to that customer. public Task ProofAsync(string snapshotId, string userId) => _c.ObjAsync("GET", $"/reserves/snapshots/{Seg(snapshotId)}/proof", null, Q(("user_id", userId))); } // ---------------------------------------------------------------------------------------------- webhooks, co-signer private static string HmacHex(string secret, string data) { using var h = new HMACSHA256(Encoding.UTF8.GetBytes(secret)); return Convert.ToHexString(h.ComputeHash(Encoding.UTF8.GetBytes(data))).ToLowerInvariant(); } /// fos-signature header for a body: t=<unix>,v1=<hex HMAC-SHA256 of "t.body">. For testing your endpoint. public static string SignWebhookPayload(string rawBody, string secret, long? timestamp = null) { var t = timestamp ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds(); return $"t={t},v1={HmacHex(secret, $"{t}.{rawBody}")}"; } /// /// Checks the fos-signature of a webhook (the RAW body, exactly as received) and returns the event. During a secret /// rotation the header carries one v1 per secret: any of them may match. /// public static JsonObject VerifyWebhook(string rawBody, string? signatureHeader, string secret, int toleranceSeconds = 300, long? now = null) { if (string.IsNullOrEmpty(signatureHeader)) throw new ChainvaraException("Missing fos-signature header.", 400, "signature_error", "missing_signature", null); long? t = null; var v1s = new List(); foreach (var part in signatureHeader.Split(',')) { var i = part.IndexOf('='); if (i < 0) continue; var k = part.Substring(0, i).Trim(); var v = part.Substring(i + 1).Trim(); if (k == "t" && long.TryParse(v, NumberStyles.None, CultureInfo.InvariantCulture, out var ts)) t = ts; if (k == "v1" && Regex.IsMatch(v, "^[0-9a-f]{64}$")) v1s.Add(v); } if (t == null || v1s.Count == 0) throw new ChainvaraException("Malformed fos-signature header.", 400, "signature_error", "malformed_signature", null); var current = now ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds(); if (Math.Abs(current - t.Value) > toleranceSeconds) throw new ChainvaraException("Webhook signature timestamp is outside the tolerance window.", 400, "signature_error", "timestamp_out_of_range", null); var expected = Encoding.ASCII.GetBytes(HmacHex(secret, $"{t}.{rawBody}")); var ok = false; foreach (var v in v1s) ok |= CryptographicOperations.FixedTimeEquals(expected, Encoding.ASCII.GetBytes(v)); if (!ok) throw new ChainvaraException("Webhook signature does not match.", 400, "signature_error", "invalid_signature", null); return JsonNode.Parse(rawBody) as JsonObject ?? throw new ChainvaraException("Webhook body is not a JSON object.", 400, "signature_error", "unexpected_payload", null); } /// Verifies an API co-signer request (transfer.sign_request) and returns it. public static JsonObject VerifyCosignerRequest(string rawBody, string? signatureHeader, string secret) { var req = VerifyWebhook(rawBody, signatureHeader, secret); if (!(req["type"] is JsonValue tv && tv.TryGetValue(out var type) && type == "transfer.sign_request")) throw new ChainvaraException("Not a co-signer request.", 400, "signature_error", "unexpected_type", null); return req; } /// Signed answer (HTTP 200) to a co-signer request: (body, fos-signature header). action: approve | reject. public static (string Body, string Signature) CosignerResponse(JsonObject req, string action, string secret, string? reason = null) { if (action != "approve" && action != "reject") throw new ArgumentException("action must be approve or reject"); var p = new JsonObject { ["request_id"] = req["request_id"]?.GetValue(), ["transfer_id"] = req["data"]?["id"]?.GetValue(), ["action"] = action }; if (reason != null) p["reason"] = reason; var body = p.ToJsonString(); return (body, SignWebhookPayload(body, secret)); } } }