Files
opengenesislinkserver/NexVerse/RegionModules/Economy/NexVerseMoneyModule.cs
T
OpenGenesis (MPL 2.0) 1dd46384d0 fix(g1): NV$ Classified-Fee vor Profilmutation pruefen (#432)
* feat(economy): add optional preflight contract for fee-based operations

* fix(economy): reject unconfigured fee destination before classified mutation

* fix(classifieds): preflight NV$ charges and report non-atomic fee failures

* test(g1): lock fee preflight and classified reconciliation behavior

* ci(g1): run paid-classified preflight regression

* docs(g1): operational fee wallet setup and non-atomic classified risk
2026-11-11 18:31:18 +01:00

2589 lines
88 KiB
C#

// SPDX-License-Identifier: MPL-2.0
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using NexVerse.Core.Economy;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace NexVerse.RegionModules.Economy
{
[Extension(
Path = "/OpenSim/RegionModules",
NodeName = "RegionModule",
Id = "NexVerseMoneyModule")]
public sealed class NexVerseMoneyModule :
IMoneyModule,
IMoneyChargePreflight,
INexMasterBankPayoutModule,
ISharedRegionModule
{
private static readonly ILog m_Log =
LogManager.GetLogger(typeof(NexVerseMoneyModule));
private readonly object m_Sync =
new object();
private readonly Dictionary<ulong, Scene> m_Scenes =
new Dictionary<ulong, Scene>();
// Maps the original foreign avatar to the globally namespaced wallet.
// Entries survive region changes within this simulator process. If a
// different verified home claims the same UUID, fail closed.
private readonly Dictionary<UUID, UUID> m_HypergridWallets =
new Dictionary<UUID, UUID>();
private HttpClient m_Http;
private bool m_Enabled;
private bool m_LegacyHelperRegistered;
private bool m_AllowHypergridGuests;
private NexMasterBankPayoutPolicy m_MasterBank;
private string m_LocalEconomyUrl = string.Empty;
private string m_CurrencyPurchasePortalUrl = string.Empty;
private Dictionary<string, XmlRpcMethod> m_LegacyRpcHandlers;
private string m_WorldApiBaseUrl =
string.Empty;
private string m_ApiKey =
string.Empty;
private UUID m_FeeWalletId =
UUID.Zero;
private int m_UploadCharge;
private int m_GroupCreationCharge;
private int m_RequestTimeoutMilliseconds =
3000;
private int m_BalanceRefreshSeconds =
5;
private Timer m_BalanceRefreshTimer;
private int m_BalanceRefreshRunning;
private const int InitialBalanceRetryDelayMilliseconds = 500;
private const int InitialBalanceMaxAttempts = 20;
private const int InitialBalanceConfirmDelayMilliseconds = 1500;
public event ObjectPaid OnObjectPaid;
public string Name =>
"NexVerseMoneyModule";
// This module is selected explicitly through [Economy] economymodule.
// Do not defer it through the generic replaceable-module slot: the
// legacy SampleMoneyModule uses the same IMoneyModule key and can
// otherwise overwrite this shared module before AddRegion() runs.
public Type ReplaceableInterface =>
null;
public int UploadCharge =>
m_UploadCharge;
public int GroupCreationCharge =>
m_GroupCreationCharge;
public void Initialise(
IConfigSource config)
{
string selectedModule =
(config?.Configs["Startup"]?.GetString(
"economymodule",
string.Empty) ??
string.Empty)
.Trim();
if (string.IsNullOrWhiteSpace(selectedModule))
{
IConfig economySelection =
config?.Configs["Economy"];
selectedModule =
(economySelection?.GetString(
"economymodule",
string.Empty) ??
string.Empty)
.Trim();
if (string.IsNullOrWhiteSpace(selectedModule))
{
selectedModule =
(economySelection?.GetString(
"EconomyModule",
string.Empty) ??
string.Empty)
.Trim();
}
}
if (!string.IsNullOrWhiteSpace(selectedModule) &&
!string.Equals(
selectedModule,
Name,
StringComparison.OrdinalIgnoreCase))
{
m_Enabled = false;
m_Log.InfoFormat(
"[NEX-ECONOMY-VIEWER]: Modul bleibt deaktiviert, weil [Economy] economymodule auf {0} gesetzt ist.",
selectedModule);
return;
}
IConfig economy =
config?.Configs["NexEconomyViewer"];
if (economy == null ||
!economy.GetBoolean(
"Enabled",
false))
{
m_Enabled =
false;
return;
}
m_WorldApiBaseUrl =
economy.GetString(
"WorldApiBaseUrl",
string.Empty)
.Trim()
.TrimEnd('/');
m_ApiKey =
economy.GetString(
"ApiKey",
string.Empty)
.Trim();
m_CurrencyPurchasePortalUrl =
economy.GetString(
"CurrencyPurchasePortalUrl",
string.Empty)
.Trim();
m_UploadCharge =
Math.Max(
0,
economy.GetInt(
"UploadCharge",
0));
m_GroupCreationCharge =
Math.Max(
0,
economy.GetInt(
"GroupCreationCharge",
0));
m_RequestTimeoutMilliseconds =
Math.Clamp(
economy.GetInt(
"RequestTimeoutMilliseconds",
3000),
500,
30000);
m_BalanceRefreshSeconds =
Math.Clamp(
economy.GetInt(
"BalanceRefreshSeconds",
5),
0,
300);
// Explicit opt-in. A visiting account is never inferred from
// a viewer-controlled UUID or an unverified display name.
m_AllowHypergridGuests =
economy.GetBoolean("AllowHypergridGuests", false);
// Explicitly delegated payouts from one prefunded, separate
// Business wallet. No script sees the simulator API key.
if (economy.GetBoolean("MasterBankEnabled", false))
{
string rawBank = economy.GetString("MasterBankAccountId", "");
string rawOperator = economy.GetString("MasterBankOperatorId", "");
if (!Guid.TryParse(rawBank, out Guid bankId) ||
bankId == Guid.Empty ||
!Guid.TryParse(rawOperator, out Guid operatorId) ||
operatorId == Guid.Empty)
throw new InvalidOperationException(
"Master Bank requires nonzero account/operator UUIDs.");
m_MasterBank = new NexMasterBankPayoutPolicy(
bankId, operatorId,
economy.GetInt("MasterBankMaxPayout", 100),
economy.GetString("MasterBankAuthorizedScripts", ""));
if (!m_MasterBank.Enabled)
throw new InvalidOperationException(
"Master Bank requires at least one exact object/script binding.");
}
string feeWallet =
economy.GetString(
"FeeWalletId",
string.Empty)
.Trim();
if (!string.IsNullOrWhiteSpace(
feeWallet) &&
!UUID.TryParse(
feeWallet,
out m_FeeWalletId))
{
throw new InvalidOperationException(
"[NEX-ECONOMY-VIEWER]: FeeWalletId must be a UUID.");
}
if (m_FeeWalletId.IsZero())
{
m_Log.Warn("[NEX-ECONOMY-VIEWER]: FeeWalletId fehlt. " +
"Kostenpflichtige Classifieds und andere Systemgebuehren " +
"koennen erst nach Einrichtung einer separaten NV$-Gebuehrenwallet gebucht werden.");
}
if (string.IsNullOrWhiteSpace(
m_WorldApiBaseUrl))
{
throw new InvalidOperationException(
"[NEX-ECONOMY-VIEWER]: WorldApiBaseUrl is required when enabled.");
}
if (!Uri.TryCreate(
m_WorldApiBaseUrl,
UriKind.Absolute,
out Uri baseUri) ||
(baseUri.Scheme != Uri.UriSchemeHttp &&
baseUri.Scheme != Uri.UriSchemeHttps))
{
throw new InvalidOperationException(
"[NEX-ECONOMY-VIEWER]: WorldApiBaseUrl must be an absolute HTTP(S) URL.");
}
if (string.IsNullOrWhiteSpace(
m_ApiKey))
{
throw new InvalidOperationException(
"[NEX-ECONOMY-VIEWER]: ApiKey is required when enabled.");
}
m_Http =
new HttpClient
{
Timeout =
TimeSpan.FromMilliseconds(
m_RequestTimeoutMilliseconds)
};
m_Enabled =
true;
if (m_BalanceRefreshSeconds > 0)
{
int refreshMilliseconds =
checked(
m_BalanceRefreshSeconds *
1000);
m_BalanceRefreshTimer =
new Timer(
_ => RefreshConnectedBalances(),
null,
refreshMilliseconds,
refreshMilliseconds);
}
m_Log.InfoFormat(
"[NEX-ECONOMY-VIEWER]: Central NV$ Viewer adapter enabled for {0}; externer Balance-Refresh alle {1}s.",
m_WorldApiBaseUrl,
m_BalanceRefreshSeconds > 0
? m_BalanceRefreshSeconds.ToString()
: "deaktiviert");
}
public void PostInitialise()
{
}
public void AddRegion(
Scene scene)
{
if (!m_Enabled ||
scene == null)
{
return;
}
lock (m_Sync)
m_Scenes[scene.RegionInfo.RegionHandle] =
scene;
scene.RegisterModuleInterface<IMoneyModule>(
this);
if (m_MasterBank?.Enabled == true)
scene.RegisterModuleInterface<INexMasterBankPayoutModule>(this);
scene.EventManager.OnNewClient +=
OnNewClient;
scene.EventManager.OnMoneyTransfer +=
MoneyTransferAction;
scene.EventManager.OnClientClosed +=
ClientClosed;
m_Log.InfoFormat(
"[NEX-ECONOMY-VIEWER]: Als IMoneyModule fuer Region {0} registriert; MoneyBalanceRequest ist aktiv.",
scene.RegionInfo.RegionName);
}
public void RemoveRegion(
Scene scene)
{
if (scene == null)
return;
scene.EventManager.OnNewClient -=
OnNewClient;
scene.EventManager.OnMoneyTransfer -=
MoneyTransferAction;
scene.EventManager.OnClientClosed -=
ClientClosed;
if (m_MasterBank?.Enabled == true)
scene.UnregisterModuleInterface<INexMasterBankPayoutModule>(this);
lock (m_Sync)
m_Scenes.Remove(
scene.RegionInfo.RegionHandle);
}
public void RegionLoaded(
Scene scene)
{
if (!m_Enabled ||
scene == null)
{
return;
}
EnsureLegacyEconomyHelper(
scene);
ISimulatorFeaturesModule features =
scene.RequestModuleInterface<ISimulatorFeaturesModule>();
if (features == null ||
string.IsNullOrWhiteSpace(m_LocalEconomyUrl))
{
return;
}
if (!features.TryGetOpenSimExtraFeature(
"currency-base-uri",
out OSD _))
{
features.AddOpenSimExtraFeature(
"currency-base-uri",
Util.AppendEndSlash(
m_LocalEconomyUrl));
}
}
public void Close()
{
m_Enabled =
false;
m_BalanceRefreshTimer?.Dispose();
m_BalanceRefreshTimer =
null;
lock (m_Sync)
{
m_Scenes.Clear();
m_HypergridWallets.Clear();
}
m_Http?.Dispose();
m_Http =
null;
}
public int GetBalance(
UUID agentID)
{
if (!m_Enabled ||
agentID.IsZero())
{
return 0;
}
try
{
if (!TryResolveWallet(agentID, false, out UUID walletId,
out string identityError))
{
m_Log.DebugFormat(
"[NEX-ECONOMY-VIEWER]: Kein freigegebenes NV$-HG-Wallet fuer {0}: {1}",
agentID, identityError);
return 0;
}
using HttpRequestMessage request =
CreateRequest(
HttpMethod.Get,
"/api/v1/economy/balance?account_id=" +
Uri.EscapeDataString(
walletId.ToString()));
using HttpResponseMessage response =
m_Http.Send(request);
if (!response.IsSuccessStatusCode)
{
string detail =
ReadErrorMessage(
response);
if (response.StatusCode ==
HttpStatusCode.NotFound &&
detail.IndexOf(
"NV$ account was not found",
StringComparison.OrdinalIgnoreCase) >= 0)
{
m_Log.DebugFormat(
"[NEX-ECONOMY-VIEWER]: Fuer {0} existiert noch kein NV$-Konto; Viewer-Saldo bleibt bis zur ersten Buchung 0 NV$.",
agentID);
return 0;
}
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Kontostand fuer {0} konnte nicht geladen werden. World API HTTP {1}: {2}",
agentID,
(int)response.StatusCode,
detail);
return 0;
}
string json =
response.Content
.ReadAsStringAsync()
.GetAwaiter()
.GetResult();
using JsonDocument document =
JsonDocument.Parse(json);
if (!document.RootElement.TryGetProperty(
"account",
out JsonElement account) ||
!account.TryGetProperty(
"balance",
out JsonElement balance) ||
!balance.TryGetInt64(
out long rawBalance))
{
return 0;
}
return rawBalance > int.MaxValue
? int.MaxValue
: rawBalance < int.MinValue
? int.MinValue
: (int)rawBalance;
}
catch (Exception e)
{
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Balance lookup failed for {0}: {1}",
agentID,
e.Message);
return 0;
}
}
public bool UploadCovered(
UUID agentID,
int amount) =>
AmountCovered(
agentID,
amount);
public bool AmountCovered(
UUID agentID,
int amount)
{
if (amount <= 0)
return true;
return
GetBalance(agentID) >=
amount;
}
// A separate fee destination is mandatory for system charges.
// Do not change AmountCovered: land and resident-to-resident transfers
// must continue to work even when system charges are unavailable.
public bool TryPreflightCharge(
UUID agentID,
int amount,
out string reason)
{
reason = string.Empty;
if (amount < 0)
{
reason = "Invalid NV$ charge amount.";
return false;
}
if (amount == 0)
return true;
if (!m_Enabled || m_Http == null)
{
reason = "NV$ fee service is unavailable.";
return false;
}
if (m_FeeWalletId.IsZero())
{
reason = "NV$ fee wallet is not configured. Please contact grid support.";
return false;
}
if (agentID.IsZero() || agentID == m_FeeWalletId)
{
reason = "Invalid NV$ fee payer.";
return false;
}
if (!AmountCovered(agentID, amount))
{
reason = "Insufficient NV$ or balance service unavailable.";
return false;
}
// Balance and configuration can change before the final transfer.
// The ledger debit remains the final authority.
return true;
}
public void ApplyCharge(
UUID agentID,
int amount,
MoneyTransactionType type,
string extraData = "")
{
ApplyFee(
agentID,
amount,
string.IsNullOrWhiteSpace(extraData)
? type.ToString()
: extraData);
}
public void ApplyUploadCharge(
UUID agentID,
int amount,
string text)
{
ApplyFee(
agentID,
amount,
string.IsNullOrWhiteSpace(text)
? "Asset upload"
: text);
}
public void MoveMoney(
UUID fromUser,
UUID toUser,
int amount,
string text)
{
MoveMoneyInternal(
fromUser,
toUser,
amount,
text,
"viewer-" +
Guid.NewGuid().ToString("N"),
out _);
}
public bool MoveMoney(
UUID fromUser,
UUID toUser,
int amount,
MoneyTransactionType type,
string text)
{
string reference =
string.IsNullOrWhiteSpace(text)
? type.ToString()
: text;
if (reference.StartsWith(
"Land purchase:",
StringComparison.OrdinalIgnoreCase))
{
return CommercePaymentInternal(
fromUser,
toUser,
amount,
"LandPurchase",
reference,
"viewer-land-purchase",
Guid.NewGuid(),
out _);
}
return MoveMoneyInternal(
fromUser,
toUser,
amount,
reference,
"viewer-" +
Guid.NewGuid().ToString("N"),
out _);
}
public bool IsAuthorizedBankScript(UUID objectId, UUID scriptItemId,
UUID ownerId)
{
if (!m_Enabled || m_MasterBank?.Enabled != true ||
!m_MasterBank.IsAuthorized(objectId.Guid,
scriptItemId.Guid, ownerId.Guid))
return false;
// A registered object MUST still exist as a live scene object,
// owned by the registered operator. Its inventory MUST contain
// the exact approved script instance.
lock (m_Sync)
foreach (Scene scene in m_Scenes.Values)
{
SceneObjectPart root = scene?.GetSceneObjectPart(objectId);
if (root?.ParentGroup == null ||
root.ParentGroup.IsDeleted ||
root.ParentGroup.RootPart.UUID != objectId ||
root.ParentGroup.RootPart.OwnerID != ownerId)
continue;
if (root.ParentGroup.RootPart.TaskInventory.ContainsKey(scriptItemId))
return true;
}
return false;
}
public bool TryBankPayout(UUID objectId, UUID scriptItemId,
UUID ownerId, UUID residentId, int amount, UUID transactionId,
out string reason)
{
reason = "Master Bank payout is not authorized.";
if (m_MasterBank?.CanPayout(objectId.Guid, scriptItemId.Guid,
ownerId.Guid, residentId.Guid, amount) != true ||
!IsAuthorizedBankScript(objectId, scriptItemId, ownerId))
return false;
// Only send money to a resident currently present in this
// simulator. For HG visitors this also ensures their wallet is
// resolved from the authenticated home grid circuit.
IClientAPI recipient = LocateClient(residentId);
if (recipient == null || !recipient.IsActive ||
!TryResolveWallet(residentId, false,
out UUID destinationWallet, out reason))
{
if (string.IsNullOrWhiteSpace(reason))
reason = "Recipient must be present in NexVerse.";
return false;
}
if (destinationWallet == new UUID(m_MasterBank.AccountId))
{
reason = "Master Bank cannot pay itself.";
return false;
}
if (!EnsureMasterBankAccount(out reason))
return false;
try
{
UUID paymentId = transactionId.IsZero() ?
UUID.Random() : transactionId;
byte[] payload = JsonSerializer.SerializeToUtf8Bytes(new
{
from_account_id = m_MasterBank.AccountId.ToString("D"),
to_account_id = destinationWallet.ToString(),
amount,
reference = "Authorized Master Bank payout (" +
objectId.ToString() + "/" + scriptItemId.ToString() + ")"
});
using HttpRequestMessage request = CreateRequest(
HttpMethod.Post, "/api/v1/banking/transfers");
request.Headers.TryAddWithoutValidation("Idempotency-Key",
"master-bank-" + paymentId.ToString());
request.Content = new ByteArrayContent(payload);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
using HttpResponseMessage response = m_Http.Send(request);
if (!response.IsSuccessStatusCode)
{
reason = ReadErrorMessage(response);
return false;
}
reason = string.Empty;
SendBalanceRefresh(residentId);
m_Log.InfoFormat(
"[NEX-MASTER-BANK]: Verified script {0}/{1} paid {2} NV$ to {3}; txn {4}.",
objectId, scriptItemId, amount, destinationWallet, paymentId);
return true;
}
catch (Exception e)
{
reason = "Central Master Bank payout unavailable.";
m_Log.WarnFormat("[NEX-MASTER-BANK]: Payout failed: {0}",
e.Message);
return false;
}
}
private bool EnsureMasterBankAccount(out string reason)
{
reason = string.Empty;
try
{
byte[] payload = JsonSerializer.SerializeToUtf8Bytes(new
{
account_id = m_MasterBank.AccountId.ToString("D"),
account_class = "business",
display_name = "NexVerse Master Bank"
});
using HttpRequestMessage request = CreateRequest(
HttpMethod.Post, "/api/v1/economy/accounts/ensure");
request.Content = new ByteArrayContent(payload);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
using HttpResponseMessage response = m_Http.Send(request);
if (!response.IsSuccessStatusCode)
{
reason = ReadErrorMessage(response);
return false;
}
return true;
}
catch (Exception e)
{
reason = "Central bank wallet unavailable.";
m_Log.WarnFormat("[NEX-MASTER-BANK]: Ensure failed: {0}",
e.Message);
return false;
}
}
public bool ObjectGiveMoney(
UUID objectID,
UUID fromID,
UUID toID,
int amount,
UUID txn,
out string reason)
{
string idempotency =
txn.IsZero()
? "object-" +
Guid.NewGuid().ToString("N")
: "object-" +
txn.ToString();
bool success =
MoveMoneyInternal(
fromID,
toID,
amount,
"Object " +
objectID.ToString() +
" payment",
idempotency,
out reason);
return success;
}
private void EnsureLegacyEconomyHelper(
Scene scene)
{
lock (m_Sync)
{
if (m_LegacyHelperRegistered)
return;
string serverUri =
scene.RegionInfo?.ServerURI ??
string.Empty;
if (string.IsNullOrWhiteSpace(serverUri))
{
m_Log.Warn(
"[NEX-ECONOMY-VIEWER]: Firestorm currency helper could not be registered because the simulator ServerURI is empty.");
return;
}
m_LocalEconomyUrl =
Util.AppendEndSlash(
serverUri.Trim());
m_LegacyRpcHandlers =
new Dictionary<string, XmlRpcMethod>(
StringComparer.OrdinalIgnoreCase)
{
["getCurrencyQuote"] =
LegacyGetCurrencyQuote,
["buyCurrency"] =
LegacyBuyCurrency,
["preflightBuyLandPrep"] =
LegacyPreflightBuyLand,
["buyLandPrep"] =
LegacyBuyLandPrep
};
MainServer.Instance.AddSimpleStreamHandler(
new SimpleStreamHandler(
"/currency.php",
ProcessLegacyEconomyRpc));
MainServer.Instance.AddSimpleStreamHandler(
new SimpleStreamHandler(
"/landtool.php",
ProcessLegacyEconomyRpc));
m_LegacyHelperRegistered =
true;
m_Log.InfoFormat(
"[NEX-ECONOMY-VIEWER]: Firestorm economy compatibility helper enabled at {0}currency.php.",
m_LocalEconomyUrl);
}
}
private void ProcessLegacyEconomyRpc(
IOSHttpRequest request,
IOSHttpResponse response)
{
MainServer.Instance.HandleXmlRpcRequests(
(OSHttpRequest)request,
(OSHttpResponse)response,
m_LegacyRpcHandlers);
}
private XmlRpcResponse LegacyGetCurrencyQuote(
XmlRpcRequest request,
IPEndPoint remoteClient)
{
int requested =
LegacyRequestedCurrency(
request);
Hashtable currency =
new Hashtable
{
["estimatedCost"] = 0,
["estimatedLocalCost"] =
"NV$ purchase is handled by the secure NexVerse portal",
["currencyBuy"] =
requested
};
Hashtable result =
new Hashtable
{
["success"] = true,
["currency"] = currency,
["confirm"] =
UUID.Random().ToString()
};
return
new XmlRpcResponse
{
Value = result
};
}
private XmlRpcResponse LegacyBuyCurrency(
XmlRpcRequest request,
IPEndPoint remoteClient)
{
Hashtable result =
new Hashtable
{
["success"] = false,
["errorMessage"] =
"NV$ cannot be minted through the unauthenticated legacy Firestorm helper. Use the secure NexVerse purchase portal."
};
if (!string.IsNullOrWhiteSpace(
m_CurrencyPurchasePortalUrl))
{
result["errorURI"] =
m_CurrencyPurchasePortalUrl;
}
return
new XmlRpcResponse
{
Value = result
};
}
private XmlRpcResponse LegacyPreflightBuyLand(
XmlRpcRequest request,
IPEndPoint remoteClient)
{
Hashtable levels =
new Hashtable();
ArrayList entries =
new ArrayList();
Hashtable level =
new Hashtable
{
["id"] =
UUID.Zero.ToString(),
["description"] =
"OpenGenesisLINK resident"
};
entries.Add(
level);
levels["upgrade"] =
false;
levels["action"] =
string.Empty;
levels["levels"] =
entries;
Hashtable currency =
new Hashtable
{
["estimatedCost"] = 0
};
Hashtable landUse =
new Hashtable
{
["upgrade"] = false,
["action"] = string.Empty
};
Hashtable result =
new Hashtable
{
["success"] = true,
["currency"] = currency,
["membership"] = levels,
["landuse"] = landUse,
["confirm"] =
UUID.Random().ToString()
};
return
new XmlRpcResponse
{
Value = result
};
}
private XmlRpcResponse LegacyBuyLandPrep(
XmlRpcRequest request,
IPEndPoint remoteClient)
{
return
new XmlRpcResponse
{
Value =
new Hashtable
{
["success"] = true
}
};
}
private static int LegacyRequestedCurrency(
XmlRpcRequest request)
{
try
{
if (request?.Params == null ||
request.Params.Count == 0 ||
request.Params[0] is not Hashtable data)
{
return 0;
}
object value =
data["currencyBuy"];
return value == null
? 0
: Math.Max(
0,
Convert.ToInt32(
value));
}
catch
{
return 0;
}
}
private void OnNewClient(
IClientAPI client)
{
if (client == null)
return;
client.OnEconomyDataRequest +=
EconomyDataRequestHandler;
client.OnMoneyBalanceRequest +=
SendMoneyBalance;
client.OnObjectBuy +=
ObjectBuy;
// Firestorm's Groups > Land & NV$ tab sends these legacy UDP
// requests. OpenSim declares them but the default region module
// leaves them without replies, causing an endless spinner.
client.OnGroupAccountSummaryRequest +=
HandleGroupAccountSummaryRequest;
client.OnGroupAccountDetailsRequest +=
HandleGroupAccountDetailsRequest;
client.OnGroupAccountTransactionsRequest +=
HandleGroupAccountTransactionsRequest;
// Firestorm initializes the status bar with "?? <currency>" until a
// MoneyBalanceReply arrives. The first viewer request can race the
// OnNewClient subscription, so keep retrying until the circuit is active.
QueueInitialBalanceRefresh(client);
}
private void QueueInitialBalanceRefresh(
IClientAPI client)
{
ThreadPool.QueueUserWorkItem(
_ =>
{
for (int attempt = 1;
attempt <= InitialBalanceMaxAttempts;
attempt++)
{
Thread.Sleep(
InitialBalanceRetryDelayMilliseconds);
if (client == null)
return;
if (!client.IsActive)
continue;
try
{
m_Log.DebugFormat(
"[NEX-ECONOMY-VIEWER]: Firestorm-Kontostand wird initial an {0} gesendet (Versuch {1}).",
client.AgentId,
attempt);
SendMoneyBalance(
client,
client.AgentId,
client.SessionId,
UUID.Random());
// One confirmation refresh covers viewers that finish
// building the status bar just after the first reply.
Thread.Sleep(
InitialBalanceConfirmDelayMilliseconds);
if (client.IsActive)
{
SendMoneyBalance(
client,
client.AgentId,
client.SessionId,
UUID.Random());
}
return;
}
catch (Exception e)
{
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Initialer Firestorm-Kontostand für {0} konnte nicht gesendet werden: {1}",
client.AgentId,
e.Message);
return;
}
}
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Firestorm-Kontostand für {0} wurde nicht initial gesendet, weil der Client nicht rechtzeitig aktiv wurde.",
client?.AgentId ?? UUID.Zero);
});
}
private void ObjectBuy(
IClientAPI remoteClient,
UUID agentID,
UUID sessionID,
UUID groupID,
UUID categoryID,
uint localID,
byte saleType,
int salePrice)
{
if (remoteClient == null ||
remoteClient.AgentId != agentID ||
remoteClient.SessionId != sessionID ||
remoteClient.Scene is not Scene scene)
{
return;
}
SceneObjectPart part =
scene.GetSceneObjectPart(
localID);
if (part == null ||
part.ParentGroup == null ||
part.ParentGroup.IsDeleted)
{
remoteClient.SendAgentAlertMessage(
"Unable to buy now. The object was not found.",
false);
return;
}
SceneObjectGroup group =
part.ParentGroup;
SceneObjectPart root =
group.RootPart;
if (root.ObjectSaleType == (byte)SaleType.Not ||
root.ObjectSaleType != saleType ||
root.SalePrice != salePrice)
{
remoteClient.SendAgentAlertMessage(
"Object sale data changed. Please refresh the object properties and try again.",
false);
return;
}
IBuySellModule buySell =
scene.RequestModuleInterface<IBuySellModule>();
if (buySell == null)
{
remoteClient.SendAgentAlertMessage(
"Object buying is unavailable in this region.",
false);
return;
}
UUID seller =
group.OwnerID;
if (seller.IsZero() ||
seller == agentID)
{
remoteClient.SendAgentAlertMessage(
"This object cannot be purchased from its current owner.",
false);
return;
}
Guid orderId =
Guid.NewGuid();
string paymentError =
string.Empty;
bool paid =
salePrice <= 0 ||
CommercePaymentInternal(
agentID,
seller,
salePrice,
"ObjectSale",
"Object purchase: " +
root.Name,
"object:" +
group.UUID.ToString(),
orderId,
out paymentError);
if (!paid)
{
remoteClient.SendAgentAlertMessage(
string.IsNullOrWhiteSpace(paymentError)
? "NV$ object purchase payment failed."
: paymentError,
false);
return;
}
bool delivered =
buySell.BuyObject(
remoteClient,
categoryID,
localID,
saleType,
salePrice);
if (!delivered)
{
bool refunded =
salePrice <= 0;
string refundError =
string.Empty;
if (salePrice > 0)
{
refunded =
RefundCommerceInternal(
orderId,
"Object delivery failed",
out refundError);
}
if (!refunded)
{
m_Log.ErrorFormat(
"[NEX-ECONOMY-VIEWER]: Object delivery failed and NexCommerce refund {0} also failed: {1}",
orderId,
refundError);
}
remoteClient.SendAgentAlertMessage(
refunded
? "Object delivery failed. The completed NV$ payment was refunded."
: "Object delivery failed and the automatic NV$ refund could not be confirmed. Please contact an administrator with order " +
orderId.ToString("D") +
".",
false);
return;
}
SendBalanceRefresh(agentID);
SendBalanceRefresh(seller);
remoteClient.SendAgentAlertMessage(
salePrice > 0
? "Object purchased for " +
salePrice +
" NV$."
: "Object purchased.",
false);
}
private bool CanReadGroupAccount(IClientAPI client, UUID agentId, UUID groupId)
{
if (!m_Enabled || client == null || !client.IsActive ||
agentId.IsZero() || groupId.IsZero() ||
client.AgentId != agentId || client.Scene is not Scene scene)
return false;
IGroupsModule groups = scene.RequestModuleInterface<IGroupsModule>();
if (groups == null || groups.GetGroupRecord(groupId) == null)
return false;
// Never expose group balances on membership alone. In OpenSim the
// "Accountable" power is granted to the Owners role by default.
ulong permissions = groups.GetFullGroupPowers(agentId, groupId);
return (permissions & (ulong)GroupPowers.Accountable) != 0;
}
private void HandleGroupAccountSummaryRequest(
IClientAPI client, UUID agentId, UUID groupId, UUID requestID)
{
if (!CanReadGroupAccount(client, agentId, groupId))
{
m_Log.DebugFormat("[NEX-ECONOMY-VIEWER]: Denied group accounting summary: avatar={0}, group={1}", agentId, groupId);
// Send a non-sensitive reply so the viewer can terminate its
// loading state, without revealing an unauthorized balance.
client?.SendGroupAccountingSummary(client, groupId, requestID, 0, 0, 0);
return;
}
if (!TryGetGroupBalance(groupId, out uint balance))
{
client.SendAgentAlertMessage(
"Gruppen-NV$ sind derzeit nicht erreichbar. Bitte erneut versuchen.", false);
client.SendGroupAccountingSummary(client, groupId, requestID, 0, 0, 0);
return;
}
client.SendGroupAccountingSummary(client, groupId, requestID,
balance, 0, 0);
}
private void HandleGroupAccountDetailsRequest(
IClientAPI client, UUID agentId, UUID groupId,
UUID transactionId, UUID sessionId)
{
if (client == null || !client.IsActive || client.SessionId != sessionId ||
client.AgentId != agentId)
return;
// Do not expose any transaction detail without a genuine
// accounting power. An empty reply is safe for non-accountants.
// Even an authorized accountant must not be shown fabricated
// details; unauthorized viewers get a harmless empty response.
if (!CanReadGroupAccount(client, agentId, groupId))
m_Log.DebugFormat("[NEX-ECONOMY-VIEWER]: Denied group accounting details for {0}", groupId);
if (!CanReadGroupAccount(client, agentId, groupId))
{
client.SendGroupAccountingDetails(client, groupId, transactionId,
sessionId, 0);
return;
}
if (!TryGetGroupHistory(groupId, false,
out IReadOnlyList<GroupAccountHistoryEntry> entries))
{
client.SendAgentAlertMessage(
"Gruppen-NV$-Historie ist derzeit nicht erreichbar.", false);
client.SendGroupAccountingDetails(client, groupId, transactionId,
sessionId, 0);
return;
}
client.SendGroupAccountingDetails(client, groupId, transactionId,
sessionId, 0, entries);
}
private void HandleGroupAccountTransactionsRequest(
IClientAPI client, UUID agentId, UUID groupId,
UUID transactionId, UUID sessionId)
{
if (client == null || !client.IsActive || client.SessionId != sessionId ||
client.AgentId != agentId)
return;
if (!CanReadGroupAccount(client, agentId, groupId))
{
m_Log.DebugFormat("[NEX-ECONOMY-VIEWER]: Denied group sales detail for {0}", groupId);
client.SendGroupTransactionsSummaryDetails(client, groupId,
transactionId, sessionId, 0);
return;
}
if (!TryGetGroupHistory(groupId, true,
out IReadOnlyList<GroupAccountHistoryEntry> sales))
{
client.SendAgentAlertMessage(
"Gruppen-NV$-Verkaeufe sind derzeit nicht erreichbar.", false);
client.SendGroupTransactionsSummaryDetails(client, groupId,
transactionId, sessionId, 0);
return;
}
client.SendGroupTransactionsSummaryDetails(client, groupId,
transactionId, sessionId, 0, sales);
}
// The simulator authenticates as a narrowly scoped backend and
// verifies the connected avatar's Accountable power first. The
// World API independently checks both groups:read and economy:read.
private bool TryGetGroupHistory(UUID groupId, bool salesOnly,
out IReadOnlyList<GroupAccountHistoryEntry> entries)
{
entries = Array.Empty<GroupAccountHistoryEntry>();
try
{
using HttpRequestMessage request = CreateRequest(
HttpMethod.Get, "/api/v1/groups/" +
Uri.EscapeDataString(groupId.ToString()) + "/transactions");
using HttpResponseMessage response = m_Http.Send(request);
if (!response.IsSuccessStatusCode)
{
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Group history HTTP {0} for {1}",
(int)response.StatusCode, groupId);
return false;
}
using JsonDocument data = JsonDocument.Parse(
response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
if (!data.RootElement.TryGetProperty(
"transactions", out JsonElement items) ||
items.ValueKind != JsonValueKind.Array)
return false;
List<GroupAccountHistoryEntry> rows =
new List<GroupAccountHistoryEntry>();
foreach (JsonElement item in items.EnumerateArray())
{
if (!item.TryGetProperty("amount", out JsonElement rawAmount) ||
!rawAmount.TryGetInt64(out long signed) ||
signed < int.MinValue || signed > int.MaxValue)
return false;
string kind = item.TryGetProperty("kind", out JsonElement k) &&
k.ValueKind == JsonValueKind.String ?
k.GetString() ?? string.Empty : string.Empty;
// The legacy Sales tab must never label ordinary
// transfers or refunds as a sale.
bool isSale = signed > 0 &&
(kind.Contains("sale", StringComparison.OrdinalIgnoreCase) ||
kind.Contains("commerce", StringComparison.OrdinalIgnoreCase) ||
kind.Contains("purchase", StringComparison.OrdinalIgnoreCase));
if (salesOnly && !isSale)
continue;
string note = item.TryGetProperty("description", out JsonElement d) &&
d.ValueKind == JsonValueKind.String ?
d.GetString() ?? string.Empty : string.Empty;
string reference = item.TryGetProperty("reference", out JsonElement r) &&
r.ValueKind == JsonValueKind.String ?
r.GetString() ?? string.Empty : string.Empty;
string timestamp = item.TryGetProperty("occurred_at", out JsonElement t) &&
t.ValueKind == JsonValueKind.String ?
t.GetString() ?? string.Empty : string.Empty;
if (DateTimeOffset.TryParse(timestamp,
out DateTimeOffset occurred))
timestamp = occurred.UtcDateTime.ToString("yyyy-MM-dd HH:mm");
rows.Add(new GroupAccountHistoryEntry
{
Description = (string.IsNullOrWhiteSpace(note) ? kind : note),
Time = timestamp,
// The ledger has no authenticated buyer display
// name; never guess a resident or counterparty.
User = "NV$ Ledger",
Item = string.IsNullOrWhiteSpace(reference) ? kind : reference,
Amount = (int)signed,
Type = 0
});
if (rows.Count >= 200)
break;
}
entries = rows;
return true;
}
catch (Exception e)
{
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Group history lookup failed for {0}: {1}",
groupId, e.Message);
return false;
}
}
// Ledger API always uses the account UUID; it never trusts a viewer
// supplied name or balance. Only authenticated group accountants
// reach this helper. Provisioning the group wallet is idempotent and
// does not create any NV$ or ledger postings.
private bool TryGetGroupBalance(UUID groupId, out uint balance)
{
balance = 0;
try
{
using HttpRequestMessage request = CreateRequest(
HttpMethod.Get, "/api/v1/economy/balance?account_id=" +
Uri.EscapeDataString(groupId.ToString()));
using HttpResponseMessage response = m_Http.Send(request);
if (response.StatusCode == HttpStatusCode.NotFound)
{
using HttpRequestMessage create = CreateRequest(
HttpMethod.Post, "/api/v1/economy/accounts/ensure");
create.Content = new StringContent(JsonSerializer.Serialize(new
{
account_id = groupId.ToString(),
account_class = "group",
display_name = "Group " + groupId.ToString()
}), Encoding.UTF8, "application/json");
using HttpResponseMessage created = m_Http.Send(create);
if (!created.IsSuccessStatusCode)
{
m_Log.WarnFormat("[NEX-ECONOMY-VIEWER]: Group wallet provision failed ({0}): HTTP {1}",
groupId, (int)created.StatusCode);
return false;
}
// A newly provisioned group wallet has no postings.
balance = 0;
return true;
}
if (!response.IsSuccessStatusCode)
{
m_Log.WarnFormat("[NEX-ECONOMY-VIEWER]: Group balance HTTP {0} for group {1}",
(int)response.StatusCode, groupId);
return false;
}
using JsonDocument json = JsonDocument.Parse(
response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
if (!json.RootElement.TryGetProperty("account", out JsonElement wallet) ||
!wallet.TryGetProperty("balance", out JsonElement money) ||
!money.TryGetInt64(out long ledgerBalance))
return false;
// The viewer packet uses uint, while the ledger is signed
// 64-bit. Do not silently saturate or replace a negative
// balance with an apparently valid amount.
if (ledgerBalance < 0 || ledgerBalance > uint.MaxValue)
{
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Group balance outside viewer range for {0}",
groupId);
return false;
}
balance = (uint)ledgerBalance;
return true;
}
catch (Exception e)
{
m_Log.WarnFormat("[NEX-ECONOMY-VIEWER]: Group balance failed for {0}: {1}",
groupId, e.Message);
return false;
}
}
private void ClientClosed(
UUID agentId,
Scene scene)
{
// Client event subscriptions die with the client connection.
// Keep this handler only to match the EventManager contract and
// avoid retaining per-client state in this module.
}
private void EconomyDataRequestHandler(
IClientAPI client)
{
if (client?.Scene is not Scene scene)
return;
client.SendEconomyData(
1f,
scene.RegionInfo.ObjectCapacity,
0,
0,
GroupCreationCharge,
0,
0,
10f,
0,
1f,
0,
0,
0,
0,
UploadCharge,
0,
2f);
}
private void SendMoneyBalance(
IClientAPI client,
UUID agentID,
UUID sessionID,
UUID transactionID)
{
if (client == null ||
client.AgentId != agentID ||
client.SessionId != sessionID)
{
return;
}
int balance =
GetBalance(agentID);
client.SendMoneyBalance(
transactionID,
true,
Array.Empty<byte>(),
balance,
0,
UUID.Zero,
false,
UUID.Zero,
false,
0,
string.Empty);
m_Log.InfoFormat(
"[NEX-ECONOMY-VIEWER]: MoneyBalanceReply mit {0} NV$ an Firestorm-Client {1} gesendet.",
balance,
agentID);
}
private void MoneyTransferAction(
object sender,
EventManager.MoneyTransferArgs e)
{
if (e == null ||
e.amount <= 0)
{
return;
}
UUID paymentReceiver =
e.receiver;
bool objectPayment =
TryResolveLocalObjectOwner(
e.receiver,
out UUID objectOwner);
if (objectPayment)
paymentReceiver = objectOwner;
Guid commerceOrderId =
Guid.NewGuid();
string reason;
bool success;
if (objectPayment)
{
success =
CommercePaymentInternal(
e.sender,
paymentReceiver,
e.amount,
"VendorPayment",
string.IsNullOrWhiteSpace(e.description)
? "Inworld object payment"
: e.description,
"object:" +
e.receiver.ToString(),
commerceOrderId,
out reason);
}
else
{
success =
MoveMoneyInternal(
e.sender,
paymentReceiver,
e.amount,
e.description,
"viewer-event-" +
Guid.NewGuid().ToString("N"),
out reason);
}
if (!success)
{
IClientAPI client =
LocateClient(
e.sender);
client?.SendAgentAlertMessage(
string.IsNullOrWhiteSpace(reason)
? "NV$ transfer failed."
: reason,
false);
return;
}
SendBalanceRefresh(
e.sender);
SendBalanceRefresh(
paymentReceiver);
LocateClient(
e.sender)
?.SendAgentAlertMessage(
"NV$ transfer completed: " +
e.amount +
" NV$.",
false);
IClientAPI receiverClient =
LocateClient(
paymentReceiver);
if (receiverClient != null &&
paymentReceiver != e.sender)
{
receiverClient.SendAgentAlertMessage(
"NV$ received: " +
e.amount +
" NV$.",
false);
}
if (objectPayment)
{
try
{
OnObjectPaid?.Invoke(
e.receiver,
e.sender,
e.amount);
}
catch (Exception ex)
{
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: ObjectPaid subscriber failed: {0}",
ex.Message);
}
}
}
private void ApplyFee(
UUID agentID,
int amount,
string reference)
{
if (amount <= 0)
return;
if (m_FeeWalletId.IsZero())
{
throw new InvalidOperationException(
"NV$ fee wallet is not configured.");
}
if (!MoveMoneyInternal(
agentID,
m_FeeWalletId,
amount,
reference,
"fee-" +
Guid.NewGuid().ToString("N"),
out string reason))
{
throw new InvalidOperationException(
string.IsNullOrWhiteSpace(reason)
? "NV$ fee transfer failed."
: reason);
}
}
private bool CommercePaymentInternal(
UUID buyer,
UUID seller,
int amount,
string kind,
string reference,
string externalReference,
Guid orderId,
out string reason)
{
reason =
string.Empty;
if (!m_Enabled ||
buyer.IsZero() ||
seller.IsZero() ||
buyer == seller ||
amount <= 0 ||
orderId == Guid.Empty)
{
reason =
"Invalid NV$ commerce payment.";
return false;
}
try
{
if (!TryResolveWallet(buyer, true, out UUID buyerWallet,
out reason) ||
!TryResolveWallet(seller, false, out UUID sellerWallet,
out reason) ||
!EnsureLocalServiceWallet(buyer, out reason) ||
!EnsureLocalServiceWallet(seller, out reason))
return false;
byte[] payload =
JsonSerializer.SerializeToUtf8Bytes(
new
{
order_id =
orderId.ToString(),
kind,
buyer_account_id =
buyerWallet.ToString(),
seller_account_id =
sellerWallet.ToString(),
amount,
reference =
string.IsNullOrWhiteSpace(reference)
? "NexCommerce payment"
: reference,
external_reference =
externalReference ??
string.Empty
});
using HttpRequestMessage request =
CreateRequest(
HttpMethod.Post,
"/api/v1/commerce/orders");
request.Content =
new ByteArrayContent(
payload);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue(
"application/json");
using HttpResponseMessage response =
m_Http.Send(request);
if (response.IsSuccessStatusCode)
return true;
reason =
ReadErrorMessage(
response);
return false;
}
catch (Exception e)
{
reason =
"NexCommerce service unavailable.";
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Commerce payment {0}->{1} failed: {2}",
buyer,
seller,
e.Message);
return false;
}
}
private bool RefundCommerceInternal(
Guid orderId,
string reasonText,
out string reason)
{
reason =
string.Empty;
try
{
byte[] payload =
JsonSerializer.SerializeToUtf8Bytes(
new
{
reason =
string.IsNullOrWhiteSpace(reasonText)
? "Commerce rollback"
: reasonText
});
using HttpRequestMessage request =
CreateRequest(
HttpMethod.Post,
"/api/v1/commerce/orders/" +
orderId.ToString("D") +
"/refund");
request.Content =
new ByteArrayContent(
payload);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue(
"application/json");
using HttpResponseMessage response =
m_Http.Send(request);
if (response.IsSuccessStatusCode)
return true;
reason =
ReadErrorMessage(
response);
return false;
}
catch (Exception e)
{
reason =
"NexCommerce refund service unavailable.";
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Commerce refund {0} failed: {1}",
orderId,
e.Message);
return false;
}
}
private bool MoveMoneyInternal(
UUID fromUser,
UUID toUser,
int amount,
string reference,
string idempotencyKey,
out string reason)
{
reason =
string.Empty;
if (!m_Enabled ||
fromUser.IsZero() ||
toUser.IsZero() ||
fromUser == toUser ||
amount <= 0)
{
reason =
"Invalid NV$ transfer.";
return false;
}
try
{
if (!TryResolveWallet(fromUser, true, out UUID fromWallet,
out reason) ||
!TryResolveWallet(toUser, false, out UUID toWallet,
out reason) ||
fromWallet == toWallet ||
!EnsureLocalServiceWallet(fromUser, out reason) ||
!EnsureLocalServiceWallet(toUser, out reason))
return false;
byte[] payload =
JsonSerializer.SerializeToUtf8Bytes(
new
{
from_account_id =
fromWallet.ToString(),
to_account_id =
toWallet.ToString(),
amount,
reference =
string.IsNullOrWhiteSpace(reference)
? "Viewer transfer"
: reference
});
using HttpRequestMessage request =
CreateRequest(
HttpMethod.Post,
"/api/v1/economy/transfers");
request.Headers.TryAddWithoutValidation(
"Idempotency-Key",
idempotencyKey);
request.Content =
new ByteArrayContent(
payload);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue(
"application/json");
using HttpResponseMessage response =
m_Http.Send(request);
if (response.IsSuccessStatusCode)
return true;
reason =
ReadErrorMessage(
response);
return false;
}
catch (Exception e)
{
reason =
"NV$ service unavailable.";
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Transfer {0}->{1} failed: {2}",
fromUser,
toUser,
e.Message);
return false;
}
}
private HttpRequestMessage CreateRequest(
HttpMethod method,
string path)
{
HttpRequestMessage request =
new HttpRequestMessage(
method,
m_WorldApiBaseUrl +
path);
request.Headers.TryAddWithoutValidation(
"X-NexVerse-Api-Key",
m_ApiKey);
request.Headers.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
return request;
}
private static string ReadErrorMessage(
HttpResponseMessage response)
{
try
{
string json =
response.Content
.ReadAsStringAsync()
.GetAwaiter()
.GetResult();
using JsonDocument document =
JsonDocument.Parse(
json);
if (document.RootElement.TryGetProperty(
"message",
out JsonElement message) &&
message.ValueKind ==
JsonValueKind.String)
{
return
message.GetString() ??
"NV$ transfer failed.";
}
}
catch
{
}
return
"NV$ request failed (" +
(int)response.StatusCode +
").";
}
private IClientAPI LocateClient(
UUID agentId)
{
lock (m_Sync)
{
foreach (Scene scene in
m_Scenes.Values)
{
ScenePresence presence =
scene.GetScenePresence(
agentId);
if (presence?.ControllingClient !=
null)
{
return
presence.ControllingClient;
}
}
}
return null;
}
private void SendBalanceRefresh(
UUID agentId)
{
IClientAPI client =
LocateClient(
agentId);
if (client == null ||
!client.IsActive)
{
return;
}
client.SendMoneyBalance(
UUID.Random(),
true,
Array.Empty<byte>(),
GetBalance(agentId),
0,
UUID.Zero,
false,
UUID.Zero,
false,
0,
string.Empty);
}
private void RefreshConnectedBalances()
{
if (!m_Enabled ||
Interlocked.Exchange(
ref m_BalanceRefreshRunning,
1) != 0)
{
return;
}
try
{
Scene[] scenes;
lock (m_Sync)
{
scenes =
new List<Scene>(
m_Scenes.Values)
.ToArray();
}
HashSet<UUID> refreshed =
new HashSet<UUID>();
foreach (Scene scene in scenes)
{
if (scene == null)
continue;
foreach (ScenePresence presence in
scene.GetScenePresences())
{
if (presence == null ||
presence.IsDeleted ||
presence.IsChildAgent ||
presence.IsNPC)
{
continue;
}
IClientAPI client =
presence.ControllingClient;
if (client == null ||
!client.IsActive ||
!refreshed.Add(
client.AgentId))
{
continue;
}
try
{
SendBalanceRefresh(
client.AgentId);
}
catch (Exception e)
{
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Periodischer Kontostands-Refresh fuer {0} fehlgeschlagen: {1}",
client.AgentId,
e.Message);
}
}
}
}
finally
{
Volatile.Write(
ref m_BalanceRefreshRunning,
0);
}
}
// Account IDs in the Viewer are raw avatar UUIDs. Never use a HG
// avatar's bare UUID as ledger authority: two foreign homes may use
// the same UUID, or it may collide with a local Resident.
private bool TryResolveWallet(UUID avatarId, bool activeGuestDebit,
out UUID walletId, out string reason)
{
walletId = avatarId;
reason = string.Empty;
if (avatarId.IsZero())
{
reason = "NV$ account ID missing.";
return false;
}
Scene[] scenes;
lock (m_Sync)
scenes = new List<Scene>(m_Scenes.Values).ToArray();
foreach (Scene scene in scenes)
{
if (scene == null ||
!scene.TryGetScenePresence(avatarId, out ScenePresence sp) ||
sp == null || sp.IsDeleted || sp.IsChildAgent ||
sp.IsNPC || sp.IsInTransit || sp.ControllingClient == null)
continue;
var circuit = scene.AuthenticateHandler?.GetAgentCircuitData(avatarId);
if (circuit == null || circuit.AgentID != avatarId ||
circuit.SessionID.IsZero() ||
circuit.SessionID != sp.ControllingClient.SessionId ||
sp.ControllingClient.AgentId != avatarId ||
!sp.ControllingClient.IsActive)
{
reason = "No authenticated active avatar circuit.";
return false;
}
// ViaHGLogin also occurs when OUR OWN residents return home
// from another grid. The flag is a route hint, not proof that
// an avatar owns a foreign wallet.
bool viaHypergrid = (circuit.teleportFlags &
(uint)Constants.TeleportFlags.ViaHGLogin) != 0;
bool userManagementLocal = scene.UserManagementModule == null ||
scene.UserManagementModule.IsLocalGridUser(avatarId);
// Check the authoritative local account, rather than trusting
// the user-management name/home cache or the teleport flag.
UserAccount account = scene.UserAccountService?
.GetUserAccount(scene.RegionInfo.ScopeID, avatarId);
bool hasLocalAccount = account != null && account.LocalToGrid;
string home = null;
if (circuit.ServiceURLs != null &&
circuit.ServiceURLs.TryGetValue("HomeURI", out object rawHome) &&
rawHome != null)
home = rawHome.ToString();
bool hasHome = !string.IsNullOrWhiteSpace(home);
bool localHome = hasHome && scene.SceneGridInfo != null &&
scene.SceneGridInfo.IsLocalHome(home) == 1;
if (hasLocalAccount)
{
// Never accept a foreign HomeURI as authority to spend a
// local account, even when its UUID matches UserAccounts.
// The Gatekeeper normally rejects this impersonation; the
// money module must enforce it independently as well.
if (hasHome && !localHome)
{
reason = "Local avatar UUID has a non-local HG HomeURI.";
return false;
}
if (viaHypergrid && !localHome)
{
reason = "Local HG return lacks verified local HomeURI.";
return false;
}
lock (m_Sync)
{
if (m_HypergridWallets.TryGetValue(avatarId,
out UUID cached))
{
// Old versions incorrectly cached home-returning
// residents as HG guests. Remove ONLY a binding
// derived from this verified local home, not one
// from a different grid with a colliding UUID.
UUID localHomeWallet = UUID.Zero;
if (localHome)
{
try
{
localHomeWallet = new UUID(
NexHypergridWalletIdentity.AccountId(
home, avatarId.Guid));
}
catch (ArgumentException)
{
reason = "Invalid verified local HomeURI.";
return false;
}
}
if (!localHome || cached != localHomeWallet)
{
reason = "Ambiguous avatar UUID across grid identities.";
return false;
}
m_HypergridWallets.Remove(avatarId);
m_Log.InfoFormat(
"[NEX-ECONOMY-VIEWER]: Entfernte veraltete HG-Wallet-Zuordnung fuer bestaetigten lokalen Avatar {0} nach HG-Rueckkehr.",
avatarId);
}
}
// Local residents ALWAYS use their original avatar UUID
// as the NV$ account. AllowHypergridGuests stays available to
// real foreign guests; it does not affect local wallets.
return true;
}
bool guest = viaHypergrid || !userManagementLocal ||
(account != null && !account.LocalToGrid);
if (!guest)
{
reason = "No authoritative local account for active avatar.";
return false;
}
if (localHome)
{
// Claimed local HomeURI, but no authoritative local user:
// never manufacture a foreign wallet for this identity.
reason = "Local HG HomeURI without a local user account.";
return false;
}
if (!m_AllowHypergridGuests)
{
reason = "HG NV$ participation is disabled by the operator.";
return false;
}
if (!hasHome)
{
reason = "Verified Hypergrid home URI is missing.";
return false;
}
UUID expected;
try
{
expected = new UUID(NexHypergridWalletIdentity.AccountId(
home, avatarId.Guid));
}
catch (ArgumentException)
{
reason = "Invalid verified Hypergrid home URI.";
return false;
}
lock (m_Sync)
if (m_HypergridWallets.TryGetValue(avatarId, out UUID previous) &&
previous != expected)
{
reason = "Conflicting verified Hypergrid homes for avatar UUID.";
return false;
}
if (!EnsureHypergridServiceWallet(avatarId, home,
expected, out reason))
return false;
lock (m_Sync)
m_HypergridWallets[avatarId] = expected;
walletId = expected;
return true;
}
// An already-authenticated guest can receive NV$ after
// leaving a local region, but cannot debit an offline wallet.
lock (m_Sync)
if (m_HypergridWallets.TryGetValue(avatarId, out UUID cached))
{
if (activeGuestDebit)
{
reason = "HG NV$ debits require a live verified session.";
return false;
}
walletId = cached;
return true;
}
// Ordinary local accounts and local group wallets remain
// fully backward compatible with their original UUIDs.
return true;
}
private bool EnsureHypergridServiceWallet(UUID avatarId, string home,
UUID expectedWallet, out string reason)
{
reason = string.Empty;
lock (m_Sync)
if (m_HypergridWallets.TryGetValue(avatarId, out UUID cached) &&
cached == expectedWallet)
return true;
try
{
byte[] body = JsonSerializer.SerializeToUtf8Bytes(new
{
avatar_id = avatarId.ToString(),
home_uri = home,
display_name = "HG " + avatarId.ToString()
});
using HttpRequestMessage request = CreateRequest(
HttpMethod.Post, "/api/v1/economy/hypergrid/wallets/ensure");
request.Content = new ByteArrayContent(body);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
using HttpResponseMessage response = m_Http.Send(request);
if (!response.IsSuccessStatusCode)
{
reason = "Central HG wallet provisioning rejected: " +
ReadErrorMessage(response);
return false;
}
using JsonDocument json = JsonDocument.Parse(
response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
if (!json.RootElement.TryGetProperty("account",
out JsonElement account) ||
!account.TryGetProperty("account_id", out JsonElement rawId) ||
!UUID.TryParse(rawId.GetString(), out UUID actual) ||
actual != expectedWallet)
{
reason = "Untrusted HG wallet provisioning response.";
return false;
}
return true;
}
catch (Exception e)
{
reason = "HG wallet service unavailable.";
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: HG wallet provisioning failed: {0}",
e.Message);
return false;
}
}
private bool EnsureLocalServiceWallet(
UUID accountId,
out string reason)
{
reason =
string.Empty;
if (!TryResolveLocalGroup(
accountId,
out string groupName))
{
return true;
}
try
{
byte[] payload =
JsonSerializer.SerializeToUtf8Bytes(
new
{
account_id =
accountId.ToString(),
account_class =
"group",
display_name =
string.IsNullOrWhiteSpace(groupName)
? accountId.ToString()
: groupName
});
using HttpRequestMessage request =
CreateRequest(
HttpMethod.Post,
"/api/v1/economy/accounts/ensure");
request.Content =
new ByteArrayContent(
payload);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue(
"application/json");
using HttpResponseMessage response =
m_Http.Send(request);
if (response.IsSuccessStatusCode)
return true;
reason =
ReadErrorMessage(
response);
return false;
}
catch (Exception e)
{
reason =
"NV$ group wallet provisioning failed.";
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Group wallet {0} provisioning failed: {1}",
accountId,
e.Message);
return false;
}
}
private bool TryResolveLocalGroup(
UUID groupId,
out string groupName)
{
groupName =
string.Empty;
if (groupId.IsZero())
return false;
lock (m_Sync)
{
foreach (Scene scene in
m_Scenes.Values)
{
IGroupsModule groups =
scene.RequestModuleInterface<IGroupsModule>();
GroupRecord record =
groups?.GetGroupRecord(
groupId);
if (record == null)
continue;
groupName =
record.GroupName ??
string.Empty;
return true;
}
}
return false;
}
private bool TryResolveLocalObjectOwner(
UUID objectId,
out UUID ownerId)
{
ownerId =
UUID.Zero;
lock (m_Sync)
{
foreach (Scene scene in
m_Scenes.Values)
{
SceneObjectPart part =
scene.GetSceneObjectPart(
objectId);
if (part?.ParentGroup == null ||
part.ParentGroup.IsDeleted)
{
continue;
}
ownerId =
part.ParentGroup.OwnerID;
return !ownerId.IsZero();
}
}
return false;
}
private bool IsLocalObject(
UUID objectId)
{
lock (m_Sync)
{
foreach (Scene scene in
m_Scenes.Values)
{
if (scene.GetSceneObjectPart(
objectId) != null)
{
return true;
}
}
}
return false;
}
}
}