diff --git a/packages/swift-sdk/SCHEMA_RELEASES.md b/packages/swift-sdk/SCHEMA_RELEASES.md index 2c4e67b1aff..2183bfbe76d 100644 --- a/packages/swift-sdk/SCHEMA_RELEASES.md +++ b/packages/swift-sdk/SCHEMA_RELEASES.md @@ -2,12 +2,40 @@ SwiftData schemas become supported history when a build reaches App Store distribution. TestFlight uploads capture provenance and a synthetic SQLite -fixture, but do not by themselves register a released schema. V1 is the agreed -existing baseline. Intermediate pre-release V2–V5 schemas have been collapsed -into the working V2, including the public-key usage-limit columns. A separate -compatibility bridge handles older, unregistered `1.0.0` database layouts when -they can migrate without losing existing data. Other intermediate development -databases are unsupported. +fixture, but do not by themselves register a released schema. The accepted frozen V1 remains unchanged. Historical V2 is now reconstructed +from `52e8d4ec68f0c772313fa1bbef223fb1eabbf1cc`; all 35 entity hashes and the +model checksum match the observed App Store 9.0.2 database. Active models are +V3. Other intermediate development shapes remain unsupported. + +The old V2 fixture was generated from September 8 sources containing 13 +properties added on August 28, after the August 27 App Store release. The +reconstructed V2 instead predates those additions. Its synthetic fixture and +source provenance live in `schema-releases.json` under `historical_schemas`, +separate from archive-captured releases. This identifies a matching model +source, not the confirmed build commit of Apple's binary. V2 is reserved: +automated release capture must not register another shape under that number. + +The main migration plan is historical V2 → V3. Accepted V1 has a separate +V1 → V3 plan: V1 already contains the 13 properties missing from historical +V2, so a V1 → V2 → V3 chain could discard values. Routing uses model metadata +and runs after recovery; a version label alone never selects an unknown beta +schema. The former live V2 is accepted only when its complete graph matches +current V3 exactly, entity hashes and checksum alike. That alias therefore +lasts only until the next live-graph change: after it, every store still +labelled `2.0.0` with the former live shape becomes `unsupported-v2` and fails +closed. Check internal devices still carrying that label before the next +shape change and migrate or deliberately reset them then, rather than +discovering them afterwards as failed opens. + +The route decision is logged as `store_migration_route` with the validated +`source_version`, `source_checksum` and one of `new-store`, +`accepted-v1-to-v3`, `historical-v2-to-v3`, `previous-live-v2-current-shape`, +`unsupported-v2`, `labelled-current-v3`, `ordinary-current-plan` or, from the +bridge, `legacy-v1-bridge-to-v3`. Resolving a frozen schema's identity builds +a temporary store, so it is memoized per process and consulted only where a +label is undecidable without it (`1.0.0`, `2.0.0`); a `3.0.0` label takes the +default plan without any probe, and a probe failure on the undecidable labels +refuses the open with the probe's own error while leaving the store untouched. ## Legacy stores before the release registry @@ -19,7 +47,7 @@ the explicit migration plan; those databases still report version `1.0.0`. The shared `DashModelContainer` factory recognizes registered schema fingerprints before opening an existing store. Unknown legacy `1.0.0` stores may use the compatibility bridge: take a consistent backup including committed -WAL data, migrate an isolated copy automatically to `DashSchemaV2`, verify that +WAL data, migrate an isolated copy automatically to `DashSchemaV3`, verify that existing stored values and relationship rows survived, and reopen it through the ordinary migration plan before installing it. The backup is retained for recovery. Corruption, removed fields/entities, changed stored data, and newer @@ -109,9 +137,9 @@ The run failed before upload, so this provenance establishes a tested source layout rather than proof of publication. Regression tests exercise the public factory, data/default preservation, writes, reopen, and failure recovery. -Keep the bridge for installations that skip the V2 app release. When advancing -to V3, bind `DashSchemaV2` to its released snapshot and retain the legacy-to-V2 -step before the normal V2-to-current plan. The bridge must never automatically +Keep the bridge for installations that skip the V3 app release. When advancing +to V4, bind `DashSchemaV3` to its released snapshot and retain the legacy-to-V3 +step before the normal V3-to-current plan. The bridge must never automatically follow the latest live model graph. The release observer's one-time `bootstrap` only records its observation baseline; it neither runs this migration nor proves V1's App Store provenance. @@ -181,8 +209,9 @@ all required releases, not merely a commit from before the snapshot merge. access, and uses the PAT so its PR events trigger CI. Apple credentials stay in the iOS repository. Do not put tokens in command arguments or manifests. 3. Initialize the iOS release baseline before the first newly tracked release, - then run its monitor manually in dry-run mode. The baseline accepts V1 as - agreed and does not claim to reconstruct an earlier binary. + then run its monitor manually in dry-run mode. The baseline must reference + the verified historical V2 binding for 9.0.2. Correct the old V1 association + without moving the publication cutoff; see the iOS runbook. 4. After publication, use the iOS manual monitor for the normal operator flow. For a worker retry, select the recorded Apple version ID and a full commit on `schema-release-data`. Select `dry_run` to validate and generate the patch @@ -213,7 +242,7 @@ standard Swift/Foundation names are assumed not to be shadowed by application types. It does not prove custom encoding or helper-method behavior, so native captured-store hash/index checks and code review remain required. -A released snapshot has its own namespace, for example `DashSchemaSnapshotV2`. +A released snapshot has its own namespace, for example `DashSchemaSnapshotV3`. It is not automatically registered alongside identical current models. When changing the structure after a release, explicitly register the historical snapshot as the old schema, introduce the next active version and its migration, @@ -266,3 +295,16 @@ python3 packages/swift-sdk/scripts/historical_schema_fixture.py --check Swift SDK CI additionally checks the generated schemas against the released fixtures, including entity hashes, indexes and migration behavior. + +## Local verification with a private database copy + +`DashModelMigrationTests.testPrivateHistoricalStoreMigrationWhenExplicitlyProvided` +accepts a local standalone SQLite input through `DASH_PRIVATE_MIGRATION_STORE`. +For an Xcode simulator test run, forward it using the +`TEST_RUNNER_DASH_PRIVATE_MIGRATION_STORE` environment variable. The test copies +that input to a disposable directory, verifies preservation of every supported +SQLite table/relationship, writes through current models and reopens the copy. +Without the explicit input it skips; normal CI uses only synthetic fixtures. +Do not add a real wallet database to resources, XCTest attachments, commits or +CI artifacts. If capturing another input, preserve committed WAL contents with +a consistent SQLite backup rather than copying an active main file alone. diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Services/SDKLogger.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Services/SDKLogger.swift index 3bbefb52c37..b083ae12383 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Services/SDKLogger.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Services/SDKLogger.swift @@ -237,6 +237,14 @@ private final class SDKLoggerState: @unchecked Sendable { } } + func removeSink() { + let removed: SDKLogFileSink? = lock.withLock { + defer { sink = nil } + return sink + } + removed?.flush() + } + func destination(for severity: SDKLogSeverity) -> SDKLogFileSink? { lock.withLock { guard severity != .debug || includeDebug else { return nil } @@ -503,6 +511,13 @@ public enum SDKLogger { state.updateDebugSetting(includeDebug) } + /// Detach the process-wide file sink after flushing it. Tests that install + /// a sink in a disposable directory call this before removing the + /// directory, so later events are not written through a stale handle. + static func removeFileSink() { + state.removeSink() + } + public static func log(_ message: String, minimumLevel level: LoggingPreset = .medium) { guard LoggingPreferences.allows(level) else { return } // Mirror to NSLog (unified logging) in addition to stdout so diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacySchemaBridge.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacySchemaBridge.swift index 7fd33cb0e58..4c9438002b5 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacySchemaBridge.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacySchemaBridge.swift @@ -3,13 +3,13 @@ import Darwin import Foundation import SwiftData -/// One-time, local-store bridge into the fixed V2 schema. The ordinary migration +/// One-time, local-store bridge into the fixed V3 schema. The ordinary migration /// plan owns recognized versions. This path accepts only an older 1.0.0 graph /// whose complete existing SQLite data survives an inferred migration unchanged. /// Call before publishing any container/context for the same URL. enum DashLegacySchemaBridge { typealias SQLite = DashLegacyStoreSQLite - enum Phase { case afterSnapshot, afterMigration, beforeInstall, writeLocked, afterCommit } + enum Phase: String { case afterSnapshot, afterMigration, beforeInstall, writeLocked, afterCommit } struct Hooks { var visit: (Phase, URL) throws -> Void = { _, _ in } var availableCapacity: (URL) throws -> Int64 = DashLegacySchemaBridge.availableCapacity(at:) @@ -30,8 +30,16 @@ enum DashLegacySchemaBridge { static func open(configuration: ModelConfiguration, schema: Schema, plan: any SchemaMigrationPlan.Type, hooks: Hooks = Hooks()) throws -> ModelContainer { let url = configuration.url + func visit(_ phase: Phase, _ candidate: URL) throws { + SDKLogger.event("legacy_migration_phase", category: .persistence, + fields: ["phase": .publicText(phase.rawValue)]) + try hooks.visit(phase, candidate) + } func ordinary() throws -> ModelContainer { - try ModelContainer(for: schema, migrationPlan: plan, configurations: [configuration]) + let selectedPlan = configuration.isStoredInMemoryOnly ? plan : + try DashModelContainer.migrationPlan(at: url, defaultPlan: plan) + return try ModelContainer(for: schema, migrationPlan: selectedPlan, + configurations: [configuration]) } guard !configuration.isStoredInMemoryOnly else { return try ordinary() } let root = backupDirectory(for: url) @@ -41,7 +49,7 @@ enum DashLegacySchemaBridge { if !FileManager.default.fileExists(atPath: marker.path) { // Detection must not impose bridge-specific metadata or locking // requirements on stores handled by SwiftData's ordinary path. - let needsMigration = (try? identity(at: url)).flatMap { try? needsBridge($0, plan: plan) } ?? false + let needsMigration = (try? identity(at: url)).flatMap { try? needsBridge($0) } ?? false // Recheck after reading identity: a concurrent bridge publishes its // journal before the store can change to the destination schema. if !needsMigration && !FileManager.default.fileExists(atPath: marker.path) { @@ -59,12 +67,19 @@ enum DashLegacySchemaBridge { throw SQLite.Failure.unsupported( "The original database is missing while migration recovery is pending. Recovery files remain at \(root.path). Restore the original database from a verified backup with the app closed, or contact support for deliberate recovery. Do not delete the journal or create an empty database.") } + SDKLogger.event("legacy_migration_phase", category: .persistence, + fields: ["phase": .publicText("recovery")]) try SQLite.recoverRollbackJournal(at: url) try recoverIfNeeded(at: url, root: root) // Another opener may have finished migration before this lock was // acquired. Recovery errors above remain fatal; ordinary detection does not. guard let source = try? identity(at: url), - (try? needsBridge(source, plan: plan)) == true else { return try ordinary() } + (try? needsBridge(source)) == true else { return try ordinary() } + SDKLogger.event("store_migration_route", category: .persistence, fields: [ + "source_version": .publicText("1.0.0"), + "source_checksum": .publicText(Data(base64Encoded: source.checksum)?.count == 32 ? source.checksum : "unavailable"), + "route": .publicText("legacy-v1-bridge-to-v3"), + "target_version": .publicText("3.0.0")]) guard configuration.allowsSave else { throw SQLite.Failure.unsupported("The store is read-only") } let permitted = Set(Schema(versionedSchema: DashSchemaV1.self).entities.map(\.name)) let required: Set = ["PersistentWallet", "PersistentAccount", "PersistentTransaction", "PersistentTxo"] @@ -108,23 +123,23 @@ enum DashLegacySchemaBridge { guard try SQLite.rawDigest(url) == rawSource else { throw SQLite.Failure.sourceChanged } try SQLite.integrityCheck(backup) guard try identity(at: backup) == source else { throw SQLite.Failure.sourceChanged } - try hooks.visit(.afterSnapshot, url) + try visit(.afterSnapshot, url) try createProtectedFile(candidate, like: url) try SQLite.copy(from: backup, to: candidate) // Never replace this with `schema` or the latest version. Users can skip - // the V2 app; later releases must keep V2's frozen graph as this target. + // the V3 app; later releases must keep V3's frozen graph as this target. try autoreleasepool { - let bridgeSchema = Schema(versionedSchema: DashSchemaV2.self) + let bridgeSchema = Schema(versionedSchema: DashSchemaV3.self) _ = try ModelContainer(for: bridgeSchema, configurations: [ ModelConfiguration(schema: bridgeSchema, url: candidate, cloudKitDatabase: .none) ]) } try SQLite.checkpoint(candidate) - try hooks.visit(.afterMigration, candidate) + try visit(.afterMigration, candidate) try rejectExternalStorage(at: candidate) try SQLite.integrityCheck(candidate) try SQLite.validatePreservation(from: backup, to: candidate) - // The normal plan must accept the fixed V2 result. In a future release + // The normal plan must accept the fixed V3 result. In a future release // it may continue through additional explicitly registered stages here. try autoreleasepool { _ = try ModelContainer(for: schema, migrationPlan: plan, configurations: [ @@ -146,16 +161,16 @@ enum DashLegacySchemaBridge { } try synchronizeDirectory(directory) try writeJournal(journal, at: root) - try hooks.visit(.beforeInstall, url) + try visit(.beforeInstall, url) try SQLite.copy(from: candidate, to: url) { // backup_step(0) owns SQLite's write lock, closing the race between // comparison and commit. Main/WAL bytes must still be the snapshot's // bytes; unrelated or concurrent writes cause a safe retry. guard try SQLite.rawDigest(url) == rawSource else { throw SQLite.Failure.sourceChanged } - try hooks.visit(.writeLocked, url) + try visit(.writeLocked, url) } committed = true - try hooks.visit(.afterCommit, url) + try visit(.afterCommit, url) let container = try ordinary() // This container has not escaped to the app, so no application writes // are permitted yet. Clearing must succeed before returning it: a stale @@ -215,11 +230,11 @@ enum DashLegacySchemaBridge { return max(0, try fileSystem()) } - private static func needsBridge(_ source: Identity, plan: any SchemaMigrationPlan.Type) throws -> Bool { + private static func needsBridge(_ source: Identity) throws -> Bool { guard source.versions == ["1.0.0"] else { return false } - for registered in plan.schemas where version(registered.versionIdentifier) == "1.0.0" { - if source == (try identity(for: registered)) { return false } - } + // Accepted V1 has its own direct route to V3, independent of the + // primary historical V2 migration plan. + if source == (try identity(for: DashSchemaV1.self)) { return false } return true } @@ -325,7 +340,7 @@ enum DashLegacySchemaBridge { } } - private static func identity(at url: URL) throws -> Identity { + static func identity(at url: URL) throws -> Identity { let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(type: .sqlite, at: url) guard let versions = metadata[NSStoreModelVersionIdentifiersKey] as? [String], let checksum = metadata["NSStoreModelVersionChecksumKey"] as? String, @@ -336,7 +351,16 @@ enum DashLegacySchemaBridge { return Identity(versions: versions, checksum: checksum, hashes: hashes) } - private static func identity(for type: any VersionedSchema.Type) throws -> Identity { + /// The identity Core Data records for a versioned schema. It is a pure + /// function of the frozen model graph, but computing it writes a complete + /// temporary store, so each successful result is kept for the process. + static func identity(for type: any VersionedSchema.Type) throws -> Identity { + try identityCache.identity(for: type) { try computeIdentity(for: type) } + } + + private static let identityCache = SchemaIdentityCache() + + private static func computeIdentity(for type: any VersionedSchema.Type) throws -> Identity { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } @@ -350,6 +374,23 @@ enum DashLegacySchemaBridge { return try identity(at: url) } + /// Process-lifetime memo of schema identities. Only successful + /// computations are stored: a failed probe (for example a full disk) is + /// retried on the next request rather than remembered. + final class SchemaIdentityCache: @unchecked Sendable { + private let lock = NSLock() + private var identities: [ObjectIdentifier: Identity] = [:] + + func identity(for type: any VersionedSchema.Type, + compute: () throws -> Identity) throws -> Identity { + let key = ObjectIdentifier(type) + if let cached = lock.withLock({ identities[key] }) { return cached } + let computed = try compute() + lock.withLock { identities[key] = computed } + return computed + } + } + private static func rejectExternalStorage(at url: URL) throws { let parent = url.deletingLastPathComponent() let names = Set([url.lastPathComponent, url.deletingPathExtension().lastPathComponent]) @@ -393,10 +434,6 @@ enum DashLegacySchemaBridge { defer { Darwin.close(descriptor) } guard fsync(descriptor) == 0 else { throw SQLite.Failure.database("Cannot persist migration journal") } } - private static func version(_ value: Schema.Version) -> String { - "\(value.major).\(value.minor).\(value.patch)" - } - private final class StoreLock { private var descriptor: Int32 init(url: URL) throws { diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift index ef7b8a13bb5..ea878415c36 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift @@ -1,3 +1,4 @@ +import CoreData import Foundation import Dispatch import SwiftData @@ -99,7 +100,7 @@ public enum DashModelContainer { /// Create the schema for all Dash Platform models public static var schema: Schema { - Schema(versionedSchema: DashSchemaV2.self) + Schema(versionedSchema: DashSchemaV3.self) } /// Create a persistent model container for storing data. @@ -170,15 +171,106 @@ public enum DashModelContainer { configuration: ModelConfiguration, bridgeLegacyStore: Bool = true ) throws -> ModelContainer { - if bridgeLegacyStore { - return try DashLegacySchemaBridge.open( - configuration: configuration, schema: schema, plan: DashMigrationPlan.self) + SDKLogger.event("store_open_started", category: .persistence, + fields: ["target_version": .publicText("3.0.0")]) + do { + let container: ModelContainer + if bridgeLegacyStore { + container = try DashLegacySchemaBridge.open( + configuration: configuration, schema: schema, plan: DashMigrationPlan.self) + } else { + container = try ModelContainer( + for: schema, + migrationPlan: try migrationPlan(at: configuration.url, defaultPlan: DashMigrationPlan.self), + configurations: [configuration]) + } + SDKLogger.event("store_open_succeeded", category: .persistence, + fields: ["target_version": .publicText("3.0.0")]) + return container + } catch { + logMigrationFailure(error) + throw error } - return try ModelContainer( - for: schema, - migrationPlan: DashMigrationPlan.self, - configurations: [configuration] - ) + } + + /// Error descriptions/userInfo can include rows, URLs and other private + /// values. Record only a known system domain (or the error's type) and code. + private static func logMigrationFailure(_ error: Error) { + let nsError = error as NSError + let systemDomains: Set = [NSCocoaErrorDomain, NSPOSIXErrorDomain, NSOSStatusErrorDomain, "NSSQLiteErrorDomain"] + let domain = systemDomains.contains(nsError.domain) ? nsError.domain : String(reflecting: type(of: error)) + SDKLogger.event("store_open_failed", category: .persistence, severity: .error, + fields: ["error_domain": .publicText(domain), "error_code": .integer(Int64(nsError.code)), + "target_version": .publicText("3.0.0")]) + } + + /// Select by the complete stored model identity, after journal recovery. + /// Accepted V1 contains fields absent from the real historical V2; sending + /// it through V2 would delete those values before V3 adds the fields again. + /// `identity` resolves a schema's stored identity; tests inject a failing + /// probe to pin which routes may depend on it. Only labels whose route is + /// undecidable without it (1.0.0, 2.0.0) consult the probe at all. + static func migrationPlan( + at url: URL, defaultPlan: any SchemaMigrationPlan.Type, + identity: (any VersionedSchema.Type) throws -> DashLegacySchemaBridge.Identity + = DashLegacySchemaBridge.identity(for:) + ) throws -> any SchemaMigrationPlan.Type { + guard ObjectIdentifier(defaultPlan) == ObjectIdentifier(DashMigrationPlan.self) else { return defaultPlan } + guard FileManager.default.fileExists(atPath: url.path) else { + SDKLogger.event("store_migration_route", category: .persistence, fields: [ + "route": .publicText("new-store"), "target_version": .publicText("3.0.0")]) + return defaultPlan + } + let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(type: .sqlite, at: url) + let versions = metadata[NSStoreModelVersionIdentifiersKey] as? [String] + let hashes = metadata[NSStoreModelVersionHashesKey] as? [String: Data] + let checksum = metadata["NSStoreModelVersionChecksumKey"] as? String + // Only validated schema metadata is public diagnostic material. Never + // log arbitrary strings from malformed store metadata or any store path. + let safeVersions = versions.flatMap { values -> String? in + guard !values.isEmpty, values.count <= 4, + values.allSatisfy({ $0.count <= 32 && $0.range(of: #"^\d+\.\d+\.\d+$"#, options: .regularExpression) != nil }) else { return nil } + return values.joined(separator: ",") + } ?? "unavailable" + let safeChecksum = checksum.flatMap { Data(base64Encoded: $0)?.count == 32 ? $0 : nil } ?? "unavailable" + func logRoute(_ route: String) { + SDKLogger.event("store_migration_route", category: .persistence, fields: [ + "source_version": .publicText(safeVersions), "source_checksum": .publicText(safeChecksum), + "route": .publicText(route), "target_version": .publicText("3.0.0")]) + } + func matches(_ type: any VersionedSchema.Type) throws -> Bool { + let expected = try identity(type) + return hashes == expected.hashes && (checksum == nil || checksum == expected.checksum) + } + // A 1.0.0 label alone cannot choose between the accepted-V1 route and + // the legacy bridge, and the default plan has no V1 stage, so a failed + // probe stays fatal here: the open fails with the probe's own error + // instead of an inapplicable plan, and the store is untouched. + if versions == ["1.0.0"], try matches(DashSchemaV1.self) { + logRoute("accepted-v1-to-v3") + return DashAcceptedV1MigrationPlan.self + } + if versions == ["2.0.0"] { + // The immediately preceding candidate used the current graph with + // a V2 label. Accept its exact shape, never arbitrary beta V2 data. + // A probe failure is equally undecidable and refuses the same way. + let historical = try matches(DashSchemaV2.self) + let previousCurrent = try !historical && matches(DashSchemaV3.self) + guard historical || previousCurrent else { + logRoute("unsupported-v2") + throw DashLegacyStoreSQLite.Failure.unsupported( + "The database identifies itself as schema 2.0.0 but its model does not match the supported historical or current schema. The original database has not been replaced. Contact support; do not delete the app.") + } + logRoute(historical ? "historical-v2-to-v3" : "previous-live-v2-current-shape") + } else if versions == ["3.0.0"] { + // Same plan either way. Opening a current store must neither wait + // on nor fail with a schema probe that could only refine this line; + // `source_checksum` above already identifies the exact graph. + logRoute("labelled-current-v3") + } else { + logRoute("ordinary-current-plan") + } + return defaultPlan } /// Create an in-memory model container for testing @@ -195,16 +287,25 @@ public enum DashModelContainer { /// SwiftData migration plan for Dash Platform model updates public enum DashMigrationPlan: SchemaMigrationPlan { public static var schemas: [any VersionedSchema.Type] { - [DashSchemaV1.self, DashSchemaV2.self] + [DashSchemaV2.self, DashSchemaV3.self] } public static var stages: [MigrationStage] { [ - .lightweight(fromVersion: DashSchemaV1.self, toVersion: DashSchemaV2.self) + .lightweight(fromVersion: DashSchemaV2.self, toVersion: DashSchemaV3.self) ] } } +/// Separate compatibility route: V1 has fields missing from historical V2. +/// Never insert V2 between this baseline and the current schema. +enum DashAcceptedV1MigrationPlan: SchemaMigrationPlan { + static var schemas: [any VersionedSchema.Type] { [DashSchemaV1.self, DashSchemaV3.self] } + static var stages: [MigrationStage] { + [.lightweight(fromVersion: DashSchemaV1.self, toVersion: DashSchemaV3.self)] + } +} + /// The accepted historical baseline, pinned by the unchanged generated V1 /// models and `Fixtures/SchemaStores/dash-v1.store`. Preserve those definitions /// and fixture bytes when introducing later schema versions. @@ -213,7 +314,7 @@ public enum DashMigrationPlan: SchemaMigrationPlan { /// the current live schema. They do not reconstruct or verify the database /// written by the original App Store binary. Other historical development /// layouts are accepted only by the local legacy bridge when every existing -/// value and relationship survives migration to fixed V2. Other layouts fail; +/// value and relationship survives migration to fixed V3. Other layouts fail; /// the container never erases or recreates a user's database. public enum DashSchemaV1: VersionedSchema { public static var versionIdentifier: Schema.Version { @@ -225,21 +326,55 @@ public enum DashSchemaV1: VersionedSchema { } } -/// Unreleased V2 combines the tracked-masternode, asset-lock recipient, sweep, -/// public-key usage limits, contract-bound variants, and balance freshness metadata. -/// V1 is the accepted -/// historical baseline. Intermediate beta layouts are not supported release schemas. -/// -/// After App Store publication a separate DashSchemaSnapshotV2 preserves the -/// complete graph. Keep this version on the live models while they match that -/// snapshot. The next shape change must move this version onto the snapshot, -/// introduce a new live version and explicitly test its migration. +/// Historical V2 reconstructed from commit 52e8d4ec68. Its complete frozen +/// graph matches the database observed on the released application. Other +/// development layouts that reused the V2 number are not historical V2. public enum DashSchemaV2: VersionedSchema { - public static var versionIdentifier: Schema.Version { - Schema.Version(2, 0, 0) - } - + public static var versionIdentifier: Schema.Version { Schema.Version(2, 0, 0) } public static var models: [any PersistentModel.Type] { - DashModelContainer.modelTypes + [ + DashSchemaV2.PersistentIdentity.self, + DashSchemaV2.PersistentDPNSName.self, + DashSchemaV2.PersistentDashpayProfile.self, + DashSchemaV2.PersistentDashpayContactProfile.self, + DashSchemaV2.PersistentDashpayContactRequest.self, + DashSchemaV2.PersistentDashpayPayment.self, + DashSchemaV2.PersistentDashpayIgnoredSender.self, + DashSchemaV2.PersistentDocument.self, + DashSchemaV2.PersistentDataContract.self, + DashSchemaV2.PersistentPublicKey.self, + DashSchemaV2.PersistentTokenBalance.self, + DashSchemaV2.PersistentKeyword.self, + DashSchemaV2.PersistentToken.self, + DashSchemaV2.PersistentDocumentType.self, + DashSchemaV2.PersistentIndex.self, + DashSchemaV2.PersistentProperty.self, + DashSchemaV2.PersistentTokenHistoryEvent.self, + DashSchemaV2.PersistentPlatformAddress.self, + DashSchemaV2.PersistentPlatformAddressesSyncState.self, + DashSchemaV2.PersistentWallet.self, + DashSchemaV2.PersistentAccount.self, + DashSchemaV2.PersistentCoreAddress.self, + DashSchemaV2.PersistentTransaction.self, + DashSchemaV2.PersistentTxo.self, + DashSchemaV2.PersistentPendingInput.self, + DashSchemaV2.PersistentWalletManagerMetadata.self, + DashSchemaV2.PersistentShieldedNote.self, + DashSchemaV2.PersistentShieldedOutgoingNote.self, + DashSchemaV2.PersistentShieldedSyncState.self, + DashSchemaV2.PersistentShieldedActivity.self, + DashSchemaV2.PersistentShieldedViewingKey.self, + DashSchemaV2.PersistentAssetLock.self, + DashSchemaV2.PersistentInvitation.self, + DashSchemaV2.PersistentMasternode.self, + DashSchemaV2.PersistentTrackedMasternode.self + ] } } + +/// Current working schema. A later shape change must preserve this graph as +/// the fixed legacy-bridge target before introducing another live version. +public enum DashSchemaV3: VersionedSchema { + public static var versionIdentifier: Schema.Version { Schema.Version(3, 0, 0) } + public static var models: [any PersistentModel.Type] { DashModelContainer.modelTypes } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentAccount.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentAccount.swift new file mode 100644 index 00000000000..df18a8da5eb --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentAccount.swift @@ -0,0 +1,78 @@ +import Foundation +import SwiftData + +// `PersistentAccount` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentAccount { + #Unique([ + \.wallet, + \.accountType, + \.accountIndex, + \.standardTag, + \.registrationIndex, + \.keyClass, + \.userIdentityId, + \.friendIdentityId, + ]) + + var accountType: UInt32 + var accountIndex: UInt32 + var accountTypeName: String + var balanceConfirmed: UInt64 + var balanceUnconfirmed: UInt64 + var externalHighestUsed: Int32 + var internalHighestUsed: Int32 + var standardTag: UInt8 + var registrationIndex: UInt32 + var keyClass: UInt32 + var userIdentityId: Data + var friendIdentityId: Data + @Attribute(.unique) var accountExtendedPubKeyBytes: Data? + var createdAt: Date + var lastUpdated: Date + + var wallet: PersistentWallet + + @Relationship(deleteRule: .cascade, inverse: \PersistentCoreAddress.account) + var coreAddresses: [PersistentCoreAddress] + + @Relationship(deleteRule: .cascade, inverse: \PersistentPlatformAddress.account) + var platformAddresses: [PersistentPlatformAddress] + + var involvedTransactions: [PersistentTransaction] = [] + + init( + wallet: PersistentWallet, + accountType: UInt32, + accountIndex: UInt32, + accountTypeName: String + ) { + self.wallet = wallet + self.accountType = accountType + self.accountIndex = accountIndex + self.accountTypeName = accountTypeName + self.balanceConfirmed = 0 + self.balanceUnconfirmed = 0 + self.externalHighestUsed = -1 + self.internalHighestUsed = -1 + self.standardTag = 0 + self.registrationIndex = 0 + self.keyClass = 0 + self.userIdentityId = Data() + self.friendIdentityId = Data() + self.accountExtendedPubKeyBytes = nil + self.createdAt = Date() + self.lastUpdated = Date() + self.coreAddresses = [] + self.platformAddresses = [] + self.involvedTransactions = [] + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentAssetLock.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentAssetLock.swift new file mode 100644 index 00000000000..0eccf4e8fef --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentAssetLock.swift @@ -0,0 +1,100 @@ +import Foundation +import SwiftData + +// `PersistentAssetLock` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentAssetLock { + #Index([\.walletId]) + + @Attribute(.unique) var outPointHex: String + + var walletId: Data + + var transactionBytes: Data + + var fundingTypeRaw: Int + + var identityIndexRaw: Int32 + + var accountIndexRaw: Int32 = 0 + + var amountDuffs: Int64 + + var statusRaw: Int + + var proofBytes: Data? + + var recipientPlatformAddressHash: Data? + + var recipientPlatformAddressType: UInt8? + + var createdAt: Date + var updatedAt: Date + + init( + outPointHex: String, + walletId: Data, + transactionBytes: Data, + fundingTypeRaw: Int, + identityIndexRaw: Int32, + accountIndexRaw: Int32 = 0, + amountDuffs: Int64, + statusRaw: Int, + proofBytes: Data? = nil + ) { + self.outPointHex = outPointHex + self.walletId = walletId + self.transactionBytes = transactionBytes + self.fundingTypeRaw = fundingTypeRaw + self.identityIndexRaw = identityIndexRaw + self.accountIndexRaw = accountIndexRaw + self.amountDuffs = amountDuffs + self.statusRaw = statusRaw + self.proofBytes = proofBytes + self.createdAt = Date() + self.updatedAt = Date() + } + } +} + +extension DashSchemaV2.PersistentAssetLock { + static func predicate(walletId: Data) -> Predicate { + #Predicate { entry in + entry.walletId == walletId + } + } + + static func predicate( + walletId: Data, + identityIndex: UInt32 + ) -> Predicate { + let identityIndexRaw = Int32(bitPattern: identityIndex) + return #Predicate { entry in + entry.walletId == walletId && entry.identityIndexRaw == identityIndexRaw + } + } +} + +extension DashSchemaV2.PersistentAssetLock { + static func encodeOutPoint(rawBytes: Data) -> String { + precondition(rawBytes.count == 36, "outpoint must be 36 bytes") + let txid = rawBytes.prefix(32) + let voutBytes = rawBytes.suffix(4) + let vout = voutBytes.withUnsafeBytes { raw -> UInt32 in + var value: UInt32 = 0 + withUnsafeMutableBytes(of: &value) { dst in + dst.copyBytes(from: raw.prefix(MemoryLayout.size)) + } + return UInt32(littleEndian: value) + } + let txidHex = txid.reversed().map { String(format: "%02x", $0) }.joined() + return "\(txidHex):\(vout)" + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentCoreAddress.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentCoreAddress.swift new file mode 100644 index 00000000000..3252a13241b --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentCoreAddress.swift @@ -0,0 +1,68 @@ +import Foundation +import SwiftData + +// `PersistentCoreAddress` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentCoreAddress { + @Attribute(.unique) var address: String + var publicKey: Data + var keyType: UInt8 = 0 + var poolTypeTag: UInt8 + var addressIndex: UInt32 + var derivationPath: String + var isUsed: Bool + var firstSeenHeight: UInt32 + var lastSeenHeight: UInt32 + var balance: UInt64 + var createdAt: Date + var lastUpdated: Date + + var account: PersistentAccount? + + @Relationship(deleteRule: .cascade, inverse: \PersistentTxo.coreAddress) + var txos: [PersistentTxo] = [] + + init( + address: String, + publicKey: Data = Data(), + keyType: UInt8 = 0, + poolTypeTag: UInt8, + addressIndex: UInt32, + derivationPath: String, + isUsed: Bool = false, + balance: UInt64 = 0 + ) { + self.address = address + self.publicKey = publicKey + self.keyType = keyType + self.poolTypeTag = poolTypeTag + self.addressIndex = addressIndex + self.derivationPath = derivationPath + self.isUsed = isUsed + self.firstSeenHeight = 0 + self.lastSeenHeight = 0 + self.balance = balance + self.createdAt = Date() + self.lastUpdated = Date() + } + } +} + +extension DashSchemaV2.PersistentCoreAddress { + var poolTypeName: String { + switch poolTypeTag { + case 0: return "External" + case 1: return "Internal" + case 2: return "Additional" + case 3: return "Additional (Hardened)" + default: return "Unknown(\(poolTypeTag))" + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDPNSName.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDPNSName.swift new file mode 100644 index 00000000000..668be5316b9 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDPNSName.swift @@ -0,0 +1,132 @@ +import Foundation +import SwiftData + +// `PersistentDPNSName` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentDPNSName { + #Unique([\.networkRaw, \.normalizedParentDomainName, \.normalizedLabel]) + + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + var label: String + + var normalizedLabel: String + + var parentDomainName: String + + var normalizedParentDomainName: String + + var acquiredAt: UInt64 + + var isOwned: Bool = true + + var documentIdBase58: String? + + var priceCredits: Int64? + + var saleStatusRaw: Int16 = 0 + + var counterpartyIdBase58: String? + + var documentCreatedAtMs: UInt64? + + var documentUpdatedAtMs: UInt64? + + var documentTransferredAtMs: UInt64? + + var marketplaceUpdatedAt: UInt64 = 0 + + var identity: PersistentIdentity + + var createdAt: Date + var lastUpdated: Date + + init( + identity: PersistentIdentity, + label: String, + parentDomainName: String = "dash", + acquiredAt: UInt64 = 0, + isOwned: Bool = true + ) { + self.identity = identity + self.networkRaw = identity.networkRaw + self.label = label + self.normalizedLabel = Self.normalize(label) + self.parentDomainName = parentDomainName + self.normalizedParentDomainName = Self.normalize(parentDomainName) + self.acquiredAt = acquiredAt + self.isOwned = isOwned + self.documentIdBase58 = nil + self.priceCredits = nil + self.saleStatusRaw = 0 + self.counterpartyIdBase58 = nil + self.documentCreatedAtMs = nil + self.documentUpdatedAtMs = nil + self.documentTransferredAtMs = nil + self.marketplaceUpdatedAt = 0 + self.createdAt = Date() + self.lastUpdated = Date() + } + } +} + +extension DashSchemaV2.PersistentDPNSName { + var saleStatus: DpnsNameSaleStatus? { + guard documentIdBase58 != nil else { return nil } + switch saleStatusRaw { + case 0: + return .owned + case 1: + guard let to = counterpartyId else { return nil } + return .sold(to: to) + case 2: + guard let to = counterpartyId else { return nil } + return .transferred(to: to) + default: + return nil + } + } + + var counterpartyId: Data? { + counterpartyIdBase58.flatMap { Data.identifier(fromBase58: $0) } + } + + var listedPriceCredits: UInt64? { + guard documentIdBase58 != nil, let priceCredits else { return nil } + return UInt64(bitPattern: priceCredits) + } +} + +extension DashSchemaV2.PersistentDPNSName { + static func normalize(_ input: String) -> String { + String(input.map { c -> Character in + switch c { + case "o", "O": return "0" + case "i", "I": return "1" + case "l", "L": return "1" + default: return Character(c.lowercased()) + } + }) + } +} + +extension DashSchemaV2.PersistentDPNSName { + static func predicate(identityId: Data) -> Predicate { + let target = identityId + return #Predicate { name in + name.identity.identityId == target && name.isOwned == true + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayContactProfile.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayContactProfile.swift new file mode 100644 index 00000000000..e8267e0c949 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayContactProfile.swift @@ -0,0 +1,97 @@ +import Foundation +import SwiftData + +// `PersistentDashpayContactProfile` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentDashpayContactProfile { + #Unique([ + \.networkRaw, \.ownerIdentityId, \.contactIdentityId + ]) + + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + var ownerIdentityId: Data + + var contactIdentityId: Data + + var displayName: String? + + var publicMessage: String? + + var bio: String? + + var avatarUrl: String? + + var avatarHash: Data? + + var avatarFingerprint: Data? + + var checkedAtMs: UInt64 + + var owner: PersistentIdentity + + var createdAt: Date + var lastUpdated: Date + + init( + owner: PersistentIdentity, + contactIdentityId: Data, + checkedAtMs: UInt64, + displayName: String? = nil, + publicMessage: String? = nil, + bio: String? = nil, + avatarUrl: String? = nil, + avatarHash: Data? = nil, + avatarFingerprint: Data? = nil + ) { + self.owner = owner + self.networkRaw = owner.networkRaw + self.ownerIdentityId = owner.identityId + self.contactIdentityId = contactIdentityId + self.checkedAtMs = checkedAtMs + self.displayName = displayName + self.publicMessage = publicMessage + self.bio = bio + self.avatarUrl = avatarUrl + self.avatarHash = avatarHash + self.avatarFingerprint = avatarFingerprint + self.createdAt = Date() + self.lastUpdated = Date() + } + } +} + +extension DashSchemaV2.PersistentDashpayContactProfile { + static func predicate( + ownerIdentityId: Data + ) -> Predicate { + let target = ownerIdentityId + return #Predicate { row in + row.ownerIdentityId == target + } + } + + static func predicate( + ownerIdentityId: Data, + contactIdentityId: Data + ) -> Predicate { + let target = ownerIdentityId + let contact = contactIdentityId + return #Predicate { row in + row.ownerIdentityId == target + && row.contactIdentityId == contact + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayContactRequest.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayContactRequest.swift new file mode 100644 index 00000000000..2fa06b963fd --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayContactRequest.swift @@ -0,0 +1,118 @@ +import Foundation +import SwiftData + +// `PersistentDashpayContactRequest` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentDashpayContactRequest { + #Unique([ + \.networkRaw, \.ownerIdentityId, \.contactIdentityId, \.isOutgoing + ]) + + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + var ownerIdentityId: Data + + var contactIdentityId: Data + + var isOutgoing: Bool + + var senderKeyIndex: UInt32 + + var recipientKeyIndex: UInt32 + + var accountReference: UInt32 + + var encryptedPublicKey: Data + + var encryptedAccountLabel: Data? + + var autoAcceptProof: Data? + + var coreHeightCreatedAt: UInt32 + + var createdAtMillis: UInt64 + + var paymentChannelBroken: Bool = false + + var contactAlias: String? + + var contactNote: String? + + var contactHidden: Bool = false + + var contactAccountLabel: String? + + var contactAcceptedAccounts: [UInt32] = [] + + var owner: PersistentIdentity + + var createdAt: Date + var lastUpdated: Date + + init( + owner: PersistentIdentity, + contactIdentityId: Data, + isOutgoing: Bool, + senderKeyIndex: UInt32, + recipientKeyIndex: UInt32, + accountReference: UInt32, + encryptedPublicKey: Data, + encryptedAccountLabel: Data? = nil, + autoAcceptProof: Data? = nil, + coreHeightCreatedAt: UInt32, + createdAtMillis: UInt64, + paymentChannelBroken: Bool = false + ) { + self.owner = owner + self.networkRaw = owner.networkRaw + self.ownerIdentityId = owner.identityId + self.contactIdentityId = contactIdentityId + self.isOutgoing = isOutgoing + self.senderKeyIndex = senderKeyIndex + self.recipientKeyIndex = recipientKeyIndex + self.accountReference = accountReference + self.encryptedPublicKey = encryptedPublicKey + self.encryptedAccountLabel = encryptedAccountLabel + self.autoAcceptProof = autoAcceptProof + self.coreHeightCreatedAt = coreHeightCreatedAt + self.createdAtMillis = createdAtMillis + self.paymentChannelBroken = paymentChannelBroken + self.createdAt = Date() + self.lastUpdated = Date() + } + } +} + +extension DashSchemaV2.PersistentDashpayContactRequest { + static func predicate( + ownerIdentityId: Data + ) -> Predicate { + let target = ownerIdentityId + return #Predicate { row in + row.ownerIdentityId == target + } + } + + static func predicate( + ownerIdentityId: Data, + isOutgoing: Bool + ) -> Predicate { + let target = ownerIdentityId + let direction = isOutgoing + return #Predicate { row in + row.ownerIdentityId == target && row.isOutgoing == direction + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayIgnoredSender.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayIgnoredSender.swift new file mode 100644 index 00000000000..2e7a9976776 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayIgnoredSender.swift @@ -0,0 +1,67 @@ +import Foundation +import SwiftData + +// `PersistentDashpayIgnoredSender` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentDashpayIgnoredSender { + #Unique([ + \.networkRaw, \.ownerIdentityId, \.ignoredSenderId + ]) + + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + var ownerIdentityId: Data + + var ignoredSenderId: Data + + var owner: PersistentIdentity + + var ignoredAt: Date + + init( + owner: PersistentIdentity, + ignoredSenderId: Data + ) { + self.owner = owner + self.networkRaw = owner.networkRaw + self.ownerIdentityId = owner.identityId + self.ignoredSenderId = ignoredSenderId + self.ignoredAt = Date() + } + } +} + +extension DashSchemaV2.PersistentDashpayIgnoredSender { + static func predicate( + ownerIdentityId: Data + ) -> Predicate { + let target = ownerIdentityId + return #Predicate { row in + row.ownerIdentityId == target + } + } + + static func predicate( + ownerIdentityId: Data, + ignoredSenderId: Data + ) -> Predicate { + let target = ownerIdentityId + let sender = ignoredSenderId + return #Predicate { row in + row.ownerIdentityId == target + && row.ignoredSenderId == sender + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayPayment.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayPayment.swift new file mode 100644 index 00000000000..a370bc00593 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayPayment.swift @@ -0,0 +1,99 @@ +import Foundation +import SwiftData + +// `PersistentDashpayPayment` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentDashpayPayment { + #Unique([ + \.networkRaw, \.ownerIdentityId, \.txid + ]) + + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + var ownerIdentityId: Data + + var counterpartyIdentityId: Data + + var amountDuffs: UInt64 + + var directionRaw: UInt8 + + var direction: DashPayPaymentDirection { + get { DashPayPaymentDirection(rawValue: directionRaw) ?? .sent } + set { directionRaw = newValue.rawValue } + } + + var statusRaw: UInt8 + + var status: DashPayPaymentStatus { + get { DashPayPaymentStatus(rawValue: statusRaw) ?? .pending } + set { statusRaw = newValue.rawValue } + } + + var txid: String + + var memo: String? + + var owner: PersistentIdentity + + var createdAt: Date + var lastUpdated: Date + + init( + owner: PersistentIdentity, + counterpartyIdentityId: Data, + amountDuffs: UInt64, + direction: DashPayPaymentDirection, + status: DashPayPaymentStatus, + txid: String, + memo: String? = nil + ) { + self.owner = owner + self.networkRaw = owner.networkRaw + self.ownerIdentityId = owner.identityId + self.counterpartyIdentityId = counterpartyIdentityId + self.amountDuffs = amountDuffs + self.directionRaw = direction.rawValue + self.statusRaw = status.rawValue + self.txid = txid + self.memo = memo + self.createdAt = Date() + self.lastUpdated = Date() + } + } +} + +extension DashSchemaV2.PersistentDashpayPayment { + static func predicate( + ownerIdentityId: Data + ) -> Predicate { + let target = ownerIdentityId + return #Predicate { row in + row.ownerIdentityId == target + } + } + + static func predicate( + ownerIdentityId: Data, + counterpartyIdentityId: Data + ) -> Predicate { + let target = ownerIdentityId + let counterparty = counterpartyIdentityId + return #Predicate { row in + row.ownerIdentityId == target + && row.counterpartyIdentityId == counterparty + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayProfile.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayProfile.swift new file mode 100644 index 00000000000..c05772d4de9 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDashpayProfile.swift @@ -0,0 +1,70 @@ +import Foundation +import SwiftData + +// `PersistentDashpayProfile` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentDashpayProfile { + #Unique([\.networkRaw, \.identity]) + + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + var displayName: String? + + var publicMessage: String? + + var bio: String? + + var avatarUrl: String? + + var avatarHash: Data? + + var avatarFingerprint: Data? + + var identity: PersistentIdentity + + var createdAt: Date + var lastUpdated: Date + + init( + identity: PersistentIdentity, + displayName: String? = nil, + publicMessage: String? = nil, + bio: String? = nil, + avatarUrl: String? = nil, + avatarHash: Data? = nil, + avatarFingerprint: Data? = nil + ) { + self.identity = identity + self.networkRaw = identity.networkRaw + self.displayName = displayName + self.publicMessage = publicMessage + self.bio = bio + self.avatarUrl = avatarUrl + self.avatarHash = avatarHash + self.avatarFingerprint = avatarFingerprint + self.createdAt = Date() + self.lastUpdated = Date() + } + } +} + +extension DashSchemaV2.PersistentDashpayProfile { + static func predicate(identityId: Data) -> Predicate { + let target = identityId + return #Predicate { profile in + profile.identity.identityId == target + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDataContract.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDataContract.swift new file mode 100644 index 00000000000..6506ef09b7c --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDataContract.swift @@ -0,0 +1,286 @@ +import Foundation +import SwiftData + +// `PersistentDataContract` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentDataContract { + #Index([\.networkRaw]) + + @Attribute(.unique) var id: Data + var name: String + var serializedContract: Data + var createdAt: Date + var lastAccessedAt: Date + + var binarySerialization: Data? + + var version: Int? + var ownerId: Data? + + @Relationship(deleteRule: .cascade, inverse: \PersistentKeyword.dataContract) + var keywordRelations: [PersistentKeyword] + var contractDescription: String? + + var schemaData: Data + var documentTypesData: Data + + var groupsData: Data? + + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + var lastUpdated: Date + var lastSyncedAt: Date? + + var canBeDeleted: Bool + var readonly: Bool + var keepsHistory: Bool + var schemaDefs: Int? + + var documentsKeepHistoryContractDefault: Bool + var documentsMutableContractDefault: Bool + var documentsCanBeDeletedContractDefault: Bool + + @Relationship(deleteRule: .cascade, inverse: \PersistentToken.dataContract) + var tokens: [PersistentToken]? + + @Relationship(deleteRule: .cascade, inverse: \PersistentDocumentType.dataContract) + var documentTypes: [PersistentDocumentType]? + + @Relationship(deleteRule: .cascade, inverse: \PersistentDocument.dataContract) + var documents: [PersistentDocument] + + @Relationship(deleteRule: .nullify, inverse: \PersistentIdentity.ownedDataContracts) + var ownerIdentity: PersistentIdentity? + + var hasTokens: Bool + var tokensData: Data? + + var idBase58: String { + id.toBase58String() + } + + var ownerIdBase58: String? { + ownerId?.toBase58String() + } + + var parsedContract: [String: Any]? { + try? JSONSerialization.jsonObject(with: serializedContract, options: []) as? [String: Any] + } + + var binarySerializationHex: String? { + binarySerialization?.toHexString() + } + + var keywords: [String] { + keywordRelations.map { $0.keyword } + } + + var schema: [String: Any] { + get { + guard let json = try? JSONSerialization.jsonObject(with: schemaData), + let dict = json as? [String: Any] else { + return [:] + } + return dict + } + set { + schemaData = (try? JSONSerialization.data(withJSONObject: newValue)) ?? Data() + lastUpdated = Date() + } + } + + var documentTypesList: [String] { + get { + guard let json = try? JSONSerialization.jsonObject(with: documentTypesData), + let array = json as? [String] else { + return [] + } + return array + } + set { + documentTypesData = (try? JSONSerialization.data(withJSONObject: newValue)) ?? Data() + lastUpdated = Date() + } + } + + var tokenConfigurations: [String: Any]? { + get { + guard let data = tokensData, + let json = try? JSONSerialization.jsonObject(with: data), + let dict = json as? [String: Any] else { + return nil + } + return dict + } + set { + if let newValue = newValue { + tokensData = try? JSONSerialization.data(withJSONObject: newValue) + hasTokens = true + } else { + tokensData = nil + hasTokens = false + } + lastUpdated = Date() + } + } + + var groups: [String: Any]? { + get { + guard let data = groupsData, + let json = try? JSONSerialization.jsonObject(with: data), + let dict = json as? [String: Any] else { + return nil + } + return dict + } + set { + if let newValue = newValue { + groupsData = try? JSONSerialization.data(withJSONObject: newValue) + } else { + groupsData = nil + } + lastUpdated = Date() + } + } + + init( + id: Data, + name: String, + serializedContract: Data, + version: Int? = 1, + ownerId: Data? = nil, + schema: [String: Any] = [:], + documentTypesList: [String] = [], + keywords: [String] = [], + description: String? = nil, + hasTokens: Bool = false, + network: Network + ) { + self.id = id + self.name = name + self.serializedContract = serializedContract + self.createdAt = Date() + self.lastAccessedAt = Date() + self.version = version + self.ownerId = ownerId + + self.schemaData = (try? JSONSerialization.data(withJSONObject: schema)) ?? Data() + self.documentTypesData = (try? JSONSerialization.data(withJSONObject: documentTypesList)) ?? Data() + + self.keywordRelations = keywords.map { PersistentKeyword(keyword: $0, contractId: id.toBase58String()) } + self.contractDescription = description + + self.hasTokens = hasTokens + self.tokensData = nil + + self.groupsData = nil + + self.documents = [] + + self.ownerIdentity = nil + + self.networkRaw = network.rawValue + self.lastUpdated = Date() + self.lastSyncedAt = nil + + self.canBeDeleted = false + self.readonly = false + self.keepsHistory = false + self.documentsKeepHistoryContractDefault = false + self.documentsMutableContractDefault = true + self.documentsCanBeDeletedContractDefault = true + } + + func updateLastAccessed() { + self.lastAccessedAt = Date() + } + + func updateVersion(_ newVersion: Int) { + self.version = newVersion + self.lastUpdated = Date() + } + + func markAsSynced() { + self.lastSyncedAt = Date() + } + + func addDocument(_ document: PersistentDocument) { + documents.append(document) + lastUpdated = Date() + } + + func removeDocument(withId documentId: String) { + if let docIdData = Data.identifier(fromBase58: documentId) { + documents.removeAll { $0.id == docIdData } + } + lastUpdated = Date() + } + } +} + +extension DashSchemaV2.PersistentDataContract { + static func predicate(contractId: String) -> Predicate { + guard let idData = Data.identifier(fromBase58: contractId) else { + return #Predicate { _ in false } + } + return #Predicate { contract in + contract.id == idData + } + } + + static func predicate(ownerId: Data) -> Predicate { + #Predicate { contract in + contract.ownerId == ownerId + } + } + + static func predicate(name: String) -> Predicate { + #Predicate { contract in + contract.name.localizedStandardContains(name) + } + } + + static var contractsWithTokensPredicate: Predicate { + #Predicate { contract in + contract.hasTokens == true + } + } + + static func predicate(keyword: String) -> Predicate { + #Predicate { contract in + contract.keywordRelations.contains { $0.keyword == keyword } + } + } + + static func needsSyncPredicate(olderThan date: Date) -> Predicate { + #Predicate { contract in + contract.lastSyncedAt == nil || contract.lastSyncedAt! < date + } + } + + static func predicate(network: Network) -> Predicate { + let target = network.rawValue + return #Predicate { contract in + contract.networkRaw == target + } + } + + static func contractsWithTokensPredicate(network: Network) -> Predicate { + let target = network.rawValue + return #Predicate { contract in + contract.hasTokens == true && contract.networkRaw == target + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDocument.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDocument.swift new file mode 100644 index 00000000000..9b87c818a03 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDocument.swift @@ -0,0 +1,181 @@ +import Foundation +import SwiftData + +// `PersistentDocument` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentDocument { + #Index([\.networkRaw]) + + @Attribute(.unique) var documentId: String + + var documentType: String + var revision: Int32 + var data: Data + + var contractId: String + var ownerId: String + + var contractIdData: Data + var ownerIdData: Data + + var createdAt: Date + var updatedAt: Date + var transferredAt: Date? + + var createdAtBlockHeight: Int64? + var updatedAtBlockHeight: Int64? + var transferredAtBlockHeight: Int64? + + var createdAtCoreBlockHeight: Int64? + var updatedAtCoreBlockHeight: Int64? + var transferredAtCoreBlockHeight: Int64? + + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + var isDeleted: Bool = false + + var localCreatedAt: Date + var localUpdatedAt: Date + + var documentType_relation: PersistentDocumentType? + var dataContract: PersistentDataContract? + + var ownerIdentity: PersistentIdentity? + + var id: Data { + Data.identifier(fromBase58: documentId) ?? Data() + } + + var idBase58: String { + documentId + } + + var ownerIdBase58: String { + ownerId + } + + var contractIdBase58: String { + contractId + } + + var properties: [String: Any]? { + try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] + } + + var displayTitle: String { + guard let props = properties else { return "Document" } + + if let title = props["title"] as? String { return title } + if let name = props["name"] as? String { return name } + if let label = props["label"] as? String { return label } + if let normalizedLabel = props["normalizedLabel"] as? String { return normalizedLabel } + + return documentType + } + + var summary: String { + var parts: [String] = [] + + parts.append("Type: \(documentType)") + parts.append("Rev: \(revision)") + + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .gregorian) + formatter.dateStyle = .short + parts.append("Created: \(formatter.string(from: createdAt))") + + return parts.joined(separator: " • ") + } + + init( + documentId: String, + documentType: String, + revision: Int32, + data: Data, + contractId: String, + ownerId: String, + network: Network + ) { + self.documentId = documentId + self.documentType = documentType + self.revision = revision + self.data = data + self.contractId = contractId + self.ownerId = ownerId + self.contractIdData = Data.identifier(fromBase58: contractId) ?? Data() + self.ownerIdData = Data.identifier(fromBase58: ownerId) ?? Data() + self.networkRaw = network.rawValue + self.createdAt = Date() + self.updatedAt = Date() + self.localCreatedAt = Date() + self.localUpdatedAt = Date() + } + + func updateProperties(_ newData: Data) { + self.data = newData + self.updatedAt = Date() + } + + func updateRevision(_ newRevision: Int64) { + self.revision = Int32(newRevision) + self.updatedAt = Date() + } + + func markAsDeleted() { + self.isDeleted = true + self.updatedAt = Date() + } + + static func predicate(documentId: String) -> Predicate { + #Predicate { doc in + doc.documentId == documentId && doc.isDeleted == false + } + } + + static func predicate(contractId: String, network: Network) -> Predicate { + let target = network.rawValue + return #Predicate { doc in + doc.contractId == contractId && doc.networkRaw == target && doc.isDeleted == false + } + } + + static func predicate(ownerId: Data) -> Predicate { + let ownerIdString = ownerId.toBase58String() + return #Predicate { doc in + doc.ownerId == ownerIdString && doc.isDeleted == false + } + } + + func linkToLocalIdentityIfNeeded(in modelContext: ModelContext) { + guard ownerIdentity == nil else { return } + + let ownerIdToMatch = self.ownerIdData + let identityPredicate = #Predicate { identity in + identity.identityId == ownerIdToMatch && identity.isLocal == true + } + + let descriptor = FetchDescriptor(predicate: identityPredicate) + + do { + if let localIdentity = try modelContext.fetch(descriptor).first { + self.ownerIdentity = localIdentity + self.localUpdatedAt = Date() + } + } catch { + print("Failed to link document to local identity: \(error)") + } + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDocumentType.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDocumentType.swift new file mode 100644 index 00000000000..70b356986f3 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentDocumentType.swift @@ -0,0 +1,99 @@ +import Foundation +import SwiftData + +// `PersistentDocumentType` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentDocumentType { + @Attribute(.unique) var id: Data + var contractId: Data + var name: String + + var schemaJSON: Data + var propertiesJSON: Data + + var documentsKeepHistory: Bool + var documentsMutable: Bool + var documentsCanBeDeleted: Bool + var documentsTransferable: Bool + + var requiredFieldsJSON: Data? + + var securityLevel: Int + + var tradeMode: Int + var creationRestrictionMode: Int + + var requiresIdentityEncryptionBoundedKey: Bool + var requiresIdentityDecryptionBoundedKey: Bool + + var createdAt: Date + var lastAccessedAt: Date + + var dataContract: PersistentDataContract? + + @Relationship(deleteRule: .cascade, inverse: \PersistentDocument.documentType_relation) + var documents: [PersistentDocument]? + + @Relationship(deleteRule: .cascade, inverse: \PersistentIndex.documentType) + var indices: [PersistentIndex]? + + @Relationship(deleteRule: .cascade, inverse: \PersistentProperty.documentType) + var propertiesList: [PersistentProperty]? + + init(contractId: Data, name: String, schemaJSON: Data, propertiesJSON: Data) { + var idData = contractId + idData.append(name.data(using: .utf8) ?? Data()) + self.id = idData + + self.contractId = contractId + self.name = name + self.schemaJSON = schemaJSON + self.propertiesJSON = propertiesJSON + self.documentsKeepHistory = false + self.documentsMutable = true + self.documentsCanBeDeleted = true + self.documentsTransferable = false + self.securityLevel = 0 + self.tradeMode = 0 + self.creationRestrictionMode = 0 + self.requiresIdentityEncryptionBoundedKey = false + self.requiresIdentityDecryptionBoundedKey = false + self.createdAt = Date() + self.lastAccessedAt = Date() + } + } +} + +extension DashSchemaV2.PersistentDocumentType { + var contractIdBase58: String { + contractId.toBase58String() + } + + var schema: [String: Any]? { + try? JSONSerialization.jsonObject(with: schemaJSON, options: []) as? [String: Any] + } + + var properties: [String: Any]? { + try? JSONSerialization.jsonObject(with: propertiesJSON, options: []) as? [String: Any] + } + + var persistentProperties: [DashSchemaV2.PersistentProperty]? { + return propertiesList + } + + var requiredFields: [String]? { + guard let data = requiredFieldsJSON else { return nil } + return try? JSONSerialization.jsonObject(with: data, options: []) as? [String] + } + + var documentCount: Int { + documents?.count ?? 0 + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentIdentity.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentIdentity.swift new file mode 100644 index 00000000000..7334a17c9fd --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentIdentity.swift @@ -0,0 +1,274 @@ +import Foundation +import SwiftData + +// `PersistentIdentity` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentIdentity { + #Index([\.networkRaw]) + + @Attribute(.unique) var identityId: Data + var balance: Int64 + var revision: Int64 + var isLocal: Bool + var alias: String? + var dpnsName: String? + var mainDpnsName: String? + var identityType: String + + var votingPrivateKeyIdentifier: String? + var ownerPrivateKeyIdentifier: String? + var payoutPrivateKeyIdentifier: String? + + @Relationship(deleteRule: .cascade) var publicKeys: [PersistentPublicKey] + + var createdAt: Date + var lastUpdated: Date + var lastSyncedAt: Date? + + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + var wallet: PersistentWallet? + var identityIndex: UInt32 = 0 + + @Relationship(deleteRule: .cascade, inverse: \PersistentDocument.ownerIdentity) var documents: [PersistentDocument] + @Relationship(deleteRule: .nullify) var tokenBalances: [PersistentTokenBalance] + + @Relationship(deleteRule: .cascade, inverse: \PersistentDPNSName.identity) + var dpnsNames: [PersistentDPNSName] = [] + + @Relationship(deleteRule: .cascade, inverse: \PersistentDashpayProfile.identity) + var dashpayProfile: PersistentDashpayProfile? + + @Relationship(deleteRule: .cascade, inverse: \PersistentDashpayContactRequest.owner) + var contactRequests: [PersistentDashpayContactRequest] = [] + + @Relationship(deleteRule: .cascade, inverse: \PersistentDashpayPayment.owner) + var dashpayPayments: [PersistentDashpayPayment] = [] + + @Relationship(deleteRule: .cascade, inverse: \PersistentDashpayIgnoredSender.owner) + var dashpayIgnoredSenders: [PersistentDashpayIgnoredSender] = [] + + @Relationship(deleteRule: .cascade, inverse: \PersistentDashpayContactProfile.owner) + var contactProfiles: [PersistentDashpayContactProfile] = [] + + var ownedDataContracts: [PersistentDataContract] + + init( + identityId: Data, + balance: Int64 = 0, + revision: Int64 = 0, + isLocal: Bool = true, + alias: String? = nil, + dpnsName: String? = nil, + mainDpnsName: String? = nil, + identityType: IdentityType = .user, + votingPrivateKeyIdentifier: String? = nil, + ownerPrivateKeyIdentifier: String? = nil, + payoutPrivateKeyIdentifier: String? = nil, + network: Network, + identityIndex: UInt32 = 0 + ) { + self.identityId = identityId + self.balance = balance + self.revision = revision + self.isLocal = isLocal + self.alias = alias + self.dpnsName = dpnsName + self.mainDpnsName = mainDpnsName + self.identityType = identityType.rawValue + self.votingPrivateKeyIdentifier = votingPrivateKeyIdentifier + self.ownerPrivateKeyIdentifier = ownerPrivateKeyIdentifier + self.payoutPrivateKeyIdentifier = payoutPrivateKeyIdentifier + self.networkRaw = network.rawValue + self.identityIndex = identityIndex + self.publicKeys = [] + self.documents = [] + self.tokenBalances = [] + self.dpnsNames = [] + self.dashpayProfile = nil + self.contactRequests = [] + self.dashpayPayments = [] + self.dashpayIgnoredSenders = [] + self.contactProfiles = [] + self.ownedDataContracts = [] + self.createdAt = Date() + self.lastUpdated = Date() + self.lastSyncedAt = nil + } + + var identityIdString: String { + identityId.toHexString() + } + + var identityIdBase58: String { + identityId.toBase58String() + } + + var formattedBalance: String { + let dashAmount = Double(balance) / 100_000_000_000 + return String(format: "%.8f DASH", dashAmount) + } + + var identityPublicKeys: [IdentityPublicKey] { + publicKeys.compactMap { $0.toIdentityPublicKey() } + } + + var displayName: String { + if let alias = alias, !alias.isEmpty { + return alias + } + if let mainDpnsName = mainDpnsName, !mainDpnsName.isEmpty { + return mainDpnsName + } + if let dpnsName = dpnsName, !dpnsName.isEmpty { + return dpnsName + } + return String(identityIdString.prefix(12)) + "..." + } + + var identityTypeEnum: IdentityType { + IdentityType(rawValue: identityType) ?? .user + } + + func updateBalance(_ newBalance: Int64) { + self.balance = newBalance + self.lastUpdated = Date() + } + + func updateRevision(_ newRevision: Int64) { + self.revision = newRevision + self.lastUpdated = Date() + } + + func markAsSynced() { + self.lastSyncedAt = Date() + } + + func updateDPNSName(_ name: String?) { + self.dpnsName = name + self.lastUpdated = Date() + } + + func addPublicKey(_ key: PersistentPublicKey) { + publicKeys.append(key) + lastUpdated = Date() + } + + func removePublicKey(withId keyId: Int32) { + publicKeys.removeAll { $0.keyId == keyId } + lastUpdated = Date() + } + } +} + +extension DashSchemaV2.PersistentIdentity { + static func predicate(identityId: Data) -> Predicate { + #Predicate { identity in + identity.identityId == identityId + } + } + + static var walletOwnedIdentitiesPredicate: Predicate { + #Predicate { identity in + identity.wallet != nil + } + } + + static func predicate(type: IdentityType) -> Predicate { + let typeString = type.rawValue + return #Predicate { identity in + identity.identityType == typeString + } + } + + static func needsSyncPredicate(olderThan date: Date) -> Predicate { + #Predicate { identity in + identity.lastSyncedAt == nil || identity.lastSyncedAt! < date + } + } + + static func predicate(network: Network) -> Predicate { + let target = network.rawValue + return #Predicate { identity in + identity.networkRaw == target + } + } + + static func walletOwnedIdentitiesPredicate(network: Network) -> Predicate { + let target = network.rawValue + return #Predicate { identity in + identity.wallet != nil && identity.networkRaw == target + } + } + + static func fetch( + in context: ModelContext, + identityId: Data + ) -> DashSchemaV2.PersistentIdentity? { + let target = identityId + let descriptor = FetchDescriptor( + predicate: #Predicate { $0.identityId == target } + ) + return try? context.fetch(descriptor).first + } +} + +extension DashSchemaV2.PersistentIdentity { + @discardableResult + static func updateBalance( + in context: ModelContext, + identityId: Data, + balance: UInt64 + ) -> Bool { + guard let row = fetch(in: context, identityId: identityId) else { return false } + row.balance = Int64(bitPattern: balance) + row.lastUpdated = Date() + return true + } + + @discardableResult + static func updateDpnsName( + in context: ModelContext, + identityId: Data, + dpnsName: String? + ) -> Bool { + guard let row = fetch(in: context, identityId: identityId) else { return false } + row.dpnsName = dpnsName + row.lastUpdated = Date() + return true + } + + @discardableResult + static func updateMainDpnsName( + in context: ModelContext, + identityId: Data, + mainDpnsName: String? + ) -> Bool { + guard let row = fetch(in: context, identityId: identityId) else { return false } + row.mainDpnsName = mainDpnsName + row.lastUpdated = Date() + return true + } + + @discardableResult + static func remove( + in context: ModelContext, + identityId: Data + ) -> Bool { + guard let row = fetch(in: context, identityId: identityId) else { return false } + context.delete(row) + return true + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentIndex.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentIndex.swift new file mode 100644 index 00000000000..c5460923a9f --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentIndex.swift @@ -0,0 +1,64 @@ +import Foundation +import SwiftData + +// `PersistentIndex` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentIndex { + @Attribute(.unique) var id: Data + var contractId: Data + var documentTypeName: String + var name: String + + var unique: Bool + var nullSearchable: Bool + var contested: Bool + + var propertiesJSON: Data + + var contestedDetailsJSON: Data? + + var createdAt: Date + + var documentType: PersistentDocumentType? + + init(contractId: Data, documentTypeName: String, name: String, properties: [String]) { + var idData = contractId + idData.append(documentTypeName.data(using: .utf8) ?? Data()) + idData.append(name.data(using: .utf8) ?? Data()) + self.id = idData + + self.contractId = contractId + self.documentTypeName = documentTypeName + self.name = name + self.unique = false + self.nullSearchable = false + self.contested = false + + if let jsonData = try? JSONSerialization.data(withJSONObject: properties, options: []) { + self.propertiesJSON = jsonData + } else { + self.propertiesJSON = Data() + } + + self.createdAt = Date() + } + } +} + +extension DashSchemaV2.PersistentIndex { + var properties: [String]? { + try? JSONSerialization.jsonObject(with: propertiesJSON, options: []) as? [String] + } + + var contestedDetails: [String: Any]? { + guard let data = contestedDetailsJSON else { return nil } + return try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentInvitation.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentInvitation.swift new file mode 100644 index 00000000000..29b102f4451 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentInvitation.swift @@ -0,0 +1,73 @@ +import Foundation +import SwiftData + +// `PersistentInvitation` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentInvitation { + #Index([\.walletId]) + + @Attribute(.unique) var outPointHex: String + + var rawOutPoint: Data + + var walletId: Data + + var fundingIndexRaw: Int + + var amountDuffs: Int64 + + var expiryUnix: Int + + var createdAtSecs: Int + + var hasInviter: Bool + + var statusRaw: Int + + var reclaimInFlight: Bool = false + + var createdAt: Date + var updatedAt: Date + + init( + outPointHex: String, + rawOutPoint: Data, + walletId: Data, + fundingIndexRaw: Int, + amountDuffs: Int64, + expiryUnix: Int, + createdAtSecs: Int, + hasInviter: Bool, + statusRaw: Int, + reclaimInFlight: Bool = false + ) { + self.outPointHex = outPointHex + self.rawOutPoint = rawOutPoint + self.walletId = walletId + self.fundingIndexRaw = fundingIndexRaw + self.amountDuffs = amountDuffs + self.expiryUnix = expiryUnix + self.createdAtSecs = createdAtSecs + self.hasInviter = hasInviter + self.statusRaw = statusRaw + self.reclaimInFlight = reclaimInFlight + self.createdAt = Date() + self.updatedAt = Date() + } + } +} + +extension DashSchemaV2.PersistentInvitation { + static func predicate(walletId: Data) -> Predicate { + #Predicate { entry in + entry.walletId == walletId + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentKeyword.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentKeyword.swift new file mode 100644 index 00000000000..36f5a3a3d4f --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentKeyword.swift @@ -0,0 +1,40 @@ +import Foundation +import SwiftData + +// `PersistentKeyword` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentKeyword { + @Attribute(.unique) var id: String + var keyword: String + var contractId: String + + var dataContract: PersistentDataContract? + + init(keyword: String, contractId: String) { + self.id = "\(contractId)_\(keyword)" + self.keyword = keyword + self.contractId = contractId + } + } +} + +extension DashSchemaV2.PersistentKeyword { + static func predicate(keyword: String) -> Predicate { + #Predicate { item in + item.keyword.localizedStandardContains(keyword) + } + } + + static func predicate(contractId: String) -> Predicate { + #Predicate { item in + item.contractId == contractId + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentMasternode.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentMasternode.swift new file mode 100644 index 00000000000..d864f91e480 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentMasternode.swift @@ -0,0 +1,185 @@ +import Foundation +import SwiftData + +// `PersistentMasternode` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentMasternode { + #Unique([\.walletId, \.proTxHash]) + + var walletId: Data + var proTxHash: Data + var registrationTxid: Data + + var serviceAddress: String? + var isEvonode: Bool + + var ownerKeyHash: Data? + var votingKeyHash: Data? + var ownerAddress: String? + var votingAddress: String? + var operatorPublicKey: Data? + var platformNodeId: Data? + var payoutAddress: String? + var operatorPseudoAddress: String? + var platformNodeAddress: String? + + var ownerInWallet: Bool = false + var ownerAccountType: UInt8 = 0 + var ownerKeyIndex: UInt32 = 0 + var votingInWallet: Bool = false + var votingAccountType: UInt8 = 0 + var votingKeyIndex: UInt32 = 0 + var operatorInWallet: Bool = false + var operatorAccountType: UInt8 = 0 + var operatorKeyIndex: UInt32 = 0 + var platformInWallet: Bool = false + var platformAccountType: UInt8 = 0 + var platformKeyIndex: UInt32 = 0 + + var collateralTxid: Data? + var collateralVout: UInt32 + + var revoked: Bool + var revocationReason: UInt16 + var statusRaw: UInt8 = 3 + + var registrationHeight: UInt32 + var hasRegistration: Bool + var txCount: UInt32 + + var orderIndex: UInt32 + var typeIndex: UInt32 = 0 + + var createdAt: Date + var lastUpdated: Date + + init( + walletId: Data, + proTxHash: Data, + registrationTxid: Data, + serviceAddress: String? = nil, + isEvonode: Bool = false, + ownerKeyHash: Data? = nil, + votingKeyHash: Data? = nil, + ownerAddress: String? = nil, + votingAddress: String? = nil, + operatorPublicKey: Data? = nil, + platformNodeId: Data? = nil, + payoutAddress: String? = nil, + collateralTxid: Data? = nil, + collateralVout: UInt32 = 0, + revoked: Bool = false, + revocationReason: UInt16 = 0, + statusRaw: UInt8 = 3, + registrationHeight: UInt32 = 0, + hasRegistration: Bool = false, + txCount: UInt32 = 0, + orderIndex: UInt32 = 0, + typeIndex: UInt32 = 0 + ) { + self.walletId = walletId + self.proTxHash = proTxHash + self.registrationTxid = registrationTxid + self.serviceAddress = serviceAddress + self.isEvonode = isEvonode + self.ownerKeyHash = ownerKeyHash + self.votingKeyHash = votingKeyHash + self.ownerAddress = ownerAddress + self.votingAddress = votingAddress + self.operatorPublicKey = operatorPublicKey + self.platformNodeId = platformNodeId + self.payoutAddress = payoutAddress + self.collateralTxid = collateralTxid + self.collateralVout = collateralVout + self.revoked = revoked + self.revocationReason = revocationReason + self.statusRaw = statusRaw + self.registrationHeight = registrationHeight + self.hasRegistration = hasRegistration + self.txCount = txCount + self.orderIndex = orderIndex + self.typeIndex = typeIndex + self.createdAt = Date() + self.lastUpdated = Date() + } + + var proTxHashHex: String { + proTxHash.reversed().map { String(format: "%02x", $0) }.joined() + } + + var proTxHashShort: String { + let hex = proTxHashHex + guard hex.count >= 12 else { return hex } + return "\(String(hex.prefix(6)))…\(String(hex.suffix(6)))" + } + + var ownerKeyHashHex: String? { + ownerKeyHash.map { $0.map { String(format: "%02x", $0) }.joined() } + } + + var votingKeyHashHex: String? { + votingKeyHash.map { $0.map { String(format: "%02x", $0) }.joined() } + } + + static func providerAccountTypeName(_ tag: UInt8) -> String { + switch tag { + case 8: return "ProviderVotingKeys" + case 9: return "ProviderOwnerKeys" + case 10: return "ProviderOperatorKeys" + case 11: return "ProviderPlatformKeys" + default: return "Unknown(\(tag))" + } + } + + static func keyOwnershipLabel( + inWallet: Bool, + accountType: UInt8, + index: UInt32 + ) -> String { + inWallet + ? "\(providerAccountTypeName(accountType)) #\(index)" + : "not in this wallet" + } + + var operatorPublicKeyHex: String? { + operatorPublicKey.map { $0.map { String(format: "%02x", $0) }.joined() } + } + + var platformNodeIdHex: String? { + platformNodeId.map { $0.map { String(format: "%02x", $0) }.joined() } + } + + var collateralDisplay: String? { + guard let txid = collateralTxid else { return nil } + let hex = txid.reversed().map { String(format: "%02x", $0) }.joined() + return "\(hex):\(collateralVout)" + } + + var displayNumber: Int { + Int(typeIndex) + } + + var typeName: String { + isEvonode ? "Evonode" : "Masternode" + } + + var displayTitle: String { + "\(typeName) \(displayNumber)" + } + + var status: MasternodeStatus { + MasternodeStatus(rawValue: statusRaw) ?? .unknown + } + + var statusName: String { + status.displayName + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPendingInput.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPendingInput.swift new file mode 100644 index 00000000000..366c766ba99 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPendingInput.swift @@ -0,0 +1,42 @@ +import Foundation +import SwiftData + +// `PersistentPendingInput` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentPendingInput { + #Index([\.outpoint], [\.walletId]) + var outpoint: Data + + var inputIndex: UInt32 + + var spendingTxid: Data + + var spendingTransaction: PersistentTransaction? + + var walletId: Data + + var createdAt: Date + + init( + outpoint: Data, + inputIndex: UInt32, + spendingTxid: Data, + spendingTransaction: PersistentTransaction?, + walletId: Data + ) { + self.outpoint = outpoint + self.inputIndex = inputIndex + self.spendingTxid = spendingTxid + self.spendingTransaction = spendingTransaction + self.walletId = walletId + self.createdAt = Date() + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPlatformAddress.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPlatformAddress.swift new file mode 100644 index 00000000000..510abb2232d --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPlatformAddress.swift @@ -0,0 +1,78 @@ +import Foundation +import SwiftData + +// `PersistentPlatformAddress` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentPlatformAddress { + #Index([\.walletId]) + + @Attribute(.unique) var address: String + var addressType: UInt8 + @Attribute(.unique) var addressHash: Data + var publicKey: Data + var accountIndex: UInt32 + var addressIndex: UInt32 + var derivationPath: String + var isUsed: Bool + var balance: UInt64 + var nonce: UInt32 + var firstSeenHeight: UInt32 + var lastSeenHeight: UInt64 + var walletId: Data + var createdAt: Date + var lastUpdated: Date + + var account: PersistentAccount? + + init( + address: String, + addressType: UInt8, + addressHash: Data, + publicKey: Data = Data(), + accountIndex: UInt32, + addressIndex: UInt32, + derivationPath: String, + isUsed: Bool = false, + balance: UInt64 = 0, + nonce: UInt32 = 0, + walletId: Data + ) { + self.address = address + self.addressType = addressType + self.addressHash = addressHash + self.publicKey = publicKey + self.accountIndex = accountIndex + self.addressIndex = addressIndex + self.derivationPath = derivationPath + self.isUsed = isUsed + self.balance = balance + self.nonce = nonce + self.firstSeenHeight = 0 + self.lastSeenHeight = 0 + self.walletId = walletId + self.createdAt = Date() + self.lastUpdated = Date() + } + } +} + +extension DashSchemaV2.PersistentPlatformAddress { + static func predicate(walletId: Data) -> Predicate { + #Predicate { entry in + entry.walletId == walletId + } + } + + static var nonZeroBalancesPredicate: Predicate { + #Predicate { entry in + entry.balance > 0 + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPlatformAddressesSyncState.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPlatformAddressesSyncState.swift new file mode 100644 index 00000000000..6d728296fc8 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPlatformAddressesSyncState.swift @@ -0,0 +1,41 @@ +import Foundation +import SwiftData + +// `PersistentPlatformAddressesSyncState` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentPlatformAddressesSyncState { + @Attribute(.unique) var walletId: Data + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + var syncHeight: UInt64 + var syncTimestamp: UInt64 + var lastKnownRecentBlock: UInt64 + var lastUpdated: Date + + init( + walletId: Data, + network: Network, + syncHeight: UInt64, + syncTimestamp: UInt64, + lastKnownRecentBlock: UInt64 + ) { + self.walletId = walletId + self.networkRaw = network.rawValue + self.syncHeight = syncHeight + self.syncTimestamp = syncTimestamp + self.lastKnownRecentBlock = lastKnownRecentBlock + self.lastUpdated = Date() + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentProperty.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentProperty.swift new file mode 100644 index 00000000000..a86f3487eb4 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentProperty.swift @@ -0,0 +1,55 @@ +import Foundation +import SwiftData + +// `PersistentProperty` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentProperty { + @Attribute(.unique) var id: Data + var contractId: Data + var documentTypeName: String + var name: String + + var type: String + var format: String? + var contentMediaType: String? + var byteArray: Bool + var minItems: Int? + var maxItems: Int? + var pattern: String? + var minLength: Int? + var maxLength: Int? + var minValue: Int? + var maxValue: Int? + var fieldDescription: String? + + var transient: Bool + var isRequired: Bool + + var createdAt: Date + + var documentType: PersistentDocumentType? + + init(contractId: Data, documentTypeName: String, name: String, type: String) { + var idData = contractId + idData.append(documentTypeName.data(using: .utf8) ?? Data()) + idData.append(name.data(using: .utf8) ?? Data()) + self.id = idData + + self.contractId = contractId + self.documentTypeName = documentTypeName + self.name = name + self.type = type + self.byteArray = false + self.transient = false + self.isRequired = false + self.createdAt = Date() + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPublicKey.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPublicKey.swift new file mode 100644 index 00000000000..3abc50b89c9 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentPublicKey.swift @@ -0,0 +1,171 @@ +import Foundation +import SwiftData + +// `PersistentPublicKey` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentPublicKey { + var keyId: Int32 + var purpose: String + var securityLevel: String + var keyType: String + var readOnly: Bool + var disabledAt: Int64? + + var publicKeyData: Data + + var contractBoundsData: Data? + + var contractBoundsDocumentTypeName: String? + + var privateKeyKeychainIdentifier: String? + + var walletId: Data? + + var identityDerivationPath: String? + + var identityId: String + var createdAt: Date + var lastAccessed: Date? + + @Relationship(inverse: \PersistentIdentity.publicKeys) + var identity: PersistentIdentity? + + init( + keyId: Int32, + purpose: KeyPurpose, + securityLevel: SecurityLevel, + keyType: KeyType, + publicKeyData: Data, + readOnly: Bool = false, + disabledAt: Int64? = nil, + contractBounds: [Data]? = nil, + contractBoundsDocumentTypeName: String? = nil, + identityId: String + ) { + self.keyId = keyId + self.purpose = String(purpose.rawValue) + self.securityLevel = String(securityLevel.rawValue) + self.keyType = String(keyType.rawValue) + self.publicKeyData = publicKeyData + self.readOnly = readOnly + self.disabledAt = disabledAt + if let contractBounds = contractBounds { + self.contractBoundsData = try? JSONSerialization.data(withJSONObject: contractBounds.map { $0.base64EncodedString() }) + } else { + self.contractBoundsData = nil + } + self.contractBoundsDocumentTypeName = contractBoundsDocumentTypeName + self.identityId = identityId + self.createdAt = Date() + } + + var contractBounds: [Data]? { + get { + guard let data = contractBoundsData, + let json = try? JSONSerialization.jsonObject(with: data), + let strings = json as? [String] else { + return nil + } + return strings.compactMap { Data(base64Encoded: $0) } + } + set { + contractBoundsDocumentTypeName = nil + if let newValue = newValue { + contractBoundsData = try? JSONSerialization.data(withJSONObject: newValue.map { $0.base64EncodedString() }) + } else { + contractBoundsData = nil + } + } + } + + var purposeEnum: KeyPurpose? { + guard let purposeInt = UInt8(purpose) else { return nil } + return KeyPurpose(rawValue: purposeInt) + } + + var securityLevelEnum: SecurityLevel? { + guard let levelInt = UInt8(securityLevel) else { return nil } + return SecurityLevel(rawValue: levelInt) + } + + var keyTypeEnum: KeyType? { + guard let typeInt = UInt8(keyType) else { return nil } + return KeyType(rawValue: typeInt) + } + + var isDisabled: Bool { + disabledAt != nil + } + + var hasPrivateKeyIdentifier: Bool { + privateKeyKeychainIdentifier != nil + } + } +} + +extension DashSchemaV2.PersistentPublicKey { + func toIdentityPublicKey() -> IdentityPublicKey? { + guard let purpose = purposeEnum, + let securityLevel = securityLevelEnum, + let keyType = keyTypeEnum else { + return nil + } + + let bounds: ContractBounds? + if let id = contractBounds?.first, id.count == 32 { + if let docTypeName = contractBoundsDocumentTypeName, !docTypeName.isEmpty { + bounds = .singleContractDocumentType(id: id, documentTypeName: docTypeName) + } else { + bounds = .singleContract(id: id) + } + } else { + bounds = nil + } + + return IdentityPublicKey( + id: KeyID(keyId), + purpose: purpose, + securityLevel: securityLevel, + contractBounds: bounds, + keyType: keyType, + readOnly: readOnly, + data: publicKeyData, + disabledAt: disabledAt.map { TimestampMillis($0) } + ) + } + + static func from(_ publicKey: IdentityPublicKey, identityId: String) -> DashSchemaV2.PersistentPublicKey? { + let boundsIds: [Data]? + let docTypeName: String? + switch publicKey.contractBounds { + case .singleContract(let id): + boundsIds = [id] + docTypeName = nil + case .singleContractDocumentType(let id, let name): + boundsIds = [id] + docTypeName = name + case .none: + boundsIds = nil + docTypeName = nil + } + return DashSchemaV2.PersistentPublicKey( + keyId: Int32(publicKey.id), + purpose: publicKey.purpose, + securityLevel: publicKey.securityLevel, + keyType: publicKey.keyType, + publicKeyData: publicKey.data, + readOnly: publicKey.readOnly, + disabledAt: publicKey.disabledAt.map { Int64($0) }, + contractBounds: boundsIds, + contractBoundsDocumentTypeName: docTypeName, + identityId: identityId + ) + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedActivity.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedActivity.swift new file mode 100644 index 00000000000..b2b240d78f5 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedActivity.swift @@ -0,0 +1,89 @@ +import Foundation +import SwiftData + +// `PersistentShieldedActivity` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentShieldedActivity { + #Unique([\.walletId, \.accountIndex, \.entryId]) + #Index([\.walletId, \.accountIndex]) + + var walletId: Data + var accountIndex: UInt32 + var entryId: Data + + var kindTag: Int + var direction: Int + var status: Int + + var amount: UInt64 + var fee: UInt64 + var hasFee: Bool + var blockHeight: UInt64 + var hasBlockHeight: Bool + var createdAtMs: UInt64 + + var minNotePosition: UInt64 = 0 + var hasMinNotePosition: Bool = false + + var identityId: Data + var counterparty: Data + var memo: Data + var noteCmxs: Data + var spentNullifiers: Data + + var createdAt: Date + var lastUpdated: Date + + init( + walletId: Data, + accountIndex: UInt32, + entryId: Data, + kindTag: Int, + direction: Int, + status: Int, + amount: UInt64, + fee: UInt64, + hasFee: Bool, + blockHeight: UInt64, + hasBlockHeight: Bool, + createdAtMs: UInt64, + minNotePosition: UInt64 = 0, + hasMinNotePosition: Bool = false, + identityId: Data, + counterparty: Data, + memo: Data, + noteCmxs: Data, + spentNullifiers: Data + ) { + self.walletId = walletId + self.accountIndex = accountIndex + self.entryId = entryId + self.kindTag = kindTag + self.direction = direction + self.status = status + self.amount = amount + self.fee = fee + self.hasFee = hasFee + self.blockHeight = blockHeight + self.hasBlockHeight = hasBlockHeight + self.createdAtMs = createdAtMs + self.minNotePosition = minNotePosition + self.hasMinNotePosition = hasMinNotePosition + self.identityId = identityId + self.counterparty = counterparty + self.memo = memo + self.noteCmxs = noteCmxs + self.spentNullifiers = spentNullifiers + let now = Date() + self.createdAt = now + self.lastUpdated = now + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedNote.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedNote.swift new file mode 100644 index 00000000000..28dd289fdc1 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedNote.swift @@ -0,0 +1,66 @@ +import Foundation +import SwiftData + +// `PersistentShieldedNote` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentShieldedNote { + #Index([\.walletId, \.accountIndex]) + + var walletId: Data + var accountIndex: UInt32 + var position: UInt64 + var cmx: Data + @Attribute(.unique) var nullifier: Data + var blockHeight: UInt64 + var isSpent: Bool + var value: UInt64 + var noteData: Data + + var createdAt: Date + var lastUpdated: Date + + init( + walletId: Data, + accountIndex: UInt32, + position: UInt64, + cmx: Data, + nullifier: Data, + blockHeight: UInt64, + isSpent: Bool, + value: UInt64, + noteData: Data + ) { + self.walletId = walletId + self.accountIndex = accountIndex + self.position = position + self.cmx = cmx + self.nullifier = nullifier + self.blockHeight = blockHeight + self.isSpent = isSpent + self.value = value + self.noteData = noteData + let now = Date() + self.createdAt = now + self.lastUpdated = now + } + } +} + +extension DashSchemaV2.PersistentShieldedNote { + static func unspentPredicate(walletId: Data) -> Predicate { + #Predicate { + $0.walletId == walletId && $0.isSpent == false + } + } + + static var unspentPredicate: Predicate { + #Predicate { $0.isSpent == false } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedOutgoingNote.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedOutgoingNote.swift new file mode 100644 index 00000000000..9cac644ff57 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedOutgoingNote.swift @@ -0,0 +1,49 @@ +import Foundation +import SwiftData + +// `PersistentShieldedOutgoingNote` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentShieldedOutgoingNote { + #Unique([\.walletId, \.accountIndex, \.cmx]) + #Index([\.walletId, \.accountIndex]) + + var walletId: Data + var accountIndex: UInt32 + var cmx: Data + var recipient: Data + var value: UInt64 + var memo: Data + var blockHeight: UInt64 + + var createdAt: Date + var lastUpdated: Date + + init( + walletId: Data, + accountIndex: UInt32, + cmx: Data, + recipient: Data, + value: UInt64, + memo: Data, + blockHeight: UInt64 + ) { + self.walletId = walletId + self.accountIndex = accountIndex + self.cmx = cmx + self.recipient = recipient + self.value = value + self.memo = memo + self.blockHeight = blockHeight + let now = Date() + self.createdAt = now + self.lastUpdated = now + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedSyncState.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedSyncState.swift new file mode 100644 index 00000000000..d0f45d91b6b --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedSyncState.swift @@ -0,0 +1,34 @@ +import Foundation +import SwiftData + +// `PersistentShieldedSyncState` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentShieldedSyncState { + #Unique([\.walletId, \.accountIndex]) + #Index([\.walletId]) + + var walletId: Data + var accountIndex: UInt32 + var lastSyncedIndex: UInt64 + + var lastUpdated: Date + + init( + walletId: Data, + accountIndex: UInt32, + lastSyncedIndex: UInt64 = 0 + ) { + self.walletId = walletId + self.accountIndex = accountIndex + self.lastSyncedIndex = lastSyncedIndex + self.lastUpdated = Date() + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedViewingKey.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedViewingKey.swift new file mode 100644 index 00000000000..60b59600ec1 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentShieldedViewingKey.swift @@ -0,0 +1,34 @@ +import Foundation +import SwiftData + +// `PersistentShieldedViewingKey` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentShieldedViewingKey { + #Unique([\.walletId, \.accountIndex]) + #Index([\.walletId]) + + var walletId: Data + var accountIndex: UInt32 + var fvkBytes: Data + + var lastUpdated: Date + + init( + walletId: Data, + accountIndex: UInt32, + fvkBytes: Data + ) { + self.walletId = walletId + self.accountIndex = accountIndex + self.fvkBytes = fvkBytes + self.lastUpdated = Date() + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentToken.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentToken.swift new file mode 100644 index 00000000000..0eb0284547f --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentToken.swift @@ -0,0 +1,376 @@ +import Foundation +import SwiftData + +// `PersistentToken` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentToken { + @Attribute(.unique) var id: Data + var contractId: Data + var position: Int + var name: String + + var baseSupply: String + var maxSupply: String? + var decimals: Int + + var localizations: [String: TokenLocalization]? + + var isPaused: Bool + var allowTransferToFrozenBalance: Bool + + var keepsTransferHistory: Bool + var keepsFreezingHistory: Bool + var keepsMintingHistory: Bool + var keepsBurningHistory: Bool + var keepsDirectPricingHistory: Bool + var keepsDirectPurchaseHistory: Bool + + var conventionsChangeRules: ChangeControlRules? + var maxSupplyChangeRules: ChangeControlRules? + var manualMintingRules: ChangeControlRules? + var manualBurningRules: ChangeControlRules? + var freezeRules: ChangeControlRules? + var unfreezeRules: ChangeControlRules? + var destroyFrozenFundsRules: ChangeControlRules? + var emergencyActionRules: ChangeControlRules? + + var perpetualDistribution: TokenPerpetualDistribution? + var preProgrammedDistribution: TokenPreProgrammedDistribution? + var newTokensDestinationIdentity: Data? + var mintingAllowChoosingDestination: Bool + var distributionChangeRules: TokenDistributionChangeRules? + + var tradeMode: TokenTradeMode + var tradeModeChangeRules: ChangeControlRules? + + var mainControlGroupPosition: Int? + var mainControlGroupCanBeModified: String? + + var tokenDescription: String? + + var createdAt: Date + var lastUpdatedAt: Date + + var dataContract: PersistentDataContract? + + @Relationship(deleteRule: .cascade) + var balances: [PersistentTokenBalance]? + + @Relationship(deleteRule: .cascade) + var historyEvents: [PersistentTokenHistoryEvent]? + + init(contractId: Data, position: Int, name: String, baseSupply: String, decimals: Int = 8) { + var idData = contractId + withUnsafeBytes(of: position.bigEndian) { bytes in + idData.append(contentsOf: bytes) + } + self.id = idData + + self.contractId = contractId + self.position = position + self.name = name + self.baseSupply = baseSupply + self.decimals = decimals + + self.isPaused = false + self.allowTransferToFrozenBalance = true + self.keepsTransferHistory = true + self.keepsFreezingHistory = true + self.keepsMintingHistory = true + self.keepsBurningHistory = true + self.keepsDirectPricingHistory = true + self.keepsDirectPurchaseHistory = true + self.mintingAllowChoosingDestination = true + self.tradeMode = TokenTradeMode.notTradeable + + self.createdAt = Date() + self.lastUpdatedAt = Date() + } + } +} + +extension DashSchemaV2.PersistentToken { + var displayName: String { + if let desc = tokenDescription, !desc.isEmpty { + return desc + } + return getSingularForm() ?? name + } + + var formattedBaseSupply: String { + Self.formatSupply(baseSupply, decimals: decimals) + } + + static func formatSupply(_ raw: String, decimals: Int) -> String { + guard !raw.isEmpty, raw.allSatisfy({ $0.isASCII && $0.isNumber }) else { + return raw + } + let normalized = String(raw.drop(while: { $0 == "0" })) + let digits = normalized.isEmpty ? "0" : normalized + let scale = max(0, decimals) + let integer: String + var fraction = "" + if scale == 0 { + integer = digits + } else if digits.count <= scale { + integer = "0" + fraction = String(repeating: "0", count: scale - digits.count) + digits + } else { + let split = digits.index(digits.endIndex, offsetBy: -scale) + integer = String(digits[.. 0 && offset.isMultiple(of: 3) { grouped.append(",") } + grouped.append(character) + } + grouped = String(grouped.reversed()) + return fraction.isEmpty ? grouped : "\(grouped).\(fraction)" + } + + var contractIdBase58: String { + contractId.toBase58String() + } + + var canManuallyMint: Bool { + manualMintingRules != nil + } + + var canManuallyBurn: Bool { + manualBurningRules != nil + } + + var canFreeze: Bool { + freezeRules != nil + } + + var canUnfreeze: Bool { + unfreezeRules != nil + } + + var canDestroyFrozenFunds: Bool { + destroyFrozenFundsRules != nil + } + + var hasEmergencyActions: Bool { + emergencyActionRules != nil + } + + var canChangeMaxSupply: Bool { + maxSupplyChangeRules != nil + } + + var canChangeConventions: Bool { + conventionsChangeRules != nil + } + + var hasDistribution: Bool { + perpetualDistribution != nil || preProgrammedDistribution != nil + } + + var canChangeTradeMode: Bool { + tradeModeChangeRules != nil + } + + var keepsAnyHistory: Bool { + keepsTransferHistory || + keepsFreezingHistory || + keepsMintingHistory || + keepsBurningHistory || + keepsDirectPricingHistory || + keepsDirectPurchaseHistory + } + + var totalSupply: String { + guard let balances = balances, !balances.isEmpty else { return baseSupply } + return Self.sumUnsignedBalances(balances.map(\.unsignedBalance)) + } + + var totalFrozenBalance: String { + guard let balances = balances else { return "0" } + return Self.sumUnsignedBalances( + balances.lazy.filter(\.frozen).map(\.unsignedBalance) + ) + } + + var activeHolders: Int { + balances?.filter { $0.unsignedBalance > 0 }.count ?? 0 + } + + private static func sumUnsignedBalances(_ values: S) -> String + where S.Element == UInt64 { + var digits: [UInt8] = [0] // little-endian decimal digits + + for value in values { + var carry = 0 + let addend = String(value).utf8.reversed().map { Int($0 - 48) } + let width = max(digits.count, addend.count) + if digits.count < width { + digits.append(contentsOf: repeatElement(0, count: width - digits.count)) + } + + for index in 0.. 0 { + digits.append(UInt8(carry % 10)) + carry /= 10 + } + } + + return String(digits.reversed().map { Character(String($0)) }) + } + + var hasMaxSupply: Bool { + maxSupply != nil + } + + var isTradeable: Bool { + tradeMode != .notTradeable + } + + var newTokensDestinationIdentityBase58: String? { + newTokensDestinationIdentity?.toBase58String() + } +} + +extension DashSchemaV2.PersistentToken { + func setLocalization(languageCode: String, singularForm: String, pluralForm: String, description: String? = nil) { + if localizations == nil { + localizations = [:] + } + localizations?[languageCode] = DashSchemaV2.TokenLocalization( + singularForm: singularForm, + pluralForm: pluralForm, + description: description + ) + lastUpdatedAt = Date() + } + + func getSingularForm(languageCode: String = "en") -> String? { + return localizations?[languageCode]?.singularForm ?? localizations?["en"]?.singularForm + } + + func getPluralForm(languageCode: String = "en") -> String? { + return localizations?[languageCode]?.pluralForm ?? localizations?["en"]?.pluralForm + } +} + +extension DashSchemaV2.PersistentToken { + func getChangeControlRules(for type: ChangeControlRuleType) -> DashSchemaV2.ChangeControlRules? { + switch type { + case .conventions: return conventionsChangeRules + case .maxSupply: return maxSupplyChangeRules + case .manualMinting: return manualMintingRules + case .manualBurning: return manualBurningRules + case .freeze: return freezeRules + case .unfreeze: return unfreezeRules + case .destroyFrozenFunds: return destroyFrozenFundsRules + case .emergencyAction: return emergencyActionRules + case .tradeMode: return tradeModeChangeRules + } + } + + func setChangeControlRules(_ rules: DashSchemaV2.ChangeControlRules, for type: ChangeControlRuleType) { + switch type { + case .conventions: conventionsChangeRules = rules + case .maxSupply: maxSupplyChangeRules = rules + case .manualMinting: manualMintingRules = rules + case .manualBurning: manualBurningRules = rules + case .freeze: freezeRules = rules + case .unfreeze: unfreezeRules = rules + case .destroyFrozenFunds: destroyFrozenFundsRules = rules + case .emergencyAction: emergencyActionRules = rules + case .tradeMode: tradeModeChangeRules = rules + } + + lastUpdatedAt = Date() + } +} + +extension DashSchemaV2.PersistentToken { + static func mintableTokensPredicate() -> Predicate { + #Predicate { token in + token.manualMintingRules != nil + } + } + + static func burnableTokensPredicate() -> Predicate { + #Predicate { token in + token.manualBurningRules != nil + } + } + + static func freezableTokensPredicate() -> Predicate { + #Predicate { token in + token.freezeRules != nil + } + } + + static func distributionTokensPredicate() -> Predicate { + #Predicate { token in + token.perpetualDistribution != nil || token.preProgrammedDistribution != nil + } + } + + static func pausedTokensPredicate() -> Predicate { + #Predicate { token in + token.isPaused == true + } + } + + static func tokensByContractPredicate(contractId: Data) -> Predicate { + #Predicate { token in + token.contractId == contractId + } + } + + static func tokensWithControlRulePredicate(rule: ControlRuleType) -> Predicate { + switch rule { + case .manualMinting: + return #Predicate { token in + token.manualMintingRules != nil + } + case .manualBurning: + return #Predicate { token in + token.manualBurningRules != nil + } + case .freeze: + return #Predicate { token in + token.freezeRules != nil + } + case .unfreeze: + return #Predicate { token in + token.unfreezeRules != nil + } + case .destroyFrozenFunds: + return #Predicate { token in + token.destroyFrozenFundsRules != nil + } + case .emergencyAction: + return #Predicate { token in + token.emergencyActionRules != nil + } + case .conventions: + return #Predicate { token in + token.conventionsChangeRules != nil + } + case .maxSupply: + return #Predicate { token in + token.maxSupplyChangeRules != nil + } + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTokenBalance.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTokenBalance.swift new file mode 100644 index 00000000000..6ae2d707b74 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTokenBalance.swift @@ -0,0 +1,198 @@ +import Foundation +import SwiftData + +// `PersistentTokenBalance` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentTokenBalance { + #Index([\.networkRaw]) + + var tokenId: String + var identityId: Data + var balance: Int64 + var frozen: Bool + + var createdAt: Date + var lastUpdated: Date + var lastSyncedAt: Date? + + var tokenName: String? + var tokenSymbol: String? + var tokenDecimals: Int32? + + var networkRaw: UInt32 + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + @Relationship(deleteRule: .nullify) var identity: PersistentIdentity? + @Relationship(inverse: \PersistentToken.balances) var token: PersistentToken? + + init( + tokenId: String, + identityId: Data, + balance: Int64 = 0, + frozen: Bool = false, + tokenName: String? = nil, + tokenSymbol: String? = nil, + tokenDecimals: Int32? = nil, + network: Network + ) { + self.tokenId = tokenId + self.identityId = identityId + self.balance = balance + self.frozen = frozen + self.tokenName = tokenName + self.tokenSymbol = tokenSymbol + self.tokenDecimals = tokenDecimals + self.createdAt = Date() + self.lastUpdated = Date() + self.lastSyncedAt = nil + self.networkRaw = network.rawValue + } + + convenience init( + tokenId: String, + identityId: Data, + unsignedBalance: UInt64, + frozen: Bool = false, + tokenName: String? = nil, + tokenSymbol: String? = nil, + tokenDecimals: Int32? = nil, + network: Network + ) { + self.init( + tokenId: tokenId, + identityId: identityId, + balance: Int64(bitPattern: unsignedBalance), + frozen: frozen, + tokenName: tokenName, + tokenSymbol: tokenSymbol, + tokenDecimals: tokenDecimals, + network: network + ) + } + + var unsignedBalance: UInt64 { + get { UInt64(bitPattern: balance) } + set { balance = Int64(bitPattern: newValue) } + } + + var formattedBalance: String { + let decimals: Int + if let tokenDecimals { + decimals = Int(tokenDecimals) + } else if let tokenDecimals = token?.decimals { + decimals = tokenDecimals + } else { + return "\(unsignedBalance)" + } + + guard decimals > 0 else { return String(unsignedBalance) } + + let digits = String(unsignedBalance) + let scale = decimals + if digits.count <= scale { + return "0." + String(repeating: "0", count: scale - digits.count) + digits + } + let split = digits.index(digits.endIndex, offsetBy: -scale) + return String(digits[.. (tokenId: String, balance: UInt64, frozen: Bool) { + return (tokenId: tokenId, balance: unsignedBalance, frozen: frozen) + } +} + +extension DashSchemaV2.PersistentTokenBalance { + static func predicate(tokenId: String, identityId: Data) -> Predicate { + #Predicate { balance in + balance.tokenId == tokenId && balance.identityId == identityId + } + } + + static func predicate(identityId: Data) -> Predicate { + #Predicate { balance in + balance.identityId == identityId + } + } + + static func predicate(tokenId: String) -> Predicate { + #Predicate { balance in + balance.tokenId == tokenId + } + } + + static var nonZeroBalancesPredicate: Predicate { + #Predicate { balance in + balance.balance != 0 + } + } + + static var frozenBalancesPredicate: Predicate { + #Predicate { balance in + balance.frozen == true + } + } + + static func needsSyncPredicate(olderThan date: Date) -> Predicate { + #Predicate { balance in + balance.lastSyncedAt == nil || balance.lastSyncedAt! < date + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTokenHistoryEvent.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTokenHistoryEvent.swift new file mode 100644 index 00000000000..6b0054aea43 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTokenHistoryEvent.swift @@ -0,0 +1,112 @@ +import Foundation +import SwiftData + +// `PersistentTokenHistoryEvent` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentTokenHistoryEvent { + @Attribute(.unique) var id: UUID + + var eventType: String + var transactionId: Data? + var blockHeight: Int64? + var coreBlockHeight: Int64? + + var fromIdentity: Data? + var toIdentity: Data? + var performedByIdentity: Data + + var amount: String? + var balanceBefore: String? + var balanceAfter: String? + + var additionalDataJSON: Data? + + var eventDescription: String? + + var createdAt: Date + var eventTimestamp: Date + + @Relationship(inverse: \PersistentToken.historyEvents) + var token: PersistentToken? + + init( + eventType: TokenEventType, + performedByIdentity: Data, + eventTimestamp: Date = Date() + ) { + self.id = UUID() + self.eventType = eventType.rawValue + self.performedByIdentity = performedByIdentity + self.eventTimestamp = eventTimestamp + self.createdAt = Date() + } + + var eventTypeEnum: TokenEventType { + TokenEventType(rawValue: eventType) ?? .unknown + } + + var fromIdentityBase58: String? { + fromIdentity?.toBase58String() + } + + var toIdentityBase58: String? { + toIdentity?.toBase58String() + } + + var performedByIdentityBase58: String { + performedByIdentity.toBase58String() + } + + var displayTitle: String { + switch eventTypeEnum { + case .mint: + return "Minted \(formattedAmount)" + case .burn: + return "Burned \(formattedAmount)" + case .transfer: + return "Transfer \(formattedAmount)" + case .freeze: + return "Frozen \(formattedAmount)" + case .unfreeze: + return "Unfrozen \(formattedAmount)" + case .destroyFrozenFunds: + return "Destroyed Frozen Funds \(formattedAmount)" + case .configUpdate: + return "Configuration Updated" + case .emergencyAction: + return "Emergency Action" + case .perpetualDistribution: + return "Perpetual Distribution \(formattedAmount)" + case .preProgrammedRelease: + return "Pre-programmed Release \(formattedAmount)" + case .directPricing: + return "Direct Pricing Updated" + case .directPurchase: + return "Direct Purchase \(formattedAmount)" + case .unknown: + return "Unknown Event" + } + } + + private var formattedAmount: String { + guard let amount = amount else { return "" } + return amount + } + + func setAdditionalData(_ data: [String: Any]) { + additionalDataJSON = try? JSONSerialization.data(withJSONObject: data) + } + + func getAdditionalData() -> [String: Any]? { + guard let data = additionalDataJSON else { return nil } + return try? JSONSerialization.jsonObject(with: data) as? [String: Any] + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTrackedMasternode.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTrackedMasternode.swift new file mode 100644 index 00000000000..44ab9a23870 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTrackedMasternode.swift @@ -0,0 +1,42 @@ +import Foundation +import SwiftData + +// `PersistentTrackedMasternode` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentTrackedMasternode { + #Unique([\.networkRaw, \.proTxHash]) + #Index([\.networkRaw]) + + var networkRaw: UInt32 + var proTxHash: Data + var label: String? + var addedAt: UInt64 + var snapshotJSON: String + + var network: Network? { + get { Network(rawValue: networkRaw) } + set { networkRaw = newValue?.rawValue ?? networkRaw } + } + + init( + networkRaw: UInt32, + proTxHash: Data, + label: String?, + addedAt: UInt64, + snapshotJSON: String + ) { + self.networkRaw = networkRaw + self.proTxHash = proTxHash + self.label = label + self.addedAt = addedAt + self.snapshotJSON = snapshotJSON + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTransaction.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTransaction.swift new file mode 100644 index 00000000000..6610ec87d63 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTransaction.swift @@ -0,0 +1,167 @@ +import Foundation +import SwiftData + +// `PersistentTransaction` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentTransaction { + #Index([\.firstSeen]) + + @Attribute(.unique) var txid: Data + var transactionData: Data + var context: UInt32 + var blockHeight: UInt32 + var blockHash: Data? + var blockTimestamp: UInt32 + var blockPosition: UInt32 = 0 + var hasBlockPosition: Bool = false + var direction: UInt32 + var transactionType: String + var transactionTypeKind: UInt8 = 0xFF + var netAmount: Int64 + var fee: UInt64? + var label: String + var firstSeen: UInt64 + + var providerServiceAddress: String? = nil + var providerProTxHash: Data? = nil + var providerCollateralTxid: Data? = nil + var providerCollateralVout: UInt32 = 0 + var providerOwnerKeyHash: Data? = nil + var providerVotingKeyHash: Data? = nil + + var createdAt: Date + var lastUpdated: Date + + @Relationship(deleteRule: .cascade, inverse: \PersistentTxo.transaction) + var outputs: [PersistentTxo] = [] + + @Relationship(inverse: \PersistentTxo.spendingTransaction) + var inputs: [PersistentTxo] = [] + + @Relationship(deleteRule: .cascade, inverse: \PersistentPendingInput.spendingTransaction) + var pendingInputs: [PersistentPendingInput] = [] + + @Relationship(inverse: \PersistentAccount.involvedTransactions) + var involvedAccounts: [PersistentAccount] = [] + + init( + txid: Data, + transactionData: Data, + context: UInt32 = 0, + blockHeight: UInt32 = 0, + direction: UInt32 = 0, + transactionType: String = "Standard", + netAmount: Int64 = 0, + firstSeen: UInt64 = 0 + ) { + self.txid = txid + self.transactionData = transactionData + self.context = context + self.blockHeight = blockHeight + self.blockTimestamp = 0 + self.direction = direction + self.transactionType = transactionType + self.netAmount = netAmount + self.firstSeen = firstSeen + self.label = "" + self.createdAt = Date() + self.lastUpdated = Date() + } + + var txidHex: String { + txid.reversed().map { String(format: "%02x", $0) }.joined() + } + + var contextName: String { + switch context { + case 0: return "Mempool" + case 1: return "InstantSend" + case 2: return "In Block" + case 3: return "Chain Locked" + default: return "Unknown" + } + } + + var directionName: String { + switch direction { + case 0: return "Incoming" + case 1: return "Outgoing" + case 2: return "Internal" + case 3: return "CoinJoin" + default: return "Unknown" + } + } + + var typedKind: TransactionTypeKind? { + TransactionTypeKind(rawValue: transactionTypeKind) + } + + var isAssetLock: Bool { + typedKind == .assetLock + } + + var isAssetUnlock: Bool { + typedKind == .assetUnlock + } + + var isProviderRegistration: Bool { + typedKind == .providerRegistration + } + + var isProviderUpdateService: Bool { + typedKind == .providerUpdateService + } + + var providerProTxHashHex: String? { + providerProTxHash.map { $0.reversed().map { String(format: "%02x", $0) }.joined() } + } + + var providerCollateralDisplay: String? { + guard let txid = providerCollateralTxid else { return nil } + let hex = txid.reversed().map { String(format: "%02x", $0) }.joined() + return "\(hex):\(providerCollateralVout)" + } + + var providerOwnerKeyHashHex: String? { + providerOwnerKeyHash.map { $0.map { String(format: "%02x", $0) }.joined() } + } + + var providerVotingKeyHashHex: String? { + providerVotingKeyHash.map { $0.map { String(format: "%02x", $0) }.joined() } + } + + var isProviderSpecial: Bool { + providerSpecialName != nil + } + + var providerSpecialName: String? { + switch typedKind { + case .providerRegistration: return "Provider Registration" + case .providerUpdateRegistrar: return "Provider Update Registrar" + case .providerUpdateService: return "Provider Update Service" + case .providerUpdateRevocation: return "Provider Update Revocation" + default: return nil + } + } + + var displayDirection: String { + if isAssetLock { return "Asset Lock" } + if isAssetUnlock { return "Asset Unlock" } + if let name = providerSpecialName { return name } + return directionName + } + + var formattedAmount: String { + let dash = Double(abs(netAmount)) / 100_000_000.0 + let sign = netAmount >= 0 ? "+" : "-" + return String(format: "%@%.8f DASH", sign, dash) + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTxo.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTxo.swift new file mode 100644 index 00000000000..1f18b7b8f07 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentTxo.swift @@ -0,0 +1,97 @@ +import Foundation +import SwiftData + +// `PersistentTxo` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentTxo { + #Index([\.walletId]) + + @Attribute(.unique) var outpoint: Data + var vout: UInt32 + var amount: UInt64 + var address: String + var scriptPubKey: Data + var height: UInt32 + var isCoinbase: Bool + var isConfirmed: Bool + var isInstantLocked: Bool + var isLocked: Bool + var isSpent: Bool + var createdAt: Date + var lastUpdated: Date + + var walletId: Data = Data() + + var transaction: PersistentTransaction? + + var spendingTransaction: PersistentTransaction? + + var spendingInputIndex: UInt32? = nil + + var account: PersistentAccount? + + var coreAddress: PersistentCoreAddress? + + init( + transaction: PersistentTransaction, + vout: UInt32, + amount: UInt64, + address: String, + scriptPubKey: Data = Data(), + height: UInt32 = 0 + ) { + self.outpoint = Self.makeOutpoint(txid: transaction.txid, vout: vout) + self.vout = vout + self.amount = amount + self.address = address + self.scriptPubKey = scriptPubKey + self.height = height + self.isCoinbase = false + self.isConfirmed = false + self.isInstantLocked = false + self.isLocked = false + self.isSpent = false + self.createdAt = Date() + self.lastUpdated = Date() + self.transaction = transaction + } + + static func makeOutpoint(txid: Data, vout: UInt32) -> Data { + var data = Data(capacity: 36) + data.append(txid) + var v = vout.littleEndian + withUnsafeBytes(of: &v) { data.append(contentsOf: $0) } + return data + } + + var txid: Data { + if let transaction { + return transaction.txid + } + return outpoint.count >= 32 ? Data(outpoint.prefix(32)) : Data() + } + + var txidHex: String { + let rawTxid = txid + guard rawTxid.count == 32 else { return "" } + return rawTxid.reversed().map { String(format: "%02x", $0) }.joined() + } + + var outpointHex: String { + let hex = txidHex + return hex.isEmpty ? "" : "\(hex):\(vout)" + } + + var formattedAmount: String { + let dash = Double(amount) / 100_000_000.0 + return String(format: "%.8f DASH", dash) + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentWallet.swift new file mode 100644 index 00000000000..d688cd576eb --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentWallet.swift @@ -0,0 +1,94 @@ +import Foundation +import SwiftData + +// `PersistentWallet` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentWallet { + #Index([\.networkRaw], [\.walletGroupId]) + #Unique([\.walletId]) + + var walletId: Data + var walletGroupId: Data = Data() + var networkRaw: UInt32? + + var network: Network? { + get { + guard let raw = networkRaw else { return nil } + return Network(rawValue: raw) ?? .testnet + } + set { networkRaw = newValue?.rawValue } + } + var name: String? + var walletDescription: String? + var birthHeight: UInt32 + var syncedHeight: UInt32 + var lastSynced: UInt64 + var lastAppliedChainLockBytes: Data? + var isImported: Bool = false + var seedBindingVerifiedMarker: String? + var createdAt: Date + var lastUpdated: Date + + @Relationship(deleteRule: .cascade, inverse: \PersistentAccount.wallet) + var accounts: [PersistentAccount] + + @Relationship(deleteRule: .nullify, inverse: \PersistentIdentity.wallet) + var identities: [PersistentIdentity] + + init( + walletId: Data, + walletGroupId: Data = Data(), + network: Network? = nil, + name: String? = nil, + walletDescription: String? = nil, + birthHeight: UInt32 = 0, + syncedHeight: UInt32 = 0, + isImported: Bool = false + ) { + self.walletId = walletId + self.walletGroupId = walletGroupId + self.networkRaw = network?.rawValue + self.name = name + self.walletDescription = walletDescription + self.birthHeight = birthHeight + self.syncedHeight = syncedHeight + self.lastSynced = 0 + self.isImported = isImported + self.createdAt = Date() + self.lastUpdated = Date() + self.accounts = [] + self.identities = [] + } + } +} + +extension DashSchemaV2.PersistentWallet { + var label: String { + if let name = name, !name.isEmpty { + return name + } + let hex = walletId.prefix(4) + .map { String(format: "%02x", $0) } + .joined() + return hex.isEmpty ? "Wallet" : "Wallet \(hex)…" + } +} + +extension DashSchemaV2.PersistentWallet { + static func predicate(walletId: Data) -> Predicate { + #Predicate { $0.walletId == walletId } + } + + static func predicate( + walletGroupId: Data + ) -> Predicate { + #Predicate { $0.walletGroupId == walletGroupId } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentWalletManagerMetadata.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentWalletManagerMetadata.swift new file mode 100644 index 00000000000..697c6753283 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+PersistentWalletManagerMetadata.swift @@ -0,0 +1,34 @@ +import Foundation +import SwiftData + +// `PersistentWalletManagerMetadata` exactly as schema DashSchemaV2 registered it, generated by +// scripts/freeze_schema_models.py from the live model at commit 52e8d4ec68. +// Do not edit: every stored property, its optionality and default, and +// every @Attribute / @Relationship / #Unique here is an input to that +// version's checksum, and every #Index to the store's SQLite indexes; +// changing any of them re-breaks the stores this copy exists to keep +// openable. See the live model for what each column means. +extension DashSchemaV2 { + @Model + final class PersistentWalletManagerMetadata { + @Attribute(.unique) var networkRaw: UInt32 + var combinedSyncHeight: UInt32 + var combinedSyncBlockHash: Data? + var walletCount: Int + var createdAt: Date + var lastUpdated: Date + + var network: Network { + get { Network(rawValue: networkRaw) ?? .testnet } + set { networkRaw = newValue.rawValue } + } + + init(network: Network) { + self.networkRaw = network.rawValue + self.combinedSyncHeight = 0 + self.walletCount = 0 + self.createdAt = Date() + self.lastUpdated = Date() + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+TokenTypes.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+TokenTypes.swift new file mode 100644 index 00000000000..ed1fe3238d3 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/FrozenSchemas/DashSchemaV2+TokenTypes.swift @@ -0,0 +1,153 @@ +import Foundation +import SwiftData + +// Inline value types exactly as schema DashSchemaV2 stored them, generated +// by scripts/freeze_schema_models.py from TokenTypes.swift +// at commit 52e8d4ec68. SwiftData expands a stored Codable struct into composite +// attributes of the owning entity, so these shapes are inputs to that +// version's checksum just like the model's own properties. Do not edit. +extension DashSchemaV2 { + struct ChangeControlRules: Codable, Equatable, Sendable { + var authorizedToMakeChange: String + var adminActionTakers: String + var changingAuthorizedActionTakersToNoOneAllowed: Bool + var changingAdminActionTakersToNoOneAllowed: Bool + var selfChangingAdminActionTakersAllowed: Bool + + init( + authorizedToMakeChange: String = AuthorizedActionTakers.noOne.rawValue, + adminActionTakers: String = AuthorizedActionTakers.noOne.rawValue, + changingAuthorizedActionTakersToNoOneAllowed: Bool = false, + changingAdminActionTakersToNoOneAllowed: Bool = false, + selfChangingAdminActionTakersAllowed: Bool = false + ) { + self.authorizedToMakeChange = authorizedToMakeChange + self.adminActionTakers = adminActionTakers + self.changingAuthorizedActionTakersToNoOneAllowed = changingAuthorizedActionTakersToNoOneAllowed + self.changingAdminActionTakersToNoOneAllowed = changingAdminActionTakersToNoOneAllowed + self.selfChangingAdminActionTakersAllowed = selfChangingAdminActionTakersAllowed + } + + static func mostRestrictive() -> ChangeControlRules { + return ChangeControlRules() + } + + static func contractOwnerControlled() -> ChangeControlRules { + return ChangeControlRules( + authorizedToMakeChange: AuthorizedActionTakers.contractOwner.rawValue, + adminActionTakers: AuthorizedActionTakers.noOne.rawValue, + selfChangingAdminActionTakersAllowed: true + ) + } + } + + enum AuthorizedActionTakers: String, CaseIterable, Codable, Sendable { + case noOne = "NoOne" + case contractOwner = "ContractOwner" + case mainGroup = "MainGroup" + + static func identity(_ id: Data) -> String { + return "Identity:\(id.toBase58String())" + } + + static func group(_ position: Int) -> String { + return "Group:\(position)" + } + } + + struct TokenPerpetualDistribution: Codable, Equatable, Sendable { + var distributionType: String + var distributionRecipient: String + var enabled: Bool + var lastDistributionTime: Date? + var nextDistributionTime: Date? + + init(distributionRecipient: String = "AllEqualShare", enabled: Bool = true) { + self.distributionType = "{}" + self.distributionRecipient = distributionRecipient + self.enabled = enabled + } + } + + struct TokenPreProgrammedDistribution: Codable, Equatable, Sendable { + var distributionSchedule: [DistributionEvent] + var currentEventIndex: Int + var totalDistributed: String + var remainingToDistribute: String + var isActive: Bool + var isPaused: Bool + var isCompleted: Bool + + init() { + self.distributionSchedule = [] + self.currentEventIndex = 0 + self.totalDistributed = "0" + self.remainingToDistribute = "0" + self.isActive = true + self.isPaused = false + self.isCompleted = false + } + } + + struct DistributionEvent: Codable, Equatable, Sendable { + var id: UUID + var triggerType: String + var triggerTime: Date? + var triggerBlock: Int64? + var triggerCondition: String? + var amount: String + var recipient: String + var description: String? + + init(triggerTime: Date, amount: String, recipient: String = "AllHolders", description: String? = nil) { + self.id = UUID() + self.triggerType = "Time" + self.triggerTime = triggerTime + self.amount = amount + self.recipient = recipient + self.description = description + } + } + + struct TokenDistributionChangeRules: Codable, Equatable, Sendable { + var perpetualDistributionRules: ChangeControlRules? + var newTokensDestinationIdentityRules: ChangeControlRules? + var mintingAllowChoosingDestinationRules: ChangeControlRules? + var changeDirectPurchasePricingRules: ChangeControlRules? + + init( + perpetualDistributionRules: ChangeControlRules? = nil, + newTokensDestinationIdentityRules: ChangeControlRules? = nil, + mintingAllowChoosingDestinationRules: ChangeControlRules? = nil, + changeDirectPurchasePricingRules: ChangeControlRules? = nil + ) { + self.perpetualDistributionRules = perpetualDistributionRules + self.newTokensDestinationIdentityRules = newTokensDestinationIdentityRules + self.mintingAllowChoosingDestinationRules = mintingAllowChoosingDestinationRules + self.changeDirectPurchasePricingRules = changeDirectPurchasePricingRules + } + } + + enum TokenTradeMode: String, CaseIterable, Codable, Sendable { + case notTradeable = "NotTradeable" + + var displayName: String { + switch self { + case .notTradeable: + return "Not Tradeable" + } + } + } + + struct TokenLocalization: Codable, Equatable, Sendable { + let singularForm: String + let pluralForm: String + let description: String? + + init(singularForm: String, pluralForm: String, description: String? = nil) { + self.singularForm = singularForm + self.pluralForm = pluralForm + self.description = description + } + } +} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift index 1b3ba788568..4bdc2221cfa 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift @@ -11,15 +11,15 @@ private final class BridgeFutureMarker { var value: String = "future" init() {} } -private enum BridgeFutureV3: VersionedSchema { - static var versionIdentifier: Schema.Version { Schema.Version(3, 0, 0) } - static var models: [any PersistentModel.Type] { DashSchemaV2.models + [BridgeFutureMarker.self] } +private enum BridgeFutureV4: VersionedSchema { + static var versionIdentifier: Schema.Version { Schema.Version(4, 0, 0) } + static var models: [any PersistentModel.Type] { DashSchemaV3.models + [BridgeFutureMarker.self] } } private enum BridgeFuturePlan: SchemaMigrationPlan { - static var schemas: [any VersionedSchema.Type] { [DashSchemaV1.self, DashSchemaV2.self, BridgeFutureV3.self] } + static var schemas: [any VersionedSchema.Type] { [DashSchemaV1.self, DashSchemaV3.self, BridgeFutureV4.self] } static var stages: [MigrationStage] { - [.lightweight(fromVersion: DashSchemaV1.self, toVersion: DashSchemaV2.self), - .custom(fromVersion: DashSchemaV2.self, toVersion: BridgeFutureV3.self, + [.lightweight(fromVersion: DashSchemaV1.self, toVersion: DashSchemaV3.self), + .custom(fromVersion: DashSchemaV3.self, toVersion: BridgeFutureV4.self, willMigrate: { context in for wallet in try context.fetch(FetchDescriptor()) { wallet.name = "explicit future transformation" @@ -29,6 +29,17 @@ private enum BridgeFuturePlan: SchemaMigrationPlan { } } +// The candidate immediately before restoring historical V2 used today's +// complete graph with a V2 version label. This is one exact supported alias. +private enum PreviousLiveV2: VersionedSchema { + static var versionIdentifier: Schema.Version { Schema.Version(2, 0, 0) } + static var models: [any PersistentModel.Type] { DashSchemaV3.models } +} +private enum UnsupportedBetaV2: VersionedSchema { + static var versionIdentifier: Schema.Version { Schema.Version(2, 0, 0) } + static var models: [any PersistentModel.Type] { DashSchemaV3.models + [BridgeFutureMarker.self] } +} + @MainActor final class DashLegacySchemaMigrationTests: XCTestCase { private enum Injected: Error { case stop } @@ -107,7 +118,7 @@ final class DashLegacySchemaMigrationTests: XCTestCase { defer { Darwin.close(descriptor) } XCTAssertEqual(flock(descriptor, LOCK_EX | LOCK_NB), 0) try autoreleasepool { _ = try open(url) } // Known V1. - let current = try open(url) // Current V2. + let current = try open(url) // Current V3. XCTAssertEqual(try current.mainContext.fetchCount(FetchDescriptor()), 1) } for interrupted in [false, true] { @@ -709,21 +720,21 @@ final class DashLegacySchemaMigrationTests: XCTestCase { } } - func testSkippingV2UsesFixedBridgeThenRegisteredCustomFutureStage() throws { + func testSkippingV3UsesFixedBridgeThenRegisteredCustomFutureStage() throws { try withStore { url in - let schema = Schema(versionedSchema: BridgeFutureV3.self) - var checkedV2 = false + let schema = Schema(versionedSchema: BridgeFutureV4.self) + var checkedV3 = false let configuration = ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none) XCTAssertThrowsError(try DashLegacySchemaBridge.open( configuration: configuration, schema: schema, plan: BridgeFuturePlan.self, hooks: .init(visit: { phase, candidate in if phase == .afterMigration { - _ = try DashSchemaFixtureSupport.describeStore(at: candidate, version: Schema.Version(2, 0, 0)) - checkedV2 = true + _ = try DashSchemaFixtureSupport.describeStore(at: candidate, version: Schema.Version(3, 0, 0)) + checkedV3 = true } if phase == .afterCommit { throw Injected.stop } }))) - XCTAssertTrue(checkedV2) + XCTAssertTrue(checkedV3) let recovered = try DashLegacySchemaBridge.open( configuration: configuration, schema: schema, plan: BridgeFuturePlan.self) try verifyRows(recovered.mainContext, walletName: "explicit future transformation") @@ -820,4 +831,84 @@ final class DashLegacySchemaMigrationTests: XCTestCase { let reopened = try await DashModelContainer.createAsync(url: url) XCTAssertEqual(try reopened.mainContext.fetchCount(FetchDescriptor()), 10_000) } + + func testExactPreviousLiveV2RemainsWritableWithoutReinterpretingHistoricalV2() throws { + try withStore { url in + try autoreleasepool { + let schema = Schema(versionedSchema: PreviousLiveV2.self) + let container = try ModelContainer(for: schema, configurations: [ + ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none) + ]) + try verifyRows(container.mainContext) + } + XCTAssertEqual(try DashLegacySchemaBridge.identity(at: url).versions, ["2.0.0"]) + let container = try open(url, hooks: .init(visit: { _, _ in + XCTFail("An exact previous current shape needs no legacy inferred migration") + })) + try verifyRows(container.mainContext) + let wallet = try XCTUnwrap(container.mainContext.fetch(FetchDescriptor()).first) + wallet.name = "previous capture remains writable" + try container.mainContext.save() + } + } + + func testUnsupportedBetaV2FailsWithoutMutation() throws { + try withStore { url in + try autoreleasepool { + let schema = Schema(versionedSchema: UnsupportedBetaV2.self) + _ = try ModelContainer(for: schema, configurations: [ + ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none) + ]) + } + try DashLegacyStoreSQLite.checkpoint(url) + let before = try DashLegacyStoreSQLite.rawDigest(url) + XCTAssertThrowsError(try open(url)) { error in + XCTAssertTrue(error.localizedDescription.contains("does not match")) + } + XCTAssertEqual(try DashLegacyStoreSQLite.rawDigest(url), before) + XCTAssertTrue(try operationDirectories(url).isEmpty) + } + } + + func testPreviousLiveV2JournalRecoversBeforeChoosingMigrationRoute() throws { + struct OldJournal: Encodable { + let formatVersion: Int + let operation: UUID + let source: DashLegacySchemaBridge.Identity + let destination: DashLegacySchemaBridge.Identity + let destinationData: DashLegacyStoreSQLite.StoreEvidence? + } + for format in [1, 2] { + for installed in [false, true] { + try withStore { url in + let operation = UUID() + let root = DashLegacySchemaBridge.backupDirectory(for: url) + let directory = root.appendingPathComponent(operation.uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let backup = directory.appendingPathComponent("original.store") + let candidate = directory.appendingPathComponent("candidate.store") + try DashLegacyStoreSQLite.copy(from: url, to: backup) + try DashLegacyStoreSQLite.copy(from: url, to: candidate) + let source = try DashLegacySchemaBridge.identity(at: url) + try autoreleasepool { + let schema = Schema(versionedSchema: PreviousLiveV2.self) + _ = try ModelContainer(for: schema, configurations: [ + ModelConfiguration(schema: schema, url: candidate, cloudKitDatabase: .none) + ]) + } + try DashLegacyStoreSQLite.checkpoint(candidate) + try DashLegacyStoreSQLite.validatePreservation(from: backup, to: candidate) + let journal = OldJournal(formatVersion: format, operation: operation, source: source, + destination: try DashLegacySchemaBridge.identity(at: candidate), + destinationData: format == 2 ? try DashLegacyStoreSQLite.evidence(at: candidate) : nil) + if installed { try DashLegacyStoreSQLite.copy(from: candidate, to: url) } + let marker = root.appendingPathComponent("active.json") + try JSONEncoder().encode(journal).write(to: marker) + let container = try open(url) + try verifyRows(container.mainContext) + XCTAssertFalse(FileManager.default.fileExists(atPath: marker.path)) + } + } + } + } } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift index 6b3afc29a50..1ac6248f4cc 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift @@ -31,6 +31,8 @@ final class DashModelMigrationTests: XCTestCase { Fixture( name: "dash-v1", version: DashSchemaV1.self, hasTrackedMasternode: false, assetLockRecipientIsExternal: nil), + Fixture(name: "historical-v2", version: DashSchemaV2.self, + hasTrackedMasternode: true, assetLockRecipientIsExternal: nil), ] private static var acceptedBaselineVersions: [Schema.Version] { [Schema.Version(1, 0, 0)] } @@ -56,6 +58,107 @@ final class DashModelMigrationTests: XCTestCase { return (directory, copy) } + @MainActor + func testMigrationDiagnosticsReachExportFileWithoutVerboseLogging() throws { + let fixture = try XCTUnwrap(Self.fixtures.first { $0.name == "historical-v2" }) + let (directory, url) = try copyFixture(fixture) + defer { try? FileManager.default.removeItem(at: directory) } + let session = directory.appendingPathComponent("logs", isDirectory: true) + // This is the same file sink setting installed by the default low preset. + XCTAssertTrue(SDKLogger.installFileSink(at: session, includeDebug: false)) + // The sink is process-wide: detach it before the directory disappears. + defer { SDKLogger.removeFileSink() } + let sourceChecksum = try Self.storeHashes(at: url).0 + + try autoreleasepool { _ = try DashModelContainer.create(url: url) } + try autoreleasepool { _ = try DashModelContainer.create(url: url) } + SDKLogger.flush() + let log = try String(contentsOf: session.appendingPathComponent("swift/run.log"), encoding: .utf8) + XCTAssertTrue(log.contains("event=store_open_started")) + XCTAssertTrue(log.contains("route=\"historical-v2-to-v3\"")) + XCTAssertTrue(log.contains("source_version=\"2.0.0\"")) + XCTAssertTrue(log.contains("source_checksum=\"\(sourceChecksum)\"")) + XCTAssertTrue(log.contains("target_version=\"3.0.0\"")) + XCTAssertTrue(log.contains("route=\"labelled-current-v3\"")) + XCTAssertEqual(log.components(separatedBy: "event=store_open_succeeded").count - 1, 2) + XCTAssertFalse(log.contains("event=store_open_failed")) + XCTAssertFalse(log.contains(directory.path)) + XCTAssertFalse(log.contains("fixture wallet")) + + let freshURL = directory.appendingPathComponent("fresh.store") + try autoreleasepool { _ = try DashModelContainer.create(url: freshURL) } + // A malformed store must produce a safe error diagnostic, without its contents. + let invalidURL = directory.appendingPathComponent("invalid.store") + try Data("private-invalid-store-content".utf8).write(to: invalidURL) + XCTAssertThrowsError(try DashModelContainer.create(url: invalidURL)) + SDKLogger.flush() + let updatedLog = try String(contentsOf: session.appendingPathComponent("swift/run.log"), encoding: .utf8) + XCTAssertTrue(updatedLog.contains("route=\"new-store\"")) + let failure = try XCTUnwrap(updatedLog.split(separator: "\n").first { $0.contains("event=store_open_failed") }) + XCTAssertTrue(failure.contains("target_version=\"3.0.0\"")) + XCTAssertTrue(failure.contains("error_code=")) + XCTAssertFalse(updatedLog.contains(directory.path)) + XCTAssertFalse(updatedLog.contains("private-invalid-store-content")) + } + + /// Opening a current store must not depend on the temporary-store probe + /// that resolves a frozen schema's identity: the plan is the default + /// either way. Labels whose route is undecidable without that probe + /// (accepted V1 versus the bridge, historical V2 versus a beta layout) + /// keep failing closed, leaving the store untouched. + func testCurrentV3RouteNeverDependsOnTheSchemaIdentityProbe() throws { + struct ProbeUnavailable: Error {} + let failingProbe: (any VersionedSchema.Type) throws -> DashLegacySchemaBridge.Identity = { _ in + throw ProbeUnavailable() + } + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let current = directory.appendingPathComponent("current.store") + try autoreleasepool { _ = try DashModelContainer.create(url: current) } + XCTAssertEqual(try DashLegacySchemaBridge.identity(at: current).versions, ["3.0.0"]) + let plan = try DashModelContainer.migrationPlan( + at: current, defaultPlan: DashMigrationPlan.self, identity: failingProbe) + XCTAssertTrue(ObjectIdentifier(plan) == ObjectIdentifier(DashMigrationPlan.self)) + + for fixture in Self.fixtures { + let (fixtureDirectory, url) = try copyFixture(fixture) + defer { try? FileManager.default.removeItem(at: fixtureDirectory) } + let before = try DashLegacyStoreSQLite.rawDigest(url) + XCTAssertThrowsError(try DashModelContainer.migrationPlan( + at: url, defaultPlan: DashMigrationPlan.self, identity: failingProbe), fixture.name) { error in + XCTAssertTrue(error is ProbeUnavailable, fixture.name) + } + XCTAssertEqual(try DashLegacyStoreSQLite.rawDigest(url), before, fixture.name) + } + } + + func testSchemaIdentityIsComputedOncePerProcessAndFailuresAreNotRemembered() throws { + struct ProbeUnavailable: Error {} + let cache = DashLegacySchemaBridge.SchemaIdentityCache() + let identity = DashLegacySchemaBridge.Identity( + versions: ["3.0.0"], checksum: "checksum", hashes: ["PersistentWallet": Data([1])]) + var computations = 0 + XCTAssertThrowsError(try cache.identity(for: DashSchemaV3.self) { + computations += 1 + throw ProbeUnavailable() + }) + XCTAssertEqual(try cache.identity(for: DashSchemaV3.self) { computations += 1; return identity }, identity) + XCTAssertEqual(try cache.identity(for: DashSchemaV3.self) { + computations += 1 + throw ProbeUnavailable() + }, identity) + XCTAssertEqual(computations, 2) + XCTAssertThrowsError(try cache.identity(for: DashSchemaV2.self) { + computations += 1 + throw ProbeUnavailable() + }) + XCTAssertEqual(computations, 3) + XCTAssertEqual(try DashLegacySchemaBridge.identity(for: DashSchemaV3.self), + try DashLegacySchemaBridge.identity(for: DashSchemaV3.self)) + } + private static func storeHashes(at url: URL) throws -> (String, [String: Data]) { let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore( type: .sqlite, at: url) @@ -170,7 +273,7 @@ final class DashModelMigrationTests: XCTestCase { func testFrozenVersionsBuiltAfterTheLiveSchemaHashLikeTheStoresTheyShipped() throws { XCTAssertEqual( Self.fixtures.map { $0.version.versionIdentifier }, - Self.acceptedBaselineVersions, + Self.acceptedBaselineVersions + [Schema.Version(2, 0, 0)], "the accepted baseline must retain its existing fixture") for fixture in Self.fixtures { @@ -207,24 +310,27 @@ final class DashModelMigrationTests: XCTestCase { $0.version.versionIdentifier } let expected = Set( - Self.acceptedBaselineVersions + publishedVersions + [DashModelContainer.schema.version] + [Schema.Version(2, 0, 0)] + publishedVersions + [DashModelContainer.schema.version] ).sorted() XCTAssertEqual( DashMigrationPlan.schemas.map { $0.versionIdentifier }, expected, - "The plan must retain the accepted baseline and every published version, followed by the live version") + "The primary plan retains historical V2 and published versions; accepted V1 has a separate non-destructive route") } func testMigrationStagesConnectAdjacentRegisteredSchemas() { - let schemas = DashMigrationPlan.schemas - let stages = DashMigrationPlan.stages - XCTAssertEqual(stages.count, schemas.count - 1) - for (stage, adjacent) in zip(stages, zip(schemas, schemas.dropFirst())) { - switch stage { - case .lightweight(let from, let to), .custom(let from, let to, _, _): - XCTAssertEqual(ObjectIdentifier(from), ObjectIdentifier(adjacent.0)) - XCTAssertEqual(ObjectIdentifier(to), ObjectIdentifier(adjacent.1)) - @unknown default: - XCTFail("Unsupported migration stage") + let plans: [any SchemaMigrationPlan.Type] = [DashMigrationPlan.self, DashAcceptedV1MigrationPlan.self] + for plan in plans { + let schemas = plan.schemas + let stages = plan.stages + XCTAssertEqual(stages.count, schemas.count - 1) + for (stage, adjacent) in zip(stages, zip(schemas, schemas.dropFirst())) { + switch stage { + case .lightweight(let from, let to), .custom(let from, let to, _, _): + XCTAssertEqual(ObjectIdentifier(from), ObjectIdentifier(adjacent.0)) + XCTAssertEqual(ObjectIdentifier(to), ObjectIdentifier(adjacent.1)) + @unknown default: + XCTFail("Unsupported migration stage") + } } } } @@ -341,15 +447,15 @@ final class DashModelMigrationTests: XCTestCase { } } - func testV2AddsTrackedMasternodesAndBalanceMetadataToTheBaselineEntitySet() { + func testV3AddsTrackedMasternodesAndBalanceMetadataToTheBaselineEntitySet() { XCTAssertEqual( - Set(Schema(versionedSchema: DashSchemaV2.self).entities.map(\.name)) + Set(Schema(versionedSchema: DashSchemaV3.self).entities.map(\.name)) .subtracting(Schema(versionedSchema: DashSchemaV1.self).entities.map(\.name)), ["PersistentTrackedMasternode", "PersistentIdentityBalanceMetadata"]) } @MainActor - func testV1BalanceGetsNoWatermarkUntilOneIsPersistedInLiveV2() throws { + func testV1BalanceGetsNoWatermarkUntilOneIsPersistedInLiveV3() throws { let (directory, url) = try copyFixture(Self.fixtures[0]) defer { try? FileManager.default.removeItem(at: directory) } try autoreleasepool { @@ -375,9 +481,9 @@ final class DashModelMigrationTests: XCTestCase { } /// The accepted V1 graph predates key limits. Its keys must arrive in - /// live V2 unlimited, then accept limits through the public accessors. + /// live V3 unlimited, then accept limits through the public accessors. @MainActor - func testV1StoreMigratesToV2AndBackfillsTheKeyLimitColumns() throws { + func testV1StoreMigratesToV3AndBackfillsTheKeyLimitColumns() throws { let directory = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory( @@ -407,7 +513,7 @@ final class DashModelMigrationTests: XCTestCase { try v1Container?.mainContext.save() v1Container = nil - let v2Schema = Schema(versionedSchema: DashSchemaV2.self) + let v2Schema = Schema(versionedSchema: DashSchemaV3.self) let v2Configuration = ModelConfiguration( "DashKeyLimitsMigrationTest", schema: v2Schema, @@ -416,7 +522,7 @@ final class DashModelMigrationTests: XCTestCase { cloudKitDatabase: .none) let migrated = try ModelContainer( for: v2Schema, - migrationPlan: DashMigrationPlan.self, + migrationPlan: DashAcceptedV1MigrationPlan.self, configurations: [v2Configuration]) let keys = try migrated.mainContext.fetch(FetchDescriptor()) @@ -441,10 +547,10 @@ final class DashModelMigrationTests: XCTestCase { XCTAssertTrue(reread.hasLimits) } - /// Legacy contract bounds keep their inferred variant after V1 -> V2, + /// Legacy contract bounds keep their inferred variant after V1 -> V3, /// and the new discriminator can then represent contract groups. @MainActor - func testV1StoreMigratesToV2AndBackfillsTheContractBoundsKind() throws { + func testV1StoreMigratesToV3AndBackfillsTheContractBoundsKind() throws { let directory = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory( @@ -484,7 +590,7 @@ final class DashModelMigrationTests: XCTestCase { try v1Container?.mainContext.save() v1Container = nil - let v2Schema = Schema(versionedSchema: DashSchemaV2.self) + let v2Schema = Schema(versionedSchema: DashSchemaV3.self) let v2Configuration = ModelConfiguration( "DashContractBoundsKindMigrationTest", schema: v2Schema, @@ -493,7 +599,7 @@ final class DashModelMigrationTests: XCTestCase { cloudKitDatabase: .none) let migrated = try ModelContainer( for: v2Schema, - migrationPlan: DashMigrationPlan.self, + migrationPlan: DashAcceptedV1MigrationPlan.self, configurations: [v2Configuration]) let rows = try migrated.mainContext.fetch( @@ -518,9 +624,9 @@ final class DashModelMigrationTests: XCTestCase { XCTAssertEqual(reread[1].effectiveContractBoundsKind, 3) } - func testV2AddsKeyColumnsWithoutChangingTheFrozenBaseline() throws { + func testV3AddsKeyColumnsWithoutChangingTheFrozenBaseline() throws { let baseline = Schema(versionedSchema: DashSchemaV1.self) - let live = Schema(versionedSchema: DashSchemaV2.self) + let live = Schema(versionedSchema: DashSchemaV3.self) let oldKey = try XCTUnwrap(baseline.entities.first { $0.name == "PersistentPublicKey" }) let newKey = try XCTUnwrap(live.entities.first { $0.name == "PersistentPublicKey" }) for column in ["totalBudget", "expiresAt", "contractBoundsKind"] { @@ -528,4 +634,222 @@ final class DashModelMigrationTests: XCTestCase { XCTAssertNotNil(newKey.attributesByName[column]) } } + + /// Synthetic historical evidence generated from the reconstructed source; + /// this test never accesses a device database or keychain. + @MainActor + func testCaptureHistoricalV2Fixture() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("historical-v2.store") + try autoreleasepool { + let schema = Schema(versionedSchema: DashSchemaV2.self) + let container = try ModelContainer(for: schema, configurations: [ + ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none) + ]) + let context = container.mainContext + let wallet = DashSchemaV2.PersistentWallet( + walletId: Data(repeating: 0x31, count: 32), network: .testnet, name: "fixture wallet", + syncedHeight: 120) + context.insert(wallet) + let account = DashSchemaV2.PersistentAccount( + wallet: wallet, accountType: 0, accountIndex: 0, accountTypeName: "standard") + context.insert(account) + let address = DashSchemaV2.PersistentCoreAddress( + address: "yFixtureAddress", poolTypeTag: 0, addressIndex: 0, derivationPath: "m/0") + address.account = account + context.insert(address) + let funding = DashSchemaV2.PersistentTransaction( + txid: Data(repeating: 0x34, count: 32), transactionData: Data([3, 0]), context: 2, + blockHeight: 100) + let spend = DashSchemaV2.PersistentTransaction( + txid: Data(repeating: 0x32, count: 32), transactionData: Data([3, 0]), context: 2, + blockHeight: 110) + context.insert(funding) + context.insert(spend) + account.involvedTransactions = [funding, spend] + let txo = DashSchemaV2.PersistentTxo( + transaction: funding, vout: 0, amount: 1_000, address: "yFixtureAddress", + height: 100) + txo.walletId = Data(repeating: 0x31, count: 32) + txo.isSpent = true + txo.spendingTransaction = spend + txo.coreAddress = address + txo.account = account + context.insert(txo) + context.insert(DashSchemaV2.PersistentPendingInput( + outpoint: Data(repeating: 0x11, count: 36), inputIndex: 0, + spendingTxid: Data(repeating: 0x32, count: 32), spendingTransaction: spend, + walletId: Data(repeating: 0x31, count: 32))) + let identity = DashSchemaV2.PersistentIdentity( + identityId: Data(repeating: 0x35, count: 32), balance: 5, network: .testnet) + identity.wallet = wallet + context.insert(identity) + let key = DashSchemaV2.PersistentPublicKey( + keyId: 3, purpose: .authentication, securityLevel: .high, + keyType: .ecdsaSecp256k1, publicKeyData: Data(repeating: 0x02, count: 33), + identityId: identity.identityIdString) + key.identity = identity + context.insert(key) + context.insert(DashSchemaV2.PersistentKeyword(keyword: "preserved", contractId: "contract")) + let lock = DashSchemaV2.PersistentAssetLock( + outPointHex: String(repeating: "ab", count: 32) + ":0", + walletId: Data(repeating: 0x31, count: 32), transactionBytes: Data([1, 2, 3]), + fundingTypeRaw: 4, identityIndexRaw: -1, amountDuffs: 100_000, statusRaw: 4) + context.insert(lock) + context.insert(DashSchemaV2.PersistentTrackedMasternode( + networkRaw: Network.testnet.rawValue, proTxHash: Data(repeating: 7, count: 32), + label: "fixture", addedAt: 1, snapshotJSON: "{}")) + try context.save() + } + try DashLegacyStoreSQLite.checkpoint(url) + let metadata = try DashSchemaFixtureSupport.describeStore(at: url, version: Schema.Version(2, 0, 0)) + XCTAssertEqual(metadata.entity_hashes.count, 35) + XCTAssertEqual(metadata.model_checksum, "RrRj/iNbS9izgLQvNb2APed4iwaR7pftEE2+4tea7K8=") + let attachment = XCTAttachment(contentsOfFile: url) + attachment.name = "historical-v2.store" + attachment.lifetime = .keepAlways + add(attachment) + } + + @MainActor + func testAcceptedV1PreservesAllThirteenFieldsMissingFromHistoricalV2() throws { + let (directory, url) = try copyFixture(Self.fixtures[0]) + defer { try? FileManager.default.removeItem(at: directory) } + try autoreleasepool { + let schema = Schema(versionedSchema: DashSchemaV1.self) + let container = try ModelContainer(for: schema, configurations: [ + ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none) + ]) + let context = container.mainContext + let type = DashSchemaV1.PersistentDocumentType( + contractId: Data([41]), name: "retained", schemaJSON: Data(), propertiesJSON: Data()) + type.indexOnly = true + let index = DashSchemaV1.PersistentIndex( + contractId: Data([41]), documentTypeName: "retained", name: "retained", properties: ["name"]) + index.documentType = type + index.countable = "countableAllowingOffset" + index.summable = "amount" + index.averageable = "amount" + index.terminal = "$ownerId" + index.timeRangeJSON = Data("{\"on\":\"createdAt\"}".utf8) + index.rangeCountable = true + index.rangeSummable = true + index.rangeAverageable = true + index.rankedCountable = true + index.rankedSummable = true + index.rankedAverageable = true + index.preallocated = true + context.insert(type) + context.insert(index) + try context.save() + } + let before = directory.appendingPathComponent("before.store") + try DashLegacyStoreSQLite.copy(from: url, to: before) + try autoreleasepool { + let container = try DashModelContainer.create(url: url) + let context = container.mainContext + let type = try XCTUnwrap(context.fetch(FetchDescriptor()).first) + let index = try XCTUnwrap(context.fetch(FetchDescriptor()).first) + XCTAssertTrue(type.indexOnly) + XCTAssertEqual(index.countable, "countableAllowingOffset") + XCTAssertEqual(index.summable, "amount") + XCTAssertEqual(index.averageable, "amount") + XCTAssertEqual(index.terminal, "$ownerId") + XCTAssertEqual(index.timeRangeJSON, Data("{\"on\":\"createdAt\"}".utf8)) + XCTAssertEqual([index.rangeCountable, index.rangeSummable, index.rangeAverageable, + index.rankedCountable, index.rankedSummable, index.rankedAverageable, index.preallocated], + Array(repeating: true, count: 7)) + XCTAssertEqual(index.documentType?.persistentModelID, type.persistentModelID) + index.name = "writable" + try context.save() + index.name = "retained" + try context.save() + } + try DashLegacyStoreSQLite.validatePreservation(from: before, to: url) + } + + /// Local diagnostic only. The input never enters test resources, attachments + /// or logs, and all migration/writes happen on a disposable copy. + @MainActor + func testPrivateHistoricalStoreMigrationWhenExplicitlyProvided() throws { + let path = ProcessInfo.processInfo.environment["DASH_PRIVATE_MIGRATION_STORE"] + try XCTSkipIf(path == nil, "No private migration diagnostic input was explicitly provided") + let source = URL(fileURLWithPath: try XCTUnwrap(path)) + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, + attributes: [.posixPermissions: 0o700]) + defer { try? FileManager.default.removeItem(at: directory) } + let before = directory.appendingPathComponent("before.store") + let migrated = directory.appendingPathComponent("migrated.store") + try DashLegacyStoreSQLite.copy(from: source, to: before) + try DashLegacyStoreSQLite.copy(from: before, to: migrated) + try autoreleasepool { _ = try DashModelContainer.create(url: migrated) } + try DashLegacyStoreSQLite.validatePreservation(from: before, to: migrated) + let walletId: Data = try autoreleasepool { + let container = try DashModelContainer.create(url: migrated) + let context = container.mainContext + let wallet = try XCTUnwrap(context.fetch(FetchDescriptor()).first) + wallet.name = "temporary migration write verification" + try context.save() + return wallet.walletId + } + try autoreleasepool { + let container = try DashModelContainer.create(url: migrated) + let wallets = try container.mainContext.fetch(FetchDescriptor()) + XCTAssertTrue(wallets.contains { + $0.walletId == walletId && $0.name == "temporary migration write verification" + }, "A write to the diagnostic copy must survive reopening") + } + } + + @MainActor + func testHistoricalV2AddsDefaultsAndPreservesDocumentRelationships() throws { + let (directory, url) = try copyFixture(Self.fixtures[1]) + defer { try? FileManager.default.removeItem(at: directory) } + try autoreleasepool { + let schema = Schema(versionedSchema: DashSchemaV2.self) + let container = try ModelContainer(for: schema, configurations: [ + ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none) + ]) + let type = DashSchemaV2.PersistentDocumentType( + contractId: Data([42]), name: "historical", schemaJSON: Data([123, 125]), propertiesJSON: Data([123, 125])) + let index = DashSchemaV2.PersistentIndex( + contractId: Data([42]), documentTypeName: "historical", name: "original", properties: ["name"]) + index.documentType = type + container.mainContext.insert(type) + container.mainContext.insert(index) + try container.mainContext.save() + } + let before = directory.appendingPathComponent("before.store") + try DashLegacyStoreSQLite.copy(from: url, to: before) + try autoreleasepool { + let container = try DashModelContainer.create(url: url) + let context = container.mainContext + let type = try XCTUnwrap(context.fetch(FetchDescriptor()).first) + let index = try XCTUnwrap(context.fetch(FetchDescriptor()).first) + XCTAssertFalse(type.indexOnly) + XCTAssertNil(index.countable) + XCTAssertNil(index.summable) + XCTAssertNil(index.averageable) + XCTAssertNil(index.terminal) + XCTAssertNil(index.timeRangeJSON) + XCTAssertEqual([index.rangeCountable, index.rangeSummable, index.rangeAverageable, + index.rankedCountable, index.rankedSummable, index.rankedAverageable, index.preallocated], + Array(repeating: false, count: 7)) + XCTAssertEqual(index.documentType?.persistentModelID, type.persistentModelID) + XCTAssertEqual(type.indices?.count, 1) + XCTAssertEqual(index.properties, ["name"]) + } + try DashLegacyStoreSQLite.validatePreservation(from: before, to: url) + try autoreleasepool { + let container = try DashModelContainer.create(url: url) + let index = try XCTUnwrap(container.mainContext.fetch(FetchDescriptor()).first) + index.preallocated = true + try container.mainContext.save() + } + let reopened = try DashModelContainer.create(url: url) + XCTAssertTrue(try XCTUnwrap(reopened.mainContext.fetch(FetchDescriptor()).first).preallocated) + } } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashReleasedSchemaTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashReleasedSchemaTests.swift index 35dfdbc0097..d283b5a20c0 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashReleasedSchemaTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashReleasedSchemaTests.swift @@ -104,17 +104,20 @@ final class DashReleasedSchemaTests: XCTestCase { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } - var checksums = Set() - for type in DashMigrationPlan.schemas { - let version = type.versionIdentifier - let url = directory.appendingPathComponent(DashSchemaFixtureSupport.version(version) + ".store") - let schema = Schema(versionedSchema: type) - _ = try ModelContainer(for: schema, configurations: [ - ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none) - ]) - let metadata = try DashSchemaFixtureSupport.describeStore(at: url, version: version) - XCTAssertTrue(checksums.insert(metadata.model_checksum).inserted, - "A snapshot with unchanged shape must not become an additional runtime migration stage") + let plans: [any SchemaMigrationPlan.Type] = [DashMigrationPlan.self, DashAcceptedV1MigrationPlan.self] + for (planIndex, plan) in plans.enumerated() { + var checksums = Set() + for type in plan.schemas { + let version = type.versionIdentifier + let url = directory.appendingPathComponent("\(planIndex)-" + DashSchemaFixtureSupport.version(version) + ".store") + let schema = Schema(versionedSchema: type) + _ = try ModelContainer(for: schema, configurations: [ + ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none) + ]) + let metadata = try DashSchemaFixtureSupport.describeStore(at: url, version: version) + XCTAssertTrue(checksums.insert(metadata.model_checksum).inserted, + "A snapshot with unchanged shape must not become an additional runtime migration stage") + } } } } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/Fixtures/SchemaStores/historical-v2.store b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/Fixtures/SchemaStores/historical-v2.store new file mode 100644 index 00000000000..d411b495ed2 Binary files /dev/null and b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/Fixtures/SchemaStores/historical-v2.store differ diff --git a/packages/swift-sdk/schema-releases.json b/packages/swift-sdk/schema-releases.json index 07a64203a2b..1cb3a4f4365 100644 --- a/packages/swift-sdk/schema-releases.json +++ b/packages/swift-sdk/schema-releases.json @@ -1,5 +1,155 @@ { "format_version": 1, "schemas": {}, - "releases": {} + "releases": {}, + "historical_schemas": { + "2.0.0": { + "schema": { + "schema_version": "2.0.0", + "model_checksum": "RrRj/iNbS9izgLQvNb2APed4iwaR7pftEE2+4tea7K8=", + "entity_hashes": { + "PersistentAccount": "a5d5dc075d2d634d1a6f0ce025fe0aa323e2747443119c94eb65d024aa47985d", + "PersistentAssetLock": "7fb4ccbc526302d09df6f3f11f9d9eb269c2dd33ee93e1a4a31f72714145399c", + "PersistentCoreAddress": "2518791fe1ebe9fbab8586ba08cb0a527259360e6cfe710287ca73f8959dd14c", + "PersistentDPNSName": "0b3c83f1ed265b4ef9e4ee404d0354f3da7eb70004d38d8bded2f5bae4debaed", + "PersistentDashpayContactProfile": "a5c249ffa9d298c53329262cb85edbb5fc5b77a67f43d7343277ce58d8d4b9d3", + "PersistentDashpayContactRequest": "3ed2ec9984523024a43af961442d85cf02f5db87302e1c8aa68ef9c407d12901", + "PersistentDashpayIgnoredSender": "5386ff4fc63f0b1dfd6a42d6e9b3db3c54339691cb55593ce169c5ba4378f680", + "PersistentDashpayPayment": "5aac0e1c8d892a243dba2967170a0cee067fc56c183b2f4af06c4b66b2839630", + "PersistentDashpayProfile": "e88ec9d87a07af8c2e1faef17b0206a61c9d59322552aab0ffe3133b7059885e", + "PersistentDataContract": "c869c0a2df469be22643847a3e8331e156f364e93aefde2aedd13ef6067bcd66", + "PersistentDocument": "1e143af2e59ef70f72385d661d7ba5d1484fee34f97d9e8d0b2b56fdc879a590", + "PersistentDocumentType": "c3689448841fb9d75e55153213f960504ee839bbc6d695b33b5021d88076c41b", + "PersistentIdentity": "d0e738b1edb8dae40c4b3f916196b6bdcaa9fe499752d211bb69204d80a83418", + "PersistentIndex": "889455232bbb1ac94ab79ccefb6a1ad7de185c6b6e8c9aa7cdc01ed453d659af", + "PersistentInvitation": "4a0a75d2196279e70a911f6d7686f9e29441b582b19ac00b67bc66e88452cf57", + "PersistentKeyword": "286ac09d230fd54050fa33f989e478745766f6e456377137b124d05f2e1a82fb", + "PersistentMasternode": "b33b6a7c27a4df67e0319b96e1f4337e9a67e8213d0d97d540167a140967d656", + "PersistentPendingInput": "483084c729757b6a0acc3118f74773ade4f68b3d6210229229e95a9e49e7ca1e", + "PersistentPlatformAddress": "0cae31a85f8e343c9fe45a8bb44a14958f688456ad6a5c9e39a1331c46e16039", + "PersistentPlatformAddressesSyncState": "de52a03d68033a8cf1bf7e95f2e8f1b8e318ef67cd289ffa9f60595c0a4e24b9", + "PersistentProperty": "c7082d8dcaf538d2eb88916033b8b40f228bd399d758999f2dd0470708fc94b6", + "PersistentPublicKey": "d369346faee596c187c6851eec77d9251414f788f9a11579842cf03492380585", + "PersistentShieldedActivity": "1aef5f0ec88b4be4ccd1a549379c7ca0dfa75b6f48909c22538ba2687d487409", + "PersistentShieldedNote": "d2986310786e015f98f92c5b6cd84db1b1e98eadd623e98d94ebae778cb1e650", + "PersistentShieldedOutgoingNote": "e749ad68716dccc346b798b23c98e21072fd0df19f344bf4b752e15605fe42f1", + "PersistentShieldedSyncState": "2130e7484885f36267753ce4f6d39e216aa6b932e3660234a12b29a136335769", + "PersistentShieldedViewingKey": "bc07713a4b0a63ffdec2e53369e97f089e8de905ab2e8e7e270f71bec7668cdc", + "PersistentToken": "85dacb8b1556f06c9ece6bac94e185e0fdbd8f62554f2b5eca444c121649567c", + "PersistentTokenBalance": "6ea32b253749c13392e4c7aa471b0872d4b1a9d36bb260beb9c6bb4d40a7474e", + "PersistentTokenHistoryEvent": "6e67103e1a6caf7d04f4b5a44d1012a470fef341c36c6cefbfc0e76b440a00ab", + "PersistentTrackedMasternode": "a187e0384fc3ae3619b61b4fcb4004920846d2dce7c533875146db8c6aeb882a", + "PersistentTransaction": "daad9b22c2b6c554cc281e7e00eff39ec366373fbaf9553e03ec38ad8f794fbb", + "PersistentTxo": "0a8a83ff1b93058115b34147cc5e797c5691a4975a6892e5d11474ba9d6772b7", + "PersistentWallet": "d2ae76969b1d92b66c6e7df62f7e0ae12e05be2498c9ecf79e3b7d0aa7f96c81", + "PersistentWalletManagerMetadata": "19dbe2cfb7e0c63fa6cd69291e5b1865f58642f43a156db0d9e06028a7bd4d99" + }, + "indexes": [ + "ACHANGE ACHANGE_ZTRANSACTIONID_INDEX: CREATE INDEX ACHANGE_ZTRANSACTIONID_INDEX ON ACHANGE (ZTRANSACTIONID)", + "ATRANSACTION ATRANSACTION_ZAUTHORTS_INDEX: CREATE INDEX ATRANSACTION_ZAUTHORTS_INDEX ON ATRANSACTION (ZAUTHORTS)", + "ATRANSACTION ATRANSACTION_ZBUNDLEIDTS_INDEX: CREATE INDEX ATRANSACTION_ZBUNDLEIDTS_INDEX ON ATRANSACTION (ZBUNDLEIDTS)", + "ATRANSACTION ATRANSACTION_ZCONTEXTNAMETS_INDEX: CREATE INDEX ATRANSACTION_ZCONTEXTNAMETS_INDEX ON ATRANSACTION (ZCONTEXTNAMETS)", + "ATRANSACTION ATRANSACTION_ZPROCESSIDTS_INDEX: CREATE INDEX ATRANSACTION_ZPROCESSIDTS_INDEX ON ATRANSACTION (ZPROCESSIDTS)", + "ATRANSACTION Z_TRANSACTION_TransactionAuthorIndex: CREATE INDEX Z_TRANSACTION_TransactionAuthorIndex ON ATRANSACTION (ZAUTHOR COLLATE BINARY ASC)", + "ATRANSACTION Z_TRANSACTION_TransactionTimestampIndex: CREATE INDEX Z_TRANSACTION_TransactionTimestampIndex ON ATRANSACTION (ZTIMESTAMP COLLATE BINARY ASC)", + "ATRANSACTIONSTRING Z_TRANSACTIONSTRING_UNIQUE_NAME: CREATE UNIQUE INDEX Z_TRANSACTIONSTRING_UNIQUE_NAME ON ATRANSACTIONSTRING (ZNAME COLLATE BINARY ASC)", + "ZPERSISTENTACCOUNT ZPERSISTENTACCOUNT_ZWALLET_INDEX: CREATE INDEX ZPERSISTENTACCOUNT_ZWALLET_INDEX ON ZPERSISTENTACCOUNT (ZWALLET)", + "ZPERSISTENTACCOUNT Z_PersistentAccount_UNIQUE_accountExtendedPubKeyBytes: CREATE UNIQUE INDEX Z_PersistentAccount_UNIQUE_accountExtendedPubKeyBytes ON ZPERSISTENTACCOUNT (ZACCOUNTEXTENDEDPUBKEYBYTES COLLATE BINARY ASC)", + "ZPERSISTENTACCOUNT Z_PersistentAccount_UNIQUE_wallet_accountType_accountIndex_standardTag_registrationIndex_keyClass_userIdentityId_friendIdentityId: CREATE UNIQUE INDEX Z_PersistentAccount_UNIQUE_wallet_accountType_accountIndex_standardTag_registrationIndex_keyClass_userIdentityId_friendIdentityId ON ZPERSISTENTACCOUNT (ZWALLET COLLATE BINARY ASC, ZACCOUNTTYPE COLLATE BINARY ASC, ZACCOUNTINDEX COLLATE BINARY ASC, ZSTANDARDTAG COLLATE BINARY ASC, ZREGISTRATIONINDEX COLLATE BINARY ASC, ZKEYCLASS COLLATE BINARY ASC, ZUSERIDENTITYID COLLATE BINARY ASC, ZFRIENDIDENTITYID COLLATE BINARY ASC)", + "ZPERSISTENTASSETLOCK Z_PersistentAssetLock_SwiftDataIndexOnBinarywalletId: CREATE INDEX Z_PersistentAssetLock_SwiftDataIndexOnBinarywalletId ON ZPERSISTENTASSETLOCK (ZWALLETID COLLATE BINARY ASC)", + "ZPERSISTENTASSETLOCK Z_PersistentAssetLock_UNIQUE_outPointHex: CREATE UNIQUE INDEX Z_PersistentAssetLock_UNIQUE_outPointHex ON ZPERSISTENTASSETLOCK (ZOUTPOINTHEX COLLATE BINARY ASC)", + "ZPERSISTENTCOREADDRESS ZPERSISTENTCOREADDRESS_ZACCOUNT_INDEX: CREATE INDEX ZPERSISTENTCOREADDRESS_ZACCOUNT_INDEX ON ZPERSISTENTCOREADDRESS (ZACCOUNT)", + "ZPERSISTENTCOREADDRESS Z_PersistentCoreAddress_UNIQUE_address: CREATE UNIQUE INDEX Z_PersistentCoreAddress_UNIQUE_address ON ZPERSISTENTCOREADDRESS (ZADDRESS COLLATE BINARY ASC)", + "ZPERSISTENTDASHPAYCONTACTPROFILE ZPERSISTENTDASHPAYCONTACTPROFILE_ZOWNER_INDEX: CREATE INDEX ZPERSISTENTDASHPAYCONTACTPROFILE_ZOWNER_INDEX ON ZPERSISTENTDASHPAYCONTACTPROFILE (ZOWNER)", + "ZPERSISTENTDASHPAYCONTACTPROFILE Z_PersistentDashpayContactProfile_UNIQUE_networkRaw_ownerIdentityId_contactIdentityId: CREATE UNIQUE INDEX Z_PersistentDashpayContactProfile_UNIQUE_networkRaw_ownerIdentityId_contactIdentityId ON ZPERSISTENTDASHPAYCONTACTPROFILE (ZNETWORKRAW COLLATE BINARY ASC, ZOWNERIDENTITYID COLLATE BINARY ASC, ZCONTACTIDENTITYID COLLATE BINARY ASC)", + "ZPERSISTENTDASHPAYCONTACTREQUEST ZPERSISTENTDASHPAYCONTACTREQUEST_ZOWNER_INDEX: CREATE INDEX ZPERSISTENTDASHPAYCONTACTREQUEST_ZOWNER_INDEX ON ZPERSISTENTDASHPAYCONTACTREQUEST (ZOWNER)", + "ZPERSISTENTDASHPAYCONTACTREQUEST Z_PersistentDashpayContactRequest_UNIQUE_networkRaw_ownerIdentityId_contactIdentityId_isOutgoing: CREATE UNIQUE INDEX Z_PersistentDashpayContactRequest_UNIQUE_networkRaw_ownerIdentityId_contactIdentityId_isOutgoing ON ZPERSISTENTDASHPAYCONTACTREQUEST (ZNETWORKRAW COLLATE BINARY ASC, ZOWNERIDENTITYID COLLATE BINARY ASC, ZCONTACTIDENTITYID COLLATE BINARY ASC, ZISOUTGOING COLLATE BINARY ASC)", + "ZPERSISTENTDASHPAYIGNOREDSENDER ZPERSISTENTDASHPAYIGNOREDSENDER_ZOWNER_INDEX: CREATE INDEX ZPERSISTENTDASHPAYIGNOREDSENDER_ZOWNER_INDEX ON ZPERSISTENTDASHPAYIGNOREDSENDER (ZOWNER)", + "ZPERSISTENTDASHPAYIGNOREDSENDER Z_PersistentDashpayIgnoredSender_UNIQUE_networkRaw_ownerIdentityId_ignoredSenderId: CREATE UNIQUE INDEX Z_PersistentDashpayIgnoredSender_UNIQUE_networkRaw_ownerIdentityId_ignoredSenderId ON ZPERSISTENTDASHPAYIGNOREDSENDER (ZNETWORKRAW COLLATE BINARY ASC, ZOWNERIDENTITYID COLLATE BINARY ASC, ZIGNOREDSENDERID COLLATE BINARY ASC)", + "ZPERSISTENTDASHPAYPAYMENT ZPERSISTENTDASHPAYPAYMENT_ZOWNER_INDEX: CREATE INDEX ZPERSISTENTDASHPAYPAYMENT_ZOWNER_INDEX ON ZPERSISTENTDASHPAYPAYMENT (ZOWNER)", + "ZPERSISTENTDASHPAYPAYMENT Z_PersistentDashpayPayment_UNIQUE_networkRaw_ownerIdentityId_txid: CREATE UNIQUE INDEX Z_PersistentDashpayPayment_UNIQUE_networkRaw_ownerIdentityId_txid ON ZPERSISTENTDASHPAYPAYMENT (ZNETWORKRAW COLLATE BINARY ASC, ZOWNERIDENTITYID COLLATE BINARY ASC, ZTXID COLLATE BINARY ASC)", + "ZPERSISTENTDASHPAYPROFILE ZPERSISTENTDASHPAYPROFILE_ZIDENTITY_INDEX: CREATE INDEX ZPERSISTENTDASHPAYPROFILE_ZIDENTITY_INDEX ON ZPERSISTENTDASHPAYPROFILE (ZIDENTITY)", + "ZPERSISTENTDASHPAYPROFILE Z_PersistentDashpayProfile_UNIQUE_networkRaw_identity: CREATE UNIQUE INDEX Z_PersistentDashpayProfile_UNIQUE_networkRaw_identity ON ZPERSISTENTDASHPAYPROFILE (ZNETWORKRAW COLLATE BINARY ASC, ZIDENTITY COLLATE BINARY ASC)", + "ZPERSISTENTDATACONTRACT ZPERSISTENTDATACONTRACT_ZOWNERIDENTITY_INDEX: CREATE INDEX ZPERSISTENTDATACONTRACT_ZOWNERIDENTITY_INDEX ON ZPERSISTENTDATACONTRACT (ZOWNERIDENTITY)", + "ZPERSISTENTDATACONTRACT Z_PersistentDataContract_SwiftDataIndexOnBinarynetworkRaw: CREATE INDEX Z_PersistentDataContract_SwiftDataIndexOnBinarynetworkRaw ON ZPERSISTENTDATACONTRACT (ZNETWORKRAW COLLATE BINARY ASC)", + "ZPERSISTENTDATACONTRACT Z_PersistentDataContract_UNIQUE_id: CREATE UNIQUE INDEX Z_PersistentDataContract_UNIQUE_id ON ZPERSISTENTDATACONTRACT (ZID COLLATE BINARY ASC)", + "ZPERSISTENTDOCUMENT ZPERSISTENTDOCUMENT_ZDATACONTRACT_INDEX: CREATE INDEX ZPERSISTENTDOCUMENT_ZDATACONTRACT_INDEX ON ZPERSISTENTDOCUMENT (ZDATACONTRACT)", + "ZPERSISTENTDOCUMENT ZPERSISTENTDOCUMENT_ZDOCUMENTTYPE_RELATION_INDEX: CREATE INDEX ZPERSISTENTDOCUMENT_ZDOCUMENTTYPE_RELATION_INDEX ON ZPERSISTENTDOCUMENT (ZDOCUMENTTYPE_RELATION)", + "ZPERSISTENTDOCUMENT ZPERSISTENTDOCUMENT_ZOWNERIDENTITY_INDEX: CREATE INDEX ZPERSISTENTDOCUMENT_ZOWNERIDENTITY_INDEX ON ZPERSISTENTDOCUMENT (ZOWNERIDENTITY)", + "ZPERSISTENTDOCUMENT Z_PersistentDocument_SwiftDataIndexOnBinarynetworkRaw: CREATE INDEX Z_PersistentDocument_SwiftDataIndexOnBinarynetworkRaw ON ZPERSISTENTDOCUMENT (ZNETWORKRAW COLLATE BINARY ASC)", + "ZPERSISTENTDOCUMENT Z_PersistentDocument_UNIQUE_documentId: CREATE UNIQUE INDEX Z_PersistentDocument_UNIQUE_documentId ON ZPERSISTENTDOCUMENT (ZDOCUMENTID COLLATE BINARY ASC)", + "ZPERSISTENTDOCUMENTTYPE ZPERSISTENTDOCUMENTTYPE_ZDATACONTRACT_INDEX: CREATE INDEX ZPERSISTENTDOCUMENTTYPE_ZDATACONTRACT_INDEX ON ZPERSISTENTDOCUMENTTYPE (ZDATACONTRACT)", + "ZPERSISTENTDOCUMENTTYPE Z_PersistentDocumentType_UNIQUE_id: CREATE UNIQUE INDEX Z_PersistentDocumentType_UNIQUE_id ON ZPERSISTENTDOCUMENTTYPE (ZID COLLATE BINARY ASC)", + "ZPERSISTENTDPNSNAME ZPERSISTENTDPNSNAME_ZIDENTITY_INDEX: CREATE INDEX ZPERSISTENTDPNSNAME_ZIDENTITY_INDEX ON ZPERSISTENTDPNSNAME (ZIDENTITY)", + "ZPERSISTENTDPNSNAME Z_PersistentDPNSName_UNIQUE_networkRaw_normalizedParentDomainName_normalizedLabel: CREATE UNIQUE INDEX Z_PersistentDPNSName_UNIQUE_networkRaw_normalizedParentDomainName_normalizedLabel ON ZPERSISTENTDPNSNAME (ZNETWORKRAW COLLATE BINARY ASC, ZNORMALIZEDPARENTDOMAINNAME COLLATE BINARY ASC, ZNORMALIZEDLABEL COLLATE BINARY ASC)", + "ZPERSISTENTIDENTITY ZPERSISTENTIDENTITY_ZDASHPAYPROFILE_INDEX: CREATE INDEX ZPERSISTENTIDENTITY_ZDASHPAYPROFILE_INDEX ON ZPERSISTENTIDENTITY (ZDASHPAYPROFILE)", + "ZPERSISTENTIDENTITY ZPERSISTENTIDENTITY_ZWALLET_INDEX: CREATE INDEX ZPERSISTENTIDENTITY_ZWALLET_INDEX ON ZPERSISTENTIDENTITY (ZWALLET)", + "ZPERSISTENTIDENTITY Z_PersistentIdentity_SwiftDataIndexOnBinarynetworkRaw: CREATE INDEX Z_PersistentIdentity_SwiftDataIndexOnBinarynetworkRaw ON ZPERSISTENTIDENTITY (ZNETWORKRAW COLLATE BINARY ASC)", + "ZPERSISTENTIDENTITY Z_PersistentIdentity_UNIQUE_identityId: CREATE UNIQUE INDEX Z_PersistentIdentity_UNIQUE_identityId ON ZPERSISTENTIDENTITY (ZIDENTITYID COLLATE BINARY ASC)", + "ZPERSISTENTINDEX ZPERSISTENTINDEX_ZDOCUMENTTYPE_INDEX: CREATE INDEX ZPERSISTENTINDEX_ZDOCUMENTTYPE_INDEX ON ZPERSISTENTINDEX (ZDOCUMENTTYPE)", + "ZPERSISTENTINDEX Z_PersistentIndex_UNIQUE_id: CREATE UNIQUE INDEX Z_PersistentIndex_UNIQUE_id ON ZPERSISTENTINDEX (ZID COLLATE BINARY ASC)", + "ZPERSISTENTINVITATION Z_PersistentInvitation_SwiftDataIndexOnBinarywalletId: CREATE INDEX Z_PersistentInvitation_SwiftDataIndexOnBinarywalletId ON ZPERSISTENTINVITATION (ZWALLETID COLLATE BINARY ASC)", + "ZPERSISTENTINVITATION Z_PersistentInvitation_UNIQUE_outPointHex: CREATE UNIQUE INDEX Z_PersistentInvitation_UNIQUE_outPointHex ON ZPERSISTENTINVITATION (ZOUTPOINTHEX COLLATE BINARY ASC)", + "ZPERSISTENTKEYWORD ZPERSISTENTKEYWORD_ZDATACONTRACT_INDEX: CREATE INDEX ZPERSISTENTKEYWORD_ZDATACONTRACT_INDEX ON ZPERSISTENTKEYWORD (ZDATACONTRACT)", + "ZPERSISTENTKEYWORD Z_PersistentKeyword_UNIQUE_id: CREATE UNIQUE INDEX Z_PersistentKeyword_UNIQUE_id ON ZPERSISTENTKEYWORD (ZID COLLATE BINARY ASC)", + "ZPERSISTENTMASTERNODE Z_PersistentMasternode_UNIQUE_walletId_proTxHash: CREATE UNIQUE INDEX Z_PersistentMasternode_UNIQUE_walletId_proTxHash ON ZPERSISTENTMASTERNODE (ZWALLETID COLLATE BINARY ASC, ZPROTXHASH COLLATE BINARY ASC)", + "ZPERSISTENTPENDINGINPUT ZPERSISTENTPENDINGINPUT_ZSPENDINGTRANSACTION_INDEX: CREATE INDEX ZPERSISTENTPENDINGINPUT_ZSPENDINGTRANSACTION_INDEX ON ZPERSISTENTPENDINGINPUT (ZSPENDINGTRANSACTION)", + "ZPERSISTENTPENDINGINPUT Z_PersistentPendingInput_SwiftDataIndexOnBinaryoutpoint: CREATE INDEX Z_PersistentPendingInput_SwiftDataIndexOnBinaryoutpoint ON ZPERSISTENTPENDINGINPUT (ZOUTPOINT COLLATE BINARY ASC)", + "ZPERSISTENTPENDINGINPUT Z_PersistentPendingInput_SwiftDataIndexOnBinarywalletId: CREATE INDEX Z_PersistentPendingInput_SwiftDataIndexOnBinarywalletId ON ZPERSISTENTPENDINGINPUT (ZWALLETID COLLATE BINARY ASC)", + "ZPERSISTENTPLATFORMADDRESS ZPERSISTENTPLATFORMADDRESS_ZACCOUNT_INDEX: CREATE INDEX ZPERSISTENTPLATFORMADDRESS_ZACCOUNT_INDEX ON ZPERSISTENTPLATFORMADDRESS (ZACCOUNT)", + "ZPERSISTENTPLATFORMADDRESS Z_PersistentPlatformAddress_SwiftDataIndexOnBinarywalletId: CREATE INDEX Z_PersistentPlatformAddress_SwiftDataIndexOnBinarywalletId ON ZPERSISTENTPLATFORMADDRESS (ZWALLETID COLLATE BINARY ASC)", + "ZPERSISTENTPLATFORMADDRESS Z_PersistentPlatformAddress_UNIQUE_address: CREATE UNIQUE INDEX Z_PersistentPlatformAddress_UNIQUE_address ON ZPERSISTENTPLATFORMADDRESS (ZADDRESS COLLATE BINARY ASC)", + "ZPERSISTENTPLATFORMADDRESS Z_PersistentPlatformAddress_UNIQUE_addressHash: CREATE UNIQUE INDEX Z_PersistentPlatformAddress_UNIQUE_addressHash ON ZPERSISTENTPLATFORMADDRESS (ZADDRESSHASH COLLATE BINARY ASC)", + "ZPERSISTENTPLATFORMADDRESSESSYNCSTATE Z_PersistentPlatformAddressesSyncState_UNIQUE_walletId: CREATE UNIQUE INDEX Z_PersistentPlatformAddressesSyncState_UNIQUE_walletId ON ZPERSISTENTPLATFORMADDRESSESSYNCSTATE (ZWALLETID COLLATE BINARY ASC)", + "ZPERSISTENTPROPERTY ZPERSISTENTPROPERTY_ZDOCUMENTTYPE_INDEX: CREATE INDEX ZPERSISTENTPROPERTY_ZDOCUMENTTYPE_INDEX ON ZPERSISTENTPROPERTY (ZDOCUMENTTYPE)", + "ZPERSISTENTPROPERTY Z_PersistentProperty_UNIQUE_id: CREATE UNIQUE INDEX Z_PersistentProperty_UNIQUE_id ON ZPERSISTENTPROPERTY (ZID COLLATE BINARY ASC)", + "ZPERSISTENTPUBLICKEY ZPERSISTENTPUBLICKEY_ZIDENTITY_INDEX: CREATE INDEX ZPERSISTENTPUBLICKEY_ZIDENTITY_INDEX ON ZPERSISTENTPUBLICKEY (ZIDENTITY)", + "ZPERSISTENTSHIELDEDACTIVITY Z_PersistentShieldedActivity_SwiftDataIndexOnBinarywalletIdaccountIndex: CREATE INDEX Z_PersistentShieldedActivity_SwiftDataIndexOnBinarywalletIdaccountIndex ON ZPERSISTENTSHIELDEDACTIVITY (ZWALLETID COLLATE BINARY ASC, ZACCOUNTINDEX COLLATE BINARY ASC)", + "ZPERSISTENTSHIELDEDACTIVITY Z_PersistentShieldedActivity_UNIQUE_walletId_accountIndex_entryId: CREATE UNIQUE INDEX Z_PersistentShieldedActivity_UNIQUE_walletId_accountIndex_entryId ON ZPERSISTENTSHIELDEDACTIVITY (ZWALLETID COLLATE BINARY ASC, ZACCOUNTINDEX COLLATE BINARY ASC, ZENTRYID COLLATE BINARY ASC)", + "ZPERSISTENTSHIELDEDNOTE Z_PersistentShieldedNote_SwiftDataIndexOnBinarywalletIdaccountIndex: CREATE INDEX Z_PersistentShieldedNote_SwiftDataIndexOnBinarywalletIdaccountIndex ON ZPERSISTENTSHIELDEDNOTE (ZWALLETID COLLATE BINARY ASC, ZACCOUNTINDEX COLLATE BINARY ASC)", + "ZPERSISTENTSHIELDEDNOTE Z_PersistentShieldedNote_UNIQUE_nullifier: CREATE UNIQUE INDEX Z_PersistentShieldedNote_UNIQUE_nullifier ON ZPERSISTENTSHIELDEDNOTE (ZNULLIFIER COLLATE BINARY ASC)", + "ZPERSISTENTSHIELDEDOUTGOINGNOTE Z_PersistentShieldedOutgoingNote_SwiftDataIndexOnBinarywalletIdaccountIndex: CREATE INDEX Z_PersistentShieldedOutgoingNote_SwiftDataIndexOnBinarywalletIdaccountIndex ON ZPERSISTENTSHIELDEDOUTGOINGNOTE (ZWALLETID COLLATE BINARY ASC, ZACCOUNTINDEX COLLATE BINARY ASC)", + "ZPERSISTENTSHIELDEDOUTGOINGNOTE Z_PersistentShieldedOutgoingNote_UNIQUE_walletId_accountIndex_cmx: CREATE UNIQUE INDEX Z_PersistentShieldedOutgoingNote_UNIQUE_walletId_accountIndex_cmx ON ZPERSISTENTSHIELDEDOUTGOINGNOTE (ZWALLETID COLLATE BINARY ASC, ZACCOUNTINDEX COLLATE BINARY ASC, ZCMX COLLATE BINARY ASC)", + "ZPERSISTENTSHIELDEDSYNCSTATE Z_PersistentShieldedSyncState_SwiftDataIndexOnBinarywalletId: CREATE INDEX Z_PersistentShieldedSyncState_SwiftDataIndexOnBinarywalletId ON ZPERSISTENTSHIELDEDSYNCSTATE (ZWALLETID COLLATE BINARY ASC)", + "ZPERSISTENTSHIELDEDSYNCSTATE Z_PersistentShieldedSyncState_UNIQUE_walletId_accountIndex: CREATE UNIQUE INDEX Z_PersistentShieldedSyncState_UNIQUE_walletId_accountIndex ON ZPERSISTENTSHIELDEDSYNCSTATE (ZWALLETID COLLATE BINARY ASC, ZACCOUNTINDEX COLLATE BINARY ASC)", + "ZPERSISTENTSHIELDEDVIEWINGKEY Z_PersistentShieldedViewingKey_SwiftDataIndexOnBinarywalletId: CREATE INDEX Z_PersistentShieldedViewingKey_SwiftDataIndexOnBinarywalletId ON ZPERSISTENTSHIELDEDVIEWINGKEY (ZWALLETID COLLATE BINARY ASC)", + "ZPERSISTENTSHIELDEDVIEWINGKEY Z_PersistentShieldedViewingKey_UNIQUE_walletId_accountIndex: CREATE UNIQUE INDEX Z_PersistentShieldedViewingKey_UNIQUE_walletId_accountIndex ON ZPERSISTENTSHIELDEDVIEWINGKEY (ZWALLETID COLLATE BINARY ASC, ZACCOUNTINDEX COLLATE BINARY ASC)", + "ZPERSISTENTTOKEN ZPERSISTENTTOKEN_ZDATACONTRACT_INDEX: CREATE INDEX ZPERSISTENTTOKEN_ZDATACONTRACT_INDEX ON ZPERSISTENTTOKEN (ZDATACONTRACT)", + "ZPERSISTENTTOKEN Z_PersistentToken_UNIQUE_id: CREATE UNIQUE INDEX Z_PersistentToken_UNIQUE_id ON ZPERSISTENTTOKEN (ZID COLLATE BINARY ASC)", + "ZPERSISTENTTOKENBALANCE ZPERSISTENTTOKENBALANCE_Z13TOKENBALANCES_INDEX: CREATE INDEX ZPERSISTENTTOKENBALANCE_Z13TOKENBALANCES_INDEX ON ZPERSISTENTTOKENBALANCE (Z13TOKENBALANCES)", + "ZPERSISTENTTOKENBALANCE ZPERSISTENTTOKENBALANCE_ZIDENTITY_INDEX: CREATE INDEX ZPERSISTENTTOKENBALANCE_ZIDENTITY_INDEX ON ZPERSISTENTTOKENBALANCE (ZIDENTITY)", + "ZPERSISTENTTOKENBALANCE ZPERSISTENTTOKENBALANCE_ZTOKEN_INDEX: CREATE INDEX ZPERSISTENTTOKENBALANCE_ZTOKEN_INDEX ON ZPERSISTENTTOKENBALANCE (ZTOKEN)", + "ZPERSISTENTTOKENBALANCE Z_PersistentTokenBalance_SwiftDataIndexOnBinarynetworkRaw: CREATE INDEX Z_PersistentTokenBalance_SwiftDataIndexOnBinarynetworkRaw ON ZPERSISTENTTOKENBALANCE (ZNETWORKRAW COLLATE BINARY ASC)", + "ZPERSISTENTTOKENHISTORYEVENT ZPERSISTENTTOKENHISTORYEVENT_ZTOKEN_INDEX: CREATE INDEX ZPERSISTENTTOKENHISTORYEVENT_ZTOKEN_INDEX ON ZPERSISTENTTOKENHISTORYEVENT (ZTOKEN)", + "ZPERSISTENTTOKENHISTORYEVENT Z_PersistentTokenHistoryEvent_UNIQUE_id: CREATE UNIQUE INDEX Z_PersistentTokenHistoryEvent_UNIQUE_id ON ZPERSISTENTTOKENHISTORYEVENT (ZID COLLATE BINARY ASC)", + "ZPERSISTENTTRACKEDMASTERNODE Z_PersistentTrackedMasternode_SwiftDataIndexOnBinarynetworkRaw: CREATE INDEX Z_PersistentTrackedMasternode_SwiftDataIndexOnBinarynetworkRaw ON ZPERSISTENTTRACKEDMASTERNODE (ZNETWORKRAW COLLATE BINARY ASC)", + "ZPERSISTENTTRACKEDMASTERNODE Z_PersistentTrackedMasternode_UNIQUE_networkRaw_proTxHash: CREATE UNIQUE INDEX Z_PersistentTrackedMasternode_UNIQUE_networkRaw_proTxHash ON ZPERSISTENTTRACKEDMASTERNODE (ZNETWORKRAW COLLATE BINARY ASC, ZPROTXHASH COLLATE BINARY ASC)", + "ZPERSISTENTTRANSACTION Z_PersistentTransaction_SwiftDataIndexOnBinaryfirstSeen: CREATE INDEX Z_PersistentTransaction_SwiftDataIndexOnBinaryfirstSeen ON ZPERSISTENTTRANSACTION (ZFIRSTSEEN COLLATE BINARY ASC)", + "ZPERSISTENTTRANSACTION Z_PersistentTransaction_UNIQUE_txid: CREATE UNIQUE INDEX Z_PersistentTransaction_UNIQUE_txid ON ZPERSISTENTTRANSACTION (ZTXID COLLATE BINARY ASC)", + "ZPERSISTENTTXO ZPERSISTENTTXO_ZACCOUNT_INDEX: CREATE INDEX ZPERSISTENTTXO_ZACCOUNT_INDEX ON ZPERSISTENTTXO (ZACCOUNT)", + "ZPERSISTENTTXO ZPERSISTENTTXO_ZCOREADDRESS_INDEX: CREATE INDEX ZPERSISTENTTXO_ZCOREADDRESS_INDEX ON ZPERSISTENTTXO (ZCOREADDRESS)", + "ZPERSISTENTTXO ZPERSISTENTTXO_ZSPENDINGTRANSACTION_INDEX: CREATE INDEX ZPERSISTENTTXO_ZSPENDINGTRANSACTION_INDEX ON ZPERSISTENTTXO (ZSPENDINGTRANSACTION)", + "ZPERSISTENTTXO ZPERSISTENTTXO_ZTRANSACTION_INDEX: CREATE INDEX ZPERSISTENTTXO_ZTRANSACTION_INDEX ON ZPERSISTENTTXO (ZTRANSACTION)", + "ZPERSISTENTTXO Z_PersistentTxo_SwiftDataIndexOnBinarywalletId: CREATE INDEX Z_PersistentTxo_SwiftDataIndexOnBinarywalletId ON ZPERSISTENTTXO (ZWALLETID COLLATE BINARY ASC)", + "ZPERSISTENTTXO Z_PersistentTxo_UNIQUE_outpoint: CREATE UNIQUE INDEX Z_PersistentTxo_UNIQUE_outpoint ON ZPERSISTENTTXO (ZOUTPOINT COLLATE BINARY ASC)", + "ZPERSISTENTWALLET Z_PersistentWallet_SwiftDataIndexOnBinarynetworkRaw: CREATE INDEX Z_PersistentWallet_SwiftDataIndexOnBinarynetworkRaw ON ZPERSISTENTWALLET (ZNETWORKRAW COLLATE BINARY ASC)", + "ZPERSISTENTWALLET Z_PersistentWallet_SwiftDataIndexOnBinarywalletGroupId: CREATE INDEX Z_PersistentWallet_SwiftDataIndexOnBinarywalletGroupId ON ZPERSISTENTWALLET (ZWALLETGROUPID COLLATE BINARY ASC)", + "ZPERSISTENTWALLET Z_PersistentWallet_UNIQUE_walletId: CREATE UNIQUE INDEX Z_PersistentWallet_UNIQUE_walletId ON ZPERSISTENTWALLET (ZWALLETID COLLATE BINARY ASC)", + "ZPERSISTENTWALLETMANAGERMETADATA Z_PersistentWalletManagerMetadata_UNIQUE_networkRaw: CREATE UNIQUE INDEX Z_PersistentWalletManagerMetadata_UNIQUE_networkRaw ON ZPERSISTENTWALLETMANAGERMETADATA (ZNETWORKRAW COLLATE BINARY ASC)", + "Z_1INVOLVEDTRANSACTIONS Z_1INVOLVEDTRANSACTIONS_Z_32INVOLVEDTRANSACTIONS_INDEX: CREATE INDEX Z_1INVOLVEDTRANSACTIONS_Z_32INVOLVEDTRANSACTIONS_INDEX ON Z_1INVOLVEDTRANSACTIONS (Z_32INVOLVEDTRANSACTIONS, Z_1INVOLVEDACCOUNTS)", + "Z_1INVOLVEDTRANSACTIONS sqlite_autoindex_Z_1INVOLVEDTRANSACTIONS_1: (auto)" + ] + }, + "source_sha": "52e8d4ec68f0c772313fa1bbef223fb1eabbf1cc", + "provenance": "reconstructed-model-match", + "fixture_path": "packages/swift-sdk/SwiftTests/SwiftDashSDKTests/Fixtures/SchemaStores/historical-v2.store", + "fixture_sha256": "4c7c0516627c2cc3dc588bfe3e764755205adc0f3848f7e8b7028bf3c53f67ae", + "app_store_baseline": { + "bundle_id": "org.dashfoundation.dash", + "app_id": "1206647026", + "app_version": "9.0.2", + "release_id": "679060c3-2e64-49d6-b28e-baa307c817be" + } + } + } } diff --git a/packages/swift-sdk/scripts/freeze_appstore_release.py b/packages/swift-sdk/scripts/freeze_appstore_release.py index f3c329f7701..801b49a64ce 100644 --- a/packages/swift-sdk/scripts/freeze_appstore_release.py +++ b/packages/swift-sdk/scripts/freeze_appstore_release.py @@ -243,10 +243,17 @@ def git_environment(token): def source_commits(registry): - return { + """Every commit a later regeneration must be able to read, including the + reconstructed historical sources that never went through a release.""" + commits = { require_string(entry.get("platform_sha"), SHA, "registered Platform commit") for group in ("schemas", "releases") for entry in registry.get(group, {}).values() } + commits.update( + require_string(entry.get("source_sha"), SHA, "historical schema source commit") + for entry in registry.get("historical_schemas", {}).values() + ) + return commits def fetch_sources(clone, commits, env): @@ -373,7 +380,7 @@ def generate(*args): raise ReleaseError("Attempted to replace an existing snapshot or fixture") registry = json_object((clone / REGISTRY).read_bytes(), "snapshot registry") # The generator may append a schema, but existing snapshots are immutable. - for key in ("schemas", "releases"): + for key in ("schemas", "releases", "historical_schemas"): for identifier, value in before_registry.get(key, {}).items(): if registry.get(key, {}).get(identifier) != value: raise ReleaseError(f"Attempted to rewrite existing {key} entry: {identifier}") diff --git a/packages/swift-sdk/scripts/freeze_schema_models.py b/packages/swift-sdk/scripts/freeze_schema_models.py index 493fa2d4e33..ef4cf8b08d2 100755 --- a/packages/swift-sdk/scripts/freeze_schema_models.py +++ b/packages/swift-sdk/scripts/freeze_schema_models.py @@ -112,6 +112,8 @@ class Freeze: value_types: tuple = () +HISTORICAL_V2_SOURCE = "52e8d4ec68f0c772313fa1bbef223fb1eabbf1cc" + FREEZES = [ # The accepted V1 asset lock: the last commit before # `recipientIsExternal` was added to the live model. @@ -124,6 +126,14 @@ class Freeze: TOKEN_TYPES_FILE, tuple(TOKEN_VALUE_TYPES), ), + # Reconstructed pre-August-28 V2: all 35 hashes and the model checksum + # match the observed App Store store. This is reconstruction provenance, + # not a claim that this exact commit built the released app binary. + Freeze( + "DashSchemaV2", HISTORICAL_V2_SOURCE, + tuple(V1_GRAPH_MODELS + ["PersistentAssetLock", "PersistentTrackedMasternode"]), + TOKEN_TYPES_FILE, tuple(TOKEN_VALUE_TYPES), + ), ] HEADER = "import Foundation\nimport SwiftData\n\n" @@ -685,14 +695,60 @@ def render_snapshot(root, version, entry, *, inventory=None): return files +APP_STORE_BASELINE_FIELDS = { + "bundle_id": r"[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+", + "app_id": r"[0-9]+", + "app_version": r"[0-9]+(\.[0-9]+){1,2}", + "release_id": r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", +} + + +def validate_app_store_baseline(binding): + """The published release a historical schema is bound to. The iOS release + gate reads exactly this object, so its shape is part of the contract.""" + if not isinstance(binding, dict) or set(binding) != set(APP_STORE_BASELINE_FIELDS): + raise SystemExit("historical schema must bind exactly one App Store baseline") + for field, pattern in APP_STORE_BASELINE_FIELDS.items(): + value = binding[field] + if not isinstance(value, str) or not re.fullmatch(pattern, value): + raise SystemExit(f"invalid App Store baseline {field}") + + +def validate_historical_schemas(root, registry): + """Historical reconstruction is separate from archive-captured releases.""" + entries = registry.get("historical_schemas", {}) + if not isinstance(entries, dict): + raise SystemExit("invalid historical schema registry") + for version, entry in entries.items(): + if version != "2.0.0" or not isinstance(entry, dict): + raise SystemExit("unsupported historical schema") + schema = entry["schema"] + validate_schema(schema) + if schema["schema_version"] != version or entry.get("source_sha") != HISTORICAL_V2_SOURCE: + raise SystemExit("historical schema reconstruction provenance differs") + if entry.get("provenance") != "reconstructed-model-match": + raise SystemExit("historical schema must identify reconstruction provenance") + validate_app_store_baseline(entry.get("app_store_baseline")) + digest = entry["fixture_sha256"] + path = entry["fixture_path"] + if path != "packages/swift-sdk/SwiftTests/SwiftDashSDKTests/Fixtures/SchemaStores/historical-v2.store": + raise SystemExit("invalid historical fixture path") + fixture = pathlib.Path(root, path) + if not re.fullmatch(r"[0-9a-f]{64}", digest) or not fixture.is_file() or hashlib.sha256(fixture.read_bytes()).hexdigest() != digest: + raise SystemExit("missing or modified immutable historical fixture") + validate_fixture_description(fixture, schema) + return entries + + def render_all(root, registry=None): files = render_baseline(root) registry = read_registry(root) if registry is None else registry + historical = validate_historical_schemas(root, registry) fixtures = [] - checksums = set() + checksums = {entry["schema"]["model_checksum"] for entry in historical.values()} for version, entry in sorted(registry["schemas"].items(), key=lambda item: tuple(map(int, item[0].split('.')))): - if version == "1.0.0": - raise SystemExit("V1 is the unchanged accepted baseline, not a new release snapshot") + if version == "1.0.0" or version in historical: + raise SystemExit("Historical schema versions are reserved, not new release snapshots") checksum = entry["schema"]["model_checksum"] if checksum in checksums: raise SystemExit("two registered schema versions have the same model checksum") @@ -751,6 +807,12 @@ def add_release(root, manifest, fixture): version = schema["schema_version"] if version == "1.0.0": raise SystemExit("V1 must remain unchanged") + registry = read_registry(root) + historical = validate_historical_schemas(root, registry) + if version in historical: + raise SystemExit("Historical schema version is reserved; publish the current V3 or a later schema") + if any(entry["schema"]["model_checksum"] == schema["model_checksum"] for entry in historical.values()): + raise SystemExit("a new schema version cannot reuse a historical model checksum") commit = manifest["platform_sha"] if not isinstance(commit, str) or not re.fullmatch(r"[0-9a-f]{40}", commit): raise SystemExit("release source must be a full Git SHA") diff --git a/packages/swift-sdk/scripts/test_freeze_appstore_release.py b/packages/swift-sdk/scripts/test_freeze_appstore_release.py index 3b317cb35c5..40e52f9c025 100644 --- a/packages/swift-sdk/scripts/test_freeze_appstore_release.py +++ b/packages/swift-sdk/scripts/test_freeze_appstore_release.py @@ -448,6 +448,35 @@ def test_source_tag_retains_rewritten_history_for_fresh_clones_and_later_freezes self.assertEqual(git(newest, "cat-file", "-t", source), "commit") self.assertEqual(git(newest, "cat-file", "-t", second_source), "commit") + def test_historical_schema_source_is_fetched_and_retained_like_release_sources(self): + registry = {"format_version": 1, "schemas": {"3.0.0": {"platform_sha": "3" * 40}}, + "releases": {"r": {"platform_sha": "4" * 40}}, + "historical_schemas": {"2.0.0": {"source_sha": "5" * 40, "provenance": "reconstructed-model-match"}}} + self.assertEqual(worker.source_commits(registry), {"3" * 40, "4" * 40, "5" * 40}) + registry["historical_schemas"]["2.0.0"]["source_sha"] = "not-a-commit" + with self.assertRaisesRegex(worker.ReleaseError, "historical schema source commit"): + worker.source_commits(registry) + del registry["historical_schemas"]["2.0.0"]["source_sha"] + with self.assertRaisesRegex(worker.ReleaseError, "historical schema source commit"): + worker.source_commits(registry) + + source = self.unreachable_source("historical-v2-reconstruction-source") + base_registry = json.loads((self.platform / worker.REGISTRY).read_text()) + base_registry["historical_schemas"] = {"2.0.0": { + "source_sha": source, "provenance": "reconstructed-model-match"}} + write_json(self.platform / worker.REGISTRY, base_registry) + git(self.platform, "add", ".") + git(self.platform, "commit", "-m", "register historical source") + git(self.platform, "push", str(self.remote), f"{worker.BASE_BRANCH}:refs/heads/{worker.BASE_BRANCH}") + ref = worker.SOURCE_TAG_PREFIX + source + self.assertNotIn(ref, git(self.remote, "show-ref")) + self.prepare(dry_run=True) + self.assertNotIn(ref, git(self.remote, "show-ref")) + self.prepare() + self.assertEqual(git(self.remote, "rev-parse", ref), source) + self.assertEqual(git(self.remote, "rev-parse", worker.SOURCE_TAG_PREFIX + self.manifest["platform_sha"]), + self.manifest["platform_sha"]) + def test_conflicting_source_tag_is_never_rewritten(self): source = self.unreachable_source("released-source") self.manifest["platform_sha"] = source diff --git a/packages/swift-sdk/scripts/test_freeze_schema_models.py b/packages/swift-sdk/scripts/test_freeze_schema_models.py index d6ac0ed1d9b..128f501bd42 100644 --- a/packages/swift-sdk/scripts/test_freeze_schema_models.py +++ b/packages/swift-sdk/scripts/test_freeze_schema_models.py @@ -51,7 +51,7 @@ def setUp(self): shutil.copyfile(os.path.join(ROOT, gen.TEST_REGISTRY_FILE), target) def test_should_find_the_committed_files_are_the_generators_output(self): - self.assertEqual(len(gen.render_baseline(ROOT)), 35) + self.assertEqual(len(gen.render_baseline(ROOT)), 71) self.assertIn(gen.TEST_REGISTRY_FILE, self.files) self.assertEqual(gen.check_problems(ROOT, self.files), []) @@ -230,6 +230,65 @@ def git(root, *args): self.addCleanup(mock.patch.stopall) mock.patch.object(gen, "git", side_effect=git).start() + def historical_registry(self): + path = "packages/swift-sdk/SwiftTests/SwiftDashSDKTests/Fixtures/SchemaStores/historical-v2.store" + target = Path(self.root, path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(self.fixture.read_bytes()) + registry = gen.read_registry(self.root) + registry["historical_schemas"] = {"2.0.0": { + "schema": dict(self.schema), "fixture_path": path, + "fixture_sha256": hashlib.sha256(target.read_bytes()).hexdigest(), + "source_sha": gen.HISTORICAL_V2_SOURCE, "provenance": "reconstructed-model-match", + "app_store_baseline": { + "bundle_id": "org.dashfoundation.dash", "app_id": "1206647026", "app_version": "9.0.2", + "release_id": "679060c3-2e64-49d6-b28e-baa307c817be"}}} + Path(self.root, gen.REGISTRY_FILE).write_text(json.dumps(registry)) + return registry + + def test_should_validate_the_historical_app_store_baseline_the_ios_gate_reads(self): + self.assertEqual(gen.validate_historical_schemas(self.root, self.historical_registry()).keys(), {"2.0.0"}) + mutations = { + "missing": lambda entry: entry.pop("app_store_baseline"), + "not an object": lambda entry: entry.__setitem__("app_store_baseline", "9.0.2"), + "missing field": lambda entry: entry["app_store_baseline"].pop("release_id"), + "extra field": lambda entry: entry["app_store_baseline"].__setitem__("build_number", "30"), + "empty version": lambda entry: entry["app_store_baseline"].__setitem__("app_version", ""), + "non-string app id": lambda entry: entry["app_store_baseline"].__setitem__("app_id", 1206647026), + "malformed release id": lambda entry: entry["app_store_baseline"].__setitem__("release_id", "release-30"), + "malformed bundle id": lambda entry: entry["app_store_baseline"].__setitem__("bundle_id", "dash"), + } + for name, mutate in mutations.items(): + registry = self.historical_registry() + mutate(registry["historical_schemas"]["2.0.0"]) + with self.subTest(case=name), self.assertRaisesRegex(SystemExit, "App Store baseline"): + gen.validate_historical_schemas(self.root, registry) + + def test_should_reserve_historical_v2_without_writing_snapshot(self): + self.historical_registry() + before = Path(self.root, gen.REGISTRY_FILE).read_bytes() + with self.assertRaisesRegex(SystemExit, "Historical schema version is reserved"): + gen.add_release(self.root, self.manifest, self.fixture) + self.assertEqual(Path(self.root, gen.REGISTRY_FILE).read_bytes(), before) + self.assertFalse(Path(self.root, gen.FIXTURE_DIR).exists()) + + def test_should_reject_modified_historical_fixture(self): + registry = self.historical_registry() + Path(self.root, registry["historical_schemas"]["2.0.0"]["fixture_path"]).write_bytes(b"changed") + with self.assertRaisesRegex(SystemExit, "immutable historical fixture"): + gen.validate_historical_schemas(self.root, registry) + + def test_should_reject_changed_historical_schema_or_reconstruction_source(self): + for field in ("source_sha", "schema"): + registry = self.historical_registry() + entry = registry["historical_schemas"]["2.0.0"] + if field == "source_sha": + entry[field] = "f" * 40 + else: + entry[field]["model_checksum"] = "changed" + with self.subTest(field=field), self.assertRaises(SystemExit): + gen.validate_historical_schemas(self.root, registry) + def test_should_copy_exact_captured_commit_and_preserve_release_metadata(self): registry = gen.add_release(self.root, self.manifest, self.fixture) entry = registry["schemas"]["2.0.0"]