feat(economy): isolated Hypergrid NV$ wallets and trusted session mapping (#168)

* feat(economy): provision isolated durable NV$ Hypergrid guest wallets via trusted API

* feat(economy): route verified HG guests through isolated wallet mapping in viewer module

* test(economy): HG wallet isolation, backend transfers, opt-in config and operator docs
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-10-11 20:56:57 +02:00
1 parent 885fa72a10
commit ed37b9db72
10 files changed
+553 -19

No files matched your search

@@ -84,6 +84,57 @@ namespace NexVerse.Core.Economy
return existing;
}
/// <summary>
/// HG guest wallets live in the SAME durable NV$ ledger, but are never
/// keyed by an unqualified avatar UUID. No credit is issued on creation.
/// Only the trusted simulator may supply the verified circuit identity.
/// </summary>
public NexLedgerAccount EnsureHypergridResidentAccount(
string verifiedHomeUri, Guid originalAvatarId, string displayName)
{
Guid walletId = NexHypergridWalletIdentity.AccountId(
verifiedHomeUri, originalAvatarId);
string reference = NexHypergridWalletIdentity.Reference(
verifiedHomeUri, originalAvatarId);
NexLedgerAccount existing = m_Ledger.GetAccount(walletId);
if (existing != null)
{
if (existing.AccountClass != NexLedgerAccountClass.Resident ||
existing.NormalSide != NexLedgerSide.Credit ||
!string.Equals(existing.CurrencyCode, NexLedgerCurrency.Code,
StringComparison.Ordinal) ||
!string.Equals(existing.Reference, reference,
StringComparison.Ordinal))
throw new NexLedgerConflictException(
"HG wallet ID collision or incompatible existing wallet.");
return existing;
}
string label = string.IsNullOrWhiteSpace(displayName)
? "Hypergrid " + originalAvatarId.ToString("D")
: displayName.Trim();
if (label.Length > NexLedgerAccount.DisplayNameLengthLimit)
throw new ArgumentOutOfRangeException(nameof(displayName));
NexLedgerAccount wallet = new NexLedgerAccount(walletId,
NexLedgerAccountClass.Resident, NexLedgerSide.Credit,
reference, label);
if (m_Ledger.TryCreateAccount(wallet))
return wallet;
existing = m_Ledger.GetAccount(walletId);
if (existing == null ||
existing.AccountClass != NexLedgerAccountClass.Resident ||
existing.NormalSide != NexLedgerSide.Credit ||
!string.Equals(existing.CurrencyCode, NexLedgerCurrency.Code,
StringComparison.Ordinal) ||
!string.Equals(existing.Reference, reference, StringComparison.Ordinal))
throw new NexLedgerConflictException(
"HG wallet identity conflict after concurrent creation.");
return existing;
}
public NexLedgerAccount EnsureSystemAccount(
Guid accountId,
string displayName)
@@ -0,0 +1,54 @@
// SPDX-License-Identifier: MPL-2.0
using System;
using System.Security.Cryptography;
using System.Text;
namespace NexVerse.Core.Economy
{
/// <summary>
/// Stable, domain-separated NV$ account identity for an authenticated
/// Hypergrid session. A home URI is an identity input, not an authorization
/// proof and never triggers a network fetch.
/// </summary>
public static class NexHypergridWalletIdentity
{
public static string CanonicalHome(string verifiedHomeUri)
{
if (!Uri.TryCreate(verifiedHomeUri, UriKind.Absolute, out Uri uri) ||
(uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp) ||
!string.IsNullOrEmpty(uri.UserInfo) || !string.IsNullOrEmpty(uri.Query) ||
!string.IsNullOrEmpty(uri.Fragment) ||
(uri.AbsolutePath.TrimEnd('/').Length != 0) ||
uri.Host.Length == 0)
throw new ArgumentException(
"Verified HG home must be a canonical HTTP(S) origin.",
nameof(verifiedHomeUri));
return uri.GetLeftPart(UriPartial.Authority).TrimEnd('/');
}
public static string Reference(string verifiedHomeUri, Guid originalAvatarId)
{
if (originalAvatarId == Guid.Empty)
throw new ArgumentException("Original HG avatar UUID is required.",
nameof(originalAvatarId));
string material = "opengenesislink:nvd:hypergrid:wallet:v1\n" +
CanonicalHome(verifiedHomeUri) + "\n" +
originalAvatarId.ToString("D");
return "hg:" + Convert.ToHexString(
SHA256.HashData(Encoding.UTF8.GetBytes(material))).ToLowerInvariant();
}
public static Guid AccountId(string verifiedHomeUri, Guid originalAvatarId)
{
string reference = Reference(verifiedHomeUri, originalAvatarId);
// 128 bits of the domain-separated SHA256 digest. Set RFC 4122
// version/variant bits for a stable name-derived UUID.
byte[] bytes = Convert.FromHexString(reference.Substring(3, 32));
bytes[7] = (byte)((bytes[7] & 0x0F) | 0x50);
bytes[8] = (byte)((bytes[8] & 0x3F) | 0x80);
return new Guid(bytes);
}
}
}
@@ -13,6 +13,7 @@ using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using NexVerse.Core.Economy;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
@@ -38,10 +39,16 @@ namespace NexVerse.RegionModules.Economy
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 string m_LocalEconomyUrl = string.Empty;
private string m_CurrencyPurchasePortalUrl = string.Empty;
private Dictionary<string, XmlRpcMethod> m_LegacyRpcHandlers;
@@ -189,6 +196,10 @@ namespace NexVerse.RegionModules.Economy
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);
string feeWallet =
economy.GetString(
@@ -357,7 +368,10 @@ namespace NexVerse.RegionModules.Economy
null;
lock (m_Sync)
{
m_Scenes.Clear();
m_HypergridWallets.Clear();
}
m_Http?.Dispose();
m_Http =
@@ -375,12 +389,20 @@ namespace NexVerse.RegionModules.Economy
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(
agentID.ToString()));
walletId.ToString()));
using HttpResponseMessage response =
m_Http.Send(request);
@@ -1284,15 +1306,13 @@ namespace NexVerse.RegionModules.Economy
try
{
if (!EnsureLocalServiceWallet(
buyer,
if (!TryResolveWallet(buyer, true, out UUID buyerWallet,
out reason) ||
!EnsureLocalServiceWallet(
seller,
out reason))
{
!TryResolveWallet(seller, false, out UUID sellerWallet,
out reason) ||
!EnsureLocalServiceWallet(buyer, out reason) ||
!EnsureLocalServiceWallet(seller, out reason))
return false;
}
byte[] payload =
JsonSerializer.SerializeToUtf8Bytes(
@@ -1302,9 +1322,9 @@ namespace NexVerse.RegionModules.Economy
orderId.ToString(),
kind,
buyer_account_id =
buyer.ToString(),
buyerWallet.ToString(),
seller_account_id =
seller.ToString(),
sellerWallet.ToString(),
amount,
reference =
string.IsNullOrWhiteSpace(reference)
@@ -1434,24 +1454,23 @@ namespace NexVerse.RegionModules.Economy
try
{
if (!EnsureLocalServiceWallet(
fromUser,
if (!TryResolveWallet(fromUser, true, out UUID fromWallet,
out reason) ||
!EnsureLocalServiceWallet(
toUser,
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 =
fromUser.ToString(),
fromWallet.ToString(),
to_account_id =
toUser.ToString(),
toWallet.ToString(),
amount,
reference =
string.IsNullOrWhiteSpace(reference)
@@ -1685,6 +1704,177 @@ namespace NexVerse.RegionModules.Economy
}
// 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;
}
bool guest = (circuit.teleportFlags &
(uint)Constants.TeleportFlags.ViaHGLogin) != 0 ||
(scene.UserManagementModule != null &&
!scene.UserManagementModule.IsLocalGridUser(avatarId));
if (!guest)
{
// A stale HG binding and a new local session with the
// same UUID must never share financial authority.
lock (m_Sync)
if (m_HypergridWallets.ContainsKey(avatarId))
{
reason = "Ambiguous avatar UUID across grid identities.";
return false;
}
return true;
}
if (!m_AllowHypergridGuests)
{
reason = "HG NV$ participation is disabled by the operator.";
return false;
}
if (circuit.ServiceURLs == null ||
!circuit.ServiceURLs.TryGetValue("HomeURI", out object rawHome) ||
rawHome == null)
{
reason = "Verified Hypergrid home URI is missing.";
return false;
}
string home = rawHome.ToString();
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)
+80
View File
@@ -185,6 +185,33 @@ namespace NexVerse.Server.Api
return;
}
// Dedicated service-only endpoint: the receiving simulator
// extracts home_uri and avatar_id from an authenticated circuit.
// Resident bearer tokens MUST NOT be able to mint HG identities.
if (string.Equals(path,
"/api/v1/economy/hypergrid/wallets/ensure",
StringComparison.OrdinalIgnoreCase))
{
if (!method.Equals("POST", StringComparison.OrdinalIgnoreCase))
{
MethodNotAllowed(response, "POST");
return;
}
if (!Authenticate(request, response, NexScopes.EconomyTransfer,
out NexPrincipal principal, out UserAccount account))
return;
if (account != null)
{
WriteError(response, HttpStatusCode.Forbidden,
"hypergrid_service_required",
"HG wallet provisioning requires a trusted simulator service.");
return;
}
HandleEnsureHypergridWallet(request, response, principal);
return;
}
const string transactionPrefix =
"/api/v1/economy/transactions/";
@@ -658,6 +685,59 @@ namespace NexVerse.Server.Api
}
}
private void HandleEnsureHypergridWallet(IOSHttpRequest request,
IOSHttpResponse response, NexPrincipal principal)
{
NexEconomyService economy = RequireEconomy(response);
if (economy == null || !TryBody(request, response, out JsonElement body))
return;
if (!TryGuid(body, "avatar_id", out Guid avatarId) ||
avatarId == Guid.Empty)
{
WriteError(response, HttpStatusCode.BadRequest,
"hypergrid_avatar_required", "A valid HG avatar_id is required.");
return;
}
string home = GetOptionalString(body, "home_uri");
string name = GetOptionalString(body, "display_name");
if (home.Length > 512 || name.Length > 255)
{
WriteError(response, HttpStatusCode.BadRequest,
"hypergrid_identity_too_long", "HG wallet identity is too long.");
return;
}
try
{
NexLedgerAccount wallet = economy.EnsureHypergridResidentAccount(
home, avatarId, name);
m_Audit.Record(new NexAuditEvent(principal.Subject,
"economy.hypergrid.wallet.ensure",
"ledger-account:" + wallet.AccountId.ToString("D"),
Correlation(response),
new Dictionary<string, string> {
["account_class"] = "hypergrid_resident"
}));
WriteJson(response, new {
account = AccountPayload(wallet,
economy.GetBalance(wallet.AccountId),
economy.GetAccountState(wallet.AccountId)),
correlation_id = Correlation(response)
}, HttpStatusCode.OK);
}
catch (ArgumentException)
{
WriteError(response, HttpStatusCode.BadRequest,
"hypergrid_identity_invalid", "Invalid verified HG home or avatar identity.");
}
catch (Exception e)
{
WriteEconomyFailure(response, e);
}
}
private void HandleEnsureWallet(
IOSHttpRequest request,
IOSHttpResponse response,
+6
View File
@@ -1063,6 +1063,12 @@
; Set to 0 to disable periodic refresh.
BalanceRefreshSeconds = 5
; Hypergrid guests can hold independent NV$ accounts, derived from the
; trusted simulator circuit HomeURI + original avatar UUID. Disabled
; until operators validate HG sessions and local payout policies.
; No foreign-grid currency exchange and no ATM withdrawals are enabled.
AllowHypergridGuests = false
; Optional secure web portal opened/recommended by the legacy Firestorm
; buy-currency helper. No currency is minted by unauthenticated XML-RPC.
CurrencyPurchasePortalUrl = ""
+6
View File
@@ -1076,6 +1076,12 @@
; Set to 0 to disable periodic refresh.
BalanceRefreshSeconds = 5
; Hypergrid guests can hold independent NV$ accounts, derived from the
; trusted simulator circuit HomeURI + original avatar UUID. Disabled
; until operators validate HG sessions and local payout policies.
; No foreign-grid currency exchange and no ATM withdrawals are enabled.
AllowHypergridGuests = false
; Optional secure web portal opened/recommended by the legacy Firestorm
; buy-currency helper. No currency is minted by unauthenticated XML-RPC.
CurrencyPurchasePortalUrl = ""
+59
View File
@@ -118,3 +118,62 @@ Ledger-Schema v4 ergaenzt ausschliesslich Workflow-Zustaende neben dem unveraend
NexCommerce vereinheitlicht Vendor-Zahlungen, Objektverkaeufe, Marketplace, Landkauf, Eventtickets, Mieten und Merchant-Refunds ueber persistente Orders, die auf ihre Ledger-Transaktionen zeigen. Der Viewer und Simulator behalten keine eigene Geld-Datenbank.
Der Landhandel trennt Katalog und Weltzustand: Listings/Leases sind OpenGenesisLINK-Workflowdaten; die eigentlichen Parcel-Rechte bleiben im nativen LandManagementModule. Beim Viewer-Landkauf wird der Eigentumswechsel erst nach erfolgreichem NV$-Settlement ausgefuehrt.
## Hypergrid-Bewohner als NV$-Teilnehmer (11.10.2026, opt-in)
**Ziel:** Besucher aus anderen OpenSimulator-Hypergrids duerfen im
NexVerse-Grid dieselbe **virtuelle** NV$-Wirtschaft verwenden, ohne
dass Guthaben oder Rechte eines lokalen Avatars vermischt werden.
- **Identitaet:** Die Region liest `HomeURI`, urspruengliche Avatar-UUID
und Session-ID ausschliesslich aus der serverseitig authentifizierten
Hypergrid-AgentCircuitData. Die Herkunft wird bei jeder lebenden
Gast-Session prueft. Ein Name, Objekttext oder Viewer-POST gilt
**niemals** als Identitaetsnachweis.
- **Wallet:** `NexHypergridWalletIdentity` erzeugt eine stabile,
gehaertete Account-UUID aus kanonischem Home-Grid-Origin und
Original-Avatar-UUID. Anderes Grid, gleiche Avatar-UUID → **anderes NV$-Konto**.
Der Ledger speichert das Konto als Resident-Wallet mit eindeutigem
`hg:`-Referenzschluessel und dem ueblichen Double-Entry-Journal.
- **Robust:** `POST /api/v1/economy/hypergrid/wallets/ensure`
ist ausschliesslich mit einem vertrauenswuerdigen Maschinen-Key
(`economy:transfer`, kein Avatar-Bearer) aufrufbar. Die Ableitung
erfolgt dort *erneut*. Wallet-Neuanlage ist idempotent und vergibt
**0 NV$**; NVBAN kann anschliessend als Alias vergeben werden.
Der Simulator speichert keine Ledgerdatenbank.
- **Viewer & Zahlungen:** Der `NexVerseMoneyModule`-Adapter bildet den
Live-Agent auf das HG-Wallet ab. Anzeige des NV$-Saldos, normale
Transfers und Inworld-Kaeufe laufen ueber die existierende zentrale
Economy-/Commerce-Policy; fehlende oder widerspruechliche Identitaet
verweigert die Zahlung. Beim Verlassen der Region sind Ausgaben
von diesem Gast ohne erneut gepruefte Live-Session gesperrt.
- **Aktivierung:** Unter `[NexEconomyViewer]` in der tatsaechlich
geladenen Simulator-INI `AllowHypergridGuests = true` setzen,
**erst nach Test** mit mindestens zwei verschiedenen Home-Grids.
Standard: `false`. Der vorhandene `NEXVERSE_ECONOMY_API_KEY`
benoetigt weiterhin die bisherigen minimalen `economy:read` und
`economy:transfer`-Scopes. Kein HG-Economy-Key im Viewer.
**Explizit NICHT enthalten:** Transfer von Fremdgrid-Waehrungen,
Hypergrid-weite Echtgeld-Zahlungen, grenzueberschreitender Wallet-Zugriff
ohne lokale authentifizierte Session, NV$-Wechselkurse und Geldautomaten.
Ein HG-Gast hat **nur ein NexVerse-NV$-Guthaben**, kein
geldliches Guthaben auf seinem Heimatgrid.
### Spaeterer NexVerse-Geldautomat
Einzahlung/Auszahlung soll als **rein virtuelle NV$-Umbuchung**
zwischen bestaetigtem Gast-Wallet und einem getrennten,
autorisierten Bank-/Reservekonto erfolgen. Beide Wege benoetigen:
aktive inworld-Sitzung, HG-Identitaetsbeweis, Rate-Limits,
Betragsgrenzen, Idempotency-Key, genug Deckung, unveraenderliches
Double-Entry-Journal und expliziten Kontoauszug. Eine NVBAN ist
lediglich ein Alias und **kein zweiter Saldo**. Reale Geldzahlungen
oder die Uebertragung auf fremde Hypergrid-Economy-Systeme erfordern
spaeter eine gesonderte, autorisierte Integration; sie duerfen nicht
durch einen normalen LSL-`llGiveMoney`-Trick simuliert werden.
**Release-Status:** Opt-in Entwicklungsumfang, keine Live-Garantie.
Ein Test mit mindestens zwei fremden Home-Grids, identischen
Original-UUIDs auf unterschiedlichen Home-Grids und getrennten
Sim-Prozessen ist fuer produktive Aktivierung Pflicht.
@@ -25,5 +25,6 @@
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerSqlStore.cs" Link="NexLedgerSqlStore.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerSqlRuntime.cs" Link="NexLedgerSqlRuntime.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexEconomyService.cs" Link="NexEconomyService.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexHypergridWalletIdentity.cs" Link="NexHypergridWalletIdentity.cs" />
</ItemGroup>
</Project>
@@ -67,6 +67,61 @@ internal static class Program
systemId,
label + ": system account ensure is not idempotent");
// An HG wallet is neither a local avatar UUID nor shared between
// home grids. Run against BOTH SQL and in-memory backing stores.
Guid foreignAvatar = Guid.NewGuid();
string hgHome = "https://grid-one.example.org/";
Guid foreignId = NexHypergridWalletIdentity.AccountId(
hgHome, foreignAvatar);
Require(foreignId != foreignAvatar &&
foreignId == NexHypergridWalletIdentity.AccountId(
"https://GRID-ONE.example.org:443", foreignAvatar) &&
foreignId != NexHypergridWalletIdentity.AccountId(
"https://grid-two.example.org/", foreignAvatar),
label + ": HG origin isolation/canonicalization failed");
RequireThrows<ArgumentException>(
() => NexHypergridWalletIdentity.AccountId(
"https://example.org/user?id=x", foreignAvatar),
label + ": HG user-specific URL must not be a wallet origin");
RequireThrows<ArgumentException>(
() => NexHypergridWalletIdentity.AccountId(
"file:///etc/passwd", foreignAvatar),
label + ": unsafe non-HTTP HG origin accepted");
RequireThrows<ArgumentException>(
() => NexHypergridWalletIdentity.AccountId(
hgHome, Guid.Empty),
label + ": empty HG avatar UUID accepted");
NexLedgerAccount guestWallet = economy.EnsureHypergridResidentAccount(
hgHome, foreignAvatar, "Guest Test");
NexLedgerAccount otherHomeWallet =
economy.EnsureHypergridResidentAccount(
"https://grid-two.example.org/", foreignAvatar, "Guest Two");
Require(guestWallet.AccountId == foreignId &&
guestWallet.AccountClass == NexLedgerAccountClass.Resident &&
guestWallet.NormalSide == NexLedgerSide.Credit &&
guestWallet.Reference.StartsWith("hg:", StringComparison.Ordinal) &&
otherHomeWallet.AccountId != foreignId &&
economy.GetBalance(foreignId) == 0 &&
economy.EnsureHypergridResidentAccount(
hgHome, foreignAvatar, "new display").AccountId == foreignId,
label + ": duplicate/incorrect HG wallet or nonzero free grant");
NexVirtualBankAccount hgNvban =
economy.EnsureVirtualBankAccount(foreignId);
Require(economy.ResolveVirtualBankAccount(hgNvban.Identifier).AccountId ==
foreignId, label + ": HG wallet missing durable NVBAN mapping");
economy.AdministrativeAdjustment(foreignId, systemId, 7,
"test-operator", "explicit HG test credit");
economy.Transfer(foreignId, otherHomeWallet.AccountId, 3, "HG transfer");
Require(economy.GetBalance(foreignId) == 4 &&
economy.GetBalance(otherHomeWallet.AccountId) == 3,
label + ": HG transfer ledger balance mismatch");
RequireThrows<NexLedgerPolicyException>(
() => economy.Transfer(foreignId, otherHomeWallet.AccountId,
9999, "HG overdraft"),
label + ": HG account allowed overdraft");
NexLedgerAccount resident =
economy.EnsureResidentAccount(
residentId,
+32
View File
@@ -140,6 +140,7 @@ assert 'WorldApiBaseUrl = "https://world.stadt-nexverse.de"' in viewer_config
assert "ConnectionString" not in viewer_config
assert "CurrencyPurchasePortalUrl" in viewer_config
assert "BalanceRefreshSeconds = 5" in viewer_config
assert "AllowHypergridGuests = false" in viewer_config
print("NV$ World API and Viewer adapter contract: OK")
@@ -158,3 +159,34 @@ assert selection_pos >= 0 and enabled_pos >= 0 and selection_pos < enabled_pos
register_pos = viewer.find("scene.RegisterModuleInterface<IMoneyModule>")
balance_hook_pos = viewer.find("client.OnMoneyBalanceRequest +=")
assert register_pos >= 0 and balance_hook_pos >= 0
# HG wallet onboarding is opt-in and derived only from the trusted
# scene agent circuit. It must never rely on a viewer-supplied home URL.
hg_identity = Path("NexVerse/Core/Economy/NexHypergridWalletIdentity.cs").read_text()
hg_service = Path("NexVerse/Core/Economy/NexEconomyService.cs").read_text()
hg_tests = Path("tools/ci/NexEconomyPolicyRegression/Program.cs").read_text()
for marker in ("CanonicalHome(", "Reference(", "AccountId(",
"opengenesislink:nvd:hypergrid:wallet:v1",
"SHA256.HashData"):
assert marker in hg_identity, "Missing namespaced HG identity: " + marker
for marker in ("EnsureHypergridResidentAccount(",
'existing.Reference, reference', "NexLedgerSide.Credit"):
assert marker in hg_service, "Missing HG wallet policy: " + marker
for marker in ("/api/v1/economy/hypergrid/wallets/ensure",
"hypergrid_service_required",
"HandleEnsureHypergridWallet(", "account != null"):
assert marker in api, "Unprotected HG wallet API: " + marker
for marker in ("GetAgentCircuitData(avatarId)",
"circuit.SessionID != sp.ControllingClient.SessionId",
'TryGetValue("HomeURI", out object rawHome)',
"NexHypergridWalletIdentity.AccountId(",
"m_AllowHypergridGuests", "TryResolveWallet(fromUser, true",
"TryResolveWallet(toUser, false",
"TryResolveWallet(buyer, true", "TryResolveWallet(seller, false",
"HG NV$ debits require a live verified session"):
assert marker in viewer, "HG user wallet not safely mapped: " + marker
assert "AllowHypergridGuests = false" in Path("bin/OpenSim.ini").read_text()
for marker in ("HG origin isolation/canonicalization failed",
"HG transfer ledger balance mismatch",
"HG account allowed overdraft"):
assert marker in hg_tests, "Missing HG wallet regression: " + marker