Просмотр исходного кода

Merge upstream master (bcrypt-free P-224 fix) into subclass work

Millie 3 недель назад
Родитель
Сommit
eadcd30783

+ 7 - 0
Sunrise/Sunrise.vcxproj

@@ -138,6 +138,11 @@
     <ClCompile Include="src\state\runtime\state_account_runtime.cpp" />
     <ClCompile Include="src\state\runtime\state_account_acquisition_runtime.cpp" />
     <ClCompile Include="src\state\runtime\state_account_dismantle_runtime.cpp" />
+    <ClCompile Include="src\state\runtime\state_account_dismantle_staging.cpp" />
+    <ClCompile Include="src\state\runtime\state_account_equipment_runtime.cpp" />
+    <ClCompile Include="src\state\runtime\state_account_identity_runtime.cpp" />
+    <ClCompile Include="src\state\runtime\state_account_profile_runtime.cpp" />
+    <ClCompile Include="src\state\runtime\state_account_socket_runtime.cpp" />
     <ClCompile Include="src\state\runtime\state_account_item_action_runtime.cpp" />
     <ClCompile Include="src\core\ui\busy\ui_busy_overlay.cpp" />
     <ClCompile Include="src\core\ui\busy\ui_busy_state.cpp" />
@@ -645,6 +650,7 @@
     <ClCompile Include="src\middleware\crypto\random_bytes.cpp" />
     <ClCompile Include="src\middleware\crypto\sha256.cpp" />
     <ClCompile Include="src\middleware\crypto\ecc_p224.cpp" />
+    <ClCompile Include="src\middleware\crypto\ecc_p224_curve.cpp" />
     <ClCompile Include="src\middleware\crypto\tiger192.cpp" />
     <ClCompile Include="src\middleware\crypto\aes_cbc.cpp" />
     <ClCompile Include="src\middleware\crypto\hmac.cpp" />
@@ -1149,6 +1155,7 @@
     <ClInclude Include="src\middleware\crypto\random_bytes.h" />
     <ClInclude Include="src\middleware\crypto\sha256.h" />
     <ClInclude Include="src\middleware\crypto\ecc_p224.h" />
+    <ClInclude Include="src\middleware\crypto\ecc_p224_curve.h" />
     <ClInclude Include="src\middleware\crypto\tiger192.h" />
     <ClInclude Include="src\middleware\crypto\aes_cbc.h" />
     <ClInclude Include="src\middleware\crypto\hmac.h" />

+ 7 - 6
Sunrise/src/client/graphics/wine_compat.cpp

@@ -1,14 +1,15 @@
 #include "wine_compat.h"
 
-#include "windows.h"
+#include <Windows.h>
 
 namespace sunrise::client::graphics {
 
-// Helper function to let wine know that we will be using the display
-void initialize_wine_display() {
-    HDC hdc = GetDC(NULL);
-    if (hdc) {
-        ReleaseDC(NULL, hdc);
+/** Opens and releases the screen device context, which is what makes Wine attach its display. */
+void initialize_wine_display() noexcept {
+    const HDC screen = GetDC(nullptr);
+    if (screen != nullptr) {
+        (void)ReleaseDC(nullptr, screen);
     }
 }
+
 } // namespace sunrise::client::graphics

+ 9 - 2
Sunrise/src/client/graphics/wine_compat.h

@@ -1,5 +1,12 @@
 #pragma once
 
 namespace sunrise::client::graphics {
-void initialize_wine_display();
-}
+
+/**
+ * Opens and releases the screen device context once, which is what makes Wine attach its display.
+ * Wine defers that attach until something asks for the display, and the renderer expects it to
+ * have happened already. On Windows the call is harmless.
+ */
+void initialize_wine_display() noexcept;
+
+} // namespace sunrise::client::graphics

+ 32 - 20
Sunrise/src/client/hooks/egress/lifecycle/egress_guard_exports.cpp

@@ -1,10 +1,10 @@
-#include <string>
+#include <string_view>
 
+#include "../../../../core/runtime/host_environment.h"
 #include "../dns/egress_dns_replacements.h"
 #include "../extensions/egress_extension_replacements.h"
 #include "../resolver/replacements.h"
 #include "../winsock/replacements.h"
-#include "core/runtime/host_environment.h"
 #include "internal.h"
 
 namespace sunrise::client::hooks::egress::lifecycle {
@@ -22,29 +22,39 @@ export_definition(ModuleSlot module, const char* name, Function replacement) noe
     return ExportDefinition{module, name, reinterpret_cast<void*>(replacement)};
 }
 
-} // namespace
+/** Winsock's own generic failure code, which a refused connection call answers with. */
+constexpr int kSocketError = -1;
+/** WSAHOST_NOT_FOUND. A refused name lookup answers with it, so nothing resolves an address. */
+constexpr int kHostNotFound = 11001;
 
-// Dummy functions, these are not exported by wine so we provide at least 5 bytes for detours to
-// copy
-__declspec(noinline) int WSAAPI Dummy_WSAConnectByList() {
-    volatile int dummy = 0;
-    dummy += 1;
-    return -1; // SOCKET_ERROR
+/**
+ * Stands in for one export Wine does not provide, so the guard still owns the call.
+ * Detours copies at least five bytes from a target, so the body must not fold away to a bare
+ * return. The volatile store is what keeps it long enough to detour.
+ * @return The refusal the real export would answer with.
+ */
+__declspec(noinline) int WSAAPI absent_connect_by_list() noexcept {
+    volatile int occupied = 0;
+    occupied += 1;
+    return kSocketError;
 }
 
-__declspec(noinline) int WSAAPI Dummy_GetAddrInfoExA() {
-    volatile int dummy = 0;
-    dummy += 1;
-    return 11001; // WSAHOST_NOT_FOUND
+/** @return The refusal the real export would answer with. See absent_connect_by_list. */
+__declspec(noinline) int WSAAPI absent_address_info_ex_a() noexcept {
+    volatile int occupied = 0;
+    occupied += 1;
+    return kHostNotFound;
 }
 
+} // namespace
+
 /** Finds the whole Windows SDK egress surface for one atomic Detours batch. */
 bool resolve_specs(std::span<hooking::detour::Spec, kHookCount> specs,
                    std::span<const char*, kHookCount> names,
                    std::span<bool, kHookCount> resolved,
                    std::size_t& count) noexcept {
     count = 0;
-    const bool is_wine = sunrise::core::runtime::is_wine();
+    const bool underWine = core::runtime::is_wine();
 
     const std::array<ExportDefinition, kHookCount> exports{
         export_definition(ModuleSlot::winsock, "connect", &winsock::connection::connect_socket),
@@ -93,12 +103,14 @@ bool resolve_specs(std::span<hooking::detour::Spec, kHookCount> specs,
         void* target = reinterpret_cast<void*>(GetProcAddress(module, definition.name));
         names[index] = definition.name;
 
-        if (target == nullptr && is_wine) {
-            const std::string_view funcName(definition.name);
-            if (funcName == "WSAConnectByList") {
-                target = reinterpret_cast<void*>(&Dummy_WSAConnectByList);
-            } else if (funcName == "GetAddrInfoExA") {
-                target = reinterpret_cast<void*>(&Dummy_GetAddrInfoExA);
+        // Wine does not export every name Windows does. A missing one still needs a target, or
+        // the guard would leave that call unowned.
+        if (target == nullptr && underWine) {
+            const std::string_view exportName(definition.name);
+            if (exportName == "WSAConnectByList") {
+                target = reinterpret_cast<void*>(&absent_connect_by_list);
+            } else if (exportName == "GetAddrInfoExA") {
+                target = reinterpret_cast<void*>(&absent_address_info_ex_a);
             }
         }
 

+ 11 - 11
Sunrise/src/core/runtime/host_environment.cpp

@@ -1,18 +1,18 @@
 #include "host_environment.h"
 
-#include "windows.h"
+#include <Windows.h>
 
 namespace sunrise::core::runtime {
-bool is_wine() {
-    static const bool is_linux = []() -> bool {
-        HMODULE hntdll = GetModuleHandleW(L"ntdll.dll");
-        if (!hntdll) {
-            return false;
-        }
-        return GetProcAddress(hntdll, "wine_get_version")
-               != nullptr; // Exported by wine to identify itself but not by real windows
-    }();
 
-    return is_linux;
+/** @return True when the loaded ntdll exports Wine's own version entry point. */
+bool is_wine() noexcept {
+    // Wine exports this from ntdll to name itself and Windows never does. The host cannot change
+    // while the process lives, so the answer is resolved once.
+    static const bool underWine = [] {
+        const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
+        return ntdll != nullptr && GetProcAddress(ntdll, "wine_get_version") != nullptr;
+    }();
+    return underWine;
 }
+
 } // namespace sunrise::core::runtime

+ 8 - 2
Sunrise/src/core/runtime/host_environment.h

@@ -1,5 +1,11 @@
 #pragma once
 
 namespace sunrise::core::runtime {
-bool is_wine();
-}
+
+/**
+ * Reports whether the process runs under Wine instead of Windows.
+ * @return True when the loaded ntdll exports Wine's own version entry point.
+ */
+[[nodiscard]] bool is_wine() noexcept;
+
+} // namespace sunrise::core::runtime

+ 50 - 121
Sunrise/src/middleware/crypto/ecc_p224.cpp

@@ -3,9 +3,11 @@
 #include <Windows.h>
 
 #include <algorithm>
-#include <bcrypt.h>
 #include <vector>
 
+#include "ecc_p224_curve.h"
+#include "random_bytes.h"
+
 namespace sunrise::middleware::crypto::ecc {
 
 namespace {
@@ -21,15 +23,11 @@ constexpr std::array<std::byte, 4> kPublicFlagBits{
     kTagBitString, std::byte{0x02}, std::byte{0x07}, std::byte{0x00}};
 /** A DER length below this fits in the single byte that follows the tag. */
 constexpr std::size_t kShortFormLimit = 0x80;
-/** Bits in one byte. */
-constexpr unsigned kByteBits = 8;
-/** Public key blobs name the curve rather than carry its parameters. */
-constexpr ULONG kGenericPublicMagic = 0x504B4345;
-
-/** @return True for a BCrypt status that reports success. */
-[[nodiscard]] bool succeeded(NTSTATUS status) noexcept {
-    return status >= 0;
-}
+/**
+ * Draws allowed while sampling a private key. A draw outside 1 to n-1 is rarer than one in 2^112,
+ * so reaching the limit means the system randomness is broken, not that the sampling was unlucky.
+ */
+constexpr unsigned kScalarAttempts = 4;
 
 /**
  * Appends one positive integer in the minimal form DER requires.
@@ -161,86 +159,25 @@ void append_integer(std::vector<std::byte>& output, std::span<const std::byte> v
 }
 
 /**
- * Opens the agreement algorithm bound to this curve.
- * @param output Receives the provider handle only on success.
- * @return True when Windows offers the curve.
+ * Draws one private key from system randomness.
+ * @param output Receives a scalar in 1 to n-1, or stays zero.
+ * @return True when a usable scalar was drawn.
  */
-[[nodiscard]] bool open_provider(BCRYPT_ALG_HANDLE& output) noexcept {
-    BCRYPT_ALG_HANDLE algorithm = nullptr;
-    if (!succeeded(BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_ECDH_ALGORITHM, nullptr, 0))) {
-        return false;
-    }
-    const auto* curve = reinterpret_cast<PUCHAR>(const_cast<wchar_t*>(BCRYPT_ECC_CURVE_SECP224R1));
-    if (!succeeded(BCryptSetProperty(algorithm,
-                                     BCRYPT_ECC_CURVE_NAME,
-                                     const_cast<PUCHAR>(curve),
-                                     sizeof(BCRYPT_ECC_CURVE_SECP224R1),
-                                     0))) {
-        BCryptCloseAlgorithmProvider(algorithm, 0);
-        return false;
-    }
-    output = algorithm;
-    return true;
-}
-
-/**
- * Imports the peer's point as a public key.
- * @param algorithm Provider bound to the curve.
- * @param x Affine x.
- * @param y Affine y.
- * @param output Receives the key handle only on success.
- * @return True when Windows accepted the point.
- */
-[[nodiscard]] bool import_peer(BCRYPT_ALG_HANDLE algorithm,
-                               const std::array<std::byte, kFieldSize>& x,
-                               const std::array<std::byte, kFieldSize>& y,
-                               BCRYPT_KEY_HANDLE& output) noexcept {
-    std::array<std::byte, sizeof(BCRYPT_ECCKEY_BLOB) + (2 * kFieldSize)> blob{};
-    auto* header = reinterpret_cast<BCRYPT_ECCKEY_BLOB*>(blob.data());
-    header->dwMagic = kGenericPublicMagic;
-    header->cbKey = static_cast<ULONG>(kFieldSize);
-    std::copy(x.begin(), x.end(), blob.begin() + sizeof(BCRYPT_ECCKEY_BLOB));
-    std::copy(y.begin(), y.end(), blob.begin() + sizeof(BCRYPT_ECCKEY_BLOB) + kFieldSize);
-    return succeeded(BCryptImportKeyPair(algorithm,
-                                         nullptr,
-                                         BCRYPT_ECCPUBLIC_BLOB,
-                                         &output,
-                                         reinterpret_cast<PUCHAR>(blob.data()),
-                                         static_cast<ULONG>(blob.size()),
-                                         0));
-}
-
-/**
- * Runs the agreement and takes the raw secret.
- * @param ours Our private key.
- * @param theirs Peer's public key.
- * @param output Receives the x coordinate, high byte first.
- * @return True when Windows produced a full-width secret.
- */
-[[nodiscard]] bool raw_secret(BCRYPT_KEY_HANDLE ours,
-                              BCRYPT_KEY_HANDLE theirs,
-                              std::array<std::byte, kFieldSize>& output) noexcept {
-    BCRYPT_SECRET_HANDLE secret = nullptr;
-    if (!succeeded(BCryptSecretAgreement(ours, theirs, &secret, 0))) {
-        return false;
-    }
-    ULONG produced = 0;
-    const bool derived = succeeded(BCryptDeriveKey(secret,
-                                                   BCRYPT_KDF_RAW_SECRET,
-                                                   nullptr,
-                                                   reinterpret_cast<PUCHAR>(output.data()),
-                                                   static_cast<ULONG>(output.size()),
-                                                   &produced,
-                                                   0));
-    BCryptDestroySecret(secret);
-    if (!derived || produced != output.size()) {
-        // A short derive can still have written part of the secret.
-        SecureZeroMemory(output.data(), output.size());
-        return false;
+[[nodiscard]] bool generate_scalar(curve::Field& output) noexcept {
+    std::array<std::byte, kFieldSize> drawn{};
+    for (unsigned attempt = 0; attempt < kScalarAttempts; ++attempt) {
+        if (!random::fill(drawn)) {
+            break;
+        }
+        curve::load(drawn, output);
+        SecureZeroMemory(drawn.data(), drawn.size());
+        if (curve::valid_scalar(output)) {
+            return true;
+        }
     }
-    // Windows hands the raw secret back low byte first; the peer reads it high byte first.
-    std::reverse(output.begin(), output.end());
-    return true;
+    SecureZeroMemory(drawn.data(), drawn.size());
+    output = {};
+    return false;
 }
 
 } // namespace
@@ -252,47 +189,39 @@ bool agree(std::span<const std::byte> peerPublicKey, Agreement& output) noexcept
     if (!decode_public_key(peerPublicKey, peerX, peerY)) {
         return false;
     }
-    BCRYPT_ALG_HANDLE algorithm = nullptr;
-    if (!open_provider(algorithm)) {
+    curve::Point peer{};
+    curve::load(peerX, peer.x);
+    curve::load(peerY, peer.y);
+    if (!curve::on_curve(peer)) {
         return false;
     }
 
-    BCRYPT_KEY_HANDLE ours = nullptr;
-    BCRYPT_KEY_HANDLE theirs = nullptr;
-    bool complete = false;
-    if (succeeded(BCryptGenerateKeyPair(algorithm, &ours, kFieldSize * kByteBits, 0))
-        && succeeded(BCryptFinalizeKeyPair(ours, 0))) {
-        std::array<std::byte, sizeof(BCRYPT_ECCKEY_BLOB) + (2 * kFieldSize)> blob{};
-        ULONG produced = 0;
-        if (succeeded(BCryptExportKey(ours,
-                                      nullptr,
-                                      BCRYPT_ECCPUBLIC_BLOB,
-                                      reinterpret_cast<PUCHAR>(blob.data()),
-                                      static_cast<ULONG>(blob.size()),
-                                      &produced,
-                                      0))
-            && produced == blob.size()) {
-            const std::span<const std::byte> point{blob.data() + sizeof(BCRYPT_ECCKEY_BLOB),
-                                                   2 * kFieldSize};
-            complete =
-                encode_public_key(point.first(kFieldSize), point.last(kFieldSize), output.publicKey)
-                && import_peer(algorithm, peerX, peerY, theirs)
-                && raw_secret(ours, theirs, output.sharedSecret);
-        }
-    }
-
-    if (theirs != nullptr) {
-        BCryptDestroyKey(theirs);
+    curve::Field secret{};
+    if (!generate_scalar(secret)) {
+        return false;
     }
-    if (ours != nullptr) {
-        BCryptDestroyKey(ours);
+    curve::Point ours{};
+    curve::Point agreed{};
+    const bool multiplied =
+        curve::multiply(secret, curve::generator(), ours) && curve::multiply(secret, peer, agreed);
+    SecureZeroMemory(secret.data(), secret.size() * sizeof(secret[0]));
+    if (!multiplied) {
+        return false;
     }
-    BCryptCloseAlgorithmProvider(algorithm, 0);
-    if (!complete) {
+
+    std::array<std::byte, kFieldSize> ourX{};
+    std::array<std::byte, kFieldSize> ourY{};
+    curve::store(ours.x, ourX);
+    curve::store(ours.y, ourY);
+    curve::store(agreed.x, output.sharedSecret);
+    // The agreed point is secret material, so only the stored copy may outlive this call.
+    SecureZeroMemory(&agreed, sizeof(agreed));
+    if (!encode_public_key(ourX, ourY, output.publicKey)) {
         SecureZeroMemory(output.sharedSecret.data(), output.sharedSecret.size());
         output = {};
+        return false;
     }
-    return complete;
+    return true;
 }
 
 } // namespace sunrise::middleware::crypto::ecc

+ 1 - 1
Sunrise/src/middleware/crypto/ecc_p224.h

@@ -24,7 +24,7 @@ struct Agreement {
  * The pair is ephemeral and is destroyed before this returns; only the agreement survives.
  * @param peerPublicKey Peer's exported key, padding included.
  * @param output Receives the public key and the secret only on success.
- * @return True when the peer key parsed and Windows completed the agreement.
+ * @return True when the peer key parsed, sits on the curve, and the agreement completed.
  */
 [[nodiscard]] bool agree(std::span<const std::byte> peerPublicKey, Agreement& output) noexcept;
 

+ 455 - 0
Sunrise/src/middleware/crypto/ecc_p224_curve.cpp

@@ -0,0 +1,455 @@
+/**
+ * secp224r1 point arithmetic, in process and with no platform provider.
+ * Windows offers this curve through CNG, Wine does not, so the agreement carries its own math.
+ * Field values live in the Montgomery domain between the entry points.
+ */
+
+#include "ecc_p224_curve.h"
+
+#include <algorithm>
+
+namespace sunrise::middleware::crypto::ecc::curve {
+namespace {
+
+/** Bits in one field word. */
+constexpr unsigned kWordBits = 32;
+/** Bytes in one field word. */
+constexpr std::size_t kWordBytes = 4;
+/** Bits in one byte of the wire form. */
+constexpr unsigned kByteBits = 8;
+/** Every word of a value the mask selects. */
+constexpr std::uint32_t kAllBits = 0xFFFFFFFFU;
+
+/** p = 2^224 - 2^96 + 1, the secp224r1 field prime. */
+constexpr Field kPrime{
+    0x00000001, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF};
+/** p - 2, the exponent that inverts a field element by Fermat's theorem. */
+constexpr Field kPrimeMinusTwo{
+    0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF};
+/** n, the order of the generator. A private key must be below it. */
+constexpr Field kOrder{
+    0x5C5C2A3D, 0x13DD2945, 0xE0B8F03E, 0xFFFF16A2, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF};
+/** b of the curve equation y^2 = x^3 - 3x + b. */
+constexpr Field kCoefficientB{
+    0x2355FFB4, 0x270B3943, 0xD7BFD8BA, 0x5044B0B7, 0xF5413256, 0x0C04B3AB, 0xB4050A85};
+/** x of the generator. */
+constexpr Field kGeneratorX{
+    0x115C1D21, 0x343280D6, 0x56C21122, 0x4A03C1D3, 0x321390B9, 0x6BB4BF7F, 0xB70E0CBD};
+/** y of the generator. */
+constexpr Field kGeneratorY{
+    0x85007E34, 0x44D58199, 0x5A074764, 0xCD4375A0, 0x4C22DFE6, 0xB5F723FB, 0xBD376388};
+/** R mod p, which is the value one takes in the Montgomery domain. */
+constexpr Field kMontgomeryOne{
+    0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000000};
+/** R squared mod p, the multiplier that moves a plain value into the Montgomery domain. */
+constexpr Field kMontgomeryR2{
+    0x00000001, 0x00000000, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000};
+/** -p^-1 mod 2^32, the word each reduction step multiplies by. p ends in 1, so this is all bits. */
+constexpr std::uint32_t kMontgomeryFactor = 0xFFFFFFFFU;
+
+/** One point in Jacobian coordinates, where x = X/Z^2 and y = Y/Z^3. Z of zero is infinity. */
+struct Jacobian {
+    Field x{};
+    Field y{};
+    Field z{};
+};
+
+/**
+ * Adds two values as plain words.
+ * @param augend Value added to.
+ * @param addend Value added.
+ * @param sum Receives the low 224 bits.
+ * @return The carry out of the top word.
+ */
+[[nodiscard]] std::uint32_t
+add_words(const Field& augend, const Field& addend, Field& sum) noexcept {
+    std::uint64_t carry = 0;
+    for (std::size_t index = 0; index < kWords; ++index) {
+        const std::uint64_t total =
+            static_cast<std::uint64_t>(augend[index]) + addend[index] + carry;
+        sum[index] = static_cast<std::uint32_t>(total);
+        carry = total >> kWordBits;
+    }
+    return static_cast<std::uint32_t>(carry);
+}
+
+/**
+ * Subtracts one value from another as plain words.
+ * @param minuend Value subtracted from.
+ * @param subtrahend Value subtracted.
+ * @param difference Receives the low 224 bits.
+ * @return One when the subtraction borrowed, which means the minuend is the smaller value.
+ */
+[[nodiscard]] std::uint32_t
+subtract_words(const Field& minuend, const Field& subtrahend, Field& difference) noexcept {
+    std::uint64_t borrow = 0;
+    for (std::size_t index = 0; index < kWords; ++index) {
+        const std::uint64_t total =
+            static_cast<std::uint64_t>(minuend[index]) - subtrahend[index] - borrow;
+        difference[index] = static_cast<std::uint32_t>(total);
+        borrow = (total >> kWordBits) & 1U;
+    }
+    return static_cast<std::uint32_t>(borrow);
+}
+
+/** @return True when every word is zero. */
+[[nodiscard]] bool is_zero(const Field& value) noexcept {
+    std::uint32_t bits = 0;
+    for (const std::uint32_t word : value) {
+        bits |= word;
+    }
+    return bits == 0;
+}
+
+/** @return True when left is below right. */
+[[nodiscard]] bool less_than(const Field& left, const Field& right) noexcept {
+    Field ignored{};
+    return subtract_words(left, right, ignored) != 0;
+}
+
+/**
+ * Picks one of two values without branching on the choice.
+ * @param take True to take the first value.
+ * @param first Value taken when the choice holds.
+ * @param second Value taken otherwise.
+ * @param output Receives the picked value.
+ */
+void select(bool take, const Field& first, const Field& second, Field& output) noexcept {
+    const std::uint32_t mask = take ? kAllBits : 0U;
+    for (std::size_t index = 0; index < kWords; ++index) {
+        output[index] = (first[index] & mask) | (second[index] & ~mask);
+    }
+}
+
+/**
+ * Multiplies in the Montgomery domain and reduces in the same pass.
+ * @param multiplicand First factor, below p.
+ * @param multiplier Second factor, below p.
+ * @param product Receives multiplicand * multiplier * R^-1 mod p. May alias either factor.
+ */
+void montgomery_multiply(const Field& multiplicand,
+                         const Field& multiplier,
+                         Field& product) noexcept {
+    // Two words above the field hold the running carries the reduction consumes.
+    std::array<std::uint32_t, kWords + 2> accumulator{};
+    for (std::size_t step = 0; step < kWords; ++step) {
+        std::uint64_t carry = 0;
+        for (std::size_t index = 0; index < kWords; ++index) {
+            const std::uint64_t sum =
+                static_cast<std::uint64_t>(accumulator[index])
+                + static_cast<std::uint64_t>(multiplicand[index]) * multiplier[step] + carry;
+            accumulator[index] = static_cast<std::uint32_t>(sum);
+            carry = sum >> kWordBits;
+        }
+        std::uint64_t top = static_cast<std::uint64_t>(accumulator[kWords]) + carry;
+        accumulator[kWords] = static_cast<std::uint32_t>(top);
+        accumulator[kWords + 1] = static_cast<std::uint32_t>(top >> kWordBits);
+
+        // Clearing the low word by a multiple of p is what divides the result by R.
+        const auto factor = static_cast<std::uint32_t>(static_cast<std::uint64_t>(accumulator[0])
+                                                       * kMontgomeryFactor);
+        carry = (static_cast<std::uint64_t>(accumulator[0])
+                 + static_cast<std::uint64_t>(factor) * kPrime[0])
+                >> kWordBits;
+        for (std::size_t index = 1; index < kWords; ++index) {
+            const std::uint64_t sum = static_cast<std::uint64_t>(accumulator[index])
+                                      + static_cast<std::uint64_t>(factor) * kPrime[index] + carry;
+            accumulator[index - 1] = static_cast<std::uint32_t>(sum);
+            carry = sum >> kWordBits;
+        }
+        top = static_cast<std::uint64_t>(accumulator[kWords]) + carry;
+        accumulator[kWords - 1] = static_cast<std::uint32_t>(top);
+        accumulator[kWords] =
+            accumulator[kWords + 1] + static_cast<std::uint32_t>(top >> kWordBits);
+    }
+
+    Field result{};
+    std::copy_n(accumulator.begin(), kWords, result.begin());
+    Field reduced{};
+    const std::uint32_t borrow = subtract_words(result, kPrime, reduced);
+    // The result is below 2p, so the one conditional subtraction always finishes it.
+    select(accumulator[kWords] != 0 || borrow == 0, reduced, result, product);
+}
+
+/** Adds two field elements mod p. The sum may alias either input. */
+void field_add(const Field& augend, const Field& addend, Field& sum) noexcept {
+    Field total{};
+    const std::uint32_t carry = add_words(augend, addend, total);
+    Field reduced{};
+    const std::uint32_t borrow = subtract_words(total, kPrime, reduced);
+    select(carry != 0 || borrow == 0, reduced, total, sum);
+}
+
+/** Subtracts one field element from another mod p. The difference may alias either input. */
+void field_subtract(const Field& minuend, const Field& subtrahend, Field& difference) noexcept {
+    Field total{};
+    const std::uint32_t borrow = subtract_words(minuend, subtrahend, total);
+    Field wrapped{};
+    (void)add_words(total, kPrime, wrapped);
+    select(borrow != 0, wrapped, total, difference);
+}
+
+/** Moves a plain value into the Montgomery domain. */
+void to_montgomery(const Field& value, Field& output) noexcept {
+    montgomery_multiply(value, kMontgomeryR2, output);
+}
+
+/** Moves a Montgomery value back to its plain form. */
+void from_montgomery(const Field& value, Field& output) noexcept {
+    Field one{};
+    one[0] = 1;
+    montgomery_multiply(value, one, output);
+}
+
+/**
+ * Inverts a field element by raising it to p - 2.
+ * @param value Montgomery value, not zero.
+ * @param output Receives the Montgomery inverse.
+ */
+void montgomery_inverse(const Field& value, Field& output) noexcept {
+    Field result = kMontgomeryOne;
+    for (std::size_t index = kWords; index-- > 0;) {
+        for (unsigned bit = kWordBits; bit-- > 0;) {
+            montgomery_multiply(result, result, result);
+            if (((kPrimeMinusTwo[index] >> bit) & 1U) != 0) {
+                montgomery_multiply(result, value, result);
+            }
+        }
+    }
+    output = result;
+}
+
+/**
+ * Doubles one Jacobian point, using that the curve has a of -3.
+ * @param point Point to double, infinity allowed.
+ * @param output Receives the doubled point. May alias the input.
+ */
+void jacobian_double(const Jacobian& point, Jacobian& output) noexcept {
+    Field delta{};
+    Field gamma{};
+    Field beta{};
+    Field alpha{};
+    Field first{};
+    Field second{};
+    Field third{};
+    montgomery_multiply(point.z, point.z, delta);
+    montgomery_multiply(point.y, point.y, gamma);
+    montgomery_multiply(point.x, gamma, beta);
+    field_subtract(point.x, delta, first);
+    field_add(point.x, delta, second);
+    montgomery_multiply(first, second, third);
+    field_add(third, third, alpha);
+    field_add(alpha, third, alpha);
+
+    Jacobian result{};
+    montgomery_multiply(alpha, alpha, first);
+    field_add(beta, beta, second);
+    field_add(second, second, second);
+    field_add(second, second, third);
+    field_subtract(first, third, result.x);
+
+    field_add(point.y, point.z, first);
+    montgomery_multiply(first, first, first);
+    field_subtract(first, gamma, first);
+    field_subtract(first, delta, result.z);
+
+    field_subtract(second, result.x, first);
+    montgomery_multiply(alpha, first, first);
+    montgomery_multiply(gamma, gamma, third);
+    field_add(third, third, third);
+    field_add(third, third, third);
+    field_add(third, third, third);
+    field_subtract(first, third, result.y);
+    output = result;
+}
+
+/**
+ * Adds two Jacobian points.
+ * @param left First point, infinity allowed.
+ * @param right Second point, infinity allowed.
+ * @param output Receives the sum. May alias either input.
+ */
+void jacobian_add(const Jacobian& left, const Jacobian& right, Jacobian& output) noexcept {
+    if (is_zero(left.z)) {
+        output = right;
+        return;
+    }
+    if (is_zero(right.z)) {
+        output = left;
+        return;
+    }
+
+    Field leftSquare{};
+    Field rightSquare{};
+    Field leftScaled{};
+    Field rightScaled{};
+    Field leftLine{};
+    Field rightLine{};
+    Field first{};
+    Field second{};
+    montgomery_multiply(left.z, left.z, leftSquare);
+    montgomery_multiply(right.z, right.z, rightSquare);
+    montgomery_multiply(left.x, rightSquare, leftScaled);
+    montgomery_multiply(right.x, leftSquare, rightScaled);
+    montgomery_multiply(right.z, rightSquare, first);
+    montgomery_multiply(left.y, first, leftLine);
+    montgomery_multiply(left.z, leftSquare, second);
+    montgomery_multiply(right.y, second, rightLine);
+
+    Field difference{};
+    Field slope{};
+    field_subtract(rightScaled, leftScaled, difference);
+    field_subtract(rightLine, leftLine, slope);
+    if (is_zero(difference)) {
+        // Equal points need the doubling formula; opposite points sum to infinity.
+        if (is_zero(slope)) {
+            jacobian_double(left, output);
+        } else {
+            output = {};
+        }
+        return;
+    }
+    field_add(slope, slope, slope);
+
+    Field square{};
+    Field cube{};
+    Field scaled{};
+    field_add(difference, difference, square);
+    montgomery_multiply(square, square, square);
+    montgomery_multiply(difference, square, cube);
+    montgomery_multiply(leftScaled, square, scaled);
+
+    Jacobian result{};
+    montgomery_multiply(slope, slope, first);
+    field_subtract(first, cube, first);
+    field_add(scaled, scaled, second);
+    field_subtract(first, second, result.x);
+
+    field_subtract(scaled, result.x, first);
+    montgomery_multiply(slope, first, first);
+    montgomery_multiply(leftLine, cube, second);
+    field_add(second, second, second);
+    field_subtract(first, second, result.y);
+
+    field_add(left.z, right.z, first);
+    montgomery_multiply(first, first, first);
+    field_subtract(first, leftSquare, first);
+    field_subtract(first, rightSquare, first);
+    montgomery_multiply(first, difference, result.z);
+    output = result;
+}
+
+/**
+ * Converts a Jacobian point to affine coordinates.
+ * @param point Point with a non-zero z.
+ * @param output Receives the plain affine coordinates.
+ */
+void to_affine(const Jacobian& point, Point& output) noexcept {
+    Field inverse{};
+    Field square{};
+    Field cube{};
+    Field value{};
+    montgomery_inverse(point.z, inverse);
+    montgomery_multiply(inverse, inverse, square);
+    montgomery_multiply(square, inverse, cube);
+    montgomery_multiply(point.x, square, value);
+    from_montgomery(value, output.x);
+    montgomery_multiply(point.y, cube, value);
+    from_montgomery(value, output.y);
+}
+
+} // namespace
+
+/** @return The curve generator, which both sides multiply. */
+Point generator() noexcept {
+    return Point{kGeneratorX, kGeneratorY};
+}
+
+/** Checks that a point may be multiplied. */
+bool on_curve(const Point& point) noexcept {
+    if (!less_than(point.x, kPrime) || !less_than(point.y, kPrime)) {
+        return false;
+    }
+    Field x{};
+    Field y{};
+    to_montgomery(point.x, x);
+    to_montgomery(point.y, y);
+
+    Field left{};
+    Field right{};
+    Field term{};
+    montgomery_multiply(y, y, left);
+    montgomery_multiply(x, x, right);
+    montgomery_multiply(right, x, right);
+    field_add(x, x, term);
+    field_add(term, x, term);
+    field_subtract(right, term, right);
+    to_montgomery(kCoefficientB, term);
+    field_add(right, term, right);
+    return left == right;
+}
+
+/** Checks one private key. */
+bool valid_scalar(const Field& scalar) noexcept {
+    return !is_zero(scalar) && less_than(scalar, kOrder);
+}
+
+/** Multiplies a point by a scalar. */
+bool multiply(const Field& scalar, const Point& point, Point& output) noexcept {
+    Jacobian base{};
+    to_montgomery(point.x, base.x);
+    to_montgomery(point.y, base.y);
+    base.z = kMontgomeryOne;
+
+    // Both branches of every bit run, so the scalar does not steer the work that is done.
+    Jacobian accumulator{};
+    for (std::size_t index = kWords; index-- > 0;) {
+        for (unsigned bit = kWordBits; bit-- > 0;) {
+            Jacobian doubled{};
+            jacobian_double(accumulator, doubled);
+            Jacobian summed{};
+            jacobian_add(doubled, base, summed);
+            const bool take = ((scalar[index] >> bit) & 1U) != 0;
+            select(take, summed.x, doubled.x, accumulator.x);
+            select(take, summed.y, doubled.y, accumulator.y);
+            select(take, summed.z, doubled.z, accumulator.z);
+        }
+    }
+    if (is_zero(accumulator.z)) {
+        return false;
+    }
+    to_affine(accumulator, output);
+    return true;
+}
+
+/** Reads a wire value into a field element. */
+void load(std::span<const std::byte> bytes, Field& output) noexcept {
+    output = {};
+    if (bytes.size() != kWords * kWordBytes) {
+        return;
+    }
+    for (std::size_t index = 0; index < kWords; ++index) {
+        const std::size_t offset = (kWords - 1 - index) * kWordBytes;
+        std::uint32_t word = 0;
+        for (std::size_t step = 0; step < kWordBytes; ++step) {
+            word = (word << kByteBits) | std::to_integer<std::uint32_t>(bytes[offset + step]);
+        }
+        output[index] = word;
+    }
+}
+
+/** Writes a field element in its wire form. */
+void store(const Field& value, std::span<std::byte> bytes) noexcept {
+    if (bytes.size() != kWords * kWordBytes) {
+        return;
+    }
+    for (std::size_t index = 0; index < kWords; ++index) {
+        const std::size_t offset = (kWords - 1 - index) * kWordBytes;
+        for (std::size_t step = 0; step < kWordBytes; ++step) {
+            const auto shift = static_cast<unsigned>((kWordBytes - 1 - step) * kByteBits);
+            bytes[offset + step] = static_cast<std::byte>((value[index] >> shift) & 0xFFU);
+        }
+    }
+}
+
+} // namespace sunrise::middleware::crypto::ecc::curve

+ 62 - 0
Sunrise/src/middleware/crypto/ecc_p224_curve.h

@@ -0,0 +1,62 @@
+#pragma once
+
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <span>
+
+namespace sunrise::middleware::crypto::ecc::curve {
+
+/** A 224-bit value is 7 words of 32 bits, least significant word first. */
+inline constexpr std::size_t kWords = 7;
+/** Field elements and scalars share one representation. */
+using Field = std::array<std::uint32_t, kWords>;
+
+/** One affine point. Infinity has no affine form and is reported by a return value instead. */
+struct Point {
+    Field x{};
+    Field y{};
+};
+
+/** @return The curve generator, which both sides multiply. */
+[[nodiscard]] Point generator() noexcept;
+
+/**
+ * Checks that a point may be multiplied.
+ * A peer key off the curve leaks the scalar, so an unchecked point is a key disclosure.
+ * @param point Affine point, both coordinates in the range the field allows.
+ * @return True when both coordinates are below p and satisfy the curve equation.
+ */
+[[nodiscard]] bool on_curve(const Point& point) noexcept;
+
+/**
+ * Checks one private key.
+ * @param scalar Candidate key.
+ * @return True when the scalar is in 1 to n-1, the range a private key must fall in.
+ */
+[[nodiscard]] bool valid_scalar(const Field& scalar) noexcept;
+
+/**
+ * Multiplies a point by a scalar.
+ * @param scalar Multiplier, taken whole with no range check.
+ * @param point Affine point on the curve.
+ * @param output Receives the product only on success.
+ * @return False when the product is infinity, which cannot be written as an affine point.
+ */
+[[nodiscard]] bool multiply(const Field& scalar, const Point& point, Point& output) noexcept;
+
+/**
+ * Reads a wire value into a field element.
+ * @param bytes Exactly 28 bytes, high byte first.
+ * @param output Receives the value, or zero when the width is wrong.
+ */
+void load(std::span<const std::byte> bytes, Field& output) noexcept;
+
+/**
+ * Writes a field element in its wire form.
+ * @param value Field element.
+ * @param bytes Exactly 28 bytes, high byte first. A wrong width writes nothing.
+ */
+void store(const Field& value, std::span<std::byte> bytes) noexcept;
+
+} // namespace sunrise::middleware::crypto::ecc::curve

+ 463 - 0
Sunrise/src/state/runtime/state_account_dismantle_staging.cpp

@@ -0,0 +1,463 @@
+/** Dismantle staging: the payout it credits and the after-image it is committed against. */
+
+#include <Windows.h>
+
+#include <algorithm>
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <cstdio>
+#include <limits>
+#include <string_view>
+#include <utility>
+
+#include "../../core/logging/log.h"
+#include "../../middleware/datagen/family4/loadout/loadout_resolver.h"
+#include "../build_data/runtime.h"
+#include "runtime.h"
+#include "state.h"
+#include "state_account_transaction_helpers.h"
+#include "storage/internal.h"
+
+namespace sunrise::state {
+namespace runtime::detail {
+
+namespace authored_inventory = account::inventory;
+namespace item_details = build_data::items::details;
+namespace inventory_buckets = build_data::inventory::buckets;
+namespace family4_loadout = middleware::datagen::family4::loadout;
+
+/** Equipment slots 0-2 are weapons and 3-7 are class-specific armor. */
+constexpr std::uint8_t kGearEquipmentSlotCount = 8;
+
+/** Writes one exhaustive item-dismantle transaction checkpoint. */
+void report_dismantle(std::string_view stage,
+                      std::string_view result,
+                      std::string_view reason,
+                      std::uint32_t definitionHash,
+                      std::uint64_t characterSoid,
+                      std::uint64_t instanceSoid,
+                      std::size_t inventoryIndex,
+                      std::uint16_t inventoryRow,
+                      std::uint8_t equipmentSlot,
+                      std::size_t movedItemCount,
+                      std::uint32_t nextInventorySerial) noexcept {
+    std::array<char, core::log::kLineCapacity> line{};
+    const int count =
+        std::snprintf(line.data(),
+                      line.size(),
+                      "ev=dismantle stage=%.*s result=%.*s reason=%.*s definition_hash=0x%08X "
+                      "character=0x%llX instance=0x%llX inventory_index=%zu inventory_row=%u "
+                      "equipment_slot=%u moved_items=%zu next_serial=%u",
+                      static_cast<int>(stage.size()),
+                      stage.data(),
+                      static_cast<int>(result.size()),
+                      result.data(),
+                      static_cast<int>(reason.size()),
+                      reason.data(),
+                      definitionHash,
+                      static_cast<unsigned long long>(characterSoid),
+                      static_cast<unsigned long long>(instanceSoid),
+                      inventoryIndex,
+                      static_cast<unsigned>(inventoryRow),
+                      static_cast<unsigned>(equipmentSlot),
+                      movedItemCount,
+                      nextInventorySerial);
+    if (count > 0) {
+        core::log::write(core::log::Channel::state,
+                         result == "ok" ? core::log::Level::debug : core::log::Level::warn,
+                         {line.data(), static_cast<std::size_t>(count)});
+    }
+}
+
+/**
+ * Credits the supported client's ordinary weapon/armor dismantle payout.
+ *
+ * Capped stacks
+ * lose only the overflowing part, matching normal profile-inventory behavior.
+ * Every credited row
+ * receives a new mutation serial so the account observer can display it.
+ */
+[[nodiscard]] bool
+apply_dismantle_rewards(const AccountState& before,
+                        std::uint8_t equipmentSlot,
+                        AccountState& after,
+                        std::array<DismantleReward, kDismantleRewardCapacity>& rewards,
+                        std::size_t& rewardCount) noexcept {
+    after = before;
+    rewards = {};
+    rewardCount = 0;
+    if (!valid_profile_inventory(before)) {
+        return false;
+    }
+    if (equipmentSlot >= kGearEquipmentSlotCount) {
+        return true;
+    }
+
+    std::int32_t greatestMutationSerial = 0;
+    for (std::size_t index = 0; index < before.profileItemCount; ++index) {
+        greatestMutationSerial =
+            (std::max)(greatestMutationSerial, before.profileItems[index].mutationSerial);
+    }
+
+    for (std::size_t policyIndex = 0; policyIndex < before.dismantleRewardCount; ++policyIndex) {
+        const DismantleRewardPolicy& policy = before.dismantleRewards[policyIndex];
+        build_data::items::Definition definition{};
+        item_details::Definition detail{};
+        inventory_buckets::Descriptor bucket{};
+        if (policy.definitionHash == authored_inventory::kNoDefinitionHash || policy.quantity <= 0
+            || !build_data::find_item_definition_hash(policy.definitionHash, definition)
+            || definition.definitionHash != policy.definitionHash
+            || !build_data::find_configured_item_detail(definition.definitionIndex, detail)
+            || detail.definitionIndex != definition.definitionIndex
+            || detail.definitionHash != definition.definitionHash
+            || detail.bucketId != definition.bucketId
+            || detail.instancedDefinitionState != item_details::InstancedDefinitionState::stackable
+            || detail.maxStackSize <= 0
+            || !build_data::find_inventory_bucket_descriptor(detail.bucketId, bucket)
+            || bucket.arraySelector != inventory_buckets::ArraySelector::profile
+            || build_data::is_profile_action_source(definition.definitionIndex,
+                                                    definition.bucketId)) {
+            return false;
+        }
+
+        std::size_t profileIndex = after.profileItemCount;
+        for (std::size_t index = 0; index < after.profileItemCount; ++index) {
+            const authored_inventory::ProfileItem& item = after.profileItems[index];
+            if (item.definitionHash != policy.definitionHash) {
+                continue;
+            }
+            if (item.instanceSoid != 0 || item.quantity <= 0
+                || item.quantity > detail.maxStackSize) {
+                return false;
+            }
+            if (profileIndex == after.profileItemCount && item.quantity < detail.maxStackSize) {
+                profileIndex = index;
+            }
+        }
+
+        const bool appended = profileIndex == after.profileItemCount;
+        if ((appended && after.profileItemCount >= after.profileItems.size())
+            || greatestMutationSerial == (std::numeric_limits<std::int32_t>::max)()) {
+            continue;
+        }
+        const std::int32_t previousQuantity =
+            appended ? 0 : after.profileItems[profileIndex].quantity;
+        const std::int32_t available = detail.maxStackSize - previousQuantity;
+        const std::int32_t credited = (std::min)(policy.quantity, available);
+        if (credited <= 0) {
+            continue;
+        }
+
+        AccountState candidate = after;
+        const std::int32_t mutationSerial = greatestMutationSerial + 1;
+        const std::int32_t afterQuantity = previousQuantity + credited;
+        if (appended) {
+            candidate.profileItems[profileIndex] = {
+                0, policy.definitionHash, afterQuantity, mutationSerial};
+            ++candidate.profileItemCount;
+        } else {
+            candidate.profileItems[profileIndex].quantity = afterQuantity;
+            candidate.profileItems[profileIndex].mutationSerial = mutationSerial;
+        }
+        // A full native bucket drops this reward, but never blocks deletion of the source item.
+        if (!account::valid(candidate) || !valid_profile_inventory(candidate)) {
+            continue;
+        }
+        if (rewardCount >= rewards.size()) {
+            return false;
+        }
+        after = candidate;
+        greatestMutationSerial = mutationSerial;
+        rewards[rewardCount++] = {
+            policy.definitionHash, profileIndex, credited, afterQuantity, mutationSerial};
+    }
+    return account::valid(after) && valid_profile_inventory(after);
+}
+
+/**
+ * Builds the one canonical dismantle transition for an exact account snapshot.
+ *
+ * Surviving authored entries keep their mutation generation unless installed row placement moves
+ * them. Generation capacity is checked for every move before any survivor is changed.
+ */
+[[nodiscard]] bool stage_item_dismantle(const AccountState& account,
+                                        std::size_t characterIndex,
+                                        std::uint64_t instanceSoid,
+                                        PendingItemDismantle& mutation) noexcept {
+    mutation = {};
+    if (instanceSoid == 0 || !account::valid(account) || characterIndex >= account.characterCount
+        || !account.characters[characterIndex].selected) {
+        return false;
+    }
+
+    const CharacterState& before = account.characters[characterIndex];
+    std::size_t inventoryIndex = before.inventory.count;
+    for (std::size_t index = 0; index < before.inventory.count; ++index) {
+        if (before.inventory.values[index].instanceSoid == instanceSoid) {
+            inventoryIndex = index;
+            break;
+        }
+    }
+    if (inventoryIndex >= before.inventory.count
+        || (before.inventory.values[inventoryIndex].flags & authored_inventory::kLockedItemFlag)
+               != 0) {
+        return false;
+    }
+
+    family4_loadout::ResolvedLoadout beforeLoadout{};
+    std::uint16_t dismantledRow = 0;
+    std::uint8_t dismantledSlot = 0;
+    if (!family4_loadout::resolve(account, characterIndex, beforeLoadout)
+        || before.nextInventorySerial
+               > static_cast<std::uint32_t>((std::numeric_limits<std::int32_t>::max)())
+        || !find_unequipped_row(beforeLoadout, instanceSoid, dismantledRow, dismantledSlot)) {
+        return false;
+    }
+
+    CharacterState after = before;
+    const authored_inventory::Item dismantledItem = after.inventory.values[inventoryIndex];
+    for (std::size_t index = inventoryIndex; index + 1U < after.inventory.count; ++index) {
+        after.inventory.values[index] = after.inventory.values[index + 1U];
+    }
+    --after.inventory.count;
+    after.inventory.values[after.inventory.count] = {};
+
+    AccountState candidate = account;
+    candidate.characters[characterIndex] = after;
+    family4_loadout::ResolvedLoadout placedAfter{};
+    if (!account::valid(candidate)
+        || !family4_loadout::resolve(candidate, characterIndex, placedAfter)
+        || loadout_contains(placedAfter, instanceSoid)
+        || beforeLoadout.itemCount != placedAfter.itemCount + 1U) {
+        return false;
+    }
+
+    std::size_t movedItemCount = 0;
+    for (std::size_t index = 0; index < after.inventory.count; ++index) {
+        const std::uint64_t survivorSoid = after.inventory.values[index].instanceSoid;
+        std::uint16_t beforeRow = 0;
+        std::uint16_t afterRow = 0;
+        std::uint8_t beforeSlot = 0;
+        std::uint8_t afterSlot = 0;
+        if (!find_unequipped_row(beforeLoadout, survivorSoid, beforeRow, beforeSlot)
+            || !find_unequipped_row(placedAfter, survivorSoid, afterRow, afterSlot)
+            || beforeSlot != afterSlot) {
+            return false;
+        }
+        movedItemCount += static_cast<std::size_t>(beforeRow != afterRow);
+    }
+
+    // The serial is signed on the wire, so it must stay inside the positive int32 range.
+    constexpr std::uint32_t kMaximumInventorySerial =
+        static_cast<std::uint32_t>((std::numeric_limits<std::int32_t>::max)());
+    if (after.nextInventorySerial > kMaximumInventorySerial
+        || movedItemCount > kMaximumInventorySerial - after.nextInventorySerial) {
+        return false;
+    }
+
+    for (std::size_t index = 0; index < after.inventory.count; ++index) {
+        const std::uint64_t survivorSoid = after.inventory.values[index].instanceSoid;
+        std::uint16_t beforeRow = 0;
+        std::uint16_t afterRow = 0;
+        std::uint8_t beforeSlot = 0;
+        std::uint8_t afterSlot = 0;
+        if (!find_unequipped_row(beforeLoadout, survivorSoid, beforeRow, beforeSlot)
+            || !find_unequipped_row(placedAfter, survivorSoid, afterRow, afterSlot)
+            || beforeSlot != afterSlot) {
+            return false;
+        }
+        if (beforeRow != afterRow) {
+            after.inventory.values[index].mutationSerial =
+                static_cast<std::int32_t>(after.nextInventorySerial++);
+        }
+    }
+
+    candidate.characters[characterIndex] = after;
+    family4_loadout::ResolvedLoadout checkedAfter{};
+    if (!account::valid(candidate)
+        || !family4_loadout::resolve(candidate, characterIndex, checkedAfter)
+        || checkedAfter.itemCount != placedAfter.itemCount
+        || loadout_contains(checkedAfter, instanceSoid)) {
+        return false;
+    }
+    for (std::size_t index = 0; index < after.inventory.count; ++index) {
+        const std::uint64_t survivorSoid = after.inventory.values[index].instanceSoid;
+        std::uint16_t placedRow = 0;
+        std::uint16_t checkedRow = 0;
+        std::uint8_t placedSlot = 0;
+        std::uint8_t checkedSlot = 0;
+        if (!find_unequipped_row(placedAfter, survivorSoid, placedRow, placedSlot)
+            || !find_unequipped_row(checkedAfter, survivorSoid, checkedRow, checkedSlot)
+            || placedRow != checkedRow || placedSlot != checkedSlot) {
+            return false;
+        }
+    }
+
+    build_data::items::Definition dismantledDefinition{};
+    item_details::Definition dismantledDetail{};
+    if (!build_data::find_item_definition_hash(dismantledItem.definitionHash, dismantledDefinition)
+        || dismantledDefinition.definitionHash != dismantledItem.definitionHash
+        || !build_data::find_configured_item_detail(dismantledDefinition.definitionIndex,
+                                                    dismantledDetail)
+        || dismantledDetail.definitionIndex != dismantledDefinition.definitionIndex
+        || dismantledDetail.definitionHash != dismantledDefinition.definitionHash
+        || dismantledDetail.bucketId != dismantledDefinition.bucketId
+        || dismantledDetail.instancedDefinitionState
+               != item_details::InstancedDefinitionState::instanced
+        || !dismantledDetail.equipmentSlot.has_value()
+        || static_cast<std::uint8_t>(*dismantledDetail.equipmentSlot) != dismantledSlot) {
+        return false;
+    }
+
+    AccountState rewarded{};
+    std::array<DismantleReward, kDismantleRewardCapacity> rewards{};
+    std::size_t rewardCount = 0;
+    if (!apply_dismantle_rewards(candidate, dismantledSlot, rewarded, rewards, rewardCount)) {
+        return false;
+    }
+    candidate = rewarded;
+
+    mutation.beforeCharacter = before;
+    mutation.afterCharacter = after;
+    mutation.beforeProfileItems = account.profileItems;
+    mutation.afterProfileItems = candidate.profileItems;
+    mutation.rewards = rewards;
+    mutation.dismantledItem = dismantledItem;
+    mutation.accountSoid = account.primarySoid;
+    mutation.characterSoid = before.soid;
+    mutation.dismantledInstanceSoid = instanceSoid;
+    mutation.characterIndex = characterIndex;
+    mutation.expectedInventoryCount = before.inventory.count;
+    mutation.expectedProfileItemCount = account.profileItemCount;
+    mutation.afterProfileItemCount = candidate.profileItemCount;
+    mutation.inventoryIndex = inventoryIndex;
+    mutation.movedInventoryItemCount = movedItemCount;
+    mutation.rewardCount = rewardCount;
+    mutation.inventoryRow = dismantledRow;
+    mutation.equipmentSlot = dismantledSlot;
+    mutation.profileChanged = rewardCount != 0;
+    mutation.prepared = true;
+    return true;
+}
+
+/** @return True when both descriptions name the same credited profile mutation. */
+[[nodiscard]] bool same_dismantle_reward(const DismantleReward& left,
+                                         const DismantleReward& right) noexcept {
+    return left.definitionHash == right.definitionHash && left.profileIndex == right.profileIndex
+           && left.quantity == right.quantity && left.afterQuantity == right.afterQuantity
+           && left.mutationSerial == right.mutationSerial;
+}
+
+/** @return True when two independently staged dismantles carry the exact same after-images. */
+[[nodiscard]] bool same_dismantle_transition(const PendingItemDismantle& left,
+                                             const PendingItemDismantle& right) noexcept {
+    if (left.prepared != right.prepared || left.accountSoid != right.accountSoid
+        || left.characterSoid != right.characterSoid
+        || left.dismantledInstanceSoid != right.dismantledInstanceSoid
+        || left.characterIndex != right.characterIndex
+        || left.expectedInventoryCount != right.expectedInventoryCount
+        || left.expectedProfileItemCount != right.expectedProfileItemCount
+        || left.afterProfileItemCount != right.afterProfileItemCount
+        || left.inventoryIndex != right.inventoryIndex
+        || left.movedInventoryItemCount != right.movedInventoryItemCount
+        || left.rewardCount != right.rewardCount || left.inventoryRow != right.inventoryRow
+        || left.equipmentSlot != right.equipmentSlot || left.profileChanged != right.profileChanged
+        || !same_stationary_item(left.dismantledItem, right.dismantledItem)
+        || !same_character(left.beforeCharacter, right.beforeCharacter)
+        || !same_character(left.afterCharacter, right.afterCharacter)
+        || !same_profile_views(left.beforeProfileItems,
+                               left.expectedProfileItemCount,
+                               right.beforeProfileItems,
+                               right.expectedProfileItemCount)
+        || !same_profile_views(left.afterProfileItems,
+                               left.afterProfileItemCount,
+                               right.afterProfileItems,
+                               right.afterProfileItemCount)) {
+        return false;
+    }
+    for (std::size_t index = 0; index < left.rewards.size(); ++index) {
+        if (!same_dismantle_reward(left.rewards[index], right.rewards[index])) {
+            return false;
+        }
+    }
+    return true;
+}
+
+/** Applies a fully checked dismantle after-image over an exact current account view. */
+[[nodiscard]] bool materialize_item_dismantle(const AccountState& current,
+                                              const PendingItemDismantle& mutation,
+                                              AccountState& after) noexcept {
+    after = {};
+    if (!mutation.prepared || mutation.accountSoid == 0 || mutation.characterSoid == 0
+        || mutation.dismantledInstanceSoid == 0
+        || mutation.dismantledItem.instanceSoid != mutation.dismantledInstanceSoid
+        || mutation.dismantledItem.definitionHash == authored_inventory::kNoDefinitionHash
+        || mutation.characterIndex >= current.characterCount || mutation.expectedInventoryCount == 0
+        || mutation.expectedInventoryCount > authored_inventory::kCharacterItemCapacity
+        || mutation.expectedProfileItemCount > authored_inventory::kProfileItemCapacity
+        || mutation.afterProfileItemCount > authored_inventory::kProfileItemCapacity
+        || mutation.inventoryIndex >= mutation.expectedInventoryCount
+        || mutation.rewardCount > mutation.rewards.size()
+        || mutation.profileChanged != (mutation.rewardCount != 0)
+        || mutation.beforeCharacter.soid != mutation.characterSoid
+        || mutation.afterCharacter.soid != mutation.characterSoid
+        || mutation.beforeCharacter.inventory.count != mutation.expectedInventoryCount
+        || mutation.afterCharacter.inventory.count + 1U != mutation.expectedInventoryCount
+        || !same_stationary_item(mutation.beforeCharacter.inventory.values[mutation.inventoryIndex],
+                                 mutation.dismantledItem)
+        || current.primarySoid != mutation.accountSoid
+        || !same_profile_inventory(
+            current, mutation.beforeProfileItems, mutation.expectedProfileItemCount)) {
+        return false;
+    }
+    const CharacterState& character = current.characters[mutation.characterIndex];
+    if (!character.selected || character.soid != mutation.characterSoid
+        || !same_character(character, mutation.beforeCharacter)) {
+        return false;
+    }
+    for (std::size_t index = 0; index < mutation.rewards.size(); ++index) {
+        const DismantleReward& reward = mutation.rewards[index];
+        if (index < mutation.rewardCount) {
+            if (reward.definitionHash == authored_inventory::kNoDefinitionHash
+                || reward.profileIndex >= mutation.afterProfileItemCount || reward.quantity <= 0
+                || reward.afterQuantity < reward.quantity || reward.mutationSerial <= 0) {
+                return false;
+            }
+            const authored_inventory::ProfileItem& row =
+                mutation.afterProfileItems[reward.profileIndex];
+            if (row.instanceSoid != 0 || row.definitionHash != reward.definitionHash
+                || row.quantity != reward.afterQuantity
+                || row.mutationSerial != reward.mutationSerial) {
+                return false;
+            }
+        } else if (reward.definitionHash != 0 || reward.profileIndex != 0 || reward.quantity != 0
+                   || reward.afterQuantity != 0 || reward.mutationSerial != 0) {
+            return false;
+        }
+    }
+    if (!mutation.profileChanged
+        && !same_profile_views(mutation.beforeProfileItems,
+                               mutation.expectedProfileItemCount,
+                               mutation.afterProfileItems,
+                               mutation.afterProfileItemCount)) {
+        return false;
+    }
+
+    PendingItemDismantle canonical{};
+    if (!stage_item_dismantle(
+            current, mutation.characterIndex, mutation.dismantledInstanceSoid, canonical)
+        || !same_dismantle_transition(canonical, mutation)) {
+        return false;
+    }
+
+    after = current;
+    after.characters[mutation.characterIndex] = mutation.afterCharacter;
+    after.profileItems = mutation.afterProfileItems;
+    after.profileItemCount = mutation.afterProfileItemCount;
+    return account::valid(after) && valid_profile_inventory(after)
+           && !identity_uses_soid(after, mutation.dismantledInstanceSoid);
+}
+
+} // namespace runtime::detail
+} // namespace sunrise::state

+ 452 - 0
Sunrise/src/state/runtime/state_account_equipment_runtime.cpp

@@ -0,0 +1,452 @@
+/**
+ * Equipment placement helpers: native and semantic slots, resolved positions, and the
+ * comparisons one equipment transition is checked against.
+ */
+
+#include <Windows.h>
+
+#include <algorithm>
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <cstdio>
+#include <limits>
+#include <string_view>
+#include <utility>
+
+#include "../../core/logging/log.h"
+#include "../../middleware/datagen/family4/loadout/loadout_resolver.h"
+#include "../build_data/runtime.h"
+#include "runtime.h"
+#include "state.h"
+#include "state_account_transaction_helpers.h"
+#include "storage/internal.h"
+
+namespace sunrise::state {
+namespace runtime::detail {
+
+namespace authored_inventory = account::inventory;
+namespace item_details = build_data::items::details;
+namespace inventory_buckets = build_data::inventory::buckets;
+namespace family4_loadout = middleware::datagen::family4::loadout;
+
+/** Resolves the installed native equipment slot for one configured authored item. */
+[[nodiscard]] bool native_equipment_slot(const authored_inventory::Item& item,
+                                         std::uint8_t& slot) noexcept {
+    build_data::items::Definition definition{};
+    item_details::Definition detail{};
+    if (!build_data::find_item_definition_hash(item.definitionHash, definition)
+        || definition.definitionHash != item.definitionHash
+        || !build_data::find_configured_item_detail(definition.definitionIndex, detail)
+        || detail.definitionIndex != definition.definitionIndex
+        || detail.definitionHash != definition.definitionHash
+        || detail.bucketId != definition.bucketId || !detail.equipmentSlot.has_value()
+        || *detail.equipmentSlot < 0
+        || static_cast<std::size_t>(*detail.equipmentSlot) >= item_details::kEquipmentSlotCount) {
+        return false;
+    }
+    slot = static_cast<std::uint8_t>(*detail.equipmentSlot);
+    return true;
+}
+
+/** Resolves the installed physical inventory bucket for one configured authored item. */
+[[nodiscard]] bool inventory_bucket_id(const authored_inventory::Item& item,
+                                       std::uint8_t& bucketId) noexcept {
+    build_data::items::Definition definition{};
+    item_details::Definition detail{};
+    if (!build_data::find_item_definition_hash(item.definitionHash, definition)
+        || definition.definitionHash != item.definitionHash
+        || !build_data::find_configured_item_detail(definition.definitionIndex, detail)
+        || detail.definitionIndex != definition.definitionIndex
+        || detail.definitionHash != definition.definitionHash
+        || detail.bucketId != definition.bucketId) {
+        return false;
+    }
+    bucketId = detail.bucketId;
+    return true;
+}
+
+/** Maps the 16 proven native equipment positions onto their stable authored State slots. */
+[[nodiscard]] bool semantic_equipment_slot(std::uint8_t nativeSlot,
+                                           std::size_t& semanticIndex) noexcept {
+    using EquipmentSlot = authored_inventory::EquipmentSlot;
+    EquipmentSlot semanticSlot = EquipmentSlot::count;
+    switch (nativeSlot) {
+    case 0:
+        semanticSlot = EquipmentSlot::subclass;
+        break;
+    case 1:
+        semanticSlot = EquipmentSlot::helmet;
+        break;
+    case 2:
+        semanticSlot = EquipmentSlot::gauntlets;
+        break;
+    case 4:
+        semanticSlot = EquipmentSlot::chest;
+        break;
+    case 5:
+        semanticSlot = EquipmentSlot::legs;
+        break;
+    case 6:
+        semanticSlot = EquipmentSlot::classItem;
+        break;
+    case 7:
+        semanticSlot = EquipmentSlot::kinetic;
+        break;
+    case 8:
+        semanticSlot = EquipmentSlot::energy;
+        break;
+    case 9:
+        semanticSlot = EquipmentSlot::heavy;
+        break;
+    case 10:
+        semanticSlot = EquipmentSlot::ship;
+        break;
+    case 11:
+        semanticSlot = EquipmentSlot::vehicle;
+        break;
+    case 12:
+        semanticSlot = EquipmentSlot::ghost;
+        break;
+    case 13:
+        semanticSlot = EquipmentSlot::emblem;
+        break;
+    case 14:
+        semanticSlot = EquipmentSlot::emote;
+        break;
+    case 15:
+        semanticSlot = EquipmentSlot::clanBanner;
+        break;
+    case 17:
+        semanticSlot = EquipmentSlot::finisher;
+        break;
+    default:
+        return false;
+    }
+    semanticIndex = static_cast<std::size_t>(semanticSlot);
+    return semanticIndex < authored_inventory::kEquipmentSlotCount;
+}
+
+/** Finds one instance exactly once in a checked, row-sorted loadout. */
+[[nodiscard]] bool find_resolved_position(const family4_loadout::ResolvedLoadout& loadout,
+                                          std::uint64_t instanceSoid,
+                                          ResolvedPosition& position) noexcept {
+    bool found = false;
+    for (std::size_t index = 0; index < loadout.itemCount; ++index) {
+        const family4_loadout::ResolvedItem& item = loadout.items[index];
+        if (item.instance.instanceSoid != instanceSoid) {
+            continue;
+        }
+        if (found) {
+            return false;
+        }
+        found = true;
+        position.inventoryRow = item.inventoryRow;
+        position.equipmentSlot = item.equipmentSlot;
+        position.equipped = item.equipped;
+        position.mutationSerial = item.mutationSerial;
+    }
+    return found;
+}
+
+/** @return True when the native placement and equipped marker are unchanged. */
+[[nodiscard]] bool same_position(const ResolvedPosition& left,
+                                 const ResolvedPosition& right) noexcept {
+    return left.inventoryRow == right.inventoryRow && left.equipmentSlot == right.equipmentSlot
+           && left.equipped == right.equipped;
+}
+
+/**
+ * Applies canonical mutation generations after one shape-only equipment transition.
+ *
+ * Every surviving instance must preserve its native bucket. A generation advances exactly when
+ * its published native row or equipped marker changes, and a second resolution proves that the
+ * stamped after-image retained the staged placement.
+ */
+[[nodiscard]] bool
+finalize_equipment_transition(const AccountState& account,
+                              std::size_t characterIndex,
+                              std::uint64_t requestedInstanceSoid,
+                              EquipmentMutationKind kind,
+                              std::uint8_t expectedNativeSlot,
+                              const family4_loadout::ResolvedLoadout& beforeLoadout,
+                              CharacterState& after,
+                              std::size_t& movedItemCount) noexcept {
+    movedItemCount = 0;
+    if (characterIndex >= account.characterCount || kind == EquipmentMutationKind::none) {
+        return false;
+    }
+
+    AccountState candidate = account;
+    candidate.characters[characterIndex] = after;
+    family4_loadout::ResolvedLoadout placedAfter{};
+    if (!account::valid(candidate)
+        || !family4_loadout::resolve(candidate, characterIndex, placedAfter)
+        || placedAfter.itemCount != beforeLoadout.itemCount) {
+        return false;
+    }
+
+    ResolvedPosition beforeRequested{};
+    ResolvedPosition afterRequested{};
+    if (!find_resolved_position(beforeLoadout, requestedInstanceSoid, beforeRequested)
+        || !find_resolved_position(placedAfter, requestedInstanceSoid, afterRequested)
+        || beforeRequested.equipmentSlot != expectedNativeSlot
+        || afterRequested.equipmentSlot != expectedNativeSlot
+        || (kind == EquipmentMutationKind::equip
+            && (beforeRequested.equipped || !afterRequested.equipped))
+        || (kind == EquipmentMutationKind::unequip
+            && (!beforeRequested.equipped || afterRequested.equipped))) {
+        return false;
+    }
+
+    const auto count_move = [&](const authored_inventory::Item& item) noexcept {
+        ResolvedPosition beforePosition{};
+        ResolvedPosition afterPosition{};
+        if (!find_resolved_position(beforeLoadout, item.instanceSoid, beforePosition)
+            || !find_resolved_position(placedAfter, item.instanceSoid, afterPosition)
+            || beforePosition.equipmentSlot != afterPosition.equipmentSlot) {
+            return false;
+        }
+        movedItemCount += static_cast<std::size_t>(!same_position(beforePosition, afterPosition));
+        return true;
+    };
+    for (const auto& item : after.equipment.slots) {
+        if (item.has_value() && !count_move(*item)) {
+            return false;
+        }
+    }
+    for (std::size_t index = 0; index < after.inventory.count; ++index) {
+        if (!count_move(after.inventory.values[index])) {
+            return false;
+        }
+    }
+
+    // The serial is signed on the wire, so it must stay inside the positive int32 range.
+    constexpr std::uint32_t kMaximumInventorySerial =
+        static_cast<std::uint32_t>((std::numeric_limits<std::int32_t>::max)());
+    if (movedItemCount == 0 || after.nextInventorySerial > kMaximumInventorySerial
+        || movedItemCount > kMaximumInventorySerial - after.nextInventorySerial) {
+        return false;
+    }
+
+    const auto stamp_move = [&](authored_inventory::Item& item) noexcept {
+        ResolvedPosition beforePosition{};
+        ResolvedPosition afterPosition{};
+        if (!find_resolved_position(beforeLoadout, item.instanceSoid, beforePosition)
+            || !find_resolved_position(placedAfter, item.instanceSoid, afterPosition)
+            || beforePosition.equipmentSlot != afterPosition.equipmentSlot) {
+            return false;
+        }
+        if (!same_position(beforePosition, afterPosition)) {
+            item.mutationSerial = static_cast<std::int32_t>(after.nextInventorySerial++);
+        }
+        return true;
+    };
+    for (auto& item : after.equipment.slots) {
+        if (item.has_value() && !stamp_move(*item)) {
+            return false;
+        }
+    }
+    for (std::size_t index = 0; index < after.inventory.count; ++index) {
+        if (!stamp_move(after.inventory.values[index])) {
+            return false;
+        }
+    }
+
+    candidate.characters[characterIndex] = after;
+    family4_loadout::ResolvedLoadout checkedAfter{};
+    if (!account::valid(candidate)
+        || !family4_loadout::resolve(candidate, characterIndex, checkedAfter)
+        || checkedAfter.itemCount != placedAfter.itemCount) {
+        return false;
+    }
+    for (const auto& item : after.equipment.slots) {
+        if (!item.has_value()) {
+            continue;
+        }
+        ResolvedPosition placed{};
+        ResolvedPosition checked{};
+        if (!find_resolved_position(placedAfter, item->instanceSoid, placed)
+            || !find_resolved_position(checkedAfter, item->instanceSoid, checked)
+            || !same_position(placed, checked) || checked.mutationSerial != item->mutationSerial) {
+            return false;
+        }
+    }
+    for (std::size_t index = 0; index < after.inventory.count; ++index) {
+        const authored_inventory::Item& item = after.inventory.values[index];
+        ResolvedPosition placed{};
+        ResolvedPosition checked{};
+        if (!find_resolved_position(placedAfter, item.instanceSoid, placed)
+            || !find_resolved_position(checkedAfter, item.instanceSoid, checked)
+            || !same_position(placed, checked) || checked.mutationSerial != item.mutationSerial) {
+            return false;
+        }
+    }
+    return true;
+}
+
+/** @return True when two authored item values are identical, including socket policy and tail. */
+[[nodiscard]] bool same_item(const authored_inventory::Item& left,
+                             const authored_inventory::Item& right) noexcept {
+    return left.instanceSoid == right.instanceSoid && left.definitionHash == right.definitionHash
+           && left.level == right.level && left.quantity == right.quantity
+           && left.flags == right.flags && left.sockets.policy == right.sockets.policy
+           && left.sockets.plugCount == right.sockets.plugCount
+           && left.sockets.plugs == right.sockets.plugs;
+}
+
+/** Records one checked native item-state transition. */
+void report_item_state(std::string_view stage,
+                       std::string_view result,
+                       std::string_view reason,
+                       std::uint64_t characterSoid,
+                       std::uint64_t instanceSoid,
+                       std::uint16_t definitionIndex,
+                       std::uint32_t beforeFlags,
+                       std::uint32_t afterFlags,
+                       bool equipped,
+                       std::size_t itemIndex) noexcept {
+    std::array<char, core::log::kLineCapacity> line{};
+    const int count = std::snprintf(
+        line.data(),
+        line.size(),
+        "ev=item_state stage=%.*s result=%.*s reason=%.*s character=0x%llX instance=0x%llX "
+        "definition=%u flags_before=0x%X flags_after=0x%X equipped=%u item_index=%zu",
+        static_cast<int>(stage.size()),
+        stage.data(),
+        static_cast<int>(result.size()),
+        result.data(),
+        static_cast<int>(reason.size()),
+        reason.data(),
+        static_cast<unsigned long long>(characterSoid),
+        static_cast<unsigned long long>(instanceSoid),
+        static_cast<unsigned>(definitionIndex),
+        beforeFlags,
+        afterFlags,
+        equipped ? 1U : 0U,
+        itemIndex);
+    if (count > 0) {
+        core::log::write(core::log::Channel::state,
+                         result == "ok" ? core::log::Level::debug : core::log::Level::warn,
+                         {line.data(), static_cast<std::size_t>(count)});
+    }
+}
+
+/** Exact stationary-item comparison, including its inventory mutation generation. */
+[[nodiscard]] bool same_stationary_item(const authored_inventory::Item& left,
+                                        const authored_inventory::Item& right) noexcept {
+    return same_item(left, right) && left.mutationSerial == right.mutationSerial;
+}
+
+/** @return True when every item-bearing field of two character views is identical. */
+[[nodiscard]] bool same_loadout(const CharacterState& left, const CharacterState& right) noexcept {
+    if (left.soid != right.soid || left.selected != right.selected || left.race != right.race
+        || left.gender != right.gender || left.characterClass != right.characterClass
+        || left.level != right.level || left.accepted != right.accepted
+        || left.previewAvailable != right.previewAvailable
+        || left.appearanceValue != right.appearanceValue
+        || left.lastOrbitedDestination != right.lastOrbitedDestination
+        || left.contentBypass != right.contentBypass
+        || left.movementAbilityEntry != right.movementAbilityEntry
+        || left.grenadeAbilityEntry != right.grenadeAbilityEntry
+        || left.superAbilityEntry != right.superAbilityEntry
+        || left.meleeAbilityEntry != right.meleeAbilityEntry
+        || left.classAbilityEntry != right.classAbilityEntry
+        || left.nextInventorySerial != right.nextInventorySerial
+        || left.inventory.count != right.inventory.count) {
+        return false;
+    }
+    for (std::size_t index = 0; index < left.equipment.slots.size(); ++index) {
+        const auto& leftItem = left.equipment.slots[index];
+        const auto& rightItem = right.equipment.slots[index];
+        if (leftItem.has_value() != rightItem.has_value()
+            || (leftItem.has_value() && !same_stationary_item(*leftItem, *rightItem))) {
+            return false;
+        }
+    }
+    for (std::size_t index = 0; index < left.inventory.count; ++index) {
+        if (!same_stationary_item(left.inventory.values[index], right.inventory.values[index])) {
+            return false;
+        }
+    }
+    return true;
+}
+
+/** Exact character comparison, including the canonical unused inventory tail. */
+[[nodiscard]] bool same_character(const CharacterState& left,
+                                  const CharacterState& right) noexcept {
+    if (!same_loadout(left, right)) {
+        return false;
+    }
+    for (std::size_t index = left.inventory.count; index < left.inventory.values.size(); ++index) {
+        if (!same_stationary_item(left.inventory.values[index], right.inventory.values[index])) {
+            return false;
+        }
+    }
+    return true;
+}
+
+/** Finds one item SOID exactly once in the character's equipment and dense inventory. */
+[[nodiscard]] bool find_character_item_location(const CharacterState& character,
+                                                std::uint64_t instanceSoid,
+                                                CharacterItemLocation& location) noexcept {
+    location = {};
+    bool found = false;
+    for (std::size_t index = 0; index < character.equipment.slots.size(); ++index) {
+        const auto& item = character.equipment.slots[index];
+        if (!item.has_value() || item->instanceSoid != instanceSoid) {
+            continue;
+        }
+        if (found) {
+            return false;
+        }
+        found = true;
+        location = {index, true};
+    }
+    for (std::size_t index = 0; index < character.inventory.count; ++index) {
+        if (character.inventory.values[index].instanceSoid != instanceSoid) {
+            continue;
+        }
+        if (found) {
+            return false;
+        }
+        found = true;
+        location = {index, false};
+    }
+    return found;
+}
+
+/** Borrows an item at a previously validated authored location. */
+[[nodiscard]] const authored_inventory::Item*
+character_item_at(const CharacterState& character, const CharacterItemLocation& location) noexcept {
+    if (location.equipped) {
+        if (location.index >= character.equipment.slots.size()
+            || !character.equipment.slots[location.index].has_value()) {
+            return nullptr;
+        }
+        return &*character.equipment.slots[location.index];
+    }
+    if (location.index >= character.inventory.count) {
+        return nullptr;
+    }
+    return &character.inventory.values[location.index];
+}
+
+/** Borrows a mutable item at a previously validated authored location. */
+[[nodiscard]] authored_inventory::Item*
+character_item_at(CharacterState& character, const CharacterItemLocation& location) noexcept {
+    if (location.equipped) {
+        if (location.index >= character.equipment.slots.size()
+            || !character.equipment.slots[location.index].has_value()) {
+            return nullptr;
+        }
+        return &*character.equipment.slots[location.index];
+    }
+    if (location.index >= character.inventory.count) {
+        return nullptr;
+    }
+    return &character.inventory.values[location.index];
+}
+
+} // namespace runtime::detail
+} // namespace sunrise::state

+ 211 - 0
Sunrise/src/state/runtime/state_account_identity_runtime.cpp

@@ -0,0 +1,211 @@
+/** Instance identity helpers: generated SOIDs, ownership tests, and loadout row lookups. */
+
+#include <Windows.h>
+
+#include <algorithm>
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <cstdio>
+#include <limits>
+#include <string_view>
+#include <utility>
+
+#include "../../core/logging/log.h"
+#include "../../middleware/datagen/family4/loadout/loadout_resolver.h"
+#include "../build_data/runtime.h"
+#include "runtime.h"
+#include "state.h"
+#include "state_account_transaction_helpers.h"
+#include "storage/internal.h"
+
+namespace sunrise::state {
+namespace runtime::detail {
+
+namespace authored_inventory = account::inventory;
+namespace item_details = build_data::items::details;
+namespace inventory_buckets = build_data::inventory::buckets;
+namespace family4_loadout = middleware::datagen::family4::loadout;
+
+/** First SOID reserved for item instances created by this local runtime. */
+constexpr std::uint64_t kFirstGeneratedItemSoid = 0x4000000000000001ULL;
+
+/** Returns one character-owned instance's definition hash for bounded transaction diagnostics. */
+[[nodiscard]] std::uint32_t character_item_definition_hash(const CharacterState& character,
+                                                           std::uint64_t instanceSoid) noexcept {
+    for (const auto& item : character.equipment.slots) {
+        if (item.has_value() && item->instanceSoid == instanceSoid) {
+            return item->definitionHash;
+        }
+    }
+    for (std::size_t index = 0; index < character.inventory.count; ++index) {
+        if (character.inventory.values[index].instanceSoid == instanceSoid) {
+            return character.inventory.values[index].definitionHash;
+        }
+    }
+    return 0;
+}
+
+/** @return True when any account, character, profile-stack, or character-item key owns one SOID. */
+[[nodiscard]] bool account_owns_soid(const AccountState& account, std::uint64_t soid) noexcept {
+    if (soid == 0 || account.primarySoid == soid) {
+        return true;
+    }
+    for (std::size_t index = 0; index < account.profileItemCount; ++index) {
+        if (account.profileItems[index].instanceSoid == soid) {
+            return true;
+        }
+    }
+    for (std::size_t characterIndex = 0; characterIndex < account.characterCount;
+         ++characterIndex) {
+        const CharacterState& character = account.characters[characterIndex];
+        if (character.soid == soid) {
+            return true;
+        }
+        for (const auto& item : character.equipment.slots) {
+            if (item.has_value() && item->instanceSoid == soid) {
+                return true;
+            }
+        }
+        for (std::size_t index = 0; index < character.inventory.count; ++index) {
+            if (character.inventory.values[index].instanceSoid == soid) {
+                return true;
+            }
+        }
+    }
+    return false;
+}
+
+/** Finds a fresh deterministic item-instance SOID without sharing any other identity key. */
+[[nodiscard]] bool next_item_instance_soid(const AccountState& account,
+                                           std::uint64_t& output) noexcept {
+    std::uint64_t candidate = kFirstGeneratedItemSoid;
+    for (std::size_t characterIndex = 0; characterIndex < account.characterCount;
+         ++characterIndex) {
+        const CharacterState& character = account.characters[characterIndex];
+        for (const auto& item : character.equipment.slots) {
+            if (!item.has_value() || item->instanceSoid < candidate) {
+                continue;
+            }
+            if (item->instanceSoid == (std::numeric_limits<std::uint64_t>::max)()) {
+                return false;
+            }
+            candidate = item->instanceSoid + 1U;
+        }
+        for (std::size_t index = 0; index < character.inventory.count; ++index) {
+            const std::uint64_t instanceSoid = character.inventory.values[index].instanceSoid;
+            if (instanceSoid < candidate) {
+                continue;
+            }
+            if (instanceSoid == (std::numeric_limits<std::uint64_t>::max)()) {
+                return false;
+            }
+            candidate = instanceSoid + 1U;
+        }
+    }
+    while (account_owns_soid(account, candidate)) {
+        if (candidate == (std::numeric_limits<std::uint64_t>::max)()) {
+            return false;
+        }
+        ++candidate;
+    }
+    output = candidate;
+    return output != 0;
+}
+
+/** Finds a collision-free SOID for one newly appended profile stack. */
+[[nodiscard]] bool next_profile_item_instance_soid(const AccountState& account,
+                                                   std::uint64_t& output) noexcept {
+    std::uint64_t candidate = authored_inventory::kFirstProfileItemInstanceSoid;
+    while (account_owns_soid(account, candidate)) {
+        if (candidate == (std::numeric_limits<std::uint64_t>::max)()) {
+            return false;
+        }
+        ++candidate;
+    }
+    output = candidate;
+    return output != 0;
+}
+
+/** @return True when an account or character identity already owns the candidate object key. */
+[[nodiscard]] bool identity_uses_soid(const AccountState& account, std::uint64_t soid) noexcept {
+    if (soid == 0 || account.primarySoid == soid) {
+        return true;
+    }
+    for (std::size_t index = 0; index < account.characterCount; ++index) {
+        if (account.characters[index].soid == soid) {
+            return true;
+        }
+    }
+    return false;
+}
+
+/** Uses the character's strongest existing item as the neutral local Collections pull level. */
+[[nodiscard]] std::int32_t acquisition_level(const CharacterState& character) noexcept {
+    std::int32_t level = 0;
+    for (const auto& item : character.equipment.slots) {
+        if (item.has_value()) {
+            level = (std::max)(level, item->level);
+        }
+    }
+    for (std::size_t index = 0; index < character.inventory.count; ++index) {
+        level = (std::max)(level, character.inventory.values[index].level);
+    }
+    return level;
+}
+
+/** Finds the one resolved unequipped row created by an acquisition candidate. */
+[[nodiscard]] bool find_acquired_row(const family4_loadout::ResolvedLoadout& loadout,
+                                     std::uint64_t instanceSoid,
+                                     std::uint16_t& inventoryRow,
+                                     std::uint8_t& equipmentSlot) noexcept {
+    bool found = false;
+    for (std::size_t index = 0; index < loadout.itemCount; ++index) {
+        const family4_loadout::ResolvedItem& item = loadout.items[index];
+        if (item.instance.instanceSoid != instanceSoid) {
+            continue;
+        }
+        if (found || item.equipped) {
+            return false;
+        }
+        found = true;
+        inventoryRow = item.inventoryRow;
+        equipmentSlot = item.equipmentSlot;
+    }
+    return found;
+}
+
+/** Finds the unique resolved unequipped position for one instance. */
+[[nodiscard]] bool find_unequipped_row(const family4_loadout::ResolvedLoadout& loadout,
+                                       std::uint64_t instanceSoid,
+                                       std::uint16_t& inventoryRow,
+                                       std::uint8_t& equipmentSlot) noexcept {
+    bool found = false;
+    for (std::size_t index = 0; index < loadout.itemCount; ++index) {
+        const family4_loadout::ResolvedItem& item = loadout.items[index];
+        if (item.instance.instanceSoid != instanceSoid) {
+            continue;
+        }
+        if (found || item.equipped) {
+            return false;
+        }
+        found = true;
+        inventoryRow = item.inventoryRow;
+        equipmentSlot = item.equipmentSlot;
+    }
+    return found;
+}
+
+/** @return True when the resolved loadout still carries an instance with this key. */
+[[nodiscard]] bool loadout_contains(const family4_loadout::ResolvedLoadout& loadout,
+                                    std::uint64_t instanceSoid) noexcept {
+    for (std::size_t index = 0; index < loadout.itemCount; ++index) {
+        if (loadout.items[index].instance.instanceSoid == instanceSoid) {
+            return true;
+        }
+    }
+    return false;
+}
+
+} // namespace runtime::detail
+} // namespace sunrise::state

+ 539 - 0
Sunrise/src/state/runtime/state_account_profile_runtime.cpp

@@ -0,0 +1,539 @@
+/**
+ * Profile-inventory helpers: the account-wide stacks, their checks, and the material
+ * costs an action charges against them.
+ */
+
+#include <Windows.h>
+
+#include <algorithm>
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <cstdio>
+#include <limits>
+#include <string_view>
+#include <utility>
+
+#include "../../core/logging/log.h"
+#include "../../middleware/datagen/family4/loadout/loadout_resolver.h"
+#include "../build_data/runtime.h"
+#include "runtime.h"
+#include "state.h"
+#include "state_account_transaction_helpers.h"
+#include "storage/internal.h"
+
+namespace sunrise::state {
+namespace runtime::detail {
+
+namespace authored_inventory = account::inventory;
+namespace item_details = build_data::items::details;
+namespace inventory_buckets = build_data::inventory::buckets;
+namespace family4_loadout = middleware::datagen::family4::loadout;
+
+/** Writes one bounded profile-stack acquisition checkpoint. */
+void report_profile_acquisition(std::string_view stage,
+                                std::string_view result,
+                                std::string_view reason,
+                                std::uint32_t definitionHash,
+                                std::uint64_t accountSoid,
+                                std::uint64_t instanceSoid,
+                                std::uint8_t bucketId,
+                                std::size_t profileIndex,
+                                std::size_t itemCount,
+                                std::int32_t previousQuantity,
+                                std::int32_t acquiredQuantity,
+                                bool appended) noexcept {
+    std::array<char, core::log::kLineCapacity> line{};
+    const int count = std::snprintf(
+        line.data(),
+        line.size(),
+        "ev=profile_acquire stage=%.*s result=%.*s reason=%.*s definition_hash=0x%08X "
+        "account=0x%llX instance=0x%llX bucket=%u profile_index=%zu item_count=%zu "
+        "quantity_before=%d "
+        "quantity_after=%d appended=%u",
+        static_cast<int>(stage.size()),
+        stage.data(),
+        static_cast<int>(result.size()),
+        result.data(),
+        static_cast<int>(reason.size()),
+        reason.data(),
+        definitionHash,
+        static_cast<unsigned long long>(accountSoid),
+        static_cast<unsigned long long>(instanceSoid),
+        static_cast<unsigned>(bucketId),
+        profileIndex,
+        itemCount,
+        previousQuantity,
+        acquiredQuantity,
+        static_cast<unsigned>(appended));
+    if (count > 0) {
+        core::log::write(core::log::Channel::state,
+                         result == "ok" ? core::log::Level::debug : core::log::Level::warn,
+                         {line.data(), static_cast<std::size_t>(count)});
+    }
+}
+
+/** @return True when two profile stack rows carry identical authored values. */
+[[nodiscard]] bool same_profile_item(const authored_inventory::ProfileItem& left,
+                                     const authored_inventory::ProfileItem& right) noexcept {
+    return left.instanceSoid == right.instanceSoid && left.definitionHash == right.definitionHash
+           && left.quantity == right.quantity && left.mutationSerial == right.mutationSerial;
+}
+
+/** @return True when a complete fixed profile inventory equals one captured view. */
+[[nodiscard]] bool
+same_profile_inventory(const AccountState& account,
+                       const std::array<authored_inventory::ProfileItem,
+                                        authored_inventory::kProfileItemCapacity>& expected,
+                       std::size_t expectedCount) noexcept {
+    if (account.profileItemCount != expectedCount) {
+        return false;
+    }
+    for (std::size_t index = 0; index < account.profileItems.size(); ++index) {
+        if (!same_profile_item(account.profileItems[index], expected[index])) {
+            return false;
+        }
+    }
+    return true;
+}
+
+/** @return True when two fixed profile views, including their empty tails, are identical. */
+[[nodiscard]] bool same_profile_views(
+    const std::array<authored_inventory::ProfileItem, authored_inventory::kProfileItemCapacity>&
+        left,
+    std::size_t leftCount,
+    const std::array<authored_inventory::ProfileItem, authored_inventory::kProfileItemCapacity>&
+        right,
+    std::size_t rightCount) noexcept {
+    if (leftCount != rightCount) {
+        return false;
+    }
+    for (std::size_t index = 0; index < left.size(); ++index) {
+        if (!same_profile_item(left[index], right[index])) {
+            return false;
+        }
+    }
+    return true;
+}
+
+/**
+ * Checks every dense profile stack and mirrors the account encoder's bucket-row placement.
+ * This keeps State rejection independent of whether a later push happens to have scratch space.
+ */
+[[nodiscard]] bool valid_profile_inventory(const AccountState& account) noexcept {
+    if (account.profileItemCount > account.profileItems.size()) {
+        return false;
+    }
+    // The bucket identity is one byte on the wire, so 256 covers every value one can carry.
+    constexpr std::size_t kBucketIdentityCapacity = 256;
+    std::array<std::uint16_t, kBucketIdentityCapacity> taken{};
+    std::array<bool, inventory_buckets::kProfileSlotCapacity> occupied{};
+    std::size_t actionSourceCount = 0;
+    for (std::size_t index = 0; index < account.profileItems.size(); ++index) {
+        const authored_inventory::ProfileItem& item = account.profileItems[index];
+        if (index >= account.profileItemCount) {
+            if (item.instanceSoid != 0 || item.definitionHash != 0 || item.quantity != 0
+                || item.mutationSerial != 0) {
+                return false;
+            }
+            continue;
+        }
+        build_data::items::Definition definition{};
+        item_details::Definition detail{};
+        inventory_buckets::Descriptor bucket{};
+        if (item.quantity <= 0 || item.mutationSerial < 0
+            || !build_data::find_item_definition_hash(item.definitionHash, definition)
+            || definition.definitionHash != item.definitionHash
+            || !build_data::find_configured_item_detail(definition.definitionIndex, detail)
+            || detail.definitionIndex != definition.definitionIndex
+            || detail.definitionHash != definition.definitionHash
+            || detail.bucketId != definition.bucketId
+            || detail.instancedDefinitionState != item_details::InstancedDefinitionState::stackable
+            || !build_data::find_inventory_bucket_descriptor(definition.bucketId, bucket)
+            || bucket.arraySelector != inventory_buckets::ArraySelector::profile) {
+            return false;
+        }
+        const bool actionSource =
+            build_data::is_profile_action_source(definition.definitionIndex, definition.bucketId);
+        if (actionSource != (item.instanceSoid != 0)
+            || (actionSource
+                && ++actionSourceCount > authored_inventory::kProfileActionSourceCapacity)) {
+            return false;
+        }
+        const std::uint16_t used = taken[definition.bucketId];
+        if (used >= bucket.slotCount) {
+            return false;
+        }
+        const std::size_t row = static_cast<std::size_t>(bucket.firstSlot) + used;
+        if (row >= occupied.size() || occupied[row]) {
+            return false;
+        }
+        occupied[row] = true;
+        taken[definition.bucketId] = static_cast<std::uint16_t>(used + 1U);
+    }
+    return true;
+}
+
+/** Resolved, aggregated material charge for one installed native requirement set. */
+struct MaterialCharge {
+    std::uint32_t definitionHash{};
+    std::uint64_t quantity{};
+    bool deleteOnAction{};
+};
+
+/**
+ * Validates one native material requirement set and applies its deletions to a copied account.
+ * Requirements which are not deleted still gate the action by balance. Material rows must be
+ * ordinary non-resident profile stacks; removing an instance-backed action source would also owe
+ * a resident release and is deliberately rejected here.
+ */
+template <typename Requirement>
+[[nodiscard]] bool apply_material_requirements(const AccountState& before,
+                                               std::span<const Requirement> requirements,
+                                               AccountState& after,
+                                               bool& changed) noexcept {
+    after = before;
+    changed = false;
+    if (requirements.size() > build_data::material_requirements::kRequirementCapacity) {
+        return false;
+    }
+
+    std::array<MaterialCharge, build_data::material_requirements::kRequirementCapacity> charges{};
+    std::size_t chargeCount = 0;
+    for (const Requirement& requirement : requirements) {
+        if (requirement.quantity == 0) {
+            continue;
+        }
+        build_data::items::Definition definition{};
+        item_details::Definition detail{};
+        inventory_buckets::Descriptor bucket{};
+        if (requirement.itemDefinitionIndex
+                == build_data::material_requirements::kUnavailableItemDefinitionIndex
+            || !build_data::find_item_definition_index(requirement.itemDefinitionIndex, definition)
+            || definition.definitionIndex != requirement.itemDefinitionIndex
+            || !build_data::find_configured_item_detail(requirement.itemDefinitionIndex, detail)
+            || detail.definitionIndex != requirement.itemDefinitionIndex
+            || detail.definitionHash != definition.definitionHash
+            || detail.bucketId != definition.bucketId
+            || detail.instancedDefinitionState != item_details::InstancedDefinitionState::stackable
+            || !build_data::find_inventory_bucket_descriptor(definition.bucketId, bucket)
+            || bucket.arraySelector != inventory_buckets::ArraySelector::profile
+            || build_data::is_profile_action_source(definition.definitionIndex,
+                                                    definition.bucketId)) {
+            return false;
+        }
+        std::size_t chargeIndex = chargeCount;
+        for (std::size_t existing = 0; existing < chargeCount; ++existing) {
+            if (charges[existing].definitionHash == definition.definitionHash
+                && charges[existing].deleteOnAction == requirement.deleteOnAction) {
+                chargeIndex = existing;
+                break;
+            }
+        }
+        if (chargeIndex == chargeCount) {
+            if (chargeCount >= charges.size()) {
+                return false;
+            }
+            charges[chargeCount].definitionHash = definition.definitionHash;
+            charges[chargeCount].deleteOnAction = requirement.deleteOnAction;
+            ++chargeCount;
+        }
+        if (charges[chargeIndex].quantity
+            > (std::numeric_limits<std::uint64_t>::max)() - requirement.quantity) {
+            return false;
+        }
+        charges[chargeIndex].quantity += requirement.quantity;
+    }
+
+    for (std::size_t charge = 0; charge < chargeCount; ++charge) {
+        std::uint64_t available = 0;
+        for (std::size_t index = 0; index < before.profileItemCount; ++index) {
+            const authored_inventory::ProfileItem& item = before.profileItems[index];
+            if (item.definitionHash != charges[charge].definitionHash) {
+                continue;
+            }
+            if (item.instanceSoid != 0 || item.quantity <= 0
+                || available > (std::numeric_limits<std::uint64_t>::max)()
+                                   - static_cast<std::uint64_t>(item.quantity)) {
+                return false;
+            }
+            available += static_cast<std::uint64_t>(item.quantity);
+        }
+        if (available < charges[charge].quantity) {
+            return false;
+        }
+    }
+
+    std::array<std::uint64_t, build_data::material_requirements::kRequirementCapacity> remaining{};
+    bool hasDeletion = false;
+    for (std::size_t charge = 0; charge < chargeCount; ++charge) {
+        if (charges[charge].deleteOnAction) {
+            remaining[charge] = charges[charge].quantity;
+            hasDeletion = true;
+        }
+    }
+    if (!hasDeletion) {
+        return true;
+    }
+
+    std::array<authored_inventory::ProfileItem, authored_inventory::kProfileItemCapacity>
+        compacted{};
+    std::size_t compactedCount = 0;
+    for (std::size_t index = 0; index < before.profileItemCount; ++index) {
+        authored_inventory::ProfileItem item = before.profileItems[index];
+        for (std::size_t charge = 0; charge < chargeCount; ++charge) {
+            if (remaining[charge] == 0 || item.definitionHash != charges[charge].definitionHash) {
+                continue;
+            }
+            const auto available = static_cast<std::uint64_t>(item.quantity);
+            const auto consumed = (std::min)(available, remaining[charge]);
+            item.quantity -= static_cast<std::int32_t>(consumed);
+            remaining[charge] -= consumed;
+        }
+        if (item.quantity != 0) {
+            if (compactedCount >= compacted.size()) {
+                return false;
+            }
+            compacted[compactedCount++] = item;
+        }
+    }
+    if (std::any_of(remaining.cbegin(),
+                    remaining.cbegin() + static_cast<std::ptrdiff_t>(chargeCount),
+                    [](std::uint64_t value) noexcept { return value != 0; })) {
+        return false;
+    }
+
+    std::int32_t greatestMutationSerial = 0;
+    for (std::size_t index = 0; index < before.profileItemCount; ++index) {
+        greatestMutationSerial =
+            (std::max)(greatestMutationSerial, before.profileItems[index].mutationSerial);
+    }
+    std::size_t changedRows = 0;
+    for (std::size_t index = 0; index < compactedCount; ++index) {
+        if (index >= before.profileItemCount
+            || !same_profile_item(compacted[index], before.profileItems[index])) {
+            ++changedRows;
+        }
+    }
+    if (changedRows > static_cast<std::size_t>((std::numeric_limits<std::int32_t>::max)()
+                                               - greatestMutationSerial)) {
+        return false;
+    }
+    for (std::size_t index = 0; index < compactedCount; ++index) {
+        if (index >= before.profileItemCount
+            || !same_profile_item(compacted[index], before.profileItems[index])) {
+            compacted[index].mutationSerial = ++greatestMutationSerial;
+        }
+    }
+    after.profileItems = compacted;
+    after.profileItemCount = compactedCount;
+    changed = !same_profile_inventory(after, before.profileItems, before.profileItemCount);
+    return changed && account::valid(after) && valid_profile_inventory(after);
+}
+
+/** Resolves one Collections row's installed cost without embedding any item or quantity policy. */
+[[nodiscard]] bool
+apply_collection_materials(const AccountState& before,
+                           const build_data::collectibles::Definition& collectible,
+                           AccountState& after,
+                           bool& changed) noexcept {
+    after = before;
+    changed = false;
+    if (collectible.materialRequirementCount == 0) {
+        return collectible.materialRequirementSetIndex
+                   == build_data::collectibles::kUnavailableMaterialRequirementSetIndex
+               && collectible.materialRequirementSetHash == 0;
+    }
+    if (collectible.materialRequirementCount > collectible.materialRequirements.size()
+        || collectible.materialRequirementSetIndex
+               == build_data::collectibles::kUnavailableMaterialRequirementSetIndex
+        || collectible.materialRequirementSetHash == 0) {
+        return false;
+    }
+    return apply_material_requirements(
+        before,
+        std::span(collectible.materialRequirements)
+            .first(static_cast<std::size_t>(collectible.materialRequirementCount)),
+        after,
+        changed);
+}
+
+/**
+ * Answers whether the account holds one applicable stack of a socket action source.
+ * @param account Account whose profile stacks are searched.
+ * @param definitionHash Plug definition the Client asked to apply.
+ * @return True when a profile stack of that definition holds at least one unit.
+ */
+[[nodiscard]] bool holds_plug_source(const AccountState& account,
+                                     std::uint32_t definitionHash) noexcept {
+    for (std::size_t index = 0; index < account.profileItemCount; ++index) {
+        const authored_inventory::ProfileItem& item = account.profileItems[index];
+        if (item.definitionHash == definitionHash && item.quantity > 0) {
+            return true;
+        }
+    }
+    return false;
+}
+
+/**
+ * Takes one unit of an owned socket action source, releasing the row when its last unit goes.
+ *
+ * An action source is an instanced profile row, so the authored-cost path cannot spend it. The
+ * row keeps its identity and position while units remain, because the Client addresses it by that
+ * identity. An emptied row is removed and the rows after it move up, which is the same shape the
+ * authored-cost path leaves behind when a stack empties.
+ *
+ * @param account Account whose profile stacks are spent in place.
+ * @param definitionHash Plug definition being applied.
+ * @return True when one unit was taken.
+ */
+[[nodiscard]] bool spend_plug_source(AccountState& account, std::uint32_t definitionHash) noexcept {
+    std::size_t row = account.profileItemCount;
+    for (std::size_t index = 0; index < account.profileItemCount; ++index) {
+        if (account.profileItems[index].definitionHash == definitionHash
+            && account.profileItems[index].quantity > 0) {
+            row = index;
+            break;
+        }
+    }
+    if (row >= account.profileItemCount) {
+        return false;
+    }
+    if (--account.profileItems[row].quantity > 0) {
+        return true;
+    }
+    for (std::size_t index = row; index + 1U < account.profileItemCount; ++index) {
+        account.profileItems[index] = account.profileItems[index + 1U];
+    }
+    account.profileItems[--account.profileItemCount] = {};
+    return true;
+}
+
+/** Applies one dense installed action-cost set resolved from the selected plug or action row. */
+[[nodiscard]] bool
+apply_action_materials(const AccountState& before,
+                       const build_data::material_requirements::Definition& definition,
+                       AccountState& after,
+                       bool& changed) noexcept {
+    if (definition.requirementSetHash == 0
+        || definition.requirementSetIndex == build_data::material_requirements::kUnavailableSetIndex
+        || definition.requirementCount == 0
+        || definition.requirementCount > definition.requirements.size()) {
+        after = {};
+        changed = false;
+        return false;
+    }
+    for (std::size_t index = 0; index < definition.requirementCount; ++index) {
+        if (definition.requirements[index].condition
+            != build_data::material_requirements::kUnconditionalRequirement) {
+            after = {};
+            changed = false;
+            return false;
+        }
+    }
+    return apply_material_requirements(
+        before,
+        std::span(definition.requirements)
+            .first(static_cast<std::size_t>(definition.requirementCount)),
+        after,
+        changed);
+}
+
+/** @return True when a pending profile acquisition carries canonical dense before/after images. */
+[[nodiscard]] bool
+valid_profile_mutation_shape(const PendingProfileItemAcquisition& mutation) noexcept {
+    if (!mutation.prepared || mutation.accountSoid == 0
+        || mutation.actionSource != (mutation.acquiredInstanceSoid != 0)
+        || mutation.acquiredDefinitionHash == authored_inventory::kNoDefinitionHash
+        || mutation.expectedItemCount > authored_inventory::kProfileItemCapacity
+        || mutation.afterItemCount > authored_inventory::kProfileItemCapacity
+        || mutation.profileIndex >= mutation.afterItemCount || mutation.previousQuantity < 0
+        || mutation.acquiredQuantity <= mutation.previousQuantity
+        || mutation.acquiredQuantity - mutation.previousQuantity != 1
+        || mutation.previousMutationSerial < 0
+        || mutation.acquiredMutationSerial <= mutation.previousMutationSerial) {
+        return false;
+    }
+    if (mutation.appended) {
+        if (mutation.afterItemCount == 0 || mutation.previousQuantity != 0) {
+            return false;
+        }
+    } else if (mutation.previousQuantity == 0) {
+        return false;
+    }
+
+    bool foundBeforeTarget = mutation.appended;
+    for (std::size_t index = 0; index < mutation.beforeItems.size(); ++index) {
+        const authored_inventory::ProfileItem& before = mutation.beforeItems[index];
+        const authored_inventory::ProfileItem& after = mutation.afterItems[index];
+        if (index < mutation.expectedItemCount
+            && before.mutationSerial >= mutation.acquiredMutationSerial) {
+            return false;
+        }
+        if (index >= mutation.expectedItemCount
+            && (before.instanceSoid != 0 || before.definitionHash != 0 || before.quantity != 0
+                || before.mutationSerial != 0)) {
+            return false;
+        }
+        if (index >= mutation.afterItemCount
+            && (after.instanceSoid != 0 || after.definitionHash != 0 || after.quantity != 0
+                || after.mutationSerial != 0)) {
+            return false;
+        }
+        if (!mutation.appended && index < mutation.expectedItemCount
+            && before.instanceSoid == mutation.acquiredInstanceSoid
+            && before.definitionHash == mutation.acquiredDefinitionHash
+            && before.quantity == mutation.previousQuantity
+            && before.mutationSerial == mutation.previousMutationSerial) {
+            if (foundBeforeTarget) {
+                return false;
+            }
+            foundBeforeTarget = true;
+        }
+    }
+    const authored_inventory::ProfileItem& acquired = mutation.afterItems[mutation.profileIndex];
+    return foundBeforeTarget && acquired.instanceSoid == mutation.acquiredInstanceSoid
+           && acquired.definitionHash == mutation.acquiredDefinitionHash
+           && acquired.quantity == mutation.acquiredQuantity
+           && acquired.mutationSerial == mutation.acquiredMutationSerial;
+}
+
+/** Applies one validated pending profile after-image over a current, matching account. */
+[[nodiscard]] bool materialize_profile_acquisition(const AccountState& current,
+                                                   const PendingProfileItemAcquisition& mutation,
+                                                   AccountState& after) noexcept {
+    if (!valid_profile_mutation_shape(mutation) || current.primarySoid != mutation.accountSoid
+        || !same_profile_inventory(current, mutation.beforeItems, mutation.expectedItemCount)) {
+        return false;
+    }
+    item_details::Definition detail{};
+    inventory_buckets::Descriptor bucket{};
+    build_data::items::Definition item{};
+    build_data::collectibles::Definition collectible{};
+    if (!build_data::find_collectible_definition(mutation.collectibleIndex, collectible)
+        || collectible.itemDefinitionIndex
+               == build_data::collectibles::kUnavailableItemDefinitionIndex
+        || collectible.materialRequirementSetHash != mutation.materialRequirementSetHash
+        || collectible.materialRequirementCount != mutation.materialRequirementCount
+        || !build_data::find_item_definition_hash(mutation.acquiredDefinitionHash, item)
+        || collectible.itemDefinitionIndex != item.definitionIndex
+        || !build_data::find_configured_item_detail(item.definitionIndex, detail)
+        || detail.definitionHash != mutation.acquiredDefinitionHash
+        || detail.definitionIndex != item.definitionIndex || detail.bucketId != item.bucketId
+        || detail.bucketId != mutation.bucketId
+        || detail.instancedDefinitionState != item_details::InstancedDefinitionState::stackable
+        || detail.maxStackSize <= 0 || mutation.acquiredQuantity > detail.maxStackSize
+        || !build_data::find_inventory_bucket_descriptor(detail.bucketId, bucket)
+        || bucket.arraySelector != inventory_buckets::ArraySelector::profile
+        || build_data::is_profile_action_source(item.definitionIndex, item.bucketId)
+               != mutation.actionSource) {
+        return false;
+    }
+    after = current;
+    after.profileItems = mutation.afterItems;
+    after.profileItemCount = mutation.afterItemCount;
+    return account::valid(after) && valid_profile_inventory(after);
+}
+
+} // namespace runtime::detail
+} // namespace sunrise::state

Разница между файлами не показана из-за своего большого размера
+ 53 - 1361
Sunrise/src/state/runtime/state_account_runtime.cpp


+ 363 - 0
Sunrise/src/state/runtime/state_account_socket_runtime.cpp

@@ -0,0 +1,363 @@
+/** Socket-plug and item-state staging, which both mutate one character-owned item. */
+
+#include <Windows.h>
+
+#include <algorithm>
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <cstdio>
+#include <limits>
+#include <string_view>
+#include <utility>
+
+#include "../../core/logging/log.h"
+#include "../../middleware/datagen/family4/loadout/loadout_resolver.h"
+#include "../build_data/runtime.h"
+#include "runtime.h"
+#include "state.h"
+#include "state_account_transaction_helpers.h"
+#include "storage/internal.h"
+
+namespace sunrise::state {
+namespace runtime::detail {
+
+namespace authored_inventory = account::inventory;
+namespace item_details = build_data::items::details;
+namespace inventory_buckets = build_data::inventory::buckets;
+namespace family4_loadout = middleware::datagen::family4::loadout;
+
+/** Writes one bounded opcode-903 socket-selection transaction checkpoint. */
+void report_socket_plug(std::string_view stage,
+                        std::string_view result,
+                        std::string_view reason,
+                        std::uint64_t characterSoid,
+                        std::uint64_t targetInstanceSoid,
+                        std::uint16_t targetDefinitionIndex,
+                        std::uint8_t socketLane,
+                        std::uint16_t plugDefinitionIndex,
+                        std::uint8_t targetBucketId,
+                        std::uint8_t plugBucketId,
+                        bool targetEquipped,
+                        std::size_t itemIndex) noexcept {
+    std::array<char, core::log::kLineCapacity> line{};
+    const int count = std::snprintf(
+        line.data(),
+        line.size(),
+        "ev=socket_plug stage=%.*s result=%.*s reason=%.*s character=0x%llX "
+        "instance=0x%llX target_definition=%u target_bucket=%u lane=%u plug_definition=%u "
+        "plug_bucket=%u equipped=%u item_index=%zu",
+        static_cast<int>(stage.size()),
+        stage.data(),
+        static_cast<int>(result.size()),
+        result.data(),
+        static_cast<int>(reason.size()),
+        reason.data(),
+        static_cast<unsigned long long>(characterSoid),
+        static_cast<unsigned long long>(targetInstanceSoid),
+        static_cast<unsigned>(targetDefinitionIndex),
+        static_cast<unsigned>(targetBucketId),
+        static_cast<unsigned>(socketLane),
+        static_cast<unsigned>(plugDefinitionIndex),
+        static_cast<unsigned>(plugBucketId),
+        static_cast<unsigned>(targetEquipped),
+        itemIndex);
+    if (count > 0) {
+        core::log::write(core::log::Channel::state,
+                         result == "ok" ? core::log::Level::debug : core::log::Level::warn,
+                         {line.data(), static_cast<std::size_t>(count)});
+    }
+}
+
+/** Materializes native initial plugs as a complete authored socket block. */
+[[nodiscard]] bool materialize_native_sockets(const item_details::Definition& detail,
+                                              authored_inventory::Sockets& sockets) noexcept {
+    sockets = {};
+    if (detail.ordinarySocketState != item_details::OrdinarySocketState::present
+        || detail.ordinarySocketCount > sockets.plugs.size()) {
+        return false;
+    }
+    sockets.policy = authored_inventory::SocketPolicy::authored;
+    sockets.plugCount = detail.ordinarySocketCount;
+    for (std::size_t lane = 0; lane < sockets.plugCount; ++lane) {
+        const std::uint16_t plugIndex = detail.initialPlugIndices[lane];
+        if (plugIndex == item_details::kUnavailableItemIndex) {
+            continue;
+        }
+        build_data::items::Definition plug{};
+        if (!build_data::find_item_definition_index(plugIndex, plug)
+            || plug.definitionIndex != plugIndex
+            || plug.definitionHash == authored_inventory::kNoDefinitionHash) {
+            return false;
+        }
+        sockets.plugs[lane] = plug.definitionHash;
+    }
+    return authored_inventory::valid(sockets);
+}
+
+/** Stages the canonical socket-only after-image over one already validated account snapshot. */
+[[nodiscard]] bool stage_socket_plug(const AccountState& snapshot,
+                                     std::size_t characterIndex,
+                                     std::uint64_t targetInstanceSoid,
+                                     std::uint8_t socketLane,
+                                     std::uint16_t plugDefinitionIndex,
+                                     PendingSocketPlug& mutation) noexcept {
+    mutation = {};
+    CharacterItemLocation location{};
+    build_data::items::Definition targetDefinition{};
+    build_data::items::Definition plugDefinition{};
+    const auto fail = [&](std::string_view reason) noexcept {
+        const std::uint64_t characterSoid =
+            characterIndex < snapshot.characterCount ? snapshot.characters[characterIndex].soid : 0;
+        report_socket_plug("stage_internal",
+                           "fail",
+                           reason,
+                           characterSoid,
+                           targetInstanceSoid,
+                           targetDefinition.definitionIndex,
+                           socketLane,
+                           plugDefinitionIndex,
+                           targetDefinition.bucketId,
+                           plugDefinition.bucketId,
+                           location.equipped,
+                           location.index);
+        mutation = {};
+        return false;
+    };
+    if (!account::valid(snapshot) || characterIndex >= snapshot.characterCount
+        || targetInstanceSoid == 0 || socketLane >= authored_inventory::kPlugCapacity) {
+        return fail("request_or_account");
+    }
+    const CharacterState& before = snapshot.characters[characterIndex];
+    if (!before.selected || before.soid == 0) {
+        return fail("selected_character");
+    }
+
+    family4_loadout::ResolvedLoadout beforeLoadout{};
+    if (!find_character_item_location(before, targetInstanceSoid, location)
+        || !family4_loadout::resolve(snapshot, characterIndex, beforeLoadout)) {
+        return fail("target_or_before_loadout");
+    }
+    const authored_inventory::Item* target = character_item_at(before, location);
+    item_details::Definition detail{};
+    if (target == nullptr
+        || !build_data::find_item_definition_hash(target->definitionHash, targetDefinition)
+        || targetDefinition.definitionHash != target->definitionHash
+        || !build_data::find_configured_item_detail(targetDefinition.definitionIndex, detail)
+        || detail.definitionIndex != targetDefinition.definitionIndex
+        || detail.definitionHash != targetDefinition.definitionHash
+        || detail.bucketId != targetDefinition.bucketId
+        || detail.ordinarySocketState != item_details::OrdinarySocketState::present
+        || socketLane >= detail.ordinarySocketCount
+        || detail.ordinarySocketCount > authored_inventory::kPlugCapacity
+        || !build_data::find_item_definition_index(plugDefinitionIndex, plugDefinition)
+        || plugDefinition.definitionIndex != plugDefinitionIndex
+        || plugDefinition.definitionHash == authored_inventory::kNoDefinitionHash
+        || !build_data::is_socket_plug_allowed(
+            targetDefinition.definitionIndex, socketLane, plugDefinitionIndex)) {
+        return fail("definition_or_compatibility");
+    }
+
+    // Ownership is only meaningful where the plug is a finite supply the account draws down. A
+    // shader is one: it is pulled from Collections into a profile stack and spent by applying it.
+    // An ornament is a permanent unlock the account holds once earned, not a stack it draws
+    // down, which is why the Client offers every valid one for a socket. Requiring a stack for
+    // one would refuse a plug the account already has.
+    const bool consumesStack =
+        build_data::is_profile_action_source(plugDefinitionIndex, plugDefinition.bucketId)
+        && build_data::is_consumed_on_apply(plugDefinitionIndex, plugDefinition.bucketId)
+        && !(socketLane < detail.initialPlugIndices.size()
+             && detail.initialPlugIndices[socketLane] == plugDefinitionIndex);
+    if (consumesStack && !holds_plug_source(snapshot, plugDefinition.definitionHash)) {
+        return fail("plug_ownership");
+    }
+
+    AccountState chargedAccount = snapshot;
+    build_data::material_requirements::Definition materialSet{};
+    bool profileChanged = false;
+    const std::uint16_t materialSetIndex = plugDefinition.insertionMaterialRequirementSetIndex;
+    if (materialSetIndex != build_data::items::kUnavailableMaterialRequirementSetIndex
+        && (!build_data::find_material_requirement_set(materialSetIndex, materialSet)
+            || materialSet.requirementSetIndex != materialSetIndex
+            || !apply_action_materials(snapshot, materialSet, chargedAccount, profileChanged))) {
+        return fail("materials");
+    }
+
+    // Applying spends the stack the plug came from. The insertion cost above is a separate
+    // authored charge that leaves the plug itself untouched, so the unit is taken here.
+    //
+    // The authored-cost path cannot do this. It refuses any row carrying an instance key, because
+    // it exists for the non-instanced currency and material stacks, and an action source always
+    // carries one. Spending one is therefore its own transition: the row keeps its identity while
+    // any unit remains, and releases it with the row once the last unit goes.
+    if (consumesStack && !spend_plug_source(chargedAccount, plugDefinition.definitionHash)) {
+        return fail("plug_stack");
+    }
+    profileChanged = profileChanged || consumesStack;
+
+    authored_inventory::Sockets authoredSockets{};
+    if (target->sockets.policy == authored_inventory::SocketPolicy::nativeDefaults) {
+        if (!materialize_native_sockets(detail, authoredSockets)) {
+            return fail("native_sockets");
+        }
+    } else {
+        authoredSockets = target->sockets;
+        if (authoredSockets.policy != authored_inventory::SocketPolicy::authored
+            || authoredSockets.plugCount != detail.ordinarySocketCount
+            || !authored_inventory::valid(authoredSockets)) {
+            return fail("authored_sockets");
+        }
+    }
+    if (authoredSockets.plugs[socketLane].has_value()
+        && *authoredSockets.plugs[socketLane] == plugDefinition.definitionHash) {
+        return fail("already_applied");
+    }
+    authoredSockets.plugs[socketLane] = plugDefinition.definitionHash;
+
+    CharacterState after = before;
+    authored_inventory::Item* changed = character_item_at(after, location);
+    if (changed == nullptr || changed->instanceSoid != target->instanceSoid
+        || changed->definitionHash != target->definitionHash || changed->level != target->level
+        || changed->quantity != target->quantity
+        || changed->mutationSerial != target->mutationSerial) {
+        return fail("target_copy");
+    }
+    changed->sockets = authoredSockets;
+
+    AccountState candidate = chargedAccount;
+    candidate.characters[characterIndex] = after;
+    family4_loadout::ResolvedLoadout afterLoadout{};
+    ResolvedPosition beforePosition{};
+    ResolvedPosition afterPosition{};
+    const family4_loadout::ResolvedItem* resolvedTarget = nullptr;
+    for (std::size_t index = 0; index < beforeLoadout.itemCount; ++index) {
+        const auto& resolved = beforeLoadout.items[index];
+        if (resolved.instance.instanceSoid == targetInstanceSoid
+            && resolved.instance.baseDefinitionIndex != targetDefinition.definitionIndex) {
+            return fail("before_definition");
+        }
+    }
+    if (!account::valid(candidate)
+        || !family4_loadout::resolve(candidate, characterIndex, afterLoadout)
+        || !find_resolved_position(beforeLoadout, targetInstanceSoid, beforePosition)
+        || !find_resolved_position(afterLoadout, targetInstanceSoid, afterPosition)
+        || !same_position(beforePosition, afterPosition)) {
+        return fail("candidate_or_position");
+    }
+    for (std::size_t index = 0; index < afterLoadout.itemCount; ++index) {
+        const auto& resolved = afterLoadout.items[index];
+        if (resolved.instance.instanceSoid != targetInstanceSoid) {
+            continue;
+        }
+        if (resolvedTarget != nullptr) {
+            return fail("duplicate_target");
+        }
+        resolvedTarget = &resolved;
+    }
+    if (resolvedTarget == nullptr
+        || resolvedTarget->instance.baseDefinitionIndex != targetDefinition.definitionIndex
+        || resolvedTarget->instance.ordinarySockets.state
+               != middleware::datagen::family4::instance::OrdinarySocketBlockState::present
+        || !resolvedTarget->instance.ordinarySockets.plugs[socketLane].has_value()
+        || *resolvedTarget->instance.ordinarySockets.plugs[socketLane] != plugDefinitionIndex) {
+        return fail("after_socket");
+    }
+
+    mutation.beforeCharacter = before;
+    mutation.afterCharacter = after;
+    mutation.beforeProfileItems = snapshot.profileItems;
+    mutation.afterProfileItems = chargedAccount.profileItems;
+    mutation.accountSoid = snapshot.primarySoid;
+    mutation.characterSoid = before.soid;
+    mutation.targetInstanceSoid = targetInstanceSoid;
+    mutation.targetDefinitionHash = targetDefinition.definitionHash;
+    mutation.plugDefinitionHash = plugDefinition.definitionHash;
+    mutation.materialRequirementSetHash = materialSet.requirementSetHash;
+    mutation.characterIndex = characterIndex;
+    mutation.expectedProfileItemCount = snapshot.profileItemCount;
+    mutation.afterProfileItemCount = chargedAccount.profileItemCount;
+    mutation.itemIndex = location.index;
+    mutation.targetDefinitionIndex = targetDefinition.definitionIndex;
+    mutation.plugDefinitionIndex = plugDefinitionIndex;
+    mutation.materialRequirementSetIndex = materialSetIndex;
+    mutation.socketLane = socketLane;
+    mutation.targetBucketId = targetDefinition.bucketId;
+    mutation.plugBucketId = plugDefinition.bucketId;
+    mutation.materialRequirementCount = materialSet.requirementCount;
+    mutation.profileChanged = profileChanged;
+    mutation.targetEquipped = location.equipped;
+    mutation.prepared = true;
+    return true;
+}
+
+/** Stages one complete accumulated item-state value without moving or recreating the item. */
+[[nodiscard]] bool stage_item_state(const AccountState& snapshot,
+                                    std::size_t characterIndex,
+                                    std::uint64_t targetInstanceSoid,
+                                    std::uint16_t targetDefinitionIndex,
+                                    std::uint32_t flags,
+                                    PendingItemState& mutation) noexcept {
+    mutation = {};
+    // Bits 0 and 1 are the two states the client sends. Any other bit is a request we cannot
+    // honour.
+    constexpr std::uint32_t kSupportedItemStateMask = 0x3U;
+    if (!account::valid(snapshot) || characterIndex >= snapshot.characterCount
+        || targetInstanceSoid == 0 || (flags & ~kSupportedItemStateMask) != 0) {
+        return false;
+    }
+    const CharacterState& before = snapshot.characters[characterIndex];
+    if (!before.selected || before.soid == 0) {
+        return false;
+    }
+
+    CharacterItemLocation location{};
+    family4_loadout::ResolvedLoadout beforeLoadout{};
+    if (!find_character_item_location(before, targetInstanceSoid, location)
+        || !family4_loadout::resolve(snapshot, characterIndex, beforeLoadout)) {
+        return false;
+    }
+    const authored_inventory::Item* target = character_item_at(before, location);
+    build_data::items::Definition definition{};
+    ResolvedPosition beforePosition{};
+    if (target == nullptr || target->flags == flags
+        || !build_data::find_item_definition_hash(target->definitionHash, definition)
+        || definition.definitionHash != target->definitionHash
+        || definition.definitionIndex != targetDefinitionIndex
+        || !find_resolved_position(beforeLoadout, targetInstanceSoid, beforePosition)) {
+        return false;
+    }
+
+    CharacterState after = before;
+    authored_inventory::Item* changed = character_item_at(after, location);
+    if (changed == nullptr || !same_stationary_item(*changed, *target)) {
+        return false;
+    }
+    changed->flags = flags;
+
+    AccountState candidate = snapshot;
+    candidate.characters[characterIndex] = after;
+    family4_loadout::ResolvedLoadout afterLoadout{};
+    ResolvedPosition afterPosition{};
+    if (!account::valid(candidate)
+        || !family4_loadout::resolve(candidate, characterIndex, afterLoadout)
+        || !find_resolved_position(afterLoadout, targetInstanceSoid, afterPosition)
+        || !same_position(beforePosition, afterPosition)) {
+        return false;
+    }
+
+    mutation.beforeCharacter = before;
+    mutation.afterCharacter = after;
+    mutation.characterSoid = before.soid;
+    mutation.targetInstanceSoid = targetInstanceSoid;
+    mutation.characterIndex = characterIndex;
+    mutation.itemIndex = location.index;
+    mutation.targetDefinitionIndex = targetDefinitionIndex;
+    mutation.beforeFlags = target->flags;
+    mutation.afterFlags = flags;
+    mutation.targetEquipped = location.equipped;
+    mutation.prepared = true;
+    return true;
+}
+
+} // namespace runtime::detail
+} // namespace sunrise::state

+ 37 - 0
Sunrise/src/state/runtime/state_account_transaction_helpers.h

@@ -18,6 +18,12 @@ struct ResolvedPosition {
     std::int32_t mutationSerial{};
 };
 
+/** Stable location of one character-owned item inside authored State. */
+struct CharacterItemLocation {
+    std::size_t index{};
+    bool equipped{};
+};
+
 void report_equipment(std::string_view stage,
                       std::string_view result,
                       EquipmentMutationKind kind,
@@ -164,5 +170,36 @@ find_acquired_row(const middleware::datagen::family4::loadout::ResolvedLoadout&
                                               const PendingItemDismantle& mutation,
                                               AccountState& after) noexcept;
 [[nodiscard]] bool identity_uses_soid(const AccountState& account, std::uint64_t soid) noexcept;
+[[nodiscard]] bool holds_plug_source(const AccountState& account,
+                                     std::uint32_t definitionHash) noexcept;
+[[nodiscard]] bool spend_plug_source(AccountState& account, std::uint32_t definitionHash) noexcept;
+[[nodiscard]] bool
+apply_action_materials(const AccountState& before,
+                       const build_data::material_requirements::Definition& definition,
+                       AccountState& after,
+                       bool& changed) noexcept;
+[[nodiscard]] bool inventory_bucket_id(const account::inventory::Item& item,
+                                       std::uint8_t& bucketId) noexcept;
+[[nodiscard]] bool same_position(const ResolvedPosition& left,
+                                 const ResolvedPosition& right) noexcept;
+[[nodiscard]] bool same_stationary_item(const account::inventory::Item& left,
+                                        const account::inventory::Item& right) noexcept;
+[[nodiscard]] bool find_character_item_location(const CharacterState& character,
+                                                std::uint64_t instanceSoid,
+                                                CharacterItemLocation& location) noexcept;
+[[nodiscard]] const account::inventory::Item*
+character_item_at(const CharacterState& character, const CharacterItemLocation& location) noexcept;
+[[nodiscard]] account::inventory::Item*
+character_item_at(CharacterState& character, const CharacterItemLocation& location) noexcept;
+[[nodiscard]] std::uint32_t character_item_definition_hash(const CharacterState& character,
+                                                           std::uint64_t instanceSoid) noexcept;
+[[nodiscard]] bool
+find_unequipped_row(const middleware::datagen::family4::loadout::ResolvedLoadout& loadout,
+                    std::uint64_t instanceSoid,
+                    std::uint16_t& inventoryRow,
+                    std::uint8_t& equipmentSlot) noexcept;
+[[nodiscard]] bool
+loadout_contains(const middleware::datagen::family4::loadout::ResolvedLoadout& loadout,
+                 std::uint64_t instanceSoid) noexcept;
 
 } // namespace sunrise::state::runtime::detail

Некоторые файлы не были показаны из-за большого количества измененных файлов