Files
opengenesislinkserver/addons/SysApi/SysApiNvMoney.cs
T

180 lines
8.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: LicenseRef-OpenGenesisLINK-EULA
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using NexVerse.Core.Economy;
using NexVerse.Server.Api;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenGenesisLINK.SysApi;
/// <summary>
/// Security boundary for administrative NV$ credits. Reuses the live,
/// MariaDB-backed NexVerse double-entry ledger; never maintains a second balance.
/// No payment-provider event can independently authorize a credit.
/// </summary>
public sealed class SysApiNvMoney
{
private static readonly Guid CounterpartyId =
Guid.Parse("4e565324-5359-5341-5049-444d00000001");
private readonly IUserAccountService _accounts;
private readonly Func<NexEconomyService?> _getEconomy;
private readonly byte[] _portalToken;
private readonly object _payoutGate = new();
public bool AdminEnabled { get; }
public bool PortalEnabled { get; }
public int MaxNv { get; }
public const int NvPerEuro = 100;
public SysApiNvMoney(
IUserAccountService accounts,
bool adminEnabled, bool portalEnabled, int maxNv, string portalToken,
Func<NexEconomyService?>? getEconomy = null)
{
_accounts = accounts ?? throw new ArgumentNullException(nameof(accounts));
if (maxNv is < 1 or > 1000000) throw new ArgumentOutOfRangeException(nameof(maxNv));
_getEconomy = getEconomy is not null ? getEconomy :
() => NexEconomyConnector.Current?.Enabled == true
? NexEconomyConnector.Current.Economy
: null;
AdminEnabled = adminEnabled;
MaxNv = maxNv;
if (portalToken.Length != 0 &&
(portalToken.Length is < 64 or > 128 || !portalToken.All(Uri.IsHexDigit)))
throw new ArgumentException("Portal money token must be 64–128 hex characters");
_portalToken = Encoding.ASCII.GetBytes(portalToken);
PortalEnabled = portalEnabled && _portalToken.Length >= 64;
if (portalEnabled && !PortalEnabled)
throw new InvalidOperationException("Dedicated portal payout credential is missing");
}
public bool ValidPortalCredential(HttpListenerRequest request)
{
if (!PortalEnabled) return false;
string authorization = request.Headers["Authorization"] ?? "";
if (!authorization.StartsWith("Bearer ", StringComparison.Ordinal) ||
authorization.Length != _portalToken.Length + 7) return false;
return CryptographicOperations.FixedTimeEquals(
Encoding.ASCII.GetBytes(authorization[7..]), _portalToken);
}
public object Status() => new {
enabled = AdminEnabled,
portalEnabled = PortalEnabled,
ledgerAvailable = _getEconomy() is not null,
maxPayoutNv = MaxNv,
nvPerEuro = NvPerEuro,
euroCurrency = "EUR",
settlementProviders = new[] {"stripe: not configured", "paypal: not configured"},
paymentSettlementEnabled = false
};
public static long EuroCentsToNv(long euroCents)
{
// Exactly 100 NV$ per EUR. No floating-point arithmetic.
if (euroCents <= 0 || euroCents > 100000000)
throw new ArgumentOutOfRangeException(nameof(euroCents));
return euroCents;
}
public NvPayoutReceipt Pay(NvPayoutInput? input, string actor, bool portal)
{
if (portal ? !PortalEnabled : !AdminEnabled)
throw new InvalidOperationException("NV$ payout feature is disabled");
if (input is null ||
!Guid.TryParse(input.AvatarId, out Guid residentId) ||
residentId == Guid.Empty ||
!Guid.TryParse(input.RequestId, out Guid requestId) ||
requestId == Guid.Empty)
throw new ArgumentException("Valid avatarId and requestId UUIDs required");
if (input.AmountNv is < 1 or > int.MaxValue ||
input.AmountNv > MaxNv)
throw new ArgumentException("NV$ payout amount is outside configured limits");
string reason = (input.Description ?? "").Trim();
if (reason.Length is < 4 or > 120 ||
reason.Any(char.IsControl))
throw new ArgumentException("Transaction description must be 4–120 printable characters");
// A public payment success flag must NEVER be accepted as proof of settled
// funds. Stripe/PayPal adapters require server-side signed-event verification.
if (!string.Equals(input.Source,
portal ? "portal-manual" : "admin-manual",
StringComparison.Ordinal))
throw new ArgumentException("Only explicitly authorized manual payouts are accepted");
string ledgerActor = portal ? "sysapi-portal" : "sysapi-admin:" + actor;
Guid transactionId = TransactionGuid(requestId);
string correlationId = "sysapi-nv-payout-" + requestId.ToString("N");
lock (_payoutGate)
{
NexEconomyService economy = _getEconomy() ??
throw new InvalidOperationException("NV$ durable ledger unavailable");
var account = _accounts.GetUserAccount(UUID.Zero, new UUID(residentId));
if (account is null || !account.LocalToGrid ||
account.PrincipalID.Guid != residentId)
throw new ArgumentException("Avatar must be an existing local grid resident");
// Check existing records first, then verify the ENTIRE immutable
// request identity. Never re-credit on HTTP retries or duplicated
// payment callbacks. The ledger's transaction UUID is unique in SQL.
NexLedgerTransaction? existing = economy.GetTransaction(transactionId);
if (existing != null)
return ValidateExisting(existing, residentId, input.AmountNv,
reason, ledgerActor, correlationId, economy);
economy.EnsureResidentAccount(residentId, account.EffectiveDisplayName);
economy.EnsureSystemAccount(CounterpartyId, "NV$ SYS.API Administration");
NexLedgerAppendResult result = economy.AdministrativeAdjustment(
residentId, CounterpartyId, input.AmountNv,
ledgerActor, reason, correlationId, transactionId);
var verified = ValidateExisting(result.Transaction, residentId,
input.AmountNv, reason, ledgerActor, correlationId, economy);
return new NvPayoutReceipt(verified.TransactionId, residentId,
input.AmountNv, verified.BalanceNv, !result.Created);
}
}
private static NvPayoutReceipt ValidateExisting(
NexLedgerTransaction transaction, Guid residentId, long amount,
string reason, string actor, string correlationId, NexEconomyService economy)
{
if (transaction.Kind != "admin_adjustment" ||
transaction.Postings.Count != 2 ||
transaction.Postings[0].AccountId != CounterpartyId ||
transaction.Postings[0].Side != NexLedgerSide.Debit ||
transaction.Postings[0].AmountMinor != amount ||
transaction.Postings[1].AccountId != residentId ||
transaction.Postings[1].Side != NexLedgerSide.Credit ||
transaction.Postings[1].AmountMinor != amount ||
transaction.CorrelationId != correlationId ||
!transaction.Metadata.TryGetValue("actor", out string? previousActor) ||
!string.Equals(previousActor, actor, StringComparison.Ordinal) ||
!transaction.Metadata.TryGetValue("reason", out string? previousReason) ||
!string.Equals(previousReason, reason, StringComparison.Ordinal))
throw new NexLedgerConflictException("The request ID belongs to a different payout");
return new NvPayoutReceipt(transaction.TransactionId, residentId,
amount, economy.GetBalance(residentId), true);
}
public static Guid TransactionGuid(Guid requestId)
{
byte[] hash = SHA256.HashData(
Encoding.UTF8.GetBytes("ogl-sysapi-nv-grant-v1:" + requestId.ToString("N")));
return new Guid(hash.AsSpan(0, 16));
}
}
public sealed record NvPayoutInput(
string? AvatarId, long AmountNv, string? Description,
string? RequestId, string? Source);
public sealed record NvPayoutReceipt(
Guid TransactionId, Guid AvatarId, long AmountNv,
long BalanceNv, bool Duplicate);