feat(gen1): route registered NexRent rental orders to central NV$ treasury
This commit is contained in:
1 parent
88aaf386ec
commit
a12941aca4
1 file changed
+218
-5
@@ -3,6 +3,7 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
@@ -70,6 +71,14 @@ namespace NexVerse.RegionModules.Economy
|
||||
5;
|
||||
private Timer m_BalanceRefreshTimer;
|
||||
private int m_BalanceRefreshRunning;
|
||||
// Immutable, explicitly registered root-object / owner pairs.
|
||||
private bool m_NexRentTreasuryEnabled;
|
||||
private UUID m_NexRentTreasuryWallet = UUID.Zero;
|
||||
private string m_NexRentTreasuryApiUrl = string.Empty;
|
||||
private string m_NexRentTreasurySecret = string.Empty;
|
||||
private readonly Dictionary<UUID, UUID> m_NexRentTreasuryBindings = new();
|
||||
private Timer m_NexRentTreasuryRetryTimer;
|
||||
private int m_NexRentTreasuryRetryRunning;
|
||||
|
||||
private const int InitialBalanceRetryDelayMilliseconds = 500;
|
||||
private const int InitialBalanceMaxAttempts = 20;
|
||||
@@ -200,6 +209,37 @@ namespace NexVerse.RegionModules.Economy
|
||||
5),
|
||||
0,
|
||||
300);
|
||||
// Treasury opt-in is fail-closed. An object name does not confer trust.
|
||||
m_NexRentTreasuryEnabled = economy.GetBoolean("NexRentTreasuryEnabled", false);
|
||||
if (m_NexRentTreasuryEnabled)
|
||||
{
|
||||
string walletText = economy.GetString("NexRentTreasuryWalletId", "").Trim();
|
||||
m_NexRentTreasuryApiUrl = economy.GetString("NexRentTreasuryApiUrl", "").Trim();
|
||||
m_NexRentTreasurySecret = economy.GetString("NexRentTreasurySecret", "").Trim();
|
||||
if (!UUID.TryParse(walletText, out m_NexRentTreasuryWallet) || m_NexRentTreasuryWallet.IsZero()
|
||||
|| !Uri.TryCreate(m_NexRentTreasuryApiUrl, UriKind.Absolute, out Uri treasuryUrl)
|
||||
|| treasuryUrl.Scheme != Uri.UriSchemeHttps
|
||||
|| treasuryUrl.Query.Length != 0 || treasuryUrl.Fragment.Length != 0
|
||||
|| !m_NexRentTreasuryApiUrl.EndsWith("/api.php", StringComparison.OrdinalIgnoreCase)
|
||||
|| m_NexRentTreasurySecret.Length < 48)
|
||||
{
|
||||
throw new InvalidOperationException("NexRent Treasury requires a pre-provisioned wallet, HTTPS api.php URL and strong secret.");
|
||||
}
|
||||
foreach (string entry in economy.GetString("NexRentTreasuryBoxBindings", "")
|
||||
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
string[] ids = entry.Split('|', StringSplitOptions.TrimEntries);
|
||||
if (ids.Length != 2 || !UUID.TryParse(ids[0], out UUID objectId)
|
||||
|| !UUID.TryParse(ids[1], out UUID ownerId)
|
||||
|| objectId.IsZero() || ownerId.IsZero()
|
||||
|| !m_NexRentTreasuryBindings.TryAdd(objectId, ownerId))
|
||||
{
|
||||
throw new InvalidOperationException("NexRentTreasuryBoxBindings must be unique objectUUID|ownerUUID pairs separated by semicolons.");
|
||||
}
|
||||
}
|
||||
if (m_NexRentTreasuryBindings.Count == 0)
|
||||
throw new InvalidOperationException("NexRent Treasury requires at least one explicitly registered box.");
|
||||
}
|
||||
// Explicit opt-in. A visiting account is never inferred from
|
||||
// a viewer-controlled UUID or an unverified display name.
|
||||
m_AllowHypergridGuests =
|
||||
@@ -286,6 +326,15 @@ namespace NexVerse.RegionModules.Economy
|
||||
m_Enabled =
|
||||
true;
|
||||
|
||||
if (m_NexRentTreasuryEnabled)
|
||||
{
|
||||
m_NexRentTreasuryRetryTimer = new Timer(
|
||||
_ => RetryNexRentTreasuryReceipts(), null,
|
||||
TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(60));
|
||||
m_Log.InfoFormat("[NEXRENT TREASURY]: Enabled for {0} registered objects; normal object payments unchanged.",
|
||||
m_NexRentTreasuryBindings.Count);
|
||||
}
|
||||
|
||||
if (m_BalanceRefreshSeconds > 0)
|
||||
{
|
||||
int refreshMilliseconds =
|
||||
@@ -401,6 +450,7 @@ namespace NexVerse.RegionModules.Economy
|
||||
false;
|
||||
|
||||
m_BalanceRefreshTimer?.Dispose();
|
||||
m_NexRentTreasuryRetryTimer?.Dispose();
|
||||
m_BalanceRefreshTimer =
|
||||
null;
|
||||
|
||||
@@ -1653,12 +1703,36 @@ namespace NexVerse.RegionModules.Economy
|
||||
|
||||
if (objectPayment)
|
||||
paymentReceiver = objectOwner;
|
||||
UUID registeredOwner = UUID.Zero;
|
||||
bool treasuryPayment = objectPayment && m_NexRentTreasuryEnabled
|
||||
&& m_NexRentTreasuryBindings.TryGetValue(e.receiver, out registeredOwner);
|
||||
if (treasuryPayment)
|
||||
{
|
||||
if (objectOwner != registeredOwner || e.sender == m_NexRentTreasuryWallet)
|
||||
{
|
||||
LocateClient(e.sender)?.SendAgentAlertMessage(
|
||||
"NexRent Treasury: object owner/binding mismatch. No NV$ debited.", false);
|
||||
return;
|
||||
}
|
||||
if (!NexRentTreasuryRequest("treasury_preflight", new
|
||||
{
|
||||
object_uuid = e.receiver.ToString(), owner_uuid = objectOwner.ToString(),
|
||||
payer_uuid = e.sender.ToString(), amount = e.amount
|
||||
}, true))
|
||||
{
|
||||
LocateClient(e.sender)?.SendAgentAlertMessage(
|
||||
"NexRent Treasury: rental authorization failed. No NV$ debited.", false);
|
||||
return;
|
||||
}
|
||||
paymentReceiver = m_NexRentTreasuryWallet;
|
||||
}
|
||||
|
||||
Guid commerceOrderId =
|
||||
Guid.NewGuid();
|
||||
|
||||
string reason;
|
||||
bool success;
|
||||
UUID ledgerTransactionId = UUID.Zero;
|
||||
|
||||
if (objectPayment)
|
||||
{
|
||||
@@ -1667,14 +1741,15 @@ namespace NexVerse.RegionModules.Economy
|
||||
e.sender,
|
||||
paymentReceiver,
|
||||
e.amount,
|
||||
"VendorPayment",
|
||||
treasuryPayment ? "Rental" : "VendorPayment",
|
||||
string.IsNullOrWhiteSpace(e.description)
|
||||
? "Inworld object payment"
|
||||
: e.description,
|
||||
"object:" +
|
||||
e.receiver.ToString(),
|
||||
treasuryPayment ? "nexrent:" + e.receiver.ToString()
|
||||
: "object:" + e.receiver.ToString(),
|
||||
commerceOrderId,
|
||||
out reason);
|
||||
out reason,
|
||||
out ledgerTransactionId);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1704,6 +1779,21 @@ namespace NexVerse.RegionModules.Economy
|
||||
return;
|
||||
}
|
||||
|
||||
if (treasuryPayment)
|
||||
{
|
||||
// World API accepted the immutable Rental commerce order.
|
||||
// Persist the callback; php:// backend can be unavailable.
|
||||
StoreAndSendNexRentTreasuryReceipt(new
|
||||
{
|
||||
order_id = commerceOrderId.ToString("D"),
|
||||
ledger_transaction_id = ledgerTransactionId.IsZero() ? "" : ledgerTransactionId.ToString(),
|
||||
object_uuid = e.receiver.ToString(),
|
||||
owner_uuid = objectOwner.ToString(),
|
||||
payer_uuid = e.sender.ToString(),
|
||||
wallet_uuid = m_NexRentTreasuryWallet.ToString(),
|
||||
amount = e.amount
|
||||
});
|
||||
}
|
||||
SendBalanceRefresh(
|
||||
e.sender);
|
||||
SendBalanceRefresh(
|
||||
@@ -1749,6 +1839,106 @@ namespace NexVerse.RegionModules.Economy
|
||||
}
|
||||
}
|
||||
|
||||
// A dedicated HTTPS+secret internal API. Never expose the secret to LSL.
|
||||
private bool NexRentTreasuryRequest(string operation, object payload, bool needsAcceptance)
|
||||
{
|
||||
if (!m_NexRentTreasuryEnabled || m_Http == null)
|
||||
return false;
|
||||
try
|
||||
{
|
||||
using HttpRequestMessage request = new(HttpMethod.Post,
|
||||
m_NexRentTreasuryApiUrl + "?op=" + operation);
|
||||
request.Headers.TryAddWithoutValidation("X-NexRent-Treasury-Secret",
|
||||
m_NexRentTreasurySecret);
|
||||
request.Content = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(payload));
|
||||
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
using HttpResponseMessage response = m_Http.Send(request);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
m_Log.WarnFormat("[NEXRENT TREASURY]: {0} returned HTTP {1}.",
|
||||
operation, (int)response.StatusCode);
|
||||
return false;
|
||||
}
|
||||
using JsonDocument json = JsonDocument.Parse(
|
||||
response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
|
||||
if (!json.RootElement.TryGetProperty("ok", out JsonElement ok)
|
||||
|| ok.ValueKind != JsonValueKind.True)
|
||||
return false;
|
||||
if (needsAcceptance)
|
||||
return json.RootElement.TryGetProperty("accepted", out JsonElement accepted)
|
||||
&& accepted.ValueKind == JsonValueKind.True;
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
m_Log.WarnFormat("[NEXRENT TREASURY]: {0} unavailable ({1}); credentials not logged.",
|
||||
operation, e.GetType().Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private string NexRentTreasuryOutboxDir => Path.Combine(
|
||||
AppContext.BaseDirectory, "ops-data", "nexrent-treasury-outbox");
|
||||
|
||||
private void StoreAndSendNexRentTreasuryReceipt(object payload)
|
||||
{
|
||||
string json = JsonSerializer.Serialize(payload);
|
||||
string path = string.Empty;
|
||||
try
|
||||
{
|
||||
string dir = NexRentTreasuryOutboxDir;
|
||||
Directory.CreateDirectory(dir);
|
||||
using JsonDocument parsed = JsonDocument.Parse(json);
|
||||
Guid id = Guid.Parse(parsed.RootElement.GetProperty("order_id").GetString());
|
||||
path = Path.Combine(dir, id.ToString("D") + ".json");
|
||||
File.WriteAllText(path, json);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// Critical: ledger already credited central wallet; reconcile by
|
||||
// immutable World API commerce order ID if filesystem fails.
|
||||
m_Log.ErrorFormat("[NEXRENT TREASURY]: Committed ledger order but callback spool failed: {0}.",
|
||||
e.GetType().Name);
|
||||
}
|
||||
if (NexRentTreasuryRequest("treasury_credit", payload, false))
|
||||
{
|
||||
if (path.Length > 0)
|
||||
try { File.Delete(path); } catch (Exception) { }
|
||||
}
|
||||
else
|
||||
m_Log.Error("[NEXRENT TREASURY]: Ledger payment completed, rental receipt callback pending. Check outbox / World API.");
|
||||
}
|
||||
|
||||
private void RetryNexRentTreasuryReceipts()
|
||||
{
|
||||
if (!m_NexRentTreasuryEnabled ||
|
||||
Interlocked.Exchange(ref m_NexRentTreasuryRetryRunning, 1) != 0)
|
||||
return;
|
||||
try
|
||||
{
|
||||
string dir = NexRentTreasuryOutboxDir;
|
||||
if (!Directory.Exists(dir)) return;
|
||||
int processed = 0;
|
||||
foreach (string path in Directory.EnumerateFiles(dir, "*.json"))
|
||||
{
|
||||
if (++processed > 40) break;
|
||||
try
|
||||
{
|
||||
string raw = File.ReadAllText(path);
|
||||
using JsonDocument parsed = JsonDocument.Parse(raw);
|
||||
if (NexRentTreasuryRequest("treasury_credit", parsed.RootElement, false))
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
m_Log.WarnFormat("[NEXRENT TREASURY]: Callback replay failed ({0}).",
|
||||
e.GetType().Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally { Interlocked.Exchange(ref m_NexRentTreasuryRetryRunning, 0); }
|
||||
}
|
||||
|
||||
private void ApplyFee(
|
||||
UUID agentID,
|
||||
int amount,
|
||||
@@ -1780,6 +1970,14 @@ namespace NexVerse.RegionModules.Economy
|
||||
}
|
||||
|
||||
|
||||
private bool CommercePaymentInternal(
|
||||
UUID buyer, UUID seller, int amount, string kind, string reference,
|
||||
string externalReference, Guid orderId, out string reason)
|
||||
{
|
||||
return CommercePaymentInternal(buyer, seller, amount, kind, reference,
|
||||
externalReference, orderId, out reason, out _);
|
||||
}
|
||||
|
||||
private bool CommercePaymentInternal(
|
||||
UUID buyer,
|
||||
UUID seller,
|
||||
@@ -1788,8 +1986,10 @@ namespace NexVerse.RegionModules.Economy
|
||||
string reference,
|
||||
string externalReference,
|
||||
Guid orderId,
|
||||
out string reason)
|
||||
out string reason,
|
||||
out UUID ledgerTransactionId)
|
||||
{
|
||||
ledgerTransactionId = UUID.Zero;
|
||||
reason =
|
||||
string.Empty;
|
||||
|
||||
@@ -1852,7 +2052,20 @@ namespace NexVerse.RegionModules.Economy
|
||||
m_Http.Send(request);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
try
|
||||
{
|
||||
using JsonDocument receipt = JsonDocument.Parse(
|
||||
response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
|
||||
JsonElement order = receipt.RootElement.GetProperty("order");
|
||||
if (order.TryGetProperty("payment_transaction_id", out JsonElement transaction)
|
||||
&& transaction.ValueKind == JsonValueKind.String
|
||||
&& UUID.TryParse(transaction.GetString(), out UUID id))
|
||||
ledgerTransactionId = id;
|
||||
}
|
||||
catch (Exception) { } // Order ID still permits ledger reconciliation.
|
||||
return true;
|
||||
}
|
||||
|
||||
reason =
|
||||
ReadErrorMessage(
|
||||
|
||||
Reference in new issue
Block a user