diff --git a/Cargo.lock b/Cargo.lock index e3097c08145..887c97b7fbf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5463,6 +5463,7 @@ dependencies = [ "key-wallet", "key-wallet-manager", "log", + "orchard", "platform-encryption", "rand 0.8.6", "rayon", diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt index e1c133c12f2..a2a9664b029 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt @@ -192,12 +192,11 @@ fun SendTransactionScreen( } } - // Shielded credits — unspent-note sum from Room, only on a shielded - // build (same source WalletDetailScreen's Shielded row reads). + // Ordinary shielded sends spend account zero. val hasShielded = remember { Sdk.hasShielded() } val shieldedBalance by remember(walletIdHex) { if (hasShielded) { - container.database.shieldedDao().observeUnspentNotesByWallet(walletId) + container.database.shieldedDao().observeUnspentNotesByWalletAccount(walletId, 0) .map { notes -> notes.sumOf { it.value } } } else { MutableStateFlow(0L) diff --git a/packages/kotlin-sdk/sdk/schemas/org.dashfoundation.dashsdk.persistence.DashDatabase/17.json b/packages/kotlin-sdk/sdk/schemas/org.dashfoundation.dashsdk.persistence.DashDatabase/17.json new file mode 100644 index 00000000000..c51c1777fd2 --- /dev/null +++ b/packages/kotlin-sdk/sdk/schemas/org.dashfoundation.dashsdk.persistence.DashDatabase/17.json @@ -0,0 +1,4314 @@ +{ + "formatVersion": 1, + "database": { + "version": 17, + "identityHash": "aa58da0a7ca53a564b0a4a9bf012000b", + "entities": [ + { + "tableName": "wallets", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `walletGroupId` BLOB NOT NULL, `networkRaw` INTEGER, `name` TEXT, `walletDescription` TEXT, `birthHeight` INTEGER NOT NULL, `syncedHeight` INTEGER NOT NULL, `lastSynced` INTEGER NOT NULL, `lastAppliedChainLockBytes` BLOB, `lastAppliedChainLockHeight` INTEGER, `dashPayBackfillFloor` INTEGER, `dashPayBackfillRewoundFrom` INTEGER, `dashPayBackfillCovered` BLOB, `isImported` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "walletGroupId", + "columnName": "walletGroupId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER" + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT" + }, + { + "fieldPath": "walletDescription", + "columnName": "walletDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "birthHeight", + "columnName": "birthHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "syncedHeight", + "columnName": "syncedHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSynced", + "columnName": "lastSynced", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastAppliedChainLockBytes", + "columnName": "lastAppliedChainLockBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "lastAppliedChainLockHeight", + "columnName": "lastAppliedChainLockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "dashPayBackfillFloor", + "columnName": "dashPayBackfillFloor", + "affinity": "INTEGER" + }, + { + "fieldPath": "dashPayBackfillRewoundFrom", + "columnName": "dashPayBackfillRewoundFrom", + "affinity": "INTEGER" + }, + { + "fieldPath": "dashPayBackfillCovered", + "columnName": "dashPayBackfillCovered", + "affinity": "BLOB" + }, + { + "fieldPath": "isImported", + "columnName": "isImported", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId" + ] + }, + "indices": [ + { + "name": "index_wallets_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallets_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + }, + { + "name": "index_wallets_walletGroupId", + "unique": false, + "columnNames": [ + "walletGroupId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallets_walletGroupId` ON `${TABLE_NAME}` (`walletGroupId`)" + } + ] + }, + { + "tableName": "accounts", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `walletId` BLOB NOT NULL, `accountType` INTEGER NOT NULL, `accountIndex` INTEGER NOT NULL, `accountTypeName` TEXT NOT NULL, `balanceConfirmed` INTEGER NOT NULL, `balanceUnconfirmed` INTEGER NOT NULL, `externalHighestUsed` INTEGER NOT NULL, `internalHighestUsed` INTEGER NOT NULL, `standardTag` INTEGER NOT NULL, `registrationIndex` INTEGER NOT NULL, `keyClass` INTEGER NOT NULL, `userIdentityId` BLOB NOT NULL, `friendIdentityId` BLOB NOT NULL, `accountExtendedPubKeyBytes` BLOB, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, FOREIGN KEY(`walletId`) REFERENCES `wallets`(`walletId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountType", + "columnName": "accountType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountTypeName", + "columnName": "accountTypeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "balanceConfirmed", + "columnName": "balanceConfirmed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "balanceUnconfirmed", + "columnName": "balanceUnconfirmed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "externalHighestUsed", + "columnName": "externalHighestUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "internalHighestUsed", + "columnName": "internalHighestUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "standardTag", + "columnName": "standardTag", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "registrationIndex", + "columnName": "registrationIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keyClass", + "columnName": "keyClass", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "userIdentityId", + "columnName": "userIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "friendIdentityId", + "columnName": "friendIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountExtendedPubKeyBytes", + "columnName": "accountExtendedPubKeyBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_accounts_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_accounts_walletId` ON `${TABLE_NAME}` (`walletId`)" + }, + { + "name": "index_accounts_walletId_accountType_accountIndex_standardTag_registrationIndex_keyClass_userIdentityId_friendIdentityId", + "unique": true, + "columnNames": [ + "walletId", + "accountType", + "accountIndex", + "standardTag", + "registrationIndex", + "keyClass", + "userIdentityId", + "friendIdentityId" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_accounts_walletId_accountType_accountIndex_standardTag_registrationIndex_keyClass_userIdentityId_friendIdentityId` ON `${TABLE_NAME}` (`walletId`, `accountType`, `accountIndex`, `standardTag`, `registrationIndex`, `keyClass`, `userIdentityId`, `friendIdentityId`)" + }, + { + "name": "index_accounts_accountExtendedPubKeyBytes", + "unique": true, + "columnNames": [ + "accountExtendedPubKeyBytes" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_accounts_accountExtendedPubKeyBytes` ON `${TABLE_NAME}` (`accountExtendedPubKeyBytes`)" + } + ], + "foreignKeys": [ + { + "table": "wallets", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "walletId" + ], + "referencedColumns": [ + "walletId" + ] + } + ] + }, + { + "tableName": "transactions", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`txid` BLOB NOT NULL, `transactionData` BLOB NOT NULL, `context` INTEGER NOT NULL, `blockHeight` INTEGER NOT NULL, `blockHash` BLOB, `blockTimestamp` INTEGER NOT NULL, `blockPosition` INTEGER NOT NULL, `hasBlockPosition` INTEGER NOT NULL, `direction` INTEGER NOT NULL, `transactionType` TEXT NOT NULL, `transactionTypeKind` INTEGER NOT NULL, `netAmount` INTEGER NOT NULL, `fee` INTEGER, `label` TEXT NOT NULL, `firstSeen` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`txid`))", + "fields": [ + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "transactionData", + "columnName": "transactionData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "context", + "columnName": "context", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "blockHeight", + "columnName": "blockHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "blockHash", + "columnName": "blockHash", + "affinity": "BLOB" + }, + { + "fieldPath": "blockTimestamp", + "columnName": "blockTimestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "blockPosition", + "columnName": "blockPosition", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasBlockPosition", + "columnName": "hasBlockPosition", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "direction", + "columnName": "direction", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "transactionType", + "columnName": "transactionType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "transactionTypeKind", + "columnName": "transactionTypeKind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "netAmount", + "columnName": "netAmount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fee", + "columnName": "fee", + "affinity": "INTEGER" + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "firstSeen", + "columnName": "firstSeen", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "txid" + ] + }, + "indices": [ + { + "name": "index_transactions_firstSeen", + "unique": false, + "columnNames": [ + "firstSeen" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_transactions_firstSeen` ON `${TABLE_NAME}` (`firstSeen`)" + } + ] + }, + { + "tableName": "transaction_account_involvements", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`transactionTxid` BLOB NOT NULL, `accountId` INTEGER NOT NULL, PRIMARY KEY(`transactionTxid`, `accountId`), FOREIGN KEY(`transactionTxid`) REFERENCES `transactions`(`txid`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`accountId`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "transactionTxid", + "columnName": "transactionTxid", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "transactionTxid", + "accountId" + ] + }, + "indices": [ + { + "name": "index_transaction_account_involvements_accountId", + "unique": false, + "columnNames": [ + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_transaction_account_involvements_accountId` ON `${TABLE_NAME}` (`accountId`)" + } + ], + "foreignKeys": [ + { + "table": "transactions", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "transactionTxid" + ], + "referencedColumns": [ + "txid" + ] + }, + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "accountId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "txos", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`outpoint` BLOB NOT NULL, `vout` INTEGER NOT NULL, `amount` INTEGER NOT NULL, `address` TEXT NOT NULL, `scriptPubKey` BLOB NOT NULL, `height` INTEGER NOT NULL, `isCoinbase` INTEGER NOT NULL, `isConfirmed` INTEGER NOT NULL, `isInstantLocked` INTEGER NOT NULL, `isLocked` INTEGER NOT NULL, `isSpent` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `walletId` BLOB NOT NULL, `txid` BLOB, `spendingTxid` BLOB, `spendingInputIndex` INTEGER, `accountId` INTEGER, `coreAddressId` TEXT, `supersededByTxid` BLOB, PRIMARY KEY(`outpoint`), FOREIGN KEY(`txid`) REFERENCES `transactions`(`txid`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`spendingTxid`) REFERENCES `transactions`(`txid`) ON UPDATE NO ACTION ON DELETE SET NULL , FOREIGN KEY(`accountId`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL , FOREIGN KEY(`coreAddressId`) REFERENCES `core_addresses`(`address`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "outpoint", + "columnName": "outpoint", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "vout", + "columnName": "vout", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scriptPubKey", + "columnName": "scriptPubKey", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "height", + "columnName": "height", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isCoinbase", + "columnName": "isCoinbase", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isConfirmed", + "columnName": "isConfirmed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isInstantLocked", + "columnName": "isInstantLocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isLocked", + "columnName": "isLocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSpent", + "columnName": "isSpent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "BLOB" + }, + { + "fieldPath": "spendingTxid", + "columnName": "spendingTxid", + "affinity": "BLOB" + }, + { + "fieldPath": "spendingInputIndex", + "columnName": "spendingInputIndex", + "affinity": "INTEGER" + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "INTEGER" + }, + { + "fieldPath": "coreAddressId", + "columnName": "coreAddressId", + "affinity": "TEXT" + }, + { + "fieldPath": "supersededByTxid", + "columnName": "supersededByTxid", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "outpoint" + ] + }, + "indices": [ + { + "name": "index_txos_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_txos_walletId` ON `${TABLE_NAME}` (`walletId`)" + }, + { + "name": "index_txos_txid", + "unique": false, + "columnNames": [ + "txid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_txos_txid` ON `${TABLE_NAME}` (`txid`)" + }, + { + "name": "index_txos_spendingTxid", + "unique": false, + "columnNames": [ + "spendingTxid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_txos_spendingTxid` ON `${TABLE_NAME}` (`spendingTxid`)" + }, + { + "name": "index_txos_accountId", + "unique": false, + "columnNames": [ + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_txos_accountId` ON `${TABLE_NAME}` (`accountId`)" + }, + { + "name": "index_txos_coreAddressId", + "unique": false, + "columnNames": [ + "coreAddressId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_txos_coreAddressId` ON `${TABLE_NAME}` (`coreAddressId`)" + } + ], + "foreignKeys": [ + { + "table": "transactions", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "txid" + ], + "referencedColumns": [ + "txid" + ] + }, + { + "table": "transactions", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "spendingTxid" + ], + "referencedColumns": [ + "txid" + ] + }, + { + "table": "accounts", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "accountId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "core_addresses", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "coreAddressId" + ], + "referencedColumns": [ + "address" + ] + } + ] + }, + { + "tableName": "core_addresses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`address` TEXT NOT NULL, `publicKey` BLOB NOT NULL, `poolTypeTag` INTEGER NOT NULL, `addressIndex` INTEGER NOT NULL, `derivationPath` TEXT NOT NULL, `isUsed` INTEGER NOT NULL, `firstSeenHeight` INTEGER NOT NULL, `lastSeenHeight` INTEGER NOT NULL, `balance` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `accountId` INTEGER, PRIMARY KEY(`address`), FOREIGN KEY(`accountId`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "poolTypeTag", + "columnName": "poolTypeTag", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addressIndex", + "columnName": "addressIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUsed", + "columnName": "isUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "firstSeenHeight", + "columnName": "firstSeenHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSeenHeight", + "columnName": "lastSeenHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "balance", + "columnName": "balance", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "address" + ] + }, + "indices": [ + { + "name": "index_core_addresses_accountId", + "unique": false, + "columnNames": [ + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_core_addresses_accountId` ON `${TABLE_NAME}` (`accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "accountId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "asset_locks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`outPointHex` TEXT NOT NULL, `walletId` BLOB NOT NULL, `transactionBytes` BLOB NOT NULL, `fundingTypeRaw` INTEGER NOT NULL, `identityIndexRaw` INTEGER NOT NULL, `accountIndexRaw` INTEGER NOT NULL, `amountDuffs` INTEGER NOT NULL, `statusRaw` INTEGER NOT NULL, `proofBytes` BLOB, `recipientPlatformAddressHash` BLOB, `recipientPlatformAddressType` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`outPointHex`))", + "fields": [ + { + "fieldPath": "outPointHex", + "columnName": "outPointHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "transactionBytes", + "columnName": "transactionBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "fundingTypeRaw", + "columnName": "fundingTypeRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "identityIndexRaw", + "columnName": "identityIndexRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountIndexRaw", + "columnName": "accountIndexRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amountDuffs", + "columnName": "amountDuffs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "statusRaw", + "columnName": "statusRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "proofBytes", + "columnName": "proofBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "recipientPlatformAddressHash", + "columnName": "recipientPlatformAddressHash", + "affinity": "BLOB" + }, + { + "fieldPath": "recipientPlatformAddressType", + "columnName": "recipientPlatformAddressType", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "outPointHex" + ] + }, + "indices": [ + { + "name": "index_asset_locks_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_asset_locks_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, + { + "tableName": "invitations", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`outPointHex` TEXT NOT NULL, `rawOutPoint` BLOB NOT NULL, `walletId` BLOB NOT NULL, `fundingIndexRaw` INTEGER NOT NULL, `amountDuffs` INTEGER NOT NULL, `expiryUnix` INTEGER NOT NULL, `createdAtSecs` INTEGER NOT NULL, `hasInviter` INTEGER NOT NULL, `statusRaw` INTEGER NOT NULL, `reclaimInFlight` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`outPointHex`))", + "fields": [ + { + "fieldPath": "outPointHex", + "columnName": "outPointHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rawOutPoint", + "columnName": "rawOutPoint", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "fundingIndexRaw", + "columnName": "fundingIndexRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amountDuffs", + "columnName": "amountDuffs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "expiryUnix", + "columnName": "expiryUnix", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAtSecs", + "columnName": "createdAtSecs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasInviter", + "columnName": "hasInviter", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "statusRaw", + "columnName": "statusRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "reclaimInFlight", + "columnName": "reclaimInFlight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "outPointHex" + ] + }, + "indices": [ + { + "name": "index_invitations_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_invitations_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, + { + "tableName": "identities", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`identityId` BLOB NOT NULL, `balance` INTEGER NOT NULL, `revision` INTEGER NOT NULL, `isLocal` INTEGER NOT NULL, `alias` TEXT, `dpnsName` TEXT, `mainDpnsName` TEXT, `identityType` TEXT NOT NULL, `votingPrivateKeyIdentifier` TEXT, `ownerPrivateKeyIdentifier` TEXT, `payoutPrivateKeyIdentifier` TEXT, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `lastSyncedAt` INTEGER, `networkRaw` INTEGER NOT NULL, `walletId` BLOB, `identityIndex` INTEGER NOT NULL, PRIMARY KEY(`identityId`), FOREIGN KEY(`walletId`) REFERENCES `wallets`(`walletId`) ON UPDATE NO ACTION ON DELETE SET NULL )", + "fields": [ + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "balance", + "columnName": "balance", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "revision", + "columnName": "revision", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isLocal", + "columnName": "isLocal", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "alias", + "columnName": "alias", + "affinity": "TEXT" + }, + { + "fieldPath": "dpnsName", + "columnName": "dpnsName", + "affinity": "TEXT" + }, + { + "fieldPath": "mainDpnsName", + "columnName": "mainDpnsName", + "affinity": "TEXT" + }, + { + "fieldPath": "identityType", + "columnName": "identityType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "votingPrivateKeyIdentifier", + "columnName": "votingPrivateKeyIdentifier", + "affinity": "TEXT" + }, + { + "fieldPath": "ownerPrivateKeyIdentifier", + "columnName": "ownerPrivateKeyIdentifier", + "affinity": "TEXT" + }, + { + "fieldPath": "payoutPrivateKeyIdentifier", + "columnName": "payoutPrivateKeyIdentifier", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSyncedAt", + "columnName": "lastSyncedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB" + }, + { + "fieldPath": "identityIndex", + "columnName": "identityIndex", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "identityId" + ] + }, + "indices": [ + { + "name": "index_identities_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_identities_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + }, + { + "name": "index_identities_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_identities_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ], + "foreignKeys": [ + { + "table": "wallets", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "walletId" + ], + "referencedColumns": [ + "walletId" + ] + } + ] + }, + { + "tableName": "public_keys", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `keyId` INTEGER NOT NULL, `purpose` TEXT NOT NULL, `securityLevel` TEXT NOT NULL, `keyType` TEXT NOT NULL, `readOnly` INTEGER NOT NULL, `disabledAt` INTEGER, `totalBudget` INTEGER, `expiresAt` INTEGER, `publicKeyData` BLOB NOT NULL, `contractBoundsData` BLOB, `contractBoundsDocumentTypeName` TEXT, `contractBoundsKind` INTEGER, `privateKeyKeychainIdentifier` TEXT, `derivationIdentityIndex` INTEGER, `derivationKeyIndex` INTEGER, `identityId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `lastAccessed` INTEGER, `identityIdData` BLOB, FOREIGN KEY(`identityIdData`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keyId", + "columnName": "keyId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "securityLevel", + "columnName": "securityLevel", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyType", + "columnName": "keyType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "readOnly", + "columnName": "readOnly", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "disabledAt", + "columnName": "disabledAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "totalBudget", + "columnName": "totalBudget", + "affinity": "INTEGER" + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicKeyData", + "columnName": "publicKeyData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractBoundsData", + "columnName": "contractBoundsData", + "affinity": "BLOB" + }, + { + "fieldPath": "contractBoundsDocumentTypeName", + "columnName": "contractBoundsDocumentTypeName", + "affinity": "TEXT" + }, + { + "fieldPath": "contractBoundsKind", + "columnName": "contractBoundsKind", + "affinity": "INTEGER" + }, + { + "fieldPath": "privateKeyKeychainIdentifier", + "columnName": "privateKeyKeychainIdentifier", + "affinity": "TEXT" + }, + { + "fieldPath": "derivationIdentityIndex", + "columnName": "derivationIdentityIndex", + "affinity": "INTEGER" + }, + { + "fieldPath": "derivationKeyIndex", + "columnName": "derivationKeyIndex", + "affinity": "INTEGER" + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastAccessed", + "columnName": "lastAccessed", + "affinity": "INTEGER" + }, + { + "fieldPath": "identityIdData", + "columnName": "identityIdData", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_public_keys_identityId_keyId", + "unique": false, + "columnNames": [ + "identityId", + "keyId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_public_keys_identityId_keyId` ON `${TABLE_NAME}` (`identityId`, `keyId`)" + }, + { + "name": "index_public_keys_identityIdData", + "unique": false, + "columnNames": [ + "identityIdData" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_public_keys_identityIdData` ON `${TABLE_NAME}` (`identityIdData`)" + }, + { + "name": "index_public_keys_publicKeyData", + "unique": false, + "columnNames": [ + "publicKeyData" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_public_keys_publicKeyData` ON `${TABLE_NAME}` (`publicKeyData`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "identityIdData" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dpns_names", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `label` TEXT NOT NULL, `normalizedLabel` TEXT NOT NULL, `parentDomainName` TEXT NOT NULL, `normalizedParentDomainName` TEXT NOT NULL, `acquiredAt` INTEGER NOT NULL, `identityId` BLOB NOT NULL, `documentId` BLOB, `isOwned` INTEGER NOT NULL, `priceCredits` INTEGER, `saleStatusRaw` INTEGER NOT NULL, `counterpartyIdentityId` BLOB, `documentCreatedAtMs` INTEGER NOT NULL, `documentUpdatedAtMs` INTEGER NOT NULL, `documentTransferredAtMs` INTEGER NOT NULL, `marketplaceUpdatedAt` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `normalizedParentDomainName`, `normalizedLabel`), FOREIGN KEY(`identityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "normalizedLabel", + "columnName": "normalizedLabel", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentDomainName", + "columnName": "parentDomainName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "normalizedParentDomainName", + "columnName": "normalizedParentDomainName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "acquiredAt", + "columnName": "acquiredAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "documentId", + "columnName": "documentId", + "affinity": "BLOB" + }, + { + "fieldPath": "isOwned", + "columnName": "isOwned", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "priceCredits", + "columnName": "priceCredits", + "affinity": "INTEGER" + }, + { + "fieldPath": "saleStatusRaw", + "columnName": "saleStatusRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "counterpartyIdentityId", + "columnName": "counterpartyIdentityId", + "affinity": "BLOB" + }, + { + "fieldPath": "documentCreatedAtMs", + "columnName": "documentCreatedAtMs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentUpdatedAtMs", + "columnName": "documentUpdatedAtMs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentTransferredAtMs", + "columnName": "documentTransferredAtMs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "marketplaceUpdatedAt", + "columnName": "marketplaceUpdatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "normalizedParentDomainName", + "normalizedLabel" + ] + }, + "indices": [ + { + "name": "index_dpns_names_identityId", + "unique": false, + "columnNames": [ + "identityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dpns_names_identityId` ON `${TABLE_NAME}` (`identityId`)" + }, + { + "name": "index_dpns_names_documentId", + "unique": false, + "columnNames": [ + "documentId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dpns_names_documentId` ON `${TABLE_NAME}` (`documentId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "identityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dashpay_profiles", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `identityId` BLOB NOT NULL, `displayName` TEXT, `publicMessage` TEXT, `bio` TEXT, `avatarUrl` TEXT, `avatarHash` BLOB, `avatarFingerprint` BLOB, `corePaymentAddress` BLOB, `platformPaymentAddress` BLOB, `shieldedAddress` BLOB, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `identityId`), FOREIGN KEY(`identityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "publicMessage", + "columnName": "publicMessage", + "affinity": "TEXT" + }, + { + "fieldPath": "bio", + "columnName": "bio", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarHash", + "columnName": "avatarHash", + "affinity": "BLOB" + }, + { + "fieldPath": "avatarFingerprint", + "columnName": "avatarFingerprint", + "affinity": "BLOB" + }, + { + "fieldPath": "corePaymentAddress", + "columnName": "corePaymentAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "platformPaymentAddress", + "columnName": "platformPaymentAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "shieldedAddress", + "columnName": "shieldedAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "identityId" + ] + }, + "indices": [ + { + "name": "index_dashpay_profiles_identityId", + "unique": false, + "columnNames": [ + "identityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dashpay_profiles_identityId` ON `${TABLE_NAME}` (`identityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "identityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dashpay_contact_requests", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `ownerIdentityId` BLOB NOT NULL, `contactIdentityId` BLOB NOT NULL, `isOutgoing` INTEGER NOT NULL, `senderKeyIndex` INTEGER NOT NULL, `recipientKeyIndex` INTEGER NOT NULL, `accountReference` INTEGER NOT NULL, `encryptedPublicKey` BLOB NOT NULL, `encryptedAccountLabel` BLOB, `autoAcceptProof` BLOB, `coreHeightCreatedAt` INTEGER NOT NULL, `createdAtMillis` INTEGER NOT NULL, `paymentChannelBroken` INTEGER NOT NULL DEFAULT 0, `contactAlias` TEXT, `contactNote` TEXT, `contactHidden` INTEGER NOT NULL DEFAULT 0, `contactAccountLabel` TEXT, `contactAcceptedAccounts` BLOB, `externalAccountReference` INTEGER, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `ownerIdentityId`, `contactIdentityId`, `isOutgoing`), FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contactIdentityId", + "columnName": "contactIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "isOutgoing", + "columnName": "isOutgoing", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderKeyIndex", + "columnName": "senderKeyIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientKeyIndex", + "columnName": "recipientKeyIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountReference", + "columnName": "accountReference", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encryptedPublicKey", + "columnName": "encryptedPublicKey", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "encryptedAccountLabel", + "columnName": "encryptedAccountLabel", + "affinity": "BLOB" + }, + { + "fieldPath": "autoAcceptProof", + "columnName": "autoAcceptProof", + "affinity": "BLOB" + }, + { + "fieldPath": "coreHeightCreatedAt", + "columnName": "coreHeightCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAtMillis", + "columnName": "createdAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "paymentChannelBroken", + "columnName": "paymentChannelBroken", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "contactAlias", + "columnName": "contactAlias", + "affinity": "TEXT" + }, + { + "fieldPath": "contactNote", + "columnName": "contactNote", + "affinity": "TEXT" + }, + { + "fieldPath": "contactHidden", + "columnName": "contactHidden", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "contactAccountLabel", + "columnName": "contactAccountLabel", + "affinity": "TEXT" + }, + { + "fieldPath": "contactAcceptedAccounts", + "columnName": "contactAcceptedAccounts", + "affinity": "BLOB" + }, + { + "fieldPath": "externalAccountReference", + "columnName": "externalAccountReference", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "ownerIdentityId", + "contactIdentityId", + "isOutgoing" + ] + }, + "indices": [ + { + "name": "index_dashpay_contact_requests_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dashpay_contact_requests_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dashpay_ignored_senders", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `ownerIdentityId` BLOB NOT NULL, `ignoredSenderId` BLOB NOT NULL, `ignoredAt` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `ownerIdentityId`, `ignoredSenderId`), FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ignoredSenderId", + "columnName": "ignoredSenderId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ignoredAt", + "columnName": "ignoredAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "ownerIdentityId", + "ignoredSenderId" + ] + }, + "indices": [ + { + "name": "index_dashpay_ignored_senders_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dashpay_ignored_senders_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dashpay_contact_profiles", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `ownerIdentityId` BLOB NOT NULL, `contactIdentityId` BLOB NOT NULL, `displayName` TEXT, `publicMessage` TEXT, `bio` TEXT, `avatarUrl` TEXT, `avatarHash` BLOB, `avatarFingerprint` BLOB, `corePaymentAddress` BLOB, `platformPaymentAddress` BLOB, `shieldedAddress` BLOB, `checkedAtMs` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `ownerIdentityId`, `contactIdentityId`), FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contactIdentityId", + "columnName": "contactIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "publicMessage", + "columnName": "publicMessage", + "affinity": "TEXT" + }, + { + "fieldPath": "bio", + "columnName": "bio", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarHash", + "columnName": "avatarHash", + "affinity": "BLOB" + }, + { + "fieldPath": "avatarFingerprint", + "columnName": "avatarFingerprint", + "affinity": "BLOB" + }, + { + "fieldPath": "corePaymentAddress", + "columnName": "corePaymentAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "platformPaymentAddress", + "columnName": "platformPaymentAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "shieldedAddress", + "columnName": "shieldedAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "checkedAtMs", + "columnName": "checkedAtMs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "ownerIdentityId", + "contactIdentityId" + ] + }, + "indices": [ + { + "name": "index_dashpay_contact_profiles_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dashpay_contact_profiles_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dashpay_payments", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `ownerIdentityId` BLOB NOT NULL, `counterpartyIdentityId` BLOB NOT NULL, `amountDuffs` INTEGER NOT NULL, `directionRaw` INTEGER NOT NULL, `statusRaw` INTEGER NOT NULL, `txid` TEXT NOT NULL, `memo` TEXT, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `ownerIdentityId`, `txid`), FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "counterpartyIdentityId", + "columnName": "counterpartyIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "amountDuffs", + "columnName": "amountDuffs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "directionRaw", + "columnName": "directionRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "statusRaw", + "columnName": "statusRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "memo", + "columnName": "memo", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "ownerIdentityId", + "txid" + ] + }, + "indices": [ + { + "name": "index_dashpay_payments_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dashpay_payments_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "data_contracts", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` BLOB NOT NULL, `name` TEXT NOT NULL, `serializedContract` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `lastAccessedAt` INTEGER NOT NULL, `binarySerialization` BLOB, `version` INTEGER, `ownerId` BLOB, `contractDescription` TEXT, `schemaData` BLOB NOT NULL, `documentTypesData` BLOB NOT NULL, `groupsData` BLOB, `networkRaw` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `lastSyncedAt` INTEGER, `canBeDeleted` INTEGER NOT NULL, `readonly` INTEGER NOT NULL, `keepsHistory` INTEGER NOT NULL, `schemaDefs` INTEGER, `documentsKeepHistoryContractDefault` INTEGER NOT NULL, `documentsMutableContractDefault` INTEGER NOT NULL, `documentsCanBeDeletedContractDefault` INTEGER NOT NULL, `hasTokens` INTEGER NOT NULL, `tokensData` BLOB, `ownerIdentityId` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE SET NULL )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "serializedContract", + "columnName": "serializedContract", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastAccessedAt", + "columnName": "lastAccessedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "binarySerialization", + "columnName": "binarySerialization", + "affinity": "BLOB" + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER" + }, + { + "fieldPath": "ownerId", + "columnName": "ownerId", + "affinity": "BLOB" + }, + { + "fieldPath": "contractDescription", + "columnName": "contractDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "schemaData", + "columnName": "schemaData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "documentTypesData", + "columnName": "documentTypesData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "groupsData", + "columnName": "groupsData", + "affinity": "BLOB" + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSyncedAt", + "columnName": "lastSyncedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "canBeDeleted", + "columnName": "canBeDeleted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "readonly", + "columnName": "readonly", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsHistory", + "columnName": "keepsHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "schemaDefs", + "columnName": "schemaDefs", + "affinity": "INTEGER" + }, + { + "fieldPath": "documentsKeepHistoryContractDefault", + "columnName": "documentsKeepHistoryContractDefault", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentsMutableContractDefault", + "columnName": "documentsMutableContractDefault", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentsCanBeDeletedContractDefault", + "columnName": "documentsCanBeDeletedContractDefault", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasTokens", + "columnName": "hasTokens", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tokensData", + "columnName": "tokensData", + "affinity": "BLOB" + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_data_contracts_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_data_contracts_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + }, + { + "name": "index_data_contracts_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_data_contracts_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "document_types", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` BLOB NOT NULL, `contractId` BLOB NOT NULL, `name` TEXT NOT NULL, `schemaJSON` BLOB NOT NULL, `propertiesJSON` BLOB NOT NULL, `documentsKeepHistory` INTEGER NOT NULL, `documentsMutable` INTEGER NOT NULL, `documentsCanBeDeleted` INTEGER NOT NULL, `documentsTransferable` INTEGER NOT NULL, `requiredFieldsJSON` BLOB, `securityLevel` INTEGER NOT NULL, `tradeMode` INTEGER NOT NULL, `creationRestrictionMode` INTEGER NOT NULL, `requiresIdentityEncryptionBoundedKey` INTEGER NOT NULL, `requiresIdentityDecryptionBoundedKey` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastAccessedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`contractId`) REFERENCES `data_contracts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "schemaJSON", + "columnName": "schemaJSON", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "propertiesJSON", + "columnName": "propertiesJSON", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "documentsKeepHistory", + "columnName": "documentsKeepHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentsMutable", + "columnName": "documentsMutable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentsCanBeDeleted", + "columnName": "documentsCanBeDeleted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentsTransferable", + "columnName": "documentsTransferable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "requiredFieldsJSON", + "columnName": "requiredFieldsJSON", + "affinity": "BLOB" + }, + { + "fieldPath": "securityLevel", + "columnName": "securityLevel", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tradeMode", + "columnName": "tradeMode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "creationRestrictionMode", + "columnName": "creationRestrictionMode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "requiresIdentityEncryptionBoundedKey", + "columnName": "requiresIdentityEncryptionBoundedKey", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "requiresIdentityDecryptionBoundedKey", + "columnName": "requiresIdentityDecryptionBoundedKey", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastAccessedAt", + "columnName": "lastAccessedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_document_types_contractId", + "unique": false, + "columnNames": [ + "contractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_document_types_contractId` ON `${TABLE_NAME}` (`contractId`)" + } + ], + "foreignKeys": [ + { + "table": "data_contracts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "contractId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "documents", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`documentId` TEXT NOT NULL, `documentType` TEXT NOT NULL, `revision` INTEGER NOT NULL, `data` BLOB NOT NULL, `contractId` TEXT NOT NULL, `ownerId` TEXT NOT NULL, `contractIdData` BLOB NOT NULL, `ownerIdData` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `transferredAt` INTEGER, `createdAtBlockHeight` INTEGER, `updatedAtBlockHeight` INTEGER, `transferredAtBlockHeight` INTEGER, `createdAtCoreBlockHeight` INTEGER, `updatedAtCoreBlockHeight` INTEGER, `transferredAtCoreBlockHeight` INTEGER, `networkRaw` INTEGER NOT NULL, `isDeleted` INTEGER NOT NULL, `localCreatedAt` INTEGER NOT NULL, `localUpdatedAt` INTEGER NOT NULL, `documentTypeRelationId` BLOB, `dataContractId` BLOB, `ownerIdentityId` BLOB, PRIMARY KEY(`documentId`), FOREIGN KEY(`documentTypeRelationId`) REFERENCES `document_types`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`dataContractId`) REFERENCES `data_contracts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "documentId", + "columnName": "documentId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "documentType", + "columnName": "documentType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "revision", + "columnName": "revision", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "data", + "columnName": "data", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerId", + "columnName": "ownerId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "contractIdData", + "columnName": "contractIdData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ownerIdData", + "columnName": "ownerIdData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "transferredAt", + "columnName": "transferredAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAtBlockHeight", + "columnName": "createdAtBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "updatedAtBlockHeight", + "columnName": "updatedAtBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "transferredAtBlockHeight", + "columnName": "transferredAtBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAtCoreBlockHeight", + "columnName": "createdAtCoreBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "updatedAtCoreBlockHeight", + "columnName": "updatedAtCoreBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "transferredAtCoreBlockHeight", + "columnName": "transferredAtCoreBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isDeleted", + "columnName": "isDeleted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "localCreatedAt", + "columnName": "localCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "localUpdatedAt", + "columnName": "localUpdatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentTypeRelationId", + "columnName": "documentTypeRelationId", + "affinity": "BLOB" + }, + { + "fieldPath": "dataContractId", + "columnName": "dataContractId", + "affinity": "BLOB" + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "documentId" + ] + }, + "indices": [ + { + "name": "index_documents_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + }, + { + "name": "index_documents_contractId", + "unique": false, + "columnNames": [ + "contractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_contractId` ON `${TABLE_NAME}` (`contractId`)" + }, + { + "name": "index_documents_ownerId", + "unique": false, + "columnNames": [ + "ownerId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_ownerId` ON `${TABLE_NAME}` (`ownerId`)" + }, + { + "name": "index_documents_documentTypeRelationId", + "unique": false, + "columnNames": [ + "documentTypeRelationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_documentTypeRelationId` ON `${TABLE_NAME}` (`documentTypeRelationId`)" + }, + { + "name": "index_documents_dataContractId", + "unique": false, + "columnNames": [ + "dataContractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_dataContractId` ON `${TABLE_NAME}` (`dataContractId`)" + }, + { + "name": "index_documents_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "document_types", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "documentTypeRelationId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "data_contracts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dataContractId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "indices", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` BLOB NOT NULL, `contractId` BLOB NOT NULL, `documentTypeName` TEXT NOT NULL, `name` TEXT NOT NULL, `unique` INTEGER NOT NULL, `nullSearchable` INTEGER NOT NULL, `contested` INTEGER NOT NULL, `propertiesJSON` BLOB NOT NULL, `contestedDetailsJSON` BLOB, `createdAt` INTEGER NOT NULL, `documentTypeId` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`documentTypeId`) REFERENCES `document_types`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "documentTypeName", + "columnName": "documentTypeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unique", + "columnName": "unique", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nullSearchable", + "columnName": "nullSearchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "contested", + "columnName": "contested", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "propertiesJSON", + "columnName": "propertiesJSON", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contestedDetailsJSON", + "columnName": "contestedDetailsJSON", + "affinity": "BLOB" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentTypeId", + "columnName": "documentTypeId", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_indices_documentTypeId", + "unique": false, + "columnNames": [ + "documentTypeId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_indices_documentTypeId` ON `${TABLE_NAME}` (`documentTypeId`)" + } + ], + "foreignKeys": [ + { + "table": "document_types", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "documentTypeId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "keywords", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `keyword` TEXT NOT NULL, `contractId` TEXT NOT NULL, `dataContractId` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`dataContractId`) REFERENCES `data_contracts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyword", + "columnName": "keyword", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dataContractId", + "columnName": "dataContractId", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_keywords_contractId", + "unique": false, + "columnNames": [ + "contractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_keywords_contractId` ON `${TABLE_NAME}` (`contractId`)" + }, + { + "name": "index_keywords_dataContractId", + "unique": false, + "columnNames": [ + "dataContractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_keywords_dataContractId` ON `${TABLE_NAME}` (`dataContractId`)" + } + ], + "foreignKeys": [ + { + "table": "data_contracts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dataContractId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "properties", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` BLOB NOT NULL, `contractId` BLOB NOT NULL, `documentTypeName` TEXT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `format` TEXT, `contentMediaType` TEXT, `byteArray` INTEGER NOT NULL, `minItems` INTEGER, `maxItems` INTEGER, `pattern` TEXT, `minLength` INTEGER, `maxLength` INTEGER, `minValue` INTEGER, `maxValue` INTEGER, `fieldDescription` TEXT, `transient` INTEGER NOT NULL, `isRequired` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `documentTypeId` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`documentTypeId`) REFERENCES `document_types`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "documentTypeName", + "columnName": "documentTypeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "format", + "columnName": "format", + "affinity": "TEXT" + }, + { + "fieldPath": "contentMediaType", + "columnName": "contentMediaType", + "affinity": "TEXT" + }, + { + "fieldPath": "byteArray", + "columnName": "byteArray", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "minItems", + "columnName": "minItems", + "affinity": "INTEGER" + }, + { + "fieldPath": "maxItems", + "columnName": "maxItems", + "affinity": "INTEGER" + }, + { + "fieldPath": "pattern", + "columnName": "pattern", + "affinity": "TEXT" + }, + { + "fieldPath": "minLength", + "columnName": "minLength", + "affinity": "INTEGER" + }, + { + "fieldPath": "maxLength", + "columnName": "maxLength", + "affinity": "INTEGER" + }, + { + "fieldPath": "minValue", + "columnName": "minValue", + "affinity": "INTEGER" + }, + { + "fieldPath": "maxValue", + "columnName": "maxValue", + "affinity": "INTEGER" + }, + { + "fieldPath": "fieldDescription", + "columnName": "fieldDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "transient", + "columnName": "transient", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isRequired", + "columnName": "isRequired", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentTypeId", + "columnName": "documentTypeId", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_properties_documentTypeId", + "unique": false, + "columnNames": [ + "documentTypeId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_properties_documentTypeId` ON `${TABLE_NAME}` (`documentTypeId`)" + } + ], + "foreignKeys": [ + { + "table": "document_types", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "documentTypeId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "pending_inputs", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `outpoint` BLOB NOT NULL, `inputIndex` INTEGER NOT NULL, `spendingTxid` BLOB NOT NULL, `spendingTransactionTxid` BLOB, `walletId` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `isSweptTombstone` INTEGER NOT NULL DEFAULT 0, `winnerMinedHeight` INTEGER, FOREIGN KEY(`spendingTransactionTxid`) REFERENCES `transactions`(`txid`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "outpoint", + "columnName": "outpoint", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "inputIndex", + "columnName": "inputIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "spendingTxid", + "columnName": "spendingTxid", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "spendingTransactionTxid", + "columnName": "spendingTransactionTxid", + "affinity": "BLOB" + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSweptTombstone", + "columnName": "isSweptTombstone", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "winnerMinedHeight", + "columnName": "winnerMinedHeight", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_pending_inputs_outpoint", + "unique": false, + "columnNames": [ + "outpoint" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_pending_inputs_outpoint` ON `${TABLE_NAME}` (`outpoint`)" + }, + { + "name": "index_pending_inputs_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_pending_inputs_walletId` ON `${TABLE_NAME}` (`walletId`)" + }, + { + "name": "index_pending_inputs_spendingTransactionTxid", + "unique": false, + "columnNames": [ + "spendingTransactionTxid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_pending_inputs_spendingTransactionTxid` ON `${TABLE_NAME}` (`spendingTransactionTxid`)" + }, + { + "name": "index_pending_inputs_spendingTxid", + "unique": false, + "columnNames": [ + "spendingTxid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_pending_inputs_spendingTxid` ON `${TABLE_NAME}` (`spendingTxid`)" + }, + { + "name": "index_pending_inputs_walletId_isSweptTombstone_winnerMinedHeight", + "unique": false, + "columnNames": [ + "walletId", + "isSweptTombstone", + "winnerMinedHeight" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_pending_inputs_walletId_isSweptTombstone_winnerMinedHeight` ON `${TABLE_NAME}` (`walletId`, `isSweptTombstone`, `winnerMinedHeight`)" + } + ], + "foreignKeys": [ + { + "table": "transactions", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "spendingTransactionTxid" + ], + "referencedColumns": [ + "txid" + ] + } + ] + }, + { + "tableName": "tokens", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` BLOB NOT NULL, `contractId` BLOB NOT NULL, `position` INTEGER NOT NULL, `name` TEXT NOT NULL, `baseSupply` TEXT NOT NULL, `maxSupply` TEXT, `decimals` INTEGER NOT NULL, `localizations` TEXT, `isPaused` INTEGER NOT NULL, `allowTransferToFrozenBalance` INTEGER NOT NULL, `keepsTransferHistory` INTEGER NOT NULL, `keepsFreezingHistory` INTEGER NOT NULL, `keepsMintingHistory` INTEGER NOT NULL, `keepsBurningHistory` INTEGER NOT NULL, `keepsDirectPricingHistory` INTEGER NOT NULL, `keepsDirectPurchaseHistory` INTEGER NOT NULL, `conventionsChangeRules` TEXT, `maxSupplyChangeRules` TEXT, `manualMintingRules` TEXT, `manualBurningRules` TEXT, `freezeRules` TEXT, `unfreezeRules` TEXT, `destroyFrozenFundsRules` TEXT, `emergencyActionRules` TEXT, `perpetualDistribution` TEXT, `preProgrammedDistribution` TEXT, `oncePerIdentityDistribution` TEXT, `newTokensDestinationIdentity` BLOB, `mintingAllowChoosingDestination` INTEGER NOT NULL, `distributionChangeRules` TEXT, `tradeMode` TEXT NOT NULL, `tradeModeChangeRules` TEXT, `mainControlGroupPosition` INTEGER, `mainControlGroupCanBeModified` TEXT, `tokenDescription` TEXT, `createdAt` INTEGER NOT NULL, `lastUpdatedAt` INTEGER NOT NULL, `canManuallyMint` INTEGER NOT NULL, `canManuallyBurn` INTEGER NOT NULL, `canFreeze` INTEGER NOT NULL, `canUnfreeze` INTEGER NOT NULL, `canDestroyFrozenFunds` INTEGER NOT NULL, `hasEmergencyActions` INTEGER NOT NULL, `canChangeMaxSupply` INTEGER NOT NULL, `canChangeConventions` INTEGER NOT NULL, `canChangeTradeMode` INTEGER NOT NULL, `hasDistribution` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`contractId`) REFERENCES `data_contracts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseSupply", + "columnName": "baseSupply", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "maxSupply", + "columnName": "maxSupply", + "affinity": "TEXT" + }, + { + "fieldPath": "decimals", + "columnName": "decimals", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "localizations", + "columnName": "localizations", + "affinity": "TEXT" + }, + { + "fieldPath": "isPaused", + "columnName": "isPaused", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "allowTransferToFrozenBalance", + "columnName": "allowTransferToFrozenBalance", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsTransferHistory", + "columnName": "keepsTransferHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsFreezingHistory", + "columnName": "keepsFreezingHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsMintingHistory", + "columnName": "keepsMintingHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsBurningHistory", + "columnName": "keepsBurningHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsDirectPricingHistory", + "columnName": "keepsDirectPricingHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsDirectPurchaseHistory", + "columnName": "keepsDirectPurchaseHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "conventionsChangeRules", + "columnName": "conventionsChangeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "maxSupplyChangeRules", + "columnName": "maxSupplyChangeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "manualMintingRules", + "columnName": "manualMintingRules", + "affinity": "TEXT" + }, + { + "fieldPath": "manualBurningRules", + "columnName": "manualBurningRules", + "affinity": "TEXT" + }, + { + "fieldPath": "freezeRules", + "columnName": "freezeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "unfreezeRules", + "columnName": "unfreezeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "destroyFrozenFundsRules", + "columnName": "destroyFrozenFundsRules", + "affinity": "TEXT" + }, + { + "fieldPath": "emergencyActionRules", + "columnName": "emergencyActionRules", + "affinity": "TEXT" + }, + { + "fieldPath": "perpetualDistribution", + "columnName": "perpetualDistribution", + "affinity": "TEXT" + }, + { + "fieldPath": "preProgrammedDistribution", + "columnName": "preProgrammedDistribution", + "affinity": "TEXT" + }, + { + "fieldPath": "oncePerIdentityDistribution", + "columnName": "oncePerIdentityDistribution", + "affinity": "TEXT" + }, + { + "fieldPath": "newTokensDestinationIdentity", + "columnName": "newTokensDestinationIdentity", + "affinity": "BLOB" + }, + { + "fieldPath": "mintingAllowChoosingDestination", + "columnName": "mintingAllowChoosingDestination", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "distributionChangeRules", + "columnName": "distributionChangeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "tradeMode", + "columnName": "tradeMode", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tradeModeChangeRules", + "columnName": "tradeModeChangeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "mainControlGroupPosition", + "columnName": "mainControlGroupPosition", + "affinity": "INTEGER" + }, + { + "fieldPath": "mainControlGroupCanBeModified", + "columnName": "mainControlGroupCanBeModified", + "affinity": "TEXT" + }, + { + "fieldPath": "tokenDescription", + "columnName": "tokenDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdatedAt", + "columnName": "lastUpdatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canManuallyMint", + "columnName": "canManuallyMint", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canManuallyBurn", + "columnName": "canManuallyBurn", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canFreeze", + "columnName": "canFreeze", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canUnfreeze", + "columnName": "canUnfreeze", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canDestroyFrozenFunds", + "columnName": "canDestroyFrozenFunds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasEmergencyActions", + "columnName": "hasEmergencyActions", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canChangeMaxSupply", + "columnName": "canChangeMaxSupply", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canChangeConventions", + "columnName": "canChangeConventions", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canChangeTradeMode", + "columnName": "canChangeTradeMode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasDistribution", + "columnName": "hasDistribution", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_tokens_contractId", + "unique": false, + "columnNames": [ + "contractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_tokens_contractId` ON `${TABLE_NAME}` (`contractId`)" + } + ], + "foreignKeys": [ + { + "table": "data_contracts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "contractId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "token_balances", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `tokenId` TEXT NOT NULL, `identityId` BLOB NOT NULL, `balance` BLOB NOT NULL, `frozen` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `lastSyncedAt` INTEGER, `tokenName` TEXT, `tokenSymbol` TEXT, `tokenDecimals` INTEGER, `networkRaw` INTEGER NOT NULL, `identityRef` BLOB, `tokenRef` BLOB, FOREIGN KEY(`identityRef`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE SET NULL , FOREIGN KEY(`tokenRef`) REFERENCES `tokens`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tokenId", + "columnName": "tokenId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "balance", + "columnName": "balance", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "frozen", + "columnName": "frozen", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSyncedAt", + "columnName": "lastSyncedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "tokenName", + "columnName": "tokenName", + "affinity": "TEXT" + }, + { + "fieldPath": "tokenSymbol", + "columnName": "tokenSymbol", + "affinity": "TEXT" + }, + { + "fieldPath": "tokenDecimals", + "columnName": "tokenDecimals", + "affinity": "INTEGER" + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "identityRef", + "columnName": "identityRef", + "affinity": "BLOB" + }, + { + "fieldPath": "tokenRef", + "columnName": "tokenRef", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_token_balances_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_balances_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + }, + { + "name": "index_token_balances_tokenId_identityId", + "unique": false, + "columnNames": [ + "tokenId", + "identityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_balances_tokenId_identityId` ON `${TABLE_NAME}` (`tokenId`, `identityId`)" + }, + { + "name": "index_token_balances_identityId", + "unique": false, + "columnNames": [ + "identityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_balances_identityId` ON `${TABLE_NAME}` (`identityId`)" + }, + { + "name": "index_token_balances_identityRef", + "unique": false, + "columnNames": [ + "identityRef" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_balances_identityRef` ON `${TABLE_NAME}` (`identityRef`)" + }, + { + "name": "index_token_balances_tokenRef", + "unique": false, + "columnNames": [ + "tokenRef" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_balances_tokenRef` ON `${TABLE_NAME}` (`tokenRef`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "identityRef" + ], + "referencedColumns": [ + "identityId" + ] + }, + { + "table": "tokens", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "tokenRef" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "token_history_events", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `eventType` TEXT NOT NULL, `transactionId` BLOB, `blockHeight` INTEGER, `coreBlockHeight` INTEGER, `fromIdentity` BLOB, `toIdentity` BLOB, `performedByIdentity` BLOB NOT NULL, `amount` TEXT, `balanceBefore` TEXT, `balanceAfter` TEXT, `additionalDataJSON` BLOB, `eventDescription` TEXT, `createdAt` INTEGER NOT NULL, `eventTimestamp` INTEGER NOT NULL, `tokenRef` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`tokenRef`) REFERENCES `tokens`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventType", + "columnName": "eventType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "transactionId", + "columnName": "transactionId", + "affinity": "BLOB" + }, + { + "fieldPath": "blockHeight", + "columnName": "blockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "coreBlockHeight", + "columnName": "coreBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "fromIdentity", + "columnName": "fromIdentity", + "affinity": "BLOB" + }, + { + "fieldPath": "toIdentity", + "columnName": "toIdentity", + "affinity": "BLOB" + }, + { + "fieldPath": "performedByIdentity", + "columnName": "performedByIdentity", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "TEXT" + }, + { + "fieldPath": "balanceBefore", + "columnName": "balanceBefore", + "affinity": "TEXT" + }, + { + "fieldPath": "balanceAfter", + "columnName": "balanceAfter", + "affinity": "TEXT" + }, + { + "fieldPath": "additionalDataJSON", + "columnName": "additionalDataJSON", + "affinity": "BLOB" + }, + { + "fieldPath": "eventDescription", + "columnName": "eventDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventTimestamp", + "columnName": "eventTimestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tokenRef", + "columnName": "tokenRef", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_token_history_events_tokenRef", + "unique": false, + "columnNames": [ + "tokenRef" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_history_events_tokenRef` ON `${TABLE_NAME}` (`tokenRef`)" + } + ], + "foreignKeys": [ + { + "table": "tokens", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "tokenRef" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "platform_addresses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`address` TEXT NOT NULL, `addressType` INTEGER NOT NULL, `addressHash` BLOB NOT NULL, `publicKey` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `addressIndex` INTEGER NOT NULL, `derivationPath` TEXT NOT NULL, `isUsed` INTEGER NOT NULL, `balance` INTEGER NOT NULL, `nonce` INTEGER NOT NULL, `firstSeenHeight` INTEGER NOT NULL, `lastSeenHeight` INTEGER NOT NULL, `walletId` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `accountId` INTEGER, PRIMARY KEY(`walletId`, `address`), FOREIGN KEY(`accountId`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addressType", + "columnName": "addressType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addressHash", + "columnName": "addressHash", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addressIndex", + "columnName": "addressIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUsed", + "columnName": "isUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "balance", + "columnName": "balance", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nonce", + "columnName": "nonce", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "firstSeenHeight", + "columnName": "firstSeenHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSeenHeight", + "columnName": "lastSeenHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "address" + ] + }, + "indices": [ + { + "name": "index_platform_addresses_walletId_addressHash", + "unique": true, + "columnNames": [ + "walletId", + "addressHash" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_platform_addresses_walletId_addressHash` ON `${TABLE_NAME}` (`walletId`, `addressHash`)" + }, + { + "name": "index_platform_addresses_accountId", + "unique": false, + "columnNames": [ + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_platform_addresses_accountId` ON `${TABLE_NAME}` (`accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "accountId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "platform_addresses_sync_states", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `networkRaw` INTEGER NOT NULL, `syncHeight` INTEGER NOT NULL, `syncTimestamp` INTEGER NOT NULL, `lastKnownRecentBlock` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "syncHeight", + "columnName": "syncHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "syncTimestamp", + "columnName": "syncTimestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastKnownRecentBlock", + "columnName": "lastKnownRecentBlock", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId" + ] + }, + "indices": [ + { + "name": "index_platform_addresses_sync_states_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_platform_addresses_sync_states_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + } + ] + }, + { + "tableName": "shielded_notes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`nullifier` BLOB NOT NULL, `walletId` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `position` INTEGER NOT NULL, `cmx` BLOB NOT NULL, `blockHeight` INTEGER NOT NULL, `isSpent` INTEGER NOT NULL, `value` INTEGER NOT NULL, `noteData` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`nullifier`))", + "fields": [ + { + "fieldPath": "nullifier", + "columnName": "nullifier", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cmx", + "columnName": "cmx", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "blockHeight", + "columnName": "blockHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSpent", + "columnName": "isSpent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "noteData", + "columnName": "noteData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "nullifier" + ] + }, + "indices": [ + { + "name": "index_shielded_notes_walletId_accountIndex", + "unique": false, + "columnNames": [ + "walletId", + "accountIndex" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_shielded_notes_walletId_accountIndex` ON `${TABLE_NAME}` (`walletId`, `accountIndex`)" + } + ] + }, + { + "tableName": "shielded_outgoing_notes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `cmx` BLOB NOT NULL, `recipient` BLOB NOT NULL, `value` INTEGER NOT NULL, `memo` BLOB NOT NULL, `blockHeight` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`, `accountIndex`, `cmx`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cmx", + "columnName": "cmx", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "recipient", + "columnName": "recipient", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memo", + "columnName": "memo", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "blockHeight", + "columnName": "blockHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "accountIndex", + "cmx" + ] + }, + "indices": [ + { + "name": "index_shielded_outgoing_notes_walletId_accountIndex", + "unique": false, + "columnNames": [ + "walletId", + "accountIndex" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_shielded_outgoing_notes_walletId_accountIndex` ON `${TABLE_NAME}` (`walletId`, `accountIndex`)" + } + ] + }, + { + "tableName": "shielded_activities", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `entryId` BLOB NOT NULL, `kindTag` INTEGER NOT NULL, `direction` INTEGER NOT NULL, `status` INTEGER NOT NULL, `amount` INTEGER NOT NULL, `fee` INTEGER NOT NULL, `hasFee` INTEGER NOT NULL, `blockHeight` INTEGER NOT NULL, `hasBlockHeight` INTEGER NOT NULL, `createdAtMs` INTEGER NOT NULL, `identityId` BLOB NOT NULL, `counterparty` BLOB NOT NULL, `memo` BLOB NOT NULL, `noteCmxs` BLOB NOT NULL, `spentNullifiers` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`, `accountIndex`, `entryId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "entryId", + "columnName": "entryId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "kindTag", + "columnName": "kindTag", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "direction", + "columnName": "direction", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fee", + "columnName": "fee", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasFee", + "columnName": "hasFee", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "blockHeight", + "columnName": "blockHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasBlockHeight", + "columnName": "hasBlockHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAtMs", + "columnName": "createdAtMs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "counterparty", + "columnName": "counterparty", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "memo", + "columnName": "memo", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "noteCmxs", + "columnName": "noteCmxs", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "spentNullifiers", + "columnName": "spentNullifiers", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "accountIndex", + "entryId" + ] + }, + "indices": [ + { + "name": "index_shielded_activities_walletId_accountIndex", + "unique": false, + "columnNames": [ + "walletId", + "accountIndex" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_shielded_activities_walletId_accountIndex` ON `${TABLE_NAME}` (`walletId`, `accountIndex`)" + } + ] + }, + { + "tableName": "shielded_sync_states", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `lastSyncedIndex` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`, `accountIndex`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSyncedIndex", + "columnName": "lastSyncedIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "accountIndex" + ] + }, + "indices": [ + { + "name": "index_shielded_sync_states_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_shielded_sync_states_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, + { + "tableName": "shielded_viewing_keys", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `fvkBytes` BLOB NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`, `accountIndex`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fvkBytes", + "columnName": "fvkBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "accountIndex" + ] + }, + "indices": [ + { + "name": "index_shielded_viewing_keys_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_shielded_viewing_keys_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, + { + "tableName": "wallet_manager_metadata", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `combinedSyncHeight` INTEGER NOT NULL, `combinedSyncBlockHash` BLOB, `walletCount` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`))", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "combinedSyncHeight", + "columnName": "combinedSyncHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "combinedSyncBlockHash", + "columnName": "combinedSyncBlockHash", + "affinity": "BLOB" + }, + { + "fieldPath": "walletCount", + "columnName": "walletCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw" + ] + } + }, + { + "tableName": "private_contact_requests_positions", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `identityId` BLOB NOT NULL, `position` INTEGER NOT NULL, `keyFingerprint` BLOB NOT NULL, `privatePaymentsUnresolved` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`walletId`, `identityId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keyFingerprint", + "columnName": "keyFingerprint", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "privatePaymentsUnresolved", + "columnName": "privatePaymentsUnresolved", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "identityId" + ] + } + }, + { + "tableName": "private_shielded_addresses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `ownerId` BLOB NOT NULL, `contactId` BLOB NOT NULL, `address` BLOB NOT NULL, PRIMARY KEY(`walletId`, `ownerId`, `contactId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ownerId", + "columnName": "ownerId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contactId", + "columnName": "contactId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "address", + "columnName": "address", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "ownerId", + "contactId" + ] + } + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'aa58da0a7ca53a564b0a4a9bf012000b')" + ] + } +} \ No newline at end of file diff --git a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseMigrationTest.kt b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseMigrationTest.kt index 19797f2678a..704e2ed2954 100644 --- a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseMigrationTest.kt +++ b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseMigrationTest.kt @@ -28,6 +28,65 @@ class DashDatabaseMigrationTest { private val dbName = "migration-test.db" + @Test + fun migrate16To17PreservesProfilesAndSweepState() { + migrateProfilesAndSweepState(16) + } + + @Test + fun migrate10To17PreservesProfilesThroughEveryMigration() { + migrateProfilesAndSweepState(10) + } + + private fun migrateProfilesAndSweepState(fromVersion: Int) { + helper.createDatabase(dbName, fromVersion).apply { + execSQL("INSERT INTO identities (identityId, balance, revision, isLocal, identityType, createdAt, lastUpdated, networkRaw, identityIndex) VALUES (x'0A', 0, 0, 1, 'User', 0, 0, 1, 0)") + execSQL("INSERT INTO dashpay_profiles (networkRaw, identityId, displayName, createdAt, lastUpdated) VALUES (1, x'0A', 'Alice', 0, 0)") + execSQL("INSERT INTO dashpay_contact_profiles (networkRaw, ownerIdentityId, contactIdentityId, displayName, checkedAtMs, createdAt, lastUpdated) VALUES (1, x'0A', x'0B', 'Bob', 123, 0, 0)") + execSQL("INSERT INTO wallets (walletId, walletGroupId, networkRaw, name, birthHeight, syncedHeight, lastSynced, isImported, createdAt, lastUpdated) VALUES (x'01', x'02', 1, 'w', 0, 0, 0, 0, 0, 0)") + execSQL("INSERT INTO pending_inputs (outpoint, inputIndex, spendingTxid, walletId, createdAt) VALUES (x'0301', 0, x'02', x'01', 0)") + if (fromVersion >= 11) { + execSQL("UPDATE wallets SET lastAppliedChainLockHeight = 4321") + execSQL("UPDATE pending_inputs SET isSweptTombstone = 1, winnerMinedHeight = 1234") + } + close() + } + val db = helper.runMigrationsAndValidate( + dbName, + 17, + true, + DashDatabase.MIGRATION_10_11, + DashDatabase.MIGRATION_11_12, + DashDatabase.MIGRATION_12_13, + DashDatabase.MIGRATION_13_14, + DashDatabase.MIGRATION_14_15, + DashDatabase.MIGRATION_15_16, + DashDatabase.MIGRATION_16_17, + ) + for ((table, name) in listOf("dashpay_profiles" to "Alice", "dashpay_contact_profiles" to "Bob")) { + db.query("SELECT displayName, corePaymentAddress, platformPaymentAddress, shieldedAddress FROM $table").use { cursor -> + assertTrue(cursor.moveToFirst()) + assertEquals(name, cursor.getString(0)) + assertTrue(cursor.isNull(1) && cursor.isNull(2) && cursor.isNull(3)) + } + db.execSQL("UPDATE $table SET shieldedAddress = ?", arrayOf(ByteArray(43) { 0x45 })) + db.query("SELECT shieldedAddress FROM $table").use { cursor -> + assertTrue(cursor.moveToFirst()) + org.junit.Assert.assertArrayEquals(ByteArray(43) { 0x45 }, cursor.getBlob(0)) + } + } + db.query("SELECT isSweptTombstone, winnerMinedHeight FROM pending_inputs").use { cursor -> + assertTrue(cursor.moveToFirst()) + assertEquals(if (fromVersion >= 11) 1 else 0, cursor.getInt(0)) + if (fromVersion >= 11) assertEquals(1234, cursor.getInt(1)) else assertTrue(cursor.isNull(1)) + } + db.query("SELECT lastAppliedChainLockHeight FROM wallets").use { cursor -> + assertTrue(cursor.moveToFirst()) + if (fromVersion >= 11) assertEquals(4321, cursor.getInt(0)) else assertTrue(cursor.isNull(0)) + } + db.close() + } + /** * v2 → v3 adds the `dashpay_contact_profiles` and `dashpay_payments` * tables (additive — no reshapes). Pre-existing v2 data must survive @@ -746,7 +805,7 @@ class DashDatabaseMigrationTest { helper.createDatabase(dbName, 4).close() helper.runMigrationsAndValidate( dbName, - 16, + 17, true, DashDatabase.MIGRATION_4_5, DashDatabase.MIGRATION_5_6, @@ -760,16 +819,17 @@ class DashDatabaseMigrationTest { DashDatabase.MIGRATION_13_14, DashDatabase.MIGRATION_14_15, DashDatabase.MIGRATION_15_16, + DashDatabase.MIGRATION_16_17, ).close() } - /** The full chain from v1 must also land on a valid v16 schema. */ + /** The full chain from v1 must also land on a valid v17 schema. */ @Test fun migrateAllTheWayFrom1() { helper.createDatabase(dbName, 1).close() helper.runMigrationsAndValidate( dbName, - 16, + 17, true, DashDatabase.MIGRATION_1_2, DashDatabase.MIGRATION_2_3, @@ -786,6 +846,7 @@ class DashDatabaseMigrationTest { DashDatabase.MIGRATION_13_14, DashDatabase.MIGRATION_14_15, DashDatabase.MIGRATION_15_16, + DashDatabase.MIGRATION_16_17, ).close() } } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/DashpayNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/DashpayNative.kt index 60f99620a5e..3d55a791b26 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/DashpayNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/DashpayNative.kt @@ -139,6 +139,12 @@ internal object DashpayNative { avatarBytes: ByteArray?, doCreate: Boolean, signerHandle: Long, + coreAddressAction: Int, + coreAddress: ByteArray?, + platformAddressAction: Int, + platformAddress: ByteArray?, + shieldedAddressAction: Int, + shieldedAddress: ByteArray?, ): String? /** diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt index fb82e03ccb3..78ea263cd93 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt @@ -16,6 +16,18 @@ package org.dashfoundation.dashsdk.ffi * non-shielded build throws [UnsatisfiedLinkError]. */ internal object FundingNative { + external fun identityAccountIndex(identityIndex: Int): Int + external fun prepareShieldedIdentityAddress( + manager: Long, walletId: ByteArray, resolver: Long, identityId: ByteArray, + ): ByteArray + external fun resolveShieldedTip(wallet: Long, username: String): ByteArray + /** A non-null [sourceIdentityId] spends that identity's tip account; otherwise [sourceAccount]. */ + external fun sendShieldedTip( + manager: Long, walletId: ByteArray, resolver: Long, sourceIdentityId: ByteArray?, sourceAccount: Int, + username: String, expectedId: ByteArray, expectedAddress: ByteArray, + amount: Long, memo: String?, + ) + external fun shieldedIdentityDebitRecoveryRecords( managerHandle: Long, diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt index ae4d7946395..49e05a3be0d 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt @@ -527,7 +527,7 @@ abstract class NativePersistenceBridge { /** * One `IdentityEntryFFI` upsert. DPNS labels + acquired-at timestamps * ride as parallel arrays. Descriptor - * `([B[BJJZIBZ[B[Ljava/lang/String;[JZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[BZ[BZLjava/lang/String;)I`. + * `([B[BJJZIBZ[B[Ljava/lang/String;[JZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[BZ[BZLjava/lang/String;[B[B[B)I`. */ @Suppress("LongParameterList") open fun onPersistIdentityUpsert( @@ -551,6 +551,28 @@ abstract class NativePersistenceBridge { dashpayAvatarFingerprint: ByteArray, dashpayAvatarFingerprintPresent: Boolean, dashpayPublicMessage: String?, + dashpayCorePaymentAddress: ByteArray? = null, + dashpayPlatformPaymentAddress: ByteArray? = null, + dashpayShieldedAddress: ByteArray? = null, + ): Int = 0 + + /** Authoritative profile update, independent of identity ownership or placement. */ + @Suppress("LongParameterList") + open fun onPersistDashpayProfile( + walletId: ByteArray, + identityId: ByteArray, + isPresent: Boolean, + displayName: String?, + bio: String?, + avatarUrl: String?, + avatarHash: ByteArray, + avatarHashPresent: Boolean, + avatarFingerprint: ByteArray, + avatarFingerprintPresent: Boolean, + publicMessage: String?, + corePaymentAddress: ByteArray?, + platformPaymentAddress: ByteArray?, + shieldedAddress: ByteArray?, ): Int = 0 /** One identity-id removal. Descriptor `([B[B)I`. */ @@ -761,7 +783,7 @@ abstract class NativePersistenceBridge { /** * One `ContactProfileRowFFI` delta riding an identity upsert * (`IdentityEntryFFI.contact_profiles`). Descriptor - * `([B[B[BZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[BZ[BZLjava/lang/String;J)I`. + * `([B[B[BZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[BZ[BZLjava/lang/String;J[B[B[B)I`. * * [isPresent] `true` ⇒ upsert the cached contact-profile row for * `(ownerId, contactId)`; `false` ⇒ tombstone — the contact removed @@ -785,6 +807,9 @@ abstract class NativePersistenceBridge { avatarFingerprintPresent: Boolean, publicMessage: String?, checkedAtMs: Long, + corePaymentAddress: ByteArray? = null, + platformPaymentAddress: ByteArray? = null, + shieldedAddress: ByteArray? = null, ): Int = 0 // ── Asset locks ─────────────────────────────────────────────────── @@ -1396,6 +1421,7 @@ class IdentityRestoreData( * re-fetches every contact. */ @JvmField val contactProfiles: Array, + @JvmField val dashpayProfile: ContactProfileRestoreData? = null, ) /** @@ -1428,6 +1454,9 @@ class ContactProfileRestoreData( @JvmField val avatarFingerprint: ByteArray?, @JvmField val publicMessage: String?, @JvmField val checkedAtMs: Long, + @JvmField val corePaymentAddress: ByteArray? = null, + @JvmField val platformPaymentAddress: ByteArray? = null, + @JvmField val shieldedAddress: ByteArray? = null, ) /** diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabase.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabase.kt index 0b3445a5397..89fcbc89ce5 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabase.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabase.kt @@ -190,9 +190,12 @@ import org.dashfoundation.dashsdk.persistence.entities.WalletManagerMetadataEnti * `onLoadPrivateContactScanState`, so a relaunch resumes the private contact * request sync where it stopped. Empty after the migration: the first sync * reads the store from its start, as every sync did before. + * + * Version 17 adds nullable Core, Platform, and shielded payment addresses + * to cached owner and contact profiles. */ @Database( - version = 16, + version = 17, exportSchema = true, entities = [ WalletEntity::class, @@ -730,6 +733,17 @@ abstract class DashDatabase : RoomDatabase() { } } + /** v16 → v17: optional public payment addresses on cached profiles. */ + val MIGRATION_16_17: Migration = object : Migration(16, 17) { + override fun migrate(db: SupportSQLiteDatabase) { + for (table in listOf("dashpay_profiles", "dashpay_contact_profiles")) { + for (column in listOf("corePaymentAddress", "platformPaymentAddress", "shieldedAddress")) { + db.execSQL("ALTER TABLE `$table` ADD COLUMN `$column` BLOB") + } + } + } + } + /** * v15 -> v16: the two private contact request scan state tables, see * the version-16 class doc above. Created empty. @@ -783,6 +797,7 @@ abstract class DashDatabase : RoomDatabase() { MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, + MIGRATION_16_17, ) .build() diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt index b33f99a467d..023a2ce2656 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt @@ -1727,6 +1727,9 @@ class PlatformWalletPersistenceHandler( dashpayAvatarFingerprint: ByteArray, dashpayAvatarFingerprintPresent: Boolean, dashpayPublicMessage: String?, + dashpayCorePaymentAddress: ByteArray?, + dashpayPlatformPaymentAddress: ByteArray?, + dashpayShieldedAddress: ByteArray?, ): Int = guarded { stage(walletId) { db -> val ownerWallet = if (walletIdIsSome) identityWalletId else walletId @@ -1827,8 +1830,6 @@ class PlatformWalletPersistenceHandler( ) } - // DashPay profile: present == "update the whole document"; - // absent == "no update" (never a delete). if (dashpayProfilePresent) { db.dashpayDao().upsertProfile( DashpayProfileEntity( @@ -1841,6 +1842,9 @@ class PlatformWalletPersistenceHandler( avatarHash = if (dashpayAvatarHashPresent) dashpayAvatarHash else null, avatarFingerprint = if (dashpayAvatarFingerprintPresent) dashpayAvatarFingerprint else null, + corePaymentAddress = dashpayCorePaymentAddress, + platformPaymentAddress = dashpayPlatformPaymentAddress, + shieldedAddress = dashpayShieldedAddress, lastUpdated = now(), ), ) @@ -1849,6 +1853,53 @@ class PlatformWalletPersistenceHandler( 0 } + @Suppress("LongParameterList") + override fun onPersistDashpayProfile( + walletId: ByteArray, + identityId: ByteArray, + isPresent: Boolean, + displayName: String?, + bio: String?, + avatarUrl: String?, + avatarHash: ByteArray, + avatarHashPresent: Boolean, + avatarFingerprint: ByteArray, + avatarFingerprintPresent: Boolean, + publicMessage: String?, + corePaymentAddress: ByteArray?, + platformPaymentAddress: ByteArray?, + shieldedAddress: ByteArray?, + ): Int = guarded { + stage(walletId) { db -> + val networkRaw = db.walletDao().getByWalletId(walletId)?.networkRaw + ?: return@stage + val identity = requireNotNull( + db.identityDao().getByIdentityAndNetwork(identityId, networkRaw) + ) + if (isPresent) { + db.dashpayDao().upsertProfile( + DashpayProfileEntity( + networkRaw = identity.networkRaw, + identityId = identityId, + displayName = displayName, + publicMessage = publicMessage, + bio = bio, + avatarUrl = avatarUrl, + avatarHash = avatarHash.takeIf { avatarHashPresent }, + avatarFingerprint = avatarFingerprint.takeIf { avatarFingerprintPresent }, + corePaymentAddress = corePaymentAddress, + platformPaymentAddress = platformPaymentAddress, + shieldedAddress = shieldedAddress, + lastUpdated = now(), + ), + ) + } else { + db.dashpayDao().deleteProfile(identity.networkRaw, identityId) + } + } + 0 + } + override fun onPersistIdentityRemoval(walletId: ByteArray, identityId: ByteArray): Int = guarded { val identityBase58 = identityId.toBase58String() stage(walletId) { db -> db.identityDao().deleteByIdentityId(identityId) } @@ -2339,6 +2390,9 @@ class PlatformWalletPersistenceHandler( avatarFingerprintPresent: Boolean, publicMessage: String?, checkedAtMs: Long, + corePaymentAddress: ByteArray?, + platformPaymentAddress: ByteArray?, + shieldedAddress: ByteArray?, ): Int = guarded { stage(walletId) { db -> // Owner identity must exist (networkRaw is read off it). In the @@ -2361,6 +2415,9 @@ class PlatformWalletPersistenceHandler( avatarUrl = avatarUrl, avatarHash = avatarHash.takeIf { avatarHashPresent }, avatarFingerprint = avatarFingerprint.takeIf { avatarFingerprintPresent }, + corePaymentAddress = corePaymentAddress, + platformPaymentAddress = platformPaymentAddress, + shieldedAddress = shieldedAddress, checkedAtMs = checkedAtMs, lastUpdated = now(), ), @@ -3141,6 +3198,9 @@ class PlatformWalletPersistenceHandler( avatarFingerprint = cp.avatarFingerprint, publicMessage = cp.publicMessage, checkedAtMs = cp.checkedAtMs, + corePaymentAddress = cp.corePaymentAddress, + platformPaymentAddress = cp.platformPaymentAddress, + shieldedAddress = cp.shieldedAddress, ) }.toTypedArray() IdentityRestoreData( @@ -3157,6 +3217,17 @@ class PlatformWalletPersistenceHandler( ignoredSenders = ignoredRows, payments = paymentRows, contactProfiles = contactProfileRows, + dashpayProfile = database.dashpayDao().getProfile(idRow.networkRaw, idRow.identityId)?.let { p -> + ContactProfileRestoreData( + contactId = idRow.identityId, + displayName = p.displayName, bio = p.bio, avatarUrl = p.avatarUrl, + avatarHash = p.avatarHash, avatarFingerprint = p.avatarFingerprint, + publicMessage = p.publicMessage, checkedAtMs = 0, + corePaymentAddress = p.corePaymentAddress, + platformPaymentAddress = p.platformPaymentAddress, + shieldedAddress = p.shieldedAddress, + ) + }, ) }.toTypedArray() } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/DashpayDao.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/DashpayDao.kt index 1948639fd38..e82b0b059fc 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/DashpayDao.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/DashpayDao.kt @@ -39,6 +39,9 @@ interface DashpayDao { @Query("DELETE FROM dashpay_profiles WHERE identityId = :identityId") suspend fun deleteProfilesByIdentity(identityId: ByteArray) + @Query("DELETE FROM dashpay_profiles WHERE networkRaw = :networkRaw AND identityId = :identityId") + suspend fun deleteProfile(networkRaw: Int, identityId: ByteArray) + @Query("DELETE FROM dashpay_profiles") suspend fun deleteAllProfiles() diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/IdentityDao.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/IdentityDao.kt index 4b89b39119b..1da3f19bdce 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/IdentityDao.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/IdentityDao.kt @@ -27,6 +27,9 @@ interface IdentityDao { @Query("SELECT * FROM identities WHERE identityId = :identityId") suspend fun getByIdentityId(identityId: ByteArray): IdentityEntity? + @Query("SELECT * FROM identities WHERE identityId = :identityId AND networkRaw = :networkRaw") + suspend fun getByIdentityAndNetwork(identityId: ByteArray, networkRaw: Int): IdentityEntity? + /** Mirror of `predicate(network:)`. */ @Query("SELECT * FROM identities WHERE networkRaw = :networkRaw") fun observeByNetwork(networkRaw: Int): Flow> diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/ShieldedDao.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/ShieldedDao.kt index 9e7ed9141e6..a5fbee6aa97 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/ShieldedDao.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/ShieldedDao.kt @@ -53,6 +53,12 @@ interface ShieldedDao { @Query("SELECT * FROM shielded_notes WHERE walletId = :walletId AND isSpent = 0") fun observeUnspentNotesByWallet(walletId: ByteArray): Flow> + @Query("SELECT * FROM shielded_notes WHERE walletId = :walletId AND accountIndex = :accountIndex AND isSpent = 0") + fun observeUnspentNotesByWalletAccount( + walletId: ByteArray, + accountIndex: Int, + ): Flow> + @Upsert suspend fun upsertNote(note: ShieldedNoteEntity) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayContactProfileEntity.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayContactProfileEntity.kt index bb72b816457..669f5274936 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayContactProfileEntity.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayContactProfileEntity.kt @@ -67,6 +67,9 @@ data class DashpayContactProfileEntity( val avatarHash: ByteArray? = null, /** 8-byte perceptual hash. */ val avatarFingerprint: ByteArray? = null, + val corePaymentAddress: ByteArray? = null, + val platformPaymentAddress: ByteArray? = null, + val shieldedAddress: ByteArray? = null, /** * Wall-clock ms of the last fetch attempt on the Rust side * (`ContactProfileEntry.checked_at_ms`) — drives the self-heal diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayProfileEntity.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayProfileEntity.kt index 6d8a8806839..a956ef22cc8 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayProfileEntity.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayProfileEntity.kt @@ -44,6 +44,9 @@ data class DashpayProfileEntity( val avatarHash: ByteArray? = null, /** 8-byte perceptual hash. */ val avatarFingerprint: ByteArray? = null, + val corePaymentAddress: ByteArray? = null, + val platformPaymentAddress: ByteArray? = null, + val shieldedAddress: ByteArray? = null, val createdAt: Date = Date(), val lastUpdated: Date = Date(), ) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/services/ShieldedService.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/services/ShieldedService.kt index 1dfb441d1b0..0733d30a557 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/services/ShieldedService.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/services/ShieldedService.kt @@ -208,7 +208,9 @@ class ShieldedService(private val database: DashDatabase) { _state.value = ShieldedSyncState() _shieldedBalance.value = database.shieldedDao() .observeUnspentNotesByWallet(walletId) - .map { notes -> notes.sumOf { it.value } } + // Rust also scans dedicated tip accounts; ordinary wallet balances only + // include the accounts selected by this service's caller. + .map { notes -> notes.filter { it.accountIndex in sortedAccounts }.sumOf { it.value } } try { manager.configureShielded(dbPath) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/Dashpay.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/Dashpay.kt index 4060881efa7..fc476498df8 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/Dashpay.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/Dashpay.kt @@ -37,6 +37,13 @@ class Dashpay internal constructor(private val walletHandle: Long, private val gate: org.dashfoundation.dashsdk.wallet.TeardownGate? = null, ) { + /** Fetch and validate the current recipient through proof-verified DPNS and profile reads. */ + suspend fun resolveShieldedTip(username: String): ShieldedTipRecipient = gate.op { + val bytes = mapNativeErrors { org.dashfoundation.dashsdk.ffi.FundingNative.resolveShieldedTip(walletHandle, username) } + check(bytes.size == 75) { "Invalid recipient response" } + ShieldedTipRecipient(bytes.copyOfRange(0, 32), bytes.copyOfRange(32, 75)) + } + /** * Send a contact request to [recipientIdentityId], signing the document * state-transition with [signerHandle] and keying the contact crypto @@ -768,11 +775,17 @@ class Dashpay internal constructor(private val walletHandle: Long, avatarBytes: ByteArray? = null, doCreate: Boolean, signerHandle: Long, + corePaymentAddress: PaymentAddressUpdate = PaymentAddressUpdate.Keep, + platformPaymentAddress: PaymentAddressUpdate = PaymentAddressUpdate.Keep, + shieldedAddress: PaymentAddressUpdate = PaymentAddressUpdate.Keep, ): String? = gate.op { mapNativeErrors { DashpayNative.createOrUpdateProfile( walletHandle, identityId, displayName, publicMessage, avatarUrl, avatarBytes, doCreate, signerHandle, + corePaymentAddress.action, corePaymentAddress.bytes, + platformPaymentAddress.action, platformPaymentAddress.bytes, + shieldedAddress.action, shieldedAddress.bytes, ) } } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/PaymentAddressUpdate.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/PaymentAddressUpdate.kt new file mode 100644 index 00000000000..2284dfa2b0c --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/PaymentAddressUpdate.kt @@ -0,0 +1,8 @@ +package org.dashfoundation.dashsdk.tokens + +/** Explicit partial-update semantics for a public profile payment address. */ +sealed class PaymentAddressUpdate(internal val action: Int, internal val bytes: ByteArray?) { + data object Keep : PaymentAddressUpdate(0, null) + class Set(bytes: ByteArray) : PaymentAddressUpdate(1, bytes.copyOf()) + data object Remove : PaymentAddressUpdate(2, null) +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt new file mode 100644 index 00000000000..353573c87a5 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt @@ -0,0 +1,41 @@ +package org.dashfoundation.dashsdk.tokens + +/** Verified recipient snapshot to bind payment confirmation to an identity and address. */ +class ShieldedTipRecipient(identityId: ByteArray, address: ByteArray) { + private val identityBytes = identityId.copyOf() + private val addressBytes = address.copyOf() + val identityId: ByteArray get() = identityBytes.copyOf() + val address: ByteArray get() = addressBytes.copyOf() + init { + require(identityBytes.size == 32) + require(addressBytes.size == 43) + } + override fun equals(other: Any?): Boolean = other is ShieldedTipRecipient && + identityBytes.contentEquals(other.identityBytes) && addressBytes.contentEquals(other.addressBytes) + override fun hashCode(): Int = 31 * identityBytes.contentHashCode() + addressBytes.contentHashCode() +} + +/** + * The account a shielded tip is paid from. Rust decides which account an + * identity's source selects, from the slot the wallet seed proves it holds. + */ +sealed class ShieldedTipSource { + /** The identity's dedicated tip account. */ + class Identity(identityId: ByteArray) : ShieldedTipSource() { + private val identityBytes = identityId.copyOf() + val identityId: ByteArray get() = identityBytes.copyOf() + init { + require(identityBytes.size == 32) { "identity id must be 32 bytes, got ${identityBytes.size}" } + } + override fun equals(other: Any?): Boolean = + other is Identity && identityBytes.contentEquals(other.identityBytes) + override fun hashCode(): Int = identityBytes.contentHashCode() + } + + /** An ordinary account, or the tip account of a retired identity. */ + data class Account(val index: Int) : ShieldedTipSource() { + init { + require(index >= 0) { "account must be non-negative, got $index" } + } + } +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/ManagedPlatformWallet.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/ManagedPlatformWallet.kt index 4a9a8455077..e28fea64825 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/ManagedPlatformWallet.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/ManagedPlatformWallet.kt @@ -1372,6 +1372,29 @@ class ManagedPlatformWallet internal constructor( } } + /** + * The HD derivation index of one managed identity, or null when the wallet + * holds no recoverable index for it (a watched or index-less identity). + * Per-identity state derived from the index — the dedicated shielded tip + * account — must treat null as "unavailable" rather than fall back to 0, + * which is identity 0's slot. Room's `IdentityEntity.identityIndex` is + * non-null and stores 0 as a placeholder, so it cannot answer this. + */ + suspend fun identityIndex(identityId: ByteArray): Int? = withContext(Dispatchers.IO) { + mapNativeErrors { + val identityHandle = translateManagedIdentityNotFoundToZero { + TokensNative.getManagedIdentity(handle, identityId) + } + if (identityHandle == 0L) return@mapNativeErrors null + try { + val index = WalletManagerNative.managedIdentityGetIdentityIndex(identityHandle) + if (index < 0) null else index.toInt() + } finally { + TokensNative.managedIdentityDestroy(identityHandle) + } + } + } + /** * The advisory "why not" reason a withdrawal preflight records when the * account can't fund one — port of the `success_with_message` reason the diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt index c1ec7960603..de5c4d58eb6 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt @@ -2035,6 +2035,32 @@ class PlatformWalletManager( // the caller must NOT retry (the spent notes stay reserved Rust-side // until a later shielded sync resolves them). + /** Dedicated account index derived by Rust's wallet convention. */ + fun shieldedIdentityAccountIndex(identityIndex: Int): Int = mapNativeErrors { FundingNative.identityAccountIndex(identityIndex) } + + suspend fun prepareShieldedIdentityAddress(walletId: ByteArray, identityId: ByteArray): ByteArray = teardownGate.op { + mapNativeErrors { FundingNative.prepareShieldedIdentityAddress(managerHandle, walletId, mnemonicResolver.nativeHandle, identityId) } + } + + /** Send only if fresh resolution still matches the recipient shown in confirmation. */ + suspend fun sendShieldedTip( + walletId: ByteArray, username: String, + recipient: org.dashfoundation.dashsdk.tokens.ShieldedTipRecipient, + amount: Long, source: org.dashfoundation.dashsdk.tokens.ShieldedTipSource, + memo: String? = null, + ): Unit = teardownGate.op { + require(amount > 0) { "amount must be positive, got $amount" } + val (sourceIdentityId, sourceAccount) = when (source) { + is org.dashfoundation.dashsdk.tokens.ShieldedTipSource.Identity -> source.identityId to 0 + is org.dashfoundation.dashsdk.tokens.ShieldedTipSource.Account -> null to source.index + } + mapNativeErrors { + FundingNative.sendShieldedTip(managerHandle, walletId, mnemonicResolver.nativeHandle, + sourceIdentityId, sourceAccount, username, recipient.identityId, recipient.address, + amount, memo) + } + } + /** * Shielded → shielded transfer (Type 16) — port of Swift's * `PlatformWalletManager.shieldedTransfer(walletId:account:recipientRaw43:amount:memo:)` diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt index ac1ae6f77ae..90135ce60c1 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt @@ -5,6 +5,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.dashfoundation.dashsdk.persistence.entities.AccountEntity import org.dashfoundation.dashsdk.persistence.entities.IdentityEntity +import org.dashfoundation.dashsdk.persistence.entities.ShieldedNoteEntity import org.dashfoundation.dashsdk.persistence.entities.ShieldedViewingKeyEntity import org.dashfoundation.dashsdk.persistence.entities.TokenBalanceEntity import org.dashfoundation.dashsdk.persistence.entities.TokenEntity @@ -42,6 +43,31 @@ class DashDatabaseTest { db.close() } + @Test + fun ordinarySendBalanceIncludesOnlyUnspentAccountZeroNotes() = runTest { + val dao = db.shieldedDao() + fun note(id: Int, account: Int, value: Long, spent: Boolean = false, wallet: ByteArray = walletId) = + ShieldedNoteEntity( + nullifier = ByteArray(32) { id.toByte() }, + walletId = wallet, + accountIndex = account, + position = id.toLong(), + cmx = ByteArray(32), + blockHeight = 1, + isSpent = spent, + value = value, + noteData = ByteArray(115), + ) + dao.upsertNote(note(1, 0x40000000, 900)) + assertEquals(0L, dao.observeUnspentNotesByWalletAccount(walletId, 0).first().sumOf { it.value }) + dao.upsertNote(note(2, 0, 100)) + dao.upsertNote(note(3, 0, 200)) + dao.upsertNote(note(4, 1, 500)) + dao.upsertNote(note(5, 0, 700, spent = true)) + dao.upsertNote(note(6, 0, 800, wallet = ByteArray(32) { 2 })) + assertEquals(300L, dao.observeUnspentNotesByWalletAccount(walletId, 0).first().sumOf { it.value }) + } + @Test fun walletRoundTripsThroughUpsertAndFlow() = runTest { val wallet = WalletEntity( @@ -242,8 +268,9 @@ class DashDatabaseTest { // 12 → 13 the contract bounds kind, 13 → 14 the token // once-per-identity distribution block, 14 → 15 the DashPay // backfill record columns on `wallets`, and 15 → 16 the private - // contact request scan state tables. - assertEquals(16, db.openHelper.readableDatabase.version) + // contact request scan state tables. 16 → 17 adds profile + // payment addresses. + assertEquals(17, db.openHelper.readableDatabase.version) val indexes = mutableSetOf() db.openHelper.readableDatabase.query("PRAGMA index_list('pending_inputs')").use { c -> val nameColumn = c.getColumnIndexOrThrow("name") diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt index 6a40c939b72..694e76cf15a 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt @@ -912,6 +912,9 @@ class PlatformWalletPersistenceHandlerTest { dashpayAvatarFingerprint = ByteArray(8), dashpayAvatarFingerprintPresent = false, dashpayPublicMessage = "hi", + dashpayCorePaymentAddress = ByteArray(21) { 1 }, + dashpayPlatformPaymentAddress = ByteArray(21) { 2 }, + dashpayShieldedAddress = ByteArray(43) { 3 }, ) handler.onChangesetEnd(walletId, success = true) @@ -930,10 +933,117 @@ class PlatformWalletPersistenceHandlerTest { assertNotNull(profile) assertEquals("Alice", profile!!.displayName) assertEquals("hi", profile.publicMessage) + assertTrue(ByteArray(21) { 1 }.contentEquals(profile.corePaymentAddress)) + assertTrue(ByteArray(21) { 2 }.contentEquals(profile.platformPaymentAddress)) + assertTrue(ByteArray(43) { 3 }.contentEquals(profile.shieldedAddress)) assertNotNull(profile.avatarHash) assertNull(profile.avatarFingerprint) } + @Test + fun shouldPreserveUnknownProfileUntilExplicitAbsence() = runTest { + // `sync_profiles` clears a profile deleted on Platform; the cached + // row must not be hydrated back on the next cold start. + handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) + handler.onPersistAccountRegistration( + walletId, 0, 0, 0, 0, 0, ByteArray(0), ByteArray(0), ByteArray(78) { 30 }, + ) + val identityId = ByteArray(32) { 13 } + + fun persistSnapshot(profilePresent: Boolean) { + handler.onChangesetBegin(walletId) + handler.onPersistIdentityUpsert( + walletId, identityId, 1, 0, true, 0, 0, true, walletId, + emptyArray(), LongArray(0), profilePresent, "Alice", null, null, + ByteArray(32), false, ByteArray(8), false, null, + dashpayShieldedAddress = if (profilePresent) ByteArray(43) { 3 } else null, + ) + handler.onChangesetEnd(walletId, success = true) + } + + persistSnapshot(profilePresent = true) + assertNotNull(db.dashpayDao().getProfile(testnet, identityId)) + // The same id's row on another network is not this snapshot's to clear. + val otherNetwork = testnet + 1 + db.dashpayDao().upsertProfile( + org.dashfoundation.dashsdk.persistence.entities.DashpayProfileEntity( + networkRaw = otherNetwork, identityId = identityId, + ), + ) + + persistSnapshot(profilePresent = false) + assertTrue(ByteArray(43) { 3 }.contentEquals(db.dashpayDao().getProfile(testnet, identityId)!!.shieldedAddress)) + handler.onChangesetBegin(walletId) + assertEquals(0, handler.onPersistDashpayProfile( + walletId, identityId, false, null, null, null, ByteArray(32), false, + ByteArray(8), false, null, null, null, null, + )) + handler.onChangesetEnd(walletId, success = true) + assertNull(db.dashpayDao().getProfile(testnet, identityId)) + assertNotNull(db.dashpayDao().getProfile(otherNetwork, identityId)) + assertNull(handler.onLoadWalletList().single().identities.single().dashpayProfile) + } + + @Test + fun observedProfileUpdateSurvivesAdoptionAndExplicitAbsenceRemovesIt() = runTest { + handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) + val identityId = ByteArray(32) { 14 } + fun snapshot(owned: Boolean) { + handler.onChangesetBegin(walletId) + handler.onPersistIdentityUpsert( + walletId, identityId, 42, 1, owned, 0, 0, owned, walletId, + emptyArray(), LongArray(0), false, null, null, null, + ByteArray(32), false, ByteArray(8), false, null, + ) + handler.onChangesetEnd(walletId, success = true) + } + snapshot(false) + handler.onChangesetBegin(walletId) + handler.onPersistDashpayProfile( + walletId, identityId, true, "Observed", null, null, ByteArray(32), false, + ByteArray(8), false, null, ByteArray(21) { 1 }, ByteArray(21) { 2 }, ByteArray(43) { 3 }, + ) + handler.onChangesetEnd(walletId, success = true) + snapshot(true) + val profile = db.dashpayDao().getProfile(testnet, identityId)!! + assertEquals("Observed", profile.displayName) + assertTrue(ByteArray(21) { 1 }.contentEquals(profile.corePaymentAddress)) + assertTrue(ByteArray(21) { 2 }.contentEquals(profile.platformPaymentAddress)) + assertTrue(ByteArray(43) { 3 }.contentEquals(profile.shieldedAddress)) + snapshot(false) + handler.onChangesetBegin(walletId) + handler.onPersistDashpayProfile( + walletId, identityId, false, null, null, null, ByteArray(32), false, + ByteArray(8), false, null, null, null, null, + ) + handler.onChangesetEnd(walletId, success = true) + assertNull(db.dashpayDao().getProfile(testnet, identityId)) + } + + @Test + fun profileOverlayRejectsIdentityFromAnotherNetwork() = runTest { + handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) + val identityId = ByteArray(32) { 15 } + handler.onChangesetBegin(walletId) + handler.onPersistIdentityUpsert( + walletId, identityId, 1, 0, true, 0, 0, true, walletId, + emptyArray(), LongArray(0), false, null, null, null, + ByteArray(32), false, ByteArray(8), false, null, + ) + handler.onChangesetEnd(walletId, success = true) + + val otherWalletId = ByteArray(32) { 16 } + handler.onPersistWalletMetadata(otherWalletId, testnet + 1, groupId, 0) + handler.onChangesetBegin(otherWalletId) + val result = handler.onPersistDashpayProfile( + otherWalletId, identityId, true, "Wrong network", null, null, + ByteArray(32), false, ByteArray(8), false, null, null, null, null, + ) + assertEquals(0, result) + assertTrue(handler.onChangesetEnd(otherWalletId, success = true) != 0) + assertNull(db.dashpayDao().getProfile(testnet + 1, identityId)) + } + @Test fun identityDpnsSnapshotRemovesStaleOwnedLabels() = runTest { handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) @@ -5036,6 +5146,9 @@ class PlatformWalletPersistenceHandlerTest { avatarFingerprintPresent = false, publicMessage = "yo", checkedAtMs = 1_700_000_111_000, + corePaymentAddress = ByteArray(21) { 1 }, + platformPaymentAddress = ByteArray(21) { 2 }, + shieldedAddress = ByteArray(43) { 3 }, ) handler.onChangesetEnd(walletId, success = true) } @@ -5164,9 +5277,18 @@ class PlatformWalletPersistenceHandlerTest { ), ) + db.dashpayDao().upsertProfile( + org.dashfoundation.dashsdk.persistence.entities.DashpayProfileEntity( + networkRaw = testnet, identityId = ownerId, + displayName = "Alice", shieldedAddress = ByteArray(43) { 7 }, + ), + ) val list = handler.onLoadWalletList() assertEquals(1, list.size) val identity = list[0].identities.single() + assertEquals("Alice", identity.dashpayProfile?.displayName) + assertTrue(ByteArray(43) { 7 }.contentEquals(identity.dashpayProfile?.shieldedAddress)) + assertEquals(1, identity.payments.size) val payment = identity.payments[0] @@ -5179,6 +5301,9 @@ class PlatformWalletPersistenceHandlerTest { assertEquals(1, identity.contactProfiles.size) val profile = identity.contactProfiles[0] + assertTrue(ByteArray(21) { 1 }.contentEquals(profile.corePaymentAddress)) + assertTrue(ByteArray(21) { 2 }.contentEquals(profile.platformPaymentAddress)) + assertTrue(ByteArray(43) { 3 }.contentEquals(profile.shieldedAddress)) assertTrue(contactId.contentEquals(profile.contactId)) assertEquals("Bob", profile.displayName) assertNull(profile.bio) diff --git a/packages/rs-platform-wallet-ffi/src/contact_request.rs b/packages/rs-platform-wallet-ffi/src/contact_request.rs index dbbb65e8938..593f711f95b 100644 --- a/packages/rs-platform-wallet-ffi/src/contact_request.rs +++ b/packages/rs-platform-wallet-ffi/src/contact_request.rs @@ -460,9 +460,8 @@ mod tests { revision: 0, }); crate::runtime::runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; - wm.get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") + let mut state = wallet.state_mut().await.expect("live wallet state"); + state .identity_manager .add_identity(identity, 0, wallet.wallet_id(), wallet.persister()) .expect("the identity"); @@ -504,10 +503,9 @@ mod tests { PLATFORM_WALLET_STORAGE .with_item(handle, |wallet| { crate::runtime::runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; + let mut state = wallet.state_mut().await.expect("live wallet state"); change( - wm.get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") + state .identity_manager .managed_identity_mut(&identity_id) .expect("the identity"), diff --git a/packages/rs-platform-wallet-ffi/src/dashpay.rs b/packages/rs-platform-wallet-ffi/src/dashpay.rs index 72c795781f2..12a568ff746 100644 --- a/packages/rs-platform-wallet-ffi/src/dashpay.rs +++ b/packages/rs-platform-wallet-ffi/src/dashpay.rs @@ -2031,9 +2031,8 @@ mod tests { revision: 0, }); runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; - wm.get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") + let mut state = wallet.state_mut().await.expect("live wallet state"); + state .identity_manager .add_identity(identity, 0, wallet.wallet_id(), wallet.persister()) .expect("the identity"); diff --git a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs index 6c83f4d459e..600d28cab47 100644 --- a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs +++ b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs @@ -4,7 +4,7 @@ use std::ffi::CStr; use std::os::raw::c_char; use std::ptr; -use platform_wallet::{DashPayProfile, ProfileUpdate}; +use platform_wallet::{DashPayProfile, PaymentAddressUpdate, ProfileUpdate}; use rs_sdk_ffi::{SignerHandle, VTableSigner}; use crate::check_ptr; @@ -14,6 +14,41 @@ use crate::runtime::block_on_worker; use crate::types::*; use crate::{unwrap_option_or_return, unwrap_result_or_return}; +/// Payment address update: action 0 keeps, 1 sets, and 2 removes the property. +/// For action 1, `bytes` must point to `len` readable bytes for the call duration. +#[repr(C)] +pub struct PaymentAddressUpdateFFI { + pub action: u32, + pub bytes: *const u8, + pub len: usize, +} + +/// Transport bound for a payment address crossing the ABI. The wallet checks +/// the exact per-field length; this only refuses absurd sizes before copying. +const MAX_PAYMENT_ADDRESS_BYTES: usize = 64; + +unsafe fn decode_address_update( + input: *const PaymentAddressUpdateFFI, +) -> Result { + if input.is_null() { + return Ok(PaymentAddressUpdate::Keep); + } + let input = &*input; + match input.action { + 0 => Ok(PaymentAddressUpdate::Keep), + 2 => Ok(PaymentAddressUpdate::Remove), + // The wallet validates the bytes for their field + // (`validate_payment_address_update`); this only marshals them. + 1 if !input.bytes.is_null() && input.len <= MAX_PAYMENT_ADDRESS_BYTES => Ok( + PaymentAddressUpdate::Set(std::slice::from_raw_parts(input.bytes, input.len).to_vec()), + ), + _ => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "Invalid payment address update".to_string(), + )), + } +} + /// Flat FFI view of a [`DashPayProfile`]. #[repr(C)] pub struct DashPayProfileFFI { @@ -24,6 +59,12 @@ pub struct DashPayProfileFFI { pub avatar_hash: [u8; 32], pub avatar_fingerprint_is_some: bool, pub avatar_fingerprint: [u8; 8], + pub core_payment_address_is_some: bool, + pub core_payment_address: [u8; 21], + pub platform_payment_address_is_some: bool, + pub platform_payment_address: [u8; 21], + pub shielded_address_is_some: bool, + pub shielded_address: [u8; 43], } impl DashPayProfileFFI { @@ -36,6 +77,12 @@ impl DashPayProfileFFI { avatar_hash: [0u8; 32], avatar_fingerprint_is_some: false, avatar_fingerprint: [0u8; 8], + core_payment_address_is_some: false, + core_payment_address: [0; 21], + platform_payment_address_is_some: false, + platform_payment_address: [0; 21], + shielded_address_is_some: false, + shielded_address: [0; 43], } } @@ -61,6 +108,33 @@ impl DashPayProfileFFI { avatar_hash, avatar_fingerprint_is_some, avatar_fingerprint, + core_payment_address_is_some: profile + .core_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + core_payment_address: profile + .core_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + platform_payment_address_is_some: profile + .platform_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + platform_payment_address: profile + .platform_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + shielded_address_is_some: profile + .shielded_address + .as_ref() + .is_some_and(|a| a.len() == 43), + shielded_address: profile + .shielded_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 43]), } } } @@ -332,56 +406,103 @@ pub unsafe extern "C" fn platform_wallet_create_or_update_dashpay_profile_with_s signer_handle: *mut SignerHandle, out_profile: *mut DashPayProfileFFI, ) -> PlatformWalletFFIResult { - check_ptr!(out_profile); - check_ptr!(signer_handle); - // `DashPayProfileFFI` owns heap C-string pointer fields freed by - // `dashpay_profile_ffi_free`; publish the empty sentinel before any - // fallible work so an error path never leaves uninitialized stack bytes - // in those pointer fields. Matches the read-side helpers in this file. - *out_profile = DashPayProfileFFI::empty(); - - let id = unwrap_result_or_return!(read_identifier(identity_id)); - - let display_name = unwrap_result_or_return!(decode_opt_c_str(display_name)); - let public_message = unwrap_result_or_return!(decode_opt_c_str(public_message)); - let avatar_url = unwrap_result_or_return!(decode_opt_c_str(avatar_url)); - - let avatar_bytes_vec: Option> = if avatar_bytes.is_null() || avatar_bytes_len == 0 { - None - } else { - Some(std::slice::from_raw_parts(avatar_bytes, avatar_bytes_len).to_vec()) - }; - - let signer_addr = signer_handle as usize; - - let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, move |wallet| { - let identity = wallet.identity().clone(); - let input = ProfileUpdate { - display_name, - public_message, - avatar_url, - avatar_bytes: avatar_bytes_vec, - }; + platform_wallet_create_or_update_dashpay_profile_with_addresses_with_signer( + wallet_handle, + identity_id, + display_name, + public_message, + avatar_url, + avatar_bytes, + avatar_bytes_len, + ptr::null(), + ptr::null(), + ptr::null(), + do_create, + signer_handle, + out_profile, + ) +} - block_on_worker(async move { - let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); - if do_create { - identity - .dashpay() - .create_profile_with_external_signer(&id, input, signer) - .await - } else { - identity - .dashpay() - .update_profile_with_external_signer(&id, input, signer) - .await - } - }) - }); - let result = unwrap_option_or_return!(option); - let profile = unwrap_result_or_return!(result); - *out_profile = DashPayProfileFFI::from_profile(&profile); - PlatformWalletFFIResult::ok() +/// Create or update a profile with explicit keep/set/remove payment address operations. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C" fn platform_wallet_create_or_update_dashpay_profile_with_addresses_with_signer( + wallet_handle: Handle, + identity_id: *const u8, + display_name: *const c_char, + public_message: *const c_char, + avatar_url: *const c_char, + avatar_bytes: *const u8, + avatar_bytes_len: usize, + core_payment_address: *const PaymentAddressUpdateFFI, + platform_payment_address: *const PaymentAddressUpdateFFI, + shielded_address: *const PaymentAddressUpdateFFI, + do_create: bool, + signer_handle: *mut SignerHandle, + out_profile: *mut DashPayProfileFFI, +) -> PlatformWalletFFIResult { + // The write broadcasts, so a panic past that point leaves its outcome + // unknown; it must not unwind through this `extern "C"` frame. + catch_panic_to_code( + "profile write", + PlatformWalletFFIResultCode::ErrorWalletOperation, + "The profile may or may not have been written; sync profiles before retrying.", + || { + check_ptr!(out_profile); + // `DashPayProfileFFI` owns heap C-string pointer fields freed by + // `dashpay_profile_ffi_free`; publish the empty sentinel before any + // fallible work so an error path never leaves uninitialized stack bytes + // in those pointer fields. Matches the read-side helpers in this file. + *out_profile = DashPayProfileFFI::empty(); + check_ptr!(signer_handle); + + let id = unwrap_result_or_return!(read_identifier(identity_id)); + + let display_name = unwrap_result_or_return!(decode_opt_c_str(display_name)); + let public_message = unwrap_result_or_return!(decode_opt_c_str(public_message)); + let avatar_url = unwrap_result_or_return!(decode_opt_c_str(avatar_url)); + + let avatar_bytes_vec: Option> = + if avatar_bytes.is_null() || avatar_bytes_len == 0 { + None + } else { + Some(std::slice::from_raw_parts(avatar_bytes, avatar_bytes_len).to_vec()) + }; + + let core_payment_address = + unwrap_result_or_return!(decode_address_update(core_payment_address)); + let platform_payment_address = + unwrap_result_or_return!(decode_address_update(platform_payment_address)); + let shielded_address = + unwrap_result_or_return!(decode_address_update(shielded_address)); + + let signer_addr = signer_handle as usize; + + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, move |wallet| { + let wallet = wallet.clone(); + let input = ProfileUpdate { + display_name, + public_message, + avatar_url, + avatar_bytes: avatar_bytes_vec, + core_payment_address, + platform_payment_address, + shielded_address, + }; + + block_on_worker(async move { + let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + wallet + .write_dashpay_profile(&id, input, signer, do_create) + .await + }) + }); + let result = unwrap_option_or_return!(option); + let profile = unwrap_result_or_return!(result); + *out_profile = DashPayProfileFFI::from_profile(&profile); + PlatformWalletFFIResult::ok() + }, + ) } #[cfg(test)] @@ -401,6 +522,83 @@ mod tests { }) } + #[test] + fn null_signer_leaves_profile_safe_to_free() { + unsafe { + let mut out = std::mem::MaybeUninit::::uninit(); + let result = platform_wallet_create_or_update_dashpay_profile_with_signer( + 0, + ptr::null(), + ptr::null(), + ptr::null(), + ptr::null(), + ptr::null(), + 0, + false, + ptr::null_mut(), + out.as_mut_ptr(), + ); + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + let mut out = out.assume_init(); + assert!(out.display_name.is_null()); + assert!(!out.shielded_address_is_some); + dashpay_profile_ffi_free(&mut out); + } + } + + #[test] + fn payment_address_updates_preserve_distinct_operations() { + unsafe { + assert!(matches!( + decode_address_update(ptr::null()).unwrap(), + PaymentAddressUpdate::Keep + )); + let mut update = PaymentAddressUpdateFFI { + action: 2, + bytes: ptr::null(), + len: 0, + }; + assert!(matches!( + decode_address_update(&update).unwrap(), + PaymentAddressUpdate::Remove + )); + update.action = 1; + assert!(decode_address_update(&update).is_err()); + let address = [7u8; 43]; + update.bytes = address.as_ptr(); + update.len = address.len(); + match decode_address_update(&update).unwrap() { + PaymentAddressUpdate::Set(bytes) => assert_eq!(bytes, address), + _ => panic!("expected set operation"), + } + let oversized = [7u8; MAX_PAYMENT_ADDRESS_BYTES + 1]; + update.bytes = oversized.as_ptr(); + update.len = oversized.len(); + assert!(decode_address_update(&update).is_err()); + update.action = 3; + assert!(decode_address_update(&update).is_err()); + } + } + + #[test] + fn profile_addresses_copy_to_owned_fixed_buffers() { + let profile = DashPayProfile { + core_payment_address: Some(vec![1; 21]), + platform_payment_address: Some(vec![2; 21]), + shielded_address: Some(vec![3; 43]), + ..Default::default() + }; + let mut ffi = DashPayProfileFFI::from_profile(&profile); + assert!(ffi.core_payment_address_is_some); + assert!(ffi.platform_payment_address_is_some); + assert!(ffi.shielded_address_is_some); + drop(profile); + assert_eq!(ffi.core_payment_address, [1; 21]); + assert_eq!(ffi.platform_payment_address, [2; 21]); + assert_eq!(ffi.shielded_address, [3; 43]); + unsafe { dashpay_profile_ffi_free(&mut ffi) }; + } + #[test] fn test_get_profile_absent_returns_false_flag() { unsafe { @@ -437,6 +635,7 @@ mod tests { avatar_hash: Some(hash), avatar_fingerprint: Some([1, 2, 3, 4, 5, 6, 7, 8]), public_message: Some("Hello world".to_string()), + ..Default::default() }); let handle = MANAGED_IDENTITY_STORAGE.insert(managed); diff --git a/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs b/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs index 02e250e9b2e..3c841810daf 100644 --- a/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs @@ -187,26 +187,24 @@ async fn should_preserve_signer_unavailable_and_unknown_submission_through_the_e ) .await .unwrap(); - wallet - .wallet_manager() - .write() - .await - .get_wallet_info_mut(&wallet.wallet_id()) - .unwrap() - .identity_manager - .add_identity( - IdentityV0 { - id: owner, - public_keys: [(1, key.clone())].into(), - balance: 100_000_000, - revision: 0, - } - .into(), - 0, - wallet.wallet_id(), - wallet.persister(), - ) - .unwrap(); + { + let mut state = wallet.state_mut().await.unwrap(); + state + .identity_manager + .add_identity( + IdentityV0 { + id: owner, + public_keys: [(1, key.clone())].into(), + balance: 100_000_000, + revision: 0, + } + .into(), + 0, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } let handle = PLATFORM_WALLET_STORAGE.insert(wallet); let signer = Box::new(VTableSigner::from_native(Arc::new(Signing(available)))); let name = CString::new("note").unwrap(); diff --git a/packages/rs-platform-wallet-ffi/src/identity_persistence.rs b/packages/rs-platform-wallet-ffi/src/identity_persistence.rs index e04c82a2ff0..de1b9bf9271 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_persistence.rs @@ -57,6 +57,9 @@ use platform_wallet::{DashPayProfile, IdentityStatus}; /// distinguish "no profile yet" (skip the row) from "profile present /// with this field unset" (clear the column). All heap-allocated /// strings are freed in [`free_identity_entry_ffi`]. +/// Confirmed absence travels separately on the size-negotiated +/// `on_persist_dashpay_profiles_fn` extension; identity placement does not +/// establish whether the profile was checked. #[repr(C)] pub struct IdentityEntryFFI { pub identity_id: [u8; 32], @@ -98,10 +101,11 @@ pub struct IdentityEntryFFI { pub dpns_names_acquired_at: *const u64, /// `true` iff the underlying [`IdentityEntry::dashpay_profile`] /// is `Some(_)`. When `false`, all `dashpay_profile_*` pointer - /// fields are null and the byte-array fields are zeroed — Swift - /// must skip the profile upsert entirely (changeset semantics: - /// `dashpay_profile: None` means "no update" rather than - /// "delete", matching the merge policy on the Rust side). + /// fields are null and the byte-array fields are zeroed. The + /// snapshot carries the identity's current profile, so for a + /// wallet-owned identity (hydrated on load) `false` means it has + /// none and hosts delete the cached row; an out-of-wallet identity + /// is never hydrated, so hosts leave its row alone. pub dashpay_profile_present: bool, /// Heap-allocated NUL-terminated UTF-8 C string for the DashPay /// profile's display name. `null` when the source field was @@ -137,6 +141,13 @@ pub struct IdentityEntryFFI { pub dashpay_profile_avatar_fingerprint: [u8; 8], /// `true` iff the source `avatar_fingerprint` was `Some(_)`. pub dashpay_profile_avatar_fingerprint_present: bool, + pub dashpay_profile_core_payment_address: [u8; 21], + pub dashpay_profile_core_payment_address_present: bool, + pub dashpay_profile_platform_payment_address: [u8; 21], + pub dashpay_profile_platform_payment_address_present: bool, + pub dashpay_profile_shielded_address: [u8; 43], + pub dashpay_profile_shielded_address_present: bool, + /// Heap-allocated NUL-terminated UTF-8 C string for the DashPay /// profile's public message. `null` when the source field was /// `None`. Owned by this FFI struct; freed in @@ -213,6 +224,13 @@ pub struct ContactProfileRowFFI { pub avatar_fingerprint: [u8; 8], /// `true` iff the source `avatar_fingerprint` was `Some(_)`. pub avatar_fingerprint_present: bool, + pub core_payment_address: [u8; 21], + pub core_payment_address_present: bool, + pub platform_payment_address: [u8; 21], + pub platform_payment_address_present: bool, + pub shielded_address: [u8; 43], + pub shielded_address_present: bool, + /// Heap-allocated `publicMessage`; `null` when `None`. Freed in /// [`free_identity_entry_ffi`]. pub public_message: *const c_char, @@ -377,38 +395,8 @@ const _: [u8; 8] = [0u8; std::mem::align_of::()]; // than a build error. Pin the expected size here so any reshape // fails the cargo build first. // -// Expected layout on 64-bit targets (all fields in declaration -// order under `#[repr(C)]`): -// -// 0..=31 identity_id [u8; 32] -// 32..=39 balance u64 -// 40..=47 revision u64 -// 48 identity_index_is_some bool -// 49..=51 (padding to 4) -// 52..=55 identity_index u32 -// 56 status u8 -// 57 wallet_id_is_some bool -// 58..=89 wallet_id [u8; 32] -// 90..=95 (padding to 8 for pointer alignment) -// 96..=103 dpns_names *const *const c_char -// 104..=111 dpns_names_count usize -// 112..=119 dpns_names_acquired_at *const u64 -// 120 dashpay_profile_present bool -// 121..=127 (padding to 8 for pointer alignment) -// 128..=135 dashpay_profile_display_name *const c_char -// 136..=143 dashpay_profile_bio *const c_char -// 144..=151 dashpay_profile_avatar_url *const c_char -// 152..=183 dashpay_profile_avatar_hash [u8; 32] -// 184 dashpay_profile_avatar_hash_present bool -// 185..=192 dashpay_profile_avatar_fingerprint [u8; 8] -// 193 dashpay_profile_avatar_fingerprint_present bool -// 194..=199 (padding to 8 for pointer alignment) -// 200..=207 dashpay_profile_public_message *const c_char -// 208..=215 contact_profiles *const ContactProfileRowFFI -// 216..=223 contact_profiles_count usize -// -// Total size = 224, alignment = 8 (from u64 / pointer). -const _: [u8; 224] = [0u8; std::mem::size_of::()]; +// Includes three fixed-size payment addresses and their presence flags. +const _: [u8; 312] = [0u8; std::mem::size_of::()]; const _: [u8; 8] = [0u8; std::mem::align_of::()]; // --------------------------------------------------------------------------- @@ -471,6 +459,15 @@ impl IdentityEntryFFI { dashpay_profile_avatar_hash_present: profile_fields.avatar_hash_present, dashpay_profile_avatar_fingerprint: profile_fields.avatar_fingerprint, dashpay_profile_avatar_fingerprint_present: profile_fields.avatar_fingerprint_present, + dashpay_profile_core_payment_address: profile_fields.core_payment_address, + dashpay_profile_core_payment_address_present: profile_fields + .core_payment_address_present, + dashpay_profile_platform_payment_address: profile_fields.platform_payment_address, + dashpay_profile_platform_payment_address_present: profile_fields + .platform_payment_address_present, + dashpay_profile_shielded_address: profile_fields.shielded_address, + dashpay_profile_shielded_address_present: profile_fields.shielded_address_present, + dashpay_profile_public_message: profile_fields.public_message, contact_profiles, contact_profiles_count, @@ -493,6 +490,13 @@ struct DashPayProfileFields { avatar_hash_present: bool, avatar_fingerprint: [u8; 8], avatar_fingerprint_present: bool, + core_payment_address: [u8; 21], + core_payment_address_present: bool, + platform_payment_address: [u8; 21], + platform_payment_address_present: bool, + shielded_address: [u8; 43], + shielded_address_present: bool, + public_message: *const c_char, } @@ -508,6 +512,13 @@ impl DashPayProfileFields { avatar_hash_present: false, avatar_fingerprint: [0u8; 8], avatar_fingerprint_present: false, + core_payment_address: [0; 21], + core_payment_address_present: false, + platform_payment_address: [0; 21], + platform_payment_address_present: false, + shielded_address: [0; 43], + shielded_address_present: false, + public_message: ptr::null(), } } @@ -535,6 +546,34 @@ impl DashPayProfileFields { avatar_hash_present, avatar_fingerprint, avatar_fingerprint_present, + core_payment_address: profile + .core_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + core_payment_address_present: profile + .core_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + platform_payment_address: profile + .platform_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + platform_payment_address_present: profile + .platform_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + shielded_address: profile + .shielded_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 43]), + shielded_address_present: profile + .shielded_address + .as_ref() + .is_some_and(|a| a.len() == 43), + public_message: optional_c_string(profile.public_message.as_deref()), } } @@ -607,7 +646,7 @@ fn allocate_dpns_arrays( /// pointers — every one must be released with `CString::from_raw` /// before the outer slice drops. [`free_identity_entry_ffi`] does this /// row-by-row, mirroring the DPNS label-array free path exactly. -fn allocate_contact_profile_rows( +pub(crate) fn allocate_contact_profile_rows( contact_profiles: &std::collections::BTreeMap< dpp::prelude::Identifier, platform_wallet::ContactProfileEntry, @@ -634,6 +673,13 @@ fn allocate_contact_profile_rows( avatar_hash_present: false, avatar_fingerprint: [0u8; 8], avatar_fingerprint_present: false, + core_payment_address: [0; 21], + core_payment_address_present: false, + platform_payment_address: [0; 21], + platform_payment_address_present: false, + shielded_address: [0; 43], + shielded_address_present: false, + public_message: ptr::null(), checked_at_ms: entry.checked_at_ms, }); @@ -657,6 +703,34 @@ fn allocate_contact_profile_rows( avatar_hash_present, avatar_fingerprint, avatar_fingerprint_present, + core_payment_address: profile + .core_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + core_payment_address_present: profile + .core_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + platform_payment_address: profile + .platform_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + platform_payment_address_present: profile + .platform_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + shielded_address: profile + .shielded_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 43]), + shielded_address_present: profile + .shielded_address + .as_ref() + .is_some_and(|a| a.len() == 43), + public_message: optional_c_string(profile.public_message.as_deref()), checked_at_ms: entry.checked_at_ms, }); @@ -853,23 +927,29 @@ pub unsafe fn free_identity_entry_ffi(entry: &mut IdentityEntryFFI) { // produced by `optional_c_string` (`CString::into_raw`) so it MUST be // reclaimed with `CString::from_raw` — the byte arrays are inline and // need no free. - if !entry.contact_profiles.is_null() && entry.contact_profiles_count > 0 { - let rows = unsafe { - std::slice::from_raw_parts_mut( - entry.contact_profiles as *mut ContactProfileRowFFI, - entry.contact_profiles_count, - ) - }; + unsafe { free_contact_profile_rows(entry.contact_profiles, entry.contact_profiles_count) }; + entry.contact_profiles = ptr::null(); + entry.contact_profiles_count = 0; +} + +/// Release rows allocated by `allocate_contact_profile_rows` after the host copied them. +/// +/// # Safety +/// The pointer and count must describe the original allocation, freed exactly once. +pub(crate) unsafe fn free_contact_profile_rows(ptr: *const ContactProfileRowFFI, count: usize) { + if !ptr.is_null() && count > 0 { + let rows = + unsafe { std::slice::from_raw_parts_mut(ptr as *mut ContactProfileRowFFI, count) }; for row in rows.iter_mut() { - free_optional_c_string(&mut row.display_name); - free_optional_c_string(&mut row.bio); - free_optional_c_string(&mut row.avatar_url); - free_optional_c_string(&mut row.public_message); + unsafe { + free_optional_c_string(&mut row.display_name); + free_optional_c_string(&mut row.bio); + free_optional_c_string(&mut row.avatar_url); + free_optional_c_string(&mut row.public_message); + } } - let _ = unsafe { Box::from_raw(rows as *mut [ContactProfileRowFFI]) }; - entry.contact_profiles = ptr::null(); + drop(unsafe { Box::from_raw(rows as *mut [ContactProfileRowFFI]) }); } - entry.contact_profiles_count = 0; } /// Release a heap-allocated C string produced by @@ -1050,6 +1130,7 @@ mod tests { avatar_hash: Some([0xAB; 32]), avatar_fingerprint: Some([0xCD; 8]), public_message: None, + ..Default::default() }), dashpay_payments: Default::default(), contact_profiles: Default::default(), @@ -1102,6 +1183,7 @@ mod tests { avatar_hash: Some([0x11; 32]), avatar_fingerprint: None, public_message: None, + ..Default::default() }), checked_at_ms: 111, }, diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs index f0ebd8ebee1..67944f59aa7 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs @@ -209,11 +209,9 @@ impl Fixture { .await .unwrap(); wallet - .wallet_manager() - .write() + .state_mut() .await - .get_wallet_info_mut(&wallet.wallet_id()) - .unwrap() + .expect("live wallet state") .identity_manager .add_identity(identity.clone(), 0, wallet.wallet_id(), wallet.persister()) .unwrap(); diff --git a/packages/rs-platform-wallet-ffi/src/manager.rs b/packages/rs-platform-wallet-ffi/src/manager.rs index 51e38104709..fbc4e6b5d6a 100644 --- a/packages/rs-platform-wallet-ffi/src/manager.rs +++ b/packages/rs-platform-wallet-ffi/src/manager.rs @@ -12,7 +12,7 @@ use crate::persistence::{ FreeTrackedMasternodesFn, LoadAssetLockOperationIdFn, LoadAssetLockShieldedRecipientFn, LoadIdentityBalanceBlockTimeFn, LoadPrivateContactScanStateFn, LoadPrivateContactScanStateWalletsFn, LoadTrackedMasternodesFn, PersistAssetLockOperationIdFn, - PersistAssetLockShieldedRecipientFn, PersistDpnsNameStatesFn, + PersistAssetLockShieldedRecipientFn, PersistDashpayProfilesFn, PersistDpnsNameStatesFn, PersistIdentityBalanceBlockTimeFn, PersistPrivateContactScanStateFn, PersistTrackedMasternodesFn, PersistWalletChangesetChainLockHeightFn, PersistWalletChangesetSweepsFn, PersistWalletChangesetUtxoVerdictsFn, @@ -408,6 +408,7 @@ unsafe fn persistence_extension_callbacks( on_load_private_contact_scan_state_wallets_free_fn, FreePrivateContactScanStateWalletsFn ), + persist_dashpay_profiles: slot!(on_persist_dashpay_profiles_fn, PersistDashpayProfilesFn), } } @@ -1693,6 +1694,39 @@ mod tests { assert!(read.wallet_dashpay_backfill.is_some()); } + #[test] + fn should_size_gate_authoritative_dashpay_profile_slot() { + unsafe extern "C" fn persist( + _: *mut c_void, + _: *const u8, + _: *const crate::identity_persistence::ContactProfileRowFFI, + _: usize, + ) -> i32 { + 0 + } + let offset = std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_dashpay_profiles_fn + ); + let mut extension = PersistenceCallbacksExtension { + on_persist_dashpay_profiles_fn: Some(persist), + ..Default::default() + }; + for size in [ + offset, + offset + std::mem::size_of::>() - 1, + ] { + extension.struct_size = size; + assert!(unsafe { persistence_extension_callbacks(&extension) } + .persist_dashpay_profiles + .is_none()); + } + extension.struct_size = std::mem::size_of::(); + assert!(unsafe { persistence_extension_callbacks(&extension) } + .persist_dashpay_profiles + .is_some()); + } + #[test] fn should_size_gate_identity_balance_watermark_slots_independently() { unsafe extern "C" fn persist( diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index 8495c4464ac..e4678aacd98 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -68,7 +68,8 @@ use crate::dpns_name_state_persistence::{ build_dpns_name_state_entries, free_dpns_name_state_entries, DpnsNameStateFFI, }; use crate::identity_persistence::{ - free_identity_entry_ffi, free_identity_key_entry_ffi, IdentityEntryFFI, IdentityKeyEntryFFI, + allocate_contact_profile_rows, free_contact_profile_rows, free_identity_entry_ffi, + free_identity_key_entry_ffi, ContactProfileRowFFI, IdentityEntryFFI, IdentityKeyEntryFFI, IdentityKeyRemovalFFI, }; use crate::invitation_persistence::{build_invitation_entries, InvitationEntryFFI}; @@ -709,6 +710,17 @@ pub struct PersistenceCallbacksExtension { wallet_ids_count: usize, ), >, + /// Authoritative profile overlays. `contact_id` is the profile identity ID; + /// `is_present == false` deletes it, independent of identity placement. + /// The host must copy all row data before returning. + pub on_persist_dashpay_profiles_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + profiles: *const ContactProfileRowFFI, + profiles_count: usize, + ) -> i32, + >, } impl Default for PersistenceCallbacksExtension { @@ -736,10 +748,18 @@ impl Default for PersistenceCallbacksExtension { on_load_private_contact_scan_state_free_fn: None, on_load_private_contact_scan_state_wallets_fn: None, on_load_private_contact_scan_state_wallets_free_fn: None, + on_persist_dashpay_profiles_fn: None, } } } +pub type PersistDashpayProfilesFn = unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + profiles: *const ContactProfileRowFFI, + profiles_count: usize, +) -> i32; + /// The additive (extension-negotiated) callbacks in Rust-side form, read /// out of a size-gated [`PersistenceCallbacksExtension`] by the manager /// create path. @@ -764,6 +784,7 @@ pub struct PersistenceExtensionCallbacks { pub load_private_contact_scan_state_free: Option, pub load_private_contact_scan_state_wallets: Option, pub load_private_contact_scan_state_wallets_free: Option, + pub persist_dashpay_profiles: Option, } /// Return value by which a persistence callback reports a **retryable** @@ -2776,6 +2797,35 @@ impl PlatformWalletPersistence for FFIPersister { } } + if let (Some(profiles), Some(cb)) = ( + changeset.dashpay_profiles.as_ref(), + self.tracked_masternodes_callbacks.persist_dashpay_profiles, + ) { + let removed = changeset + .identities + .as_ref() + .map(|identity_changes| &identity_changes.removed); + let rows = profiles + .iter() + .filter(|(id, _)| !removed.is_some_and(|ids| ids.contains(id))) + .map(|(id, profile)| { + ( + *id, + platform_wallet::ContactProfileEntry { + profile: profile.clone(), + checked_at_ms: 0, + }, + ) + }) + .collect(); + let (rows, count) = allocate_contact_profile_rows(&rows); + let rc = unsafe { cb(self.callbacks.context, wallet_id.as_ptr(), rows, count) }; + unsafe { free_contact_profile_rows(rows, count) }; + if rc != 0 { + outcome.record(rc); + } + } + // Stamp sidecars share the begin/end transaction with identity scalars. // Run after the legacy callback has staged any new identity rows. if let (Some(id_cs), Some(cb)) = ( @@ -7180,6 +7230,9 @@ fn build_wallet_identity_bucket( unsafe { restore_dashpay_payments(spec, &mut managed) }; unsafe { restore_dashpay_ignored(spec, &mut managed) }; unsafe { restore_contact_profiles(spec, &mut managed) }; + if let Some(profile) = unsafe { spec.dashpay_profile.as_ref() } { + *managed.dashpay_profile_mut() = Some(unsafe { profile_from_restore_row(profile) }); + } bucket.insert(spec.identity_index, managed); } @@ -7324,26 +7377,49 @@ unsafe fn restore_contact_profiles(spec: &IdentityRestoreEntryFFI, managed: &mut apply_contact_profile_rows(rows, managed); } -/// Maximum cached `avatarUrl` length — mirrors the -/// `MAX_AVATAR_URL_LEN` gate `platform-wallet`'s profile fetch applies -/// before caching (DIP-15's 2048-char cap). -const MAX_AVATAR_URL_LEN: usize = 2048; - -/// Defensive re-validation of a cached `avatarUrl` at restore. The -/// fetch path already dropped non-`https://` / over-length URLs before -/// caching ([`platform_wallet`]'s `is_valid_avatar_url`), but the URL is -/// attacker-controlled public data and the UI will load it, so we -/// re-apply the same `https://`-only, length-capped rule on the way back -/// in. A URL that fails is dropped to `None` (the rest of the profile is -/// still restored) rather than discarding the whole row. -fn is_valid_avatar_url(url: &str) -> bool { - !url.is_empty() && url.len() <= MAX_AVATAR_URL_LEN && url.starts_with("https://") +/// Copy a host-owned profile row. The host frees the buffers after restoration +/// returns; platform-wallet owns normalization and payment-address policy. +/// +/// # Safety +/// The row's string pointers must be null or readable NUL-terminated strings. +unsafe fn profile_from_restore_row( + row: &ContactProfileRestoreEntryFFI, +) -> platform_wallet::DashPayProfile { + let opt_string = |ptr: *const std::os::raw::c_char| -> Option { + if ptr.is_null() { + None + } else { + CStr::from_ptr(ptr).to_str().ok().map(str::to_string) + } + }; + platform_wallet::normalize_persisted_profile(platform_wallet::DashPayProfile { + display_name: opt_string(row.display_name), + bio: opt_string(row.bio), + avatar_url: opt_string(row.avatar_url), + avatar_hash: row.avatar_hash_present.then_some(row.avatar_hash), + avatar_fingerprint: row + .avatar_fingerprint_present + .then_some(row.avatar_fingerprint), + public_message: opt_string(row.public_message), + core_payment_address: row + .core_payment_address_present + .then_some(row.core_payment_address) + .map(|address| address.to_vec()), + platform_payment_address: row + .platform_payment_address_present + .then_some(row.platform_payment_address) + .map(|address| address.to_vec()), + shielded_address: row + .shielded_address_present + .then_some(row.shielded_address) + .map(|address| address.to_vec()), + }) } /// Fold a slice of [`ContactProfileRestoreEntryFFI`] rows into /// the managed identity's contact-profile cache. Split out from -/// [`restore_contact_profiles`] so the c-string decode + avatar-url -/// re-validation is unit-testable without a full +/// [`restore_contact_profiles`] so the c-string decode + profile +/// normalization is unit-testable without a full /// [`IdentityRestoreEntryFFI`]. /// /// # Safety @@ -7353,43 +7429,11 @@ unsafe fn apply_contact_profile_rows( rows: &[ContactProfileRestoreEntryFFI], managed: &mut ManagedIdentity, ) { - use platform_wallet::{ContactProfileEntry, DashPayProfile}; - - let opt_string = |ptr: *const std::os::raw::c_char| -> Option { - if ptr.is_null() { - None - } else { - CStr::from_ptr(ptr).to_str().ok().map(str::to_string) - } - }; - for row in rows { - let avatar_hash = if row.avatar_hash_present { - Some(row.avatar_hash) - } else { - None - }; - let avatar_fingerprint = if row.avatar_fingerprint_present { - Some(row.avatar_fingerprint) - } else { - None - }; - // Re-validate the public, attacker-controlled avatar URL; drop - // just the URL field (keep the rest of the profile) if it no - // longer passes the `https://` / length rule. - let avatar_url = opt_string(row.avatar_url).filter(|u| is_valid_avatar_url(u)); - managed.dashpay_contact_profiles_mut().insert( Identifier::from(row.contact_id), - ContactProfileEntry { - profile: Some(DashPayProfile { - display_name: opt_string(row.display_name), - bio: opt_string(row.bio), - avatar_url, - avatar_hash, - avatar_fingerprint, - public_message: opt_string(row.public_message), - }), + platform_wallet::ContactProfileEntry { + profile: Some(profile_from_restore_row(row)), checked_at_ms: row.checked_at_ms, }, ); @@ -9289,13 +9333,10 @@ mod tests { let wallet = create(&manager); assert_eq!(wallet.wallet_id(), wallet_id); - let held = |id: Identifier| { + let held = |id: Identifier, index: u32| { runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; - let identities = &mut wm - .get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") - .identity_manager; + let mut state = wallet.state_mut().await.expect("live wallet state"); + let identities = &mut state.identity_manager; identities .add_identity( Identity::V0(IdentityV0 { @@ -9304,7 +9345,7 @@ mod tests { balance: 0, revision: 0, }), - 0, + index, wallet.wallet_id(), wallet.persister(), ) @@ -9316,8 +9357,11 @@ mod tests { .private_payments_unrestored() }) }; - assert!(held(marked), "the identity the kept record names is held"); - assert!(!held(other), "an identity no kept record names is not"); + assert!( + held(marked, 0), + "the identity the kept record names is held" + ); + assert!(!held(other, 1), "an identity no kept record names is not"); } #[test] @@ -9446,6 +9490,174 @@ mod tests { } } + #[test] + fn should_forward_authoritative_profile_overlays_after_scalar_snapshots() { + use dpp::identity::{Identity, IdentityV0}; + use platform_wallet::changeset::{IdentityChangeSet, IdentityEntry}; + use platform_wallet::ManagedIdentity; + use std::sync::Mutex; + #[derive(Default)] + struct Host { + profiles: Mutex, bool)>>, + order: Mutex>, + } + unsafe extern "C" fn scalar( + context: *mut c_void, + _: *const u8, + entries: *const IdentityEntryFFI, + count: usize, + _: *const [u8; 32], + _: usize, + ) -> i32 { + let host = &*(context as *const Host); + assert_eq!(count, 1); + assert!(!(*entries).dashpay_profile_present); + host.order.lock().unwrap().push("scalar"); + 0 + } + unsafe extern "C" fn persist( + context: *mut c_void, + wallet: *const u8, + rows: *const ContactProfileRowFFI, + count: usize, + ) -> i32 { + assert_eq!(slice::from_raw_parts(wallet, 32), &[42; 32]); + let host = &*(context as *const Host); + host.order.lock().unwrap().push("profile"); + for row in slice::from_raw_parts(rows, count) { + assert_eq!(row.contact_id, [9; 32]); + let display = (!row.display_name.is_null()).then(|| { + CStr::from_ptr(row.display_name) + .to_str() + .unwrap() + .to_owned() + }); + host.profiles.lock().unwrap().push(( + row.is_present, + display, + row.shielded_address_present, + )); + } + 0 + } + let host = Host::default(); + let persister = FFIPersister::new_with_persistence_capabilities_and_extensions( + PersistenceCallbacks { + context: (&host as *const Host).cast_mut().cast(), + on_changeset_begin_fn: Some(noop_begin), + on_changeset_end_fn: Some(noop_end), + on_persist_identities_fn: Some(scalar), + ..Default::default() + }, + PersistenceCapabilities::NONE, + PersistenceExtensionCallbacks { + persist_dashpay_profiles: Some(persist), + ..Default::default() + }, + ); + let id = Identifier::from([9; 32]); + let managed = ManagedIdentity::new_out_of_wallet(Identity::V0(IdentityV0 { + id, + public_keys: Default::default(), + balance: 0, + revision: 0, + })); + for profile in [ + Some(platform_wallet::DashPayProfile { + display_name: Some("Owned copy".into()), + shielded_address: Some(vec![3; 43]), + ..Default::default() + }), + None, + ] { + persister + .store( + [42; 32], + PlatformWalletChangeSet { + identities: Some(IdentityChangeSet { + identities: BTreeMap::from([( + id, + IdentityEntry::from_managed(&managed), + )]), + ..Default::default() + }), + dashpay_profiles: Some(BTreeMap::from([(id, profile)])), + ..Default::default() + }, + ) + .unwrap(); + } + assert_eq!( + *host.profiles.lock().unwrap(), + vec![ + (true, Some("Owned copy".into()), true), + (false, None, false) + ] + ); + assert_eq!( + *host.order.lock().unwrap(), + vec!["scalar", "profile", "scalar", "profile"] + ); + } + + #[test] + fn should_not_forward_profile_overlay_for_identity_removed_in_same_changeset() { + use platform_wallet::changeset::IdentityChangeSet; + use std::sync::Mutex; + + #[derive(Default)] + struct Host { + ids: Mutex>, + } + + unsafe extern "C" fn persist( + context: *mut c_void, + _: *const u8, + rows: *const ContactProfileRowFFI, + count: usize, + ) -> i32 { + let host = &*(context as *const Host); + host.ids.lock().unwrap().extend( + slice::from_raw_parts(rows, count) + .iter() + .map(|row| row.contact_id), + ); + 0 + } + + let host = Host::default(); + let persister = FFIPersister::new_with_persistence_capabilities_and_extensions( + PersistenceCallbacks { + context: (&host as *const Host).cast_mut().cast(), + on_changeset_begin_fn: Some(noop_begin), + on_changeset_end_fn: Some(noop_end), + ..Default::default() + }, + PersistenceCapabilities::NONE, + PersistenceExtensionCallbacks { + persist_dashpay_profiles: Some(persist), + ..Default::default() + }, + ); + let removed = Identifier::from([9; 32]); + let kept = Identifier::from([10; 32]); + let mut identities = IdentityChangeSet::default(); + identities.removed.insert(removed); + + persister + .store( + [42; 32], + PlatformWalletChangeSet { + identities: Some(identities), + dashpay_profiles: Some(BTreeMap::from([(removed, None), (kept, None)])), + ..Default::default() + }, + ) + .unwrap(); + + assert_eq!(*host.ids.lock().unwrap(), vec![[10; 32]]); + } + // --- persists_durably: the fail-closed durability attestation --- unsafe extern "C" fn noop_begin(_ctx: *mut c_void, _wallet_id: *const u8) -> i32 { @@ -9575,6 +9787,224 @@ mod tests { "both host allocations freed" ); } + + /// A storage-form transparent payment address: a 0x00/0x01 version byte, + /// then a 20-byte hash. + fn transparent_address(version: u8, fill: u8) -> [u8; 21] { + let mut address = [fill; 21]; + address[0] = version; + address + } + + /// Orchard key-components vector 0 (`default_d || default_pk_d`), retained + /// as public profile metadata with or without shielded spending support. + /// https://github.com/zcash-hackworks/zcash-test-vectors/blob/master/orchard_key_components.py + fn shielded_fixture() -> ([u8; 43], Option>) { + let address = [ + 0x8f, 0xf3, 0x38, 0x69, 0x71, 0xcb, 0x64, 0xb8, 0xe7, 0x78, 0x99, 0x08, 0xdd, 0x8e, + 0xbd, 0x7d, 0xe9, 0x2a, 0x68, 0xe5, 0x86, 0xa3, 0x4d, 0xb8, 0xfe, 0xa9, 0x99, 0xef, + 0xd2, 0x01, 0x6f, 0xae, 0x76, 0x75, 0x0a, 0xfa, 0xe7, 0xee, 0x94, 0x16, 0x46, 0xbc, + 0xb9, + ]; + (address, Some(address.to_vec())) + } + + /// Restore re-validates each payment address as a profile fetch would, + /// dropping a wrong-version transparent address and undecodable Orchard + /// bytes from a stale or corrupt host row while keeping the rest. + #[test] + fn should_drop_invalid_payment_addresses_on_restore() { + let name = std::ffi::CString::new("Carol").unwrap(); + let row = ContactProfileRestoreEntryFFI { + contact_id: [0xDD; 32], + display_name: name.as_ptr(), + bio: std::ptr::null(), + avatar_url: std::ptr::null(), + avatar_hash: [0; 32], + avatar_hash_present: false, + avatar_fingerprint: [0; 8], + avatar_fingerprint_present: false, + core_payment_address: transparent_address(0x05, 0xC1), + core_payment_address_present: true, + platform_payment_address: transparent_address(0x01, 0xD1), + platform_payment_address_present: true, + shielded_address: [0xFF; 43], + shielded_address_present: true, + public_message: std::ptr::null(), + checked_at_ms: 0, + }; + let profile = unsafe { profile_from_restore_row(&row) }; + assert_eq!(profile.display_name.as_deref(), Some("Carol")); + assert_eq!(profile.core_payment_address, None); + assert_eq!( + profile.platform_payment_address, + Some(transparent_address(0x01, 0xD1).to_vec()) + ); + assert_eq!(profile.shielded_address, None); + } + + /// The owned DashPay profile a host supplies on the wallet-restore load + /// callback reaches the restored `ManagedIdentity` with every field, + /// including the three payment addresses, and is an owned copy: the free + /// callback scribbles over the host buffers before anything is asserted. A + /// null profile pointer restores no profile. + #[test] + fn owned_dashpay_profile_hydrates_through_the_load_callback() { + use crate::wallet_restore_types::{ContactProfileRestoreEntryFFI, IdentityRestoreEntryFFI}; + use dpp::identity::accessors::IdentitySettersV0; + use platform_wallet::changeset::IdentityEntry; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Host { + strings: Vec>, + profile: ContactProfileRestoreEntryFFI, + identities: Vec, + wallet: WalletRestoreEntryFFI, + frees: AtomicUsize, + } + fn c_buf(text: &str) -> Box<[u8]> { + let mut bytes = text.as_bytes().to_vec(); + bytes.push(0); + bytes.into_boxed_slice() + } + fn identity(id: u8, index: u32) -> IdentityRestoreEntryFFI { + IdentityRestoreEntryFFI { + identity_id: [id; 32], + balance: 7, + revision: 1, + identity_index: index, + status: 2, + dpns_names: std::ptr::null(), + dpns_names_count: 0, + contested_dpns_names: std::ptr::null(), + contested_dpns_names_count: 0, + keys: std::ptr::null(), + keys_count: 0, + contacts: std::ptr::null(), + contacts_count: 0, + payments: std::ptr::null(), + payments_count: 0, + ignored_senders: std::ptr::null(), + ignored_senders_count: 0, + contact_profiles: std::ptr::null(), + contact_profiles_count: 0, + dashpay_profile: std::ptr::null(), + } + } + unsafe extern "C" fn load_wallet( + context: *mut c_void, + entries: *mut *const WalletRestoreEntryFFI, + count: *mut usize, + ) -> i32 { + let host = &mut *(context as *mut Host); + host.strings = ["Alice", "bio text", "https://example.com/a.png", "hello"] + .into_iter() + .map(c_buf) + .collect(); + host.profile = ContactProfileRestoreEntryFFI { + contact_id: [0; 32], + display_name: host.strings[0].as_ptr().cast(), + bio: host.strings[1].as_ptr().cast(), + avatar_url: host.strings[2].as_ptr().cast(), + avatar_hash: [0xA1; 32], + avatar_hash_present: true, + avatar_fingerprint: [0xF1; 8], + avatar_fingerprint_present: true, + core_payment_address: transparent_address(0x00, 0xC1), + core_payment_address_present: true, + platform_payment_address: transparent_address(0x01, 0xD1), + platform_payment_address_present: true, + shielded_address: shielded_fixture().0, + shielded_address_present: true, + public_message: host.strings[3].as_ptr().cast(), + checked_at_ms: 0, + }; + let mut with_profile = identity(0x11, 0); + with_profile.dashpay_profile = &host.profile; + host.identities = vec![with_profile, identity(0x22, 1)]; + host.wallet = WalletRestoreEntryFFI { + wallet_id: [42; 32], + identities: host.identities.as_ptr(), + identities_count: host.identities.len(), + ..Default::default() + }; + *entries = &host.wallet; + *count = 1; + 0 + } + unsafe extern "C" fn free_wallet( + context: *mut c_void, + _entries: *const WalletRestoreEntryFFI, + _count: usize, + ) { + let host = &mut *(context as *mut Host); + // Anything Rust still borrowed would now read as garbage. + for buf in &mut host.strings { + let len = buf.len(); + buf[..len - 1].fill(b'X'); + } + host.profile.avatar_hash = [0; 32]; + host.profile.core_payment_address = [0; 21]; + host.profile.platform_payment_address = [0; 21]; + host.profile.shielded_address = [0; 43]; + host.frees.fetch_add(1, Ordering::SeqCst); + } + + let host = Box::leak(Box::new(Host { + strings: Vec::new(), + profile: unsafe { std::mem::zeroed() }, + identities: Vec::new(), + wallet: WalletRestoreEntryFFI::default(), + frees: AtomicUsize::new(0), + })); + let persister = FFIPersister::new(PersistenceCallbacks { + context: (host as *mut Host).cast(), + on_load_wallet_list_fn: Some(load_wallet), + on_load_wallet_list_free_fn: Some(free_wallet), + ..Default::default() + }); + let snapshot = persister.load().expect("host snapshot"); + assert_eq!(host.frees.load(Ordering::SeqCst), 1, "host buffers freed"); + + let bucket = &snapshot.wallets[&[42; 32]] + .identity_manager + .wallet_identities[&[42; 32]]; + let profile = bucket[&0] + .dashpay() + .profile + .clone() + .expect("owned profile restored"); + assert_eq!( + profile, + platform_wallet::DashPayProfile { + display_name: Some("Alice".into()), + bio: Some("bio text".into()), + avatar_url: Some("https://example.com/a.png".into()), + avatar_hash: Some([0xA1; 32]), + avatar_fingerprint: Some([0xF1; 8]), + public_message: Some("hello".into()), + core_payment_address: Some(transparent_address(0x00, 0xC1).to_vec()), + platform_payment_address: Some(transparent_address(0x01, 0xD1).to_vec()), + shielded_address: shielded_fixture().1, + } + ); + assert!( + bucket[&1].dashpay().profile.is_none(), + "a null profile pointer restores no profile" + ); + + let mut managed = bucket[&0].clone(); + managed.identity.set_balance(8); + let entry = IdentityEntry::from_managed(&managed); + assert_eq!(entry.balance, 8); + assert_eq!( + entry.dashpay_profile.as_ref().unwrap().shielded_address, + shielded_fixture().1, + "an unrelated scalar snapshot retains restored public address metadata" + ); + assert_eq!(entry.dashpay_profile, Some(profile)); + } + unsafe extern "C" fn noop_free_wallets( _ctx: *mut c_void, _entries: *const WalletRestoreEntryFFI, @@ -12102,6 +12532,16 @@ mod tests { PersistenceCallbacksExtension, on_load_private_contact_scan_state_wallets_free_fn ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_dashpay_profiles_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_dashpay_profiles_fn + ) + std::mem::size_of::>(), std::mem::size_of::() ); assert_eq!( @@ -13831,6 +14271,13 @@ mod tests { avatar_hash_present: true, avatar_fingerprint: [0x22; 8], avatar_fingerprint_present: true, + core_payment_address: [0; 21], + core_payment_address_present: false, + platform_payment_address: [0; 21], + platform_payment_address_present: false, + shielded_address: shielded_fixture().0, + shielded_address_present: true, + public_message: public_message.as_ptr(), checked_at_ms: 1_700_000_000_000, }, @@ -13843,6 +14290,13 @@ mod tests { avatar_hash_present: false, avatar_fingerprint: [0u8; 8], avatar_fingerprint_present: false, + core_payment_address: [0; 21], + core_payment_address_present: false, + platform_payment_address: [0; 21], + platform_payment_address_present: false, + shielded_address: [0; 43], + shielded_address_present: false, + public_message: std::ptr::null(), checked_at_ms: 1_700_000_000_001, }, @@ -13867,6 +14321,7 @@ mod tests { ); assert_eq!(alice_profile.avatar_hash, Some([0x11; 32])); assert_eq!(alice_profile.avatar_fingerprint, Some([0x22; 8])); + assert_eq!(alice_profile.shielded_address, shielded_fixture().1); assert!(alice_profile.bio.is_none()); let bob = managed diff --git a/packages/rs-platform-wallet-ffi/src/private_contact_request.rs b/packages/rs-platform-wallet-ffi/src/private_contact_request.rs index a9940b6ecc6..3f3ce470fcd 100644 --- a/packages/rs-platform-wallet-ffi/src/private_contact_request.rs +++ b/packages/rs-platform-wallet-ffi/src/private_contact_request.rs @@ -1697,11 +1697,8 @@ mod tests { PLATFORM_WALLET_STORAGE .with_item(wallet_handle, |wallet| { runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; - let manager = &mut wm - .get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") - .identity_manager; + let mut state = wallet.state_mut().await.expect("live wallet state"); + let manager = &mut state.identity_manager; manager .add_identity(bob.clone(), 0, wallet.wallet_id(), wallet.persister()) .expect("Bob"); @@ -1828,9 +1825,8 @@ mod tests { revision: 0, }); runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; - wm.get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") + let mut state = wallet.state_mut().await.expect("live wallet state"); + state .identity_manager .add_identity(identity, 0, wallet.wallet_id(), wallet.persister()) .expect("the identity"); diff --git a/packages/rs-platform-wallet-ffi/src/runtime.rs b/packages/rs-platform-wallet-ffi/src/runtime.rs index ee96010db00..7af3fb933ea 100644 --- a/packages/rs-platform-wallet-ffi/src/runtime.rs +++ b/packages/rs-platform-wallet-ffi/src/runtime.rs @@ -18,6 +18,9 @@ //! on the caller, but it parks almost immediately — all the //! compute happens on the tokio worker. +#[cfg(feature = "shielded")] +use crate::error::{catch_panic_to_code, PlatformWalletFFIResult, PlatformWalletFFIResultCode}; + /// Worker thread stack size for the shared runtime. 8 MB gives proof /// verification + GroveDB comfortable headroom without meaningfully /// affecting memory footprint (we spin up a small number of workers). @@ -89,6 +92,30 @@ pub(crate) fn run_on_big_stack_thread(f: impl FnOnce() -> T + Send) -> }) } +/// Post-panic guidance for exports that move no funds. Paired with +/// `ErrorWalletOperation` in [`catch_query_panic`]. +#[cfg(feature = "shielded")] +const QUERY_PANIC_GUIDANCE: &str = "No funds were moved; the call may be retried."; + +/// [`catch_panic_to_code`] specialized for exports that spend nothing (address +/// preparation, recipient resolution). A panic there is a plain failure of this +/// call, so it maps to [`PlatformWalletFFIResultCode::ErrorWalletOperation`] and +/// the host may retry. The boundary matters as much as on the spend path: an +/// unwind that reaches the `extern "C"` frame aborts the process before the JNI +/// guard on the far side can translate it. +#[cfg(feature = "shielded")] +pub(crate) fn catch_query_panic( + operation: &str, + body: impl FnOnce() -> PlatformWalletFFIResult, +) -> PlatformWalletFFIResult { + catch_panic_to_code( + operation, + PlatformWalletFFIResultCode::ErrorWalletOperation, + QUERY_PANIC_GUIDANCE, + body, + ) +} + #[cfg(test)] mod tests { use super::*; diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 2c28e59d1ad..141a6db1783 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -43,6 +43,7 @@ use std::ffi::CStr; use std::os::raw::{c_char, c_void}; use dpp::address_funds::{OrchardAddress, PlatformAddress}; +use dpp::prelude::Identifier; use dpp::shielded::{ compute_minimum_shielded_fee, compute_shielded_identity_balance_write_fee, compute_shielded_identity_top_up_fee, compute_shielded_unshield_fee, @@ -52,7 +53,7 @@ use dpp::state_transition::public_key_in_creation::IdentityPublicKeyInCreation; use dpp::ProtocolError; use platform_wallet::wallet::asset_lock::AssetLockFunding; use platform_wallet::wallet::shielded::CachedOrchardProver; -use platform_wallet::PlatformWalletError; +use platform_wallet::{PlatformWalletError, ShieldedTipSource}; use rs_sdk_ffi::{ MnemonicResolverCoreSigner, MnemonicResolverHandle, SignerHandle, VTableSigner, DASH_SDK_SIGNER_ERR_KEY_UNAVAILABLE_PREFIX, @@ -64,7 +65,7 @@ use crate::core_wallet_types::OutPointFFI; use crate::error::*; use crate::handle::*; use crate::identity_registration_with_signer::{decode_identity_pubkeys, IdentityPubkeyFFI}; -use crate::runtime::{block_on_worker, runtime}; +use crate::runtime::{block_on_worker, catch_query_panic, runtime}; use crate::shielded_types::{ShieldedIdentityDebitRecoveryRecordFFI, ShieldedShieldPreflightFFI}; use crate::types::read_identifier; use crate::unwrap_result_or_return; @@ -749,6 +750,26 @@ pub(crate) fn catch_spend_panic( ) } +/// Test-only fault injection for the tip exports: while set, the worker future +/// of each guarded tip call panics before it touches the wallet, so a test can +/// prove the real `extern "C"` entry point (not just the helper) contains the +/// unwind. Process-global because the future runs on a tokio worker thread; +/// consulted only by the three tip exports. +#[cfg(test)] +static INJECT_TIP_WORKER_PANIC: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + +#[cfg(test)] +fn maybe_inject_tip_worker_panic() { + if INJECT_TIP_WORKER_PANIC.load(std::sync::atomic::Ordering::SeqCst) { + panic!("injected tip worker panic"); + } +} + +#[cfg(not(test))] +#[inline(always)] +fn maybe_inject_tip_worker_panic() {} + /// Post-panic guidance for the asset-lock funding exports. Paired with /// `ErrorTransactionBroadcastUnconfirmed` in [`catch_funding_panic`]. const FUNDING_PANIC_GUIDANCE: &str = "The asset lock may or may not have been broadcast — do \ @@ -895,9 +916,9 @@ fn map_asset_lock_funding_result( /// independently if needed. /// /// `out_identity_id` is ALSO written on the [`ErrorShieldedBroadcastUnconfirmed`] result code: the -/// broadcast was accepted but its execution result couldn't be confirmed, so the derived id is -/// handed back (the identity may already exist on chain) and the host must hold the slot rather than -/// treat the registration as failed. On every other error code `out_identity_id` is left untouched. +/// broadcast could not be confirmed, or creation succeeded on chain but local registration failed. +/// The diagnostic distinguishes these outcomes. The host must hold the slot rather than re-submit +/// creation. On every other error code `out_identity_id` is left untouched. /// /// [`ErrorShieldedBroadcastUnconfirmed`]: crate::error::PlatformWalletFFIResultCode::ErrorShieldedBroadcastUnconfirmed /// @@ -1035,13 +1056,20 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_identity_create_from_p r }); + map_identity_create_result(result, &mut *out_identity_id) +} + +fn map_identity_create_result( + result: Result, + out_identity_id: &mut [u8; 32], +) -> PlatformWalletFFIResult { match result { Ok(identity_id) => { *out_identity_id = identity_id.to_buffer(); PlatformWalletFFIResult::ok() } // Broadcast accepted but its execution result couldn't be confirmed and a direct fetch came - // back empty. The identity MAY exist on chain, so — unlike every other error arm — we still + // back empty. The identity MAY exist on chain, so we still // write the derived id to `out_identity_id` (see the `# Safety` note) so the caller can hold // the slot against re-submission and surface the pending identity. The notes' reservations // were intentionally NOT released wallet-side. @@ -1057,6 +1085,13 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_identity_create_from_p ), ) } + Err(error @ PlatformWalletError::IdentityCreatedButNotRegistered { identity_id, .. }) => { + *out_identity_id = identity_id.to_buffer(); + PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorShieldedBroadcastUnconfirmed, + error.to_string(), + ) + } // Retryable: no Platform-recorded anchor covered the selected notes yet // (the commitment tree is mid-block after an index-chunk sync). Nothing // was broadcast and the notes were released, so the host may retry after @@ -2346,6 +2381,268 @@ pub(crate) fn resolve_shielded_coordinator( } } +/// Derive and register the identity's dedicated shielded account, without publishing it. +/// All ID pointers must reference 32 bytes; `out_address` must reference 43 writable bytes. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_prepare_shielded_identity_address( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + identity_id_bytes: *const u8, + out_address: *mut u8, +) -> PlatformWalletFFIResult { + check_ptr!(wallet_id_bytes); + check_ptr!(mnemonic_resolver_handle); + check_ptr!(identity_id_bytes); + check_ptr!(out_address); + std::ptr::write_bytes(out_address, 0, 43); + let wallet_id: [u8; 32] = std::slice::from_raw_parts(wallet_id_bytes, 32) + .try_into() + .unwrap(); + let identity_id = match crate::types::read_identifier(identity_id_bytes) { + Ok(id) => id, + Err(e) => return e.into(), + }; + // Wallet, coordinator and seed resolution, the worker call and its result + // mapping all sit inside the panic boundary (resolution blocks on the + // runtime, which panics when the host calls from inside one); the raw + // output write happens outside it, only on success, so a panic leaves the + // zeroed buffer untouched. + let mut address = [0u8; 43]; + let result = catch_query_panic("shielded identity address preparation", || { + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(value) => value, + Err(e) => return e, + }; + let seed = match crate::identity_keys_from_mnemonic::resolve_seed_from_resolver( + mnemonic_resolver_handle, + &wallet_id, + ) { + Ok(value) => value, + Err(e) => return e, + }; + match block_on_worker(async move { + maybe_inject_tip_worker_panic(); + wallet + .prepare_shielded_identity_address(seed.as_ref(), &identity_id, &coordinator) + .await + }) { + Ok(bytes) => { + address = bytes; + PlatformWalletFFIResult::ok() + } + Err(e) => e.into(), + } + }); + if result.code == PlatformWalletFFIResultCode::Success { + std::ptr::copy_nonoverlapping(address.as_ptr(), out_address, 43); + } + result +} + +/// Resolve a username using verified current DPNS and profile documents. +/// Outputs are 32-byte identity ID and 43-byte Orchard address buffers. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_resolve_shielded_tip( + wallet_handle: Handle, + username: *const c_char, + out_identity_id: *mut u8, + out_address: *mut u8, +) -> PlatformWalletFFIResult { + check_ptr!(username); + check_ptr!(out_identity_id); + check_ptr!(out_address); + std::ptr::write_bytes(out_identity_id, 0, 32); + std::ptr::write_bytes(out_address, 0, 43); + let username = match CStr::from_ptr(username).to_str() { + Ok(s) => s.to_owned(), + Err(e) => return e.into(), + }; + let mut identity_id = [0u8; 32]; + let mut address = [0u8; 43]; + let result = catch_query_panic("shielded tip resolution", || { + // Clone under the registry guard, then release it: the resolution makes + // DPNS and profile network requests, and holding the global wallet + // registry lock across them would block handle creation and teardown + // for unrelated wallets. + let identity = + PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| wallet.identity().clone()); + let result = identity.map(|identity| { + block_on_worker(async move { + maybe_inject_tip_worker_panic(); + identity.dashpay().resolve_shielded_tip(&username).await + }) + }); + match result { + Some(Ok(recipient)) => { + identity_id = recipient.identity_id.to_buffer(); + address = recipient.address; + PlatformWalletFFIResult::ok() + } + Some(Err(e)) => e.into(), + None => PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::NotFound, + "Wallet not found", + ), + } + }); + if result.code == PlatformWalletFFIResultCode::Success { + std::ptr::copy_nonoverlapping(identity_id.as_ptr(), out_identity_id, 32); + std::ptr::copy_nonoverlapping(address.as_ptr(), out_address, 43); + } + result +} + +/// [`ShieldedTipSourceFFI::kind`]: spend the dedicated tip account of the +/// wallet identity `identity_id`. +pub const SHIELDED_TIP_SOURCE_IDENTITY: u32 = 0; +/// [`ShieldedTipSourceFFI::kind`]: spend `account` explicitly (an ordinary +/// account, or a retired identity's tip account). +pub const SHIELDED_TIP_SOURCE_ACCOUNT: u32 = 1; + +/// The account a shielded tip is paid from. The field `kind` does not use is +/// ignored. +#[repr(C)] +pub struct ShieldedTipSourceFFI { + pub kind: u32, + pub identity_id: [u8; 32], + pub account: u32, +} + +/// The wallet's [`ShieldedTipSource`] for an FFI source; the wallet decides +/// which account an identity's source selects. +fn decode_tip_source( + source: &ShieldedTipSourceFFI, +) -> Result { + match source.kind { + SHIELDED_TIP_SOURCE_IDENTITY => Ok(ShieldedTipSource::Identity(source.identity_id.into())), + SHIELDED_TIP_SOURCE_ACCOUNT => Ok(ShieldedTipSource::Account(source.account)), + _ => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "Invalid shielded tip source".to_string(), + )), + } +} + +/// Send a tip only if fresh resolution matches the recipient the user confirmed. +/// `source` must point to a readable [`ShieldedTipSourceFFI`]; the ID/address +/// pointers must reference 32/43 readable bytes respectively. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_send_shielded_tip( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + source: *const ShieldedTipSourceFFI, + username: *const c_char, + expected_identity_id: *const u8, + expected_address: *const u8, + amount: u64, + memo_text: *const c_char, +) -> PlatformWalletFFIResult { + check_ptr!(wallet_id_bytes); + check_ptr!(mnemonic_resolver_handle); + check_ptr!(source); + check_ptr!(username); + check_ptr!(expected_identity_id); + check_ptr!(expected_address); + let source = match decode_tip_source(&*source) { + Ok(source) => source, + Err(e) => return e, + }; + let username = match CStr::from_ptr(username).to_str() { + Ok(s) => s.to_owned(), + Err(e) => return e.into(), + }; + let wallet_id: [u8; 32] = std::slice::from_raw_parts(wallet_id_bytes, 32) + .try_into() + .unwrap(); + let identity_id = match crate::types::read_identifier(expected_identity_id) { + Ok(id) => id, + Err(e) => return e.into(), + }; + let address: [u8; 43] = std::slice::from_raw_parts(expected_address, 43) + .try_into() + .unwrap(); + let memo_str = match crate::dashpay_profile::decode_opt_c_str(memo_text) { + Ok(value) => value, + Err(e) => return e, + }; + let memo = match encode_memo_text(memo_str.as_deref()) { + Ok(value) => value, + Err(e) => return e, + }; + // Resolution blocks on the runtime and can panic before anything is + // spent, so it runs under the retryable query boundary; only the spend + // itself takes the do-not-retry contract below. + let mut resolved = None; + let preflight = catch_query_panic("shielded tip preflight", || { + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(value) => value, + Err(e) => return e, + }; + let seed = match crate::identity_keys_from_mnemonic::resolve_seed_from_resolver( + mnemonic_resolver_handle, + &wallet_id, + ) { + Ok(value) => value, + Err(e) => return e, + }; + resolved = Some((wallet, coordinator, seed)); + PlatformWalletFFIResult::ok() + }); + let Some((wallet, coordinator, seed)) = resolved else { + return preflight; + }; + catch_spend_panic("shielded tip", || { + let result = block_on_worker(async move { + maybe_inject_tip_worker_panic(); + let recipient = platform_wallet::ShieldedTipRecipient { + identity_id, + address, + }; + let prover = CachedOrchardProver::new(); + let result = wallet + .send_shielded_tip( + &coordinator, + seed.as_ref(), + source, + &username, + &recipient, + amount, + memo, + &prover, + ) + .await; + poke_sync_on_unconfirmed(&result, handle); + result + }); + map_spend_result(result, "shielded tip") + }) +} + +/// Return the dedicated ZIP-32 shielded account for a wallet identity derivation index. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_shielded_identity_account_index( + identity_index: u32, + out_account: *mut u32, +) -> PlatformWalletFFIResult { + check_ptr!(out_account); + *out_account = 0; + match platform_wallet::wallet::shielded::tips::shielded_identity_account_index(identity_index) { + Ok(account) => { + *out_account = account; + PlatformWalletFFIResult::ok() + } + Err(e) => e.into(), + } +} + +/// Whether an account is reserved for a wallet identity's shielded activity. +#[no_mangle] +pub extern "C" fn platform_wallet_is_shielded_identity_account(account: u32) -> bool { + platform_wallet::wallet::shielded::is_shielded_identity_account(account) +} + #[cfg(test)] mod tests { use super::*; @@ -2358,6 +2655,28 @@ mod tests { use platform_wallet::wallet::shielded::store::PendingRedrive; use platform_wallet::wallet::shielded::{FileBackedShieldedStore, ShieldedStore, SubwalletId}; + #[test] + fn should_decode_each_tip_source_kind_and_reject_others() { + let source = |kind| ShieldedTipSourceFFI { + kind, + identity_id: [7; 32], + account: 3, + }; + assert_eq!( + decode_tip_source(&source(SHIELDED_TIP_SOURCE_IDENTITY)).ok(), + Some(ShieldedTipSource::Identity([7; 32].into())) + ); + assert_eq!( + decode_tip_source(&source(SHIELDED_TIP_SOURCE_ACCOUNT)).ok(), + Some(ShieldedTipSource::Account(3)) + ); + let refused = decode_tip_source(&source(2)).unwrap_err(); + assert_eq!( + refused.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + } + #[test] fn encode_memo_text_none_is_empty() { let bytes = encode_memo_text(None).expect("None must encode"); @@ -2897,6 +3216,288 @@ mod tests { ); } + /// A fixed BIP-39 phrase the test resolver answers for every wallet id; + /// the wallet under test is created from the same phrase so the resolved + /// seed matches it. + const TIP_TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon \ + abandon abandon abandon abandon about"; + + unsafe extern "C" fn resolve_tip_test_mnemonic( + _ctx: *const std::ffi::c_void, + _wallet_id: *const u8, + out: *mut c_char, + cap: usize, + out_len: *mut usize, + ) -> i32 { + let phrase = TIP_TEST_MNEMONIC.as_bytes(); + assert!(cap >= phrase.len()); + std::ptr::copy_nonoverlapping(phrase.as_ptr(), out.cast::(), phrase.len()); + *out_len = phrase.len(); + rs_sdk_ffi::mnemonic_resolver_result::SUCCESS + } + + unsafe extern "C" fn destroy_tip_test_resolver(_ctx: *mut std::ffi::c_void) {} + + /// A manager with a configured shielded store and one wallet created from + /// `TIP_TEST_MNEMONIC`: the state a tip export needs to get past every + /// argument check and into its guarded worker call. + fn tip_test_manager() -> (Handle, [u8; 32], std::path::PathBuf) { + let handle = recovery_test_manager(); + let path = + std::env::temp_dir().join(format!("shielded-ffi-tip-{}-{handle}", std::process::id())); + std::fs::create_dir_all(&path).expect("temporary store directory"); + let wallet_id = PLATFORM_WALLET_MANAGER_STORAGE + .with_item(handle, |manager| { + runtime().block_on(async { + manager + .configure_shielded(path.join("tree.sqlite")) + .await + .expect("configure shielded store"); + manager + .create_wallet_from_mnemonic( + TIP_TEST_MNEMONIC, + key_wallet::Network::Testnet, + WalletAccountCreationOptions::Default, + Some(0), + ) + .await + .expect("register wallet") + .wallet_id() + }) + }) + .expect("live manager"); + (handle, wallet_id, path) + } + + /// A host calling from inside a Tokio runtime makes wallet resolution's + /// `block_on` panic before anything is spent. Both manager tip exports + /// must contain it as a retryable failure, with no address escaping. + #[test] + fn tip_manager_exports_contain_a_resolution_panic_inside_a_runtime() { + let (handle, wallet_id, path) = tip_test_manager(); + let mut vtable = rs_sdk_ffi::MnemonicResolverVTable { + resolve: resolve_tip_test_mnemonic, + destroy: destroy_tip_test_resolver, + }; + let mut resolver = MnemonicResolverHandle { + ctx: std::ptr::null_mut(), + vtable: &mut vtable, + }; + let username = std::ffi::CString::new("alice").expect("username"); + let identity_id = [0x21u8; 32]; + let address = [0x43u8; 43]; + let mut out_address = [0xAAu8; 43]; + + let (mut send, mut prepare) = runtime().block_on(async { + let send = unsafe { + platform_wallet_manager_send_shielded_tip( + handle, + wallet_id.as_ptr(), + &mut resolver, + &ShieldedTipSourceFFI { + kind: SHIELDED_TIP_SOURCE_ACCOUNT, + identity_id: [0; 32], + account: 0, + }, + username.as_ptr(), + identity_id.as_ptr(), + address.as_ptr(), + 1_000, + std::ptr::null(), + ) + }; + let prepare = unsafe { + platform_wallet_manager_prepare_shielded_identity_address( + handle, + wallet_id.as_ptr(), + &mut resolver, + identity_id.as_ptr(), + out_address.as_mut_ptr(), + ) + }; + (send, prepare) + }); + + assert_eq!(send.code, PlatformWalletFFIResultCode::ErrorWalletOperation); + let message = message_of(&send); + assert!( + message.contains("shielded tip preflight panicked") + && message.contains("may be retried"), + "{message}" + ); + assert_eq!( + prepare.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + let message = message_of(&prepare); + assert!( + message.contains("shielded identity address preparation panicked"), + "{message}" + ); + assert_eq!(out_address, [0u8; 43]); + + unsafe { + crate::platform_wallet_ffi_result_free(&mut send); + crate::platform_wallet_ffi_result_free(&mut prepare); + let mut destroyed = platform_wallet_manager_destroy(handle); + crate::platform_wallet_ffi_result_free(&mut destroyed); + } + let _ = std::fs::remove_dir_all(path); + } + + /// The real exports contain a worker panic instead of letting it unwind into + /// the `extern "C"` frame: this drives the exported entry points themselves, + /// so deleting a guard at a call site fails here even while the helper-level + /// tests below stay green. One test covers all three exports because the + /// injection flag is process-global. + #[test] + fn exported_tip_entry_points_contain_a_worker_panic() { + use std::sync::atomic::Ordering::SeqCst; + + let (handle, wallet_id, path) = tip_test_manager(); + let mut vtable = rs_sdk_ffi::MnemonicResolverVTable { + resolve: resolve_tip_test_mnemonic, + destroy: destroy_tip_test_resolver, + }; + let mut resolver = MnemonicResolverHandle { + ctx: std::ptr::null_mut(), + vtable: &mut vtable, + }; + let username = std::ffi::CString::new("alice").expect("username"); + let identity_id = [0x21u8; 32]; + let address = [0x43u8; 43]; + + INJECT_TIP_WORKER_PANIC.store(true, SeqCst); + + // Spending export: the ambiguous, do-not-retry contract. + let mut send = unsafe { + platform_wallet_manager_send_shielded_tip( + handle, + wallet_id.as_ptr(), + &mut resolver, + &ShieldedTipSourceFFI { + kind: SHIELDED_TIP_SOURCE_ACCOUNT, + identity_id: [0; 32], + account: 0, + }, + username.as_ptr(), + identity_id.as_ptr(), + address.as_ptr(), + 1_000, + std::ptr::null(), + ) + }; + assert_eq!( + send.code, + PlatformWalletFFIResultCode::ErrorShieldedSpendUnconfirmed + ); + let message = message_of(&send); + assert!( + message.contains("injected tip worker panic") && message.contains("do NOT retry"), + "{message}" + ); + + // Non-spending exports: a retryable failure with the outputs left zeroed. + let mut out_address = [0xAAu8; 43]; + let mut prepare = unsafe { + platform_wallet_manager_prepare_shielded_identity_address( + handle, + wallet_id.as_ptr(), + &mut resolver, + identity_id.as_ptr(), + out_address.as_mut_ptr(), + ) + }; + assert_eq!( + prepare.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + let message = message_of(&prepare); + assert!( + message.contains("injected tip worker panic") && message.contains("may be retried"), + "{message}" + ); + assert_eq!( + out_address, [0u8; 43], + "no address may escape a failed call" + ); + + let mut wallet_handle = NULL_HANDLE; + let mut got = unsafe { + crate::manager::platform_wallet_manager_get_wallet( + handle, + &wallet_id, + &mut wallet_handle, + ) + }; + assert_eq!(got.code, PlatformWalletFFIResultCode::Success); + let mut out_identity = [0xAAu8; 32]; + let mut out_recipient = [0xAAu8; 43]; + let mut resolve = unsafe { + platform_wallet_resolve_shielded_tip( + wallet_handle, + username.as_ptr(), + out_identity.as_mut_ptr(), + out_recipient.as_mut_ptr(), + ) + }; + assert_eq!( + resolve.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + assert!(message_of(&resolve).contains("injected tip worker panic")); + assert_eq!(out_identity, [0u8; 32]); + assert_eq!(out_recipient, [0u8; 43]); + + INJECT_TIP_WORKER_PANIC.store(false, SeqCst); + unsafe { + crate::platform_wallet_ffi_result_free(&mut send); + crate::platform_wallet_ffi_result_free(&mut prepare); + crate::platform_wallet_ffi_result_free(&mut resolve); + crate::platform_wallet_ffi_result_free(&mut got); + let mut destroyed = crate::wallet::platform_wallet_destroy(wallet_handle); + crate::platform_wallet_ffi_result_free(&mut destroyed); + let mut destroyed = platform_wallet_manager_destroy(handle); + crate::platform_wallet_ffi_result_free(&mut destroyed); + } + let _ = std::fs::remove_dir_all(path); + } + + #[test] + fn catch_query_panic_maps_a_panic_to_a_retryable_wallet_operation() { + let result = catch_query_panic("shielded tip resolution", || { + panic!("tokio worker panicked"); + }); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + let message = message_of(&result); + assert!( + message.contains("shielded tip resolution panicked") + && message.contains("tokio worker panicked") + && message.contains("may be retried"), + "{message}" + ); + } + + #[test] + fn should_contain_tip_worker_panic_as_uncertain_spend() { + let result = catch_spend_panic("shielded tip", || { + let result = block_on_worker(async { + panic!("tip worker failed after possible broadcast"); + #[allow(unreachable_code)] + Ok(()) + }); + map_spend_result(result, "shielded tip") + }); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorShieldedSpendUnconfirmed + ); + assert!(message_of(&result).contains("do NOT retry")); + } + /// A panic inside the CoinJoin-drain funding export must NOT unwind into the `extern "C"` /// frame (that aborts the Android process before the JNI layer's own guard can translate it /// into a Java exception). It becomes `ErrorTransactionBroadcastUnconfirmed` — the @@ -2926,6 +3527,53 @@ mod tests { ); } + #[test] + fn should_preserve_created_identity_and_hold_its_slot_after_local_registration_failure() { + let identity_id = Identifier::from([0x42; 32]); + let error = PlatformWalletError::IdentityCreatedButNotRegistered { + identity_id, + reason: "identity slot is occupied".to_string(), + }; + let diagnostic = error.to_string(); + let mut out_identity_id = [0; 32]; + let mut result = map_identity_create_result(Err(error), &mut out_identity_id); + + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorShieldedBroadcastUnconfirmed + ); + assert_eq!(out_identity_id, identity_id.to_buffer()); + assert_eq!(message_of(&result), diagnostic); + assert!(diagnostic.contains("created on chain")); + assert!(diagnostic.contains("could not be registered locally")); + assert!(diagnostic.contains("do not re-submit")); + unsafe { platform_wallet_ffi_result_free(&mut result) }; + } + + #[test] + fn should_preserve_unconfirmed_identity_create_diagnostic_and_id() { + let identity_id = Identifier::from([0x43; 32]); + let mut out_identity_id = [0; 32]; + let mut result = map_identity_create_result( + Err(PlatformWalletError::ShieldedBroadcastUnconfirmed { + identity_id, + reason: "result proof unavailable".to_string(), + }), + &mut out_identity_id, + ); + + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorShieldedBroadcastUnconfirmed + ); + assert_eq!(out_identity_id, identity_id.to_buffer()); + assert_eq!( + message_of(&result), + format!("shielded identity-create-from-pool broadcast unconfirmed (identity {identity_id} may exist on chain): result proof unavailable") + ); + unsafe { platform_wallet_ffi_result_free(&mut result) }; + } + /// `map_spend_result` pins the retry-relevant code split the three spend /// entry points depend on: /// - `ShieldedSpendUnconfirmed` → `ErrorShieldedSpendUnconfirmed` (host diff --git a/packages/rs-platform-wallet-ffi/src/shielded_sync.rs b/packages/rs-platform-wallet-ffi/src/shielded_sync.rs index 3cdf55f5e1e..b80aa218eb5 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_sync.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_sync.rs @@ -20,7 +20,7 @@ use platform_wallet::PlatformWalletError; use crate::error::*; use crate::handle::*; -use crate::runtime::{block_on_worker, runtime}; +use crate::runtime::{block_on_worker, catch_query_panic, runtime}; use crate::shielded_types::{ ShieldedBalanceSourceFFI, ShieldedLocalAccountBalanceFFI, ShieldedLocalBalanceSnapshotFFI, ShieldedLocalBalanceStatusFFI, ShieldedSyncWalletResultFFI, @@ -890,6 +890,135 @@ fn map_shielded_error(error: PlatformWalletError, operation: &str) -> PlatformWa } } +/// Snapshot the effective bound accounts, including discovered and restored tip +/// accounts. An unbound wallet returns an empty array. The caller must release +/// a nonempty result with `platform_wallet_manager_free_shielded_account_indices`. +/// +/// # Safety +/// `wallet_id_bytes` must point to 32 readable bytes; both output pointers must +/// be writable. Returned indices are valid until freed by the caller. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_shielded_account_indices( + handle: Handle, + wallet_id_bytes: *const u8, + out_indices: *mut *mut u32, + out_count: *mut usize, +) -> PlatformWalletFFIResult { + check_ptr!(out_indices); + check_ptr!(out_count); + *out_indices = std::ptr::null_mut(); + *out_count = 0; + check_ptr!(wallet_id_bytes); + let mut wallet_id = [0; 32]; + std::ptr::copy_nonoverlapping(wallet_id_bytes, wallet_id.as_mut_ptr(), 32); + // The whole lookup runs inside the panic boundary, polled on a worker + // rather than this host thread; the outputs stay cleared on any failure. + catch_query_panic("shielded account snapshot", || { + let option = PLATFORM_WALLET_MANAGER_STORAGE + .with_item(handle, |manager| manager.get_wallet_blocking(&wallet_id)); + let Some(wallet) = unwrap_option_or_return!(option) else { + return PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorWalletOperation, + "wallet not found", + ); + }; + let indices = block_on_worker(async move { wallet.shielded_account_indices().await }); + if !indices.is_empty() { + *out_count = indices.len(); + *out_indices = Box::into_raw(indices.into_boxed_slice()) as *mut u32; + } + PlatformWalletFFIResult::ok() + }) +} + +/// Release an account snapshot returned by the matching getter. Null is a no-op. +/// +/// # Safety +/// A nonnull pointer and count must be an unfreed pair from +/// `platform_wallet_manager_shielded_account_indices`. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_free_shielded_account_indices( + indices: *mut u32, + count: usize, +) { + if !indices.is_null() { + drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut( + indices, count, + ))); + } +} + +#[cfg(test)] +mod account_indices_tests { + use super::*; + use crate::test_fixtures::mock_manager; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + + #[test] + fn invalid_handle_clears_account_snapshot_outputs() { + let mut indices = std::ptr::NonNull::::dangling().as_ptr(); + let mut count = 99; + let wallet_id = [0; 32]; + unsafe { + let result = platform_wallet_manager_shielded_account_indices( + 0, + wallet_id.as_ptr(), + &mut indices, + &mut count, + ); + assert_ne!(result.code, PlatformWalletFFIResultCode::Success); + assert!(indices.is_null()); + assert_eq!(count, 0); + platform_wallet_manager_free_shielded_account_indices(indices, count); + } + } + + /// A host calling from inside a Tokio runtime makes the worker helper's + /// `block_on` panic; the export must turn that into an error result with + /// cleared outputs instead of unwinding into the C frame. + #[test] + fn should_contain_a_panic_and_clear_outputs_when_called_inside_a_runtime() { + let manager = mock_manager(); + let wallet_id = runtime().block_on(async { + manager + .create_wallet_from_seed_bytes( + dashcore::Network::Testnet, + &[7; 64], + WalletAccountCreationOptions::Default, + Some(0), + ) + .await + .expect("create mock wallet") + .wallet_id() + }); + let handle = PLATFORM_WALLET_MANAGER_STORAGE.insert(manager); + let mut indices = std::ptr::NonNull::::dangling().as_ptr(); + let mut count = 99; + let result = runtime().block_on(async { + unsafe { + platform_wallet_manager_shielded_account_indices( + handle, + wallet_id.as_ptr(), + &mut indices, + &mut count, + ) + } + }); + PLATFORM_WALLET_MANAGER_STORAGE.remove(handle); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + let message = unsafe { CStr::from_ptr(result.message) }.to_string_lossy(); + assert!( + message.contains("shielded account snapshot panicked"), + "{message}" + ); + assert!(indices.is_null()); + assert_eq!(count, 0); + } +} + #[cfg(test)] mod recovery_error_tests { use super::*; diff --git a/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs b/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs index 1efff04981a..bdea1baceee 100644 --- a/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs +++ b/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs @@ -991,11 +991,21 @@ mod tests { #[test] fn a_heal_page_is_held_only_under_a_run_claim() { use crate::test_fixtures::mock_manager; - - let handle = PLATFORM_WALLET_MANAGER_STORAGE.insert(mock_manager()); - let wallet_id = [0x6bu8; 32]; - let (reconciler, engine) = PLATFORM_WALLET_MANAGER_STORAGE - .with_item(handle, |m| (m.txo_reconciler(), m.wallet_manager_arc())) + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + + let manager = mock_manager(); + let wallet = crate::runtime::runtime() + .block_on(manager.create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[0x6b; 64], + WalletAccountCreationOptions::None, + Some(0), + )) + .expect("an empty wallet"); + let wallet_id = wallet.wallet_id(); + let handle = PLATFORM_WALLET_MANAGER_STORAGE.insert(manager); + let reconciler = PLATFORM_WALLET_MANAGER_STORAGE + .with_item(handle, |m| m.txo_reconciler()) .expect("manager"); let heal_page = |held: &mut *mut TxoReconcileHeldVerdictsFFI| { let mut rows: *const TxoHealRowFFI = std::ptr::null(); @@ -1034,11 +1044,11 @@ mod tests { assert_eq!(result.code, PlatformWalletFFIResultCode::Success); assert!(!held.is_null()); assert!( - engine.try_write().is_err(), + wallet.try_state_mut().is_none(), "the engine is held until the page is released" ); unsafe { platform_wallet_txo_reconcile_held_verdicts_free(held) }; - assert!(engine.try_write().is_ok()); + assert!(wallet.try_state_mut().is_some()); reconciler.finish(&wallet_id, TxoReconcileFinish::NotRun); drop(PLATFORM_WALLET_MANAGER_STORAGE.remove(handle)); @@ -1118,6 +1128,7 @@ mod tests { use std::sync::Arc; use crate::test_fixtures::mock_manager; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; /// Poll `condition` until it holds, failing after [`WAIT`]. fn wait_for(what: &str, condition: impl Fn() -> bool) { @@ -1128,8 +1139,17 @@ mod tests { } } - let handle = PLATFORM_WALLET_MANAGER_STORAGE.insert(mock_manager()); - let wallet_id = [0x5au8; 32]; + let manager = mock_manager(); + let wallet = crate::runtime::runtime() + .block_on(manager.create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[0x5a; 64], + WalletAccountCreationOptions::None, + Some(0), + )) + .expect("an empty wallet"); + let wallet_id = wallet.wallet_id(); + let handle = PLATFORM_WALLET_MANAGER_STORAGE.insert(manager); let (reconciler, engine) = PLATFORM_WALLET_MANAGER_STORAGE .with_item(handle, |m| (m.txo_reconciler(), m.wallet_manager_arc())) .expect("manager"); @@ -1170,8 +1190,12 @@ mod tests { // An engine writer queued behind the guard. With the guard held, a // fresh engine read is refused exactly while a writer waits. - let writer_engine = Arc::clone(&engine); - let writer = std::thread::spawn(move || drop(writer_engine.blocking_write())); + let writer_wallet = Arc::clone(&wallet); + let writer = std::thread::spawn(move || { + writer_wallet + .state_mut_blocking() + .expect("live wallet state"); + }); wait_for("the engine writer never queued behind the guard", || { engine.try_read().is_err() }); diff --git a/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs b/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs index e5cfdfa0dab..b230dba9d7a 100644 --- a/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs +++ b/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs @@ -358,6 +358,8 @@ pub struct IdentityRestoreEntryFFI { /// identity has no cached contact profiles. pub contact_profiles: *const ContactProfileRestoreEntryFFI, pub contact_profiles_count: usize, + /// Optional owned DashPay profile; contact_id is ignored. + pub dashpay_profile: *const ContactProfileRestoreEntryFFI, } /// One DashPay payment-history row to rehydrate into @@ -388,7 +390,7 @@ pub struct PaymentRestoreEntryFFI { /// the managed identity's contact-profile cache (keyed by the contact's identity /// id) at load. Mirrors the persist-side /// [`crate::identity_persistence::ContactProfileRowFFI`] field-for-field -/// (the leading `contact_id` key, the five public profile fields with +/// (the leading `contact_id` key, the public profile fields with /// their `_present` byte-array flags, and the trailing `checked_at_ms` /// self-heal timestamp). /// @@ -420,6 +422,13 @@ pub struct ContactProfileRestoreEntryFFI { pub avatar_fingerprint: [u8; 8], /// `true` iff the source `avatar_fingerprint` was `Some(_)`. pub avatar_fingerprint_present: bool, + pub core_payment_address: [u8; 21], + pub core_payment_address_present: bool, + pub platform_payment_address: [u8; 21], + pub platform_payment_address_present: bool, + pub shielded_address: [u8; 43], + pub shielded_address_present: bool, + /// NUL-terminated `publicMessage`, or null when `None`. pub public_message: *const std::os::raw::c_char, /// Wall-clock ms of the last fetch attempt — the diff --git a/packages/rs-platform-wallet-storage/SCHEMA.md b/packages/rs-platform-wallet-storage/SCHEMA.md index 94485778a6c..f6eefa8a1c9 100644 --- a/packages/rs-platform-wallet-storage/SCHEMA.md +++ b/packages/rs-platform-wallet-storage/SCHEMA.md @@ -132,6 +132,7 @@ erDiagram BLOB wallet_id FK "NULL = orphan identity (no parent wallet yet)" INTEGER identity_index "BIP-32 index; NULL for out-of-wallet identities" BLOB entry_blob "bincode-encoded IdentityEntry" + INTEGER entry_format "V021: 0 = pre-payment-address record, 1 = current" } IDENTITY_KEYS { @@ -153,6 +154,7 @@ erDiagram DASHPAY_PROFILES { BLOB identity_id PK "one row per identity" BLOB profile_blob "bincode-encoded DashPayProfile" + INTEGER profile_format "V021: 0 = pre-payment-address record, 1 = current" } DASHPAY_PAYMENTS_OVERLAY { @@ -488,6 +490,13 @@ every identity-scoped child writer, so a changeset carrying both an upsert and a removal for one identity commits instead of pulling the FK parent out from under its own child inserts. +`entry_format` (V021) stamps the bincode shape of `entry_blob`: 0 is the +record written before `DashPayProfile` gained its payment addresses, 1 the +current one. The writer always stamps 1; the reader dispatches on the stamp +(`schema::identity_profile_encoding::decode_identity`), so rows written +before V021 stay readable until they are rewritten. The DEFAULT is 1 and the +migration stamps the rows it finds 0, so only pre-V021 rows are ever legacy. + - PK: `identity_id`. - FK: `wallet_id → wallets(wallet_id) ON DELETE CASCADE` (nullable). - Index: `idx_identities_wallet(wallet_id)`. @@ -617,8 +626,15 @@ nullable `identities.wallet_id` link; no direct `wallet_id` column exists. At most one DashPay profile blob per identity. `None` profile maps to a DELETE rather than a NULL blob — the row is absent, not nulled. -`apply` writes these rows, but `load()` does not return them today; -`DashPaySyncManager` rebuilds the canonical profile from Platform. +`apply` also folds each explicit profile update or deletion into the identity's +canonical `entry_blob`, which `load()` reads. An identity scalar snapshot with +no profile preserves the stored profile; only an explicit profile overlay +establishes absence. + +`profile_format` (V021) stamps the bincode shape of `profile_blob` the same +way `identities.entry_format` does (0 = pre-payment-address record, 1 = +current); `schema::identity_profile_encoding::decode_profile` is the stamped +reader for the day `load()` grows one. - PK: `identity_id` (single-row-per-identity). - FK: `identity_id → identities(identity_id) ON DELETE CASCADE`. @@ -851,3 +867,4 @@ table-rebuild migration, as V004 does. | V018 | `V018__identity_hard_delete.rs` | Retires identity tombstoning. Adds `cascade_children_on_identity_delete` (brooms `identity_keys` / `contacts` / `ignored_senders` / `pending_contact_crypto` by the deleted identity id, covering the rows no live FK reaches) plus its access-path indexes `idx_contacts_owner`, `idx_ignored_senders_owner`, and `idx_pending_contact_crypto_owner`; purges every already-tombstoned identity and its dependents; drops `identities.tombstoned`. | | V019 | `V019__asset_lock_operation_id.rs` | Adds the nullable `asset_locks.operation_id BLOB` column (CHECK: NULL or exactly 16 bytes) that correlates a wallet-drain operation with its funding outpoint; the lifecycle blob is untouched. Adds the unique partial index `asset_locks_wallet_operation_id` on `(wallet_id, operation_id) WHERE operation_id IS NOT NULL` and the `asset_locks_operation_id_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `operation_id`. Purely additive; existing rows read back NULL. | | V020 | `V020__asset_lock_shielded_recipient.rs` | Adds the nullable `asset_locks.shielded_recipient BLOB` column (CHECK: NULL or exactly 43 bytes, the raw Orchard address) recording the recipient a shielded asset-lock funding was built to pay, so a resume after restart pays that recipient and refuses another; the lifecycle blob is untouched. Adds the `asset_locks_shielded_recipient_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `shielded_recipient`. Purely additive; existing rows read back NULL and keep accepting the resuming caller's recipient. | +| V021 | `V021__profile_address_encoding.rs` | Adds the encoding stamps `identities.entry_format` and `dashpay_profiles.profile_format` (`INTEGER NOT NULL DEFAULT 1 CHECK IN (0, 1)`) and stamps every row present at migration time 0. `DashPayProfile` gained the core, platform and shielded payment addresses, which widens the positional bincode record embedded in both blobs; the stamp routes each row to the decoder for the shape it carries (`schema::identity_profile_encoding`). | diff --git a/packages/rs-platform-wallet-storage/migrations/V021__profile_address_encoding.rs b/packages/rs-platform-wallet-storage/migrations/V021__profile_address_encoding.rs new file mode 100644 index 00000000000..2b98b77cd6a --- /dev/null +++ b/packages/rs-platform-wallet-storage/migrations/V021__profile_address_encoding.rs @@ -0,0 +1,19 @@ +//! Stamp the bincode encoding of `identities.entry_blob` and +//! `dashpay_profiles.profile_blob`. +//! +//! Payment addresses (core, platform, shielded) extend `DashPayProfile`, which +//! is embedded positionally in both blobs, so a record written before this +//! migration decodes only against the pre-address shape. The stamp says which +//! shape a row carries: 0 is the pre-address record, 1 the current one, and +//! `schema::identity_profile_encoding` holds the decoder for each. +//! +//! Every row present when the migration runs is stamped 0. The column DEFAULT +//! is 1, so a later insert that does not name the column is read as the shape +//! the current writer produces; the CHECK refuses a stamp no decoder knows. +pub fn migration() -> String { + "ALTER TABLE identities ADD COLUMN entry_format INTEGER NOT NULL DEFAULT 1 CHECK(entry_format IN (0, 1)); + UPDATE identities SET entry_format = 0; + ALTER TABLE dashpay_profiles ADD COLUMN profile_format INTEGER NOT NULL DEFAULT 1 CHECK(profile_format IN (0, 1)); + UPDATE dashpay_profiles SET profile_format = 0;" + .to_string() +} diff --git a/packages/rs-platform-wallet-storage/src/sqlite/mod.rs b/packages/rs-platform-wallet-storage/src/sqlite/mod.rs index 6ed1f6a26ee..a179d6336a7 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/mod.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/mod.rs @@ -51,3 +51,6 @@ pub use persister::{prune_backups_in, PruneReport, RetentionPolicy, SqlitePersis pub use reports::{CommitReport, DeleteWalletReport}; #[doc(inline)] pub use schema::core_pool::OwningAccount; + +// Versioned blob readers are useful to hosts inspecting pre-migration backups. +pub use schema::{dashpay::decode_profile, identities::decode_identity}; diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/blob.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/blob.rs index 88fc75b1ea7..fb3c80c452e 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/blob.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/blob.rs @@ -1,6 +1,9 @@ //! BLOB-column codec helpers: thin `bincode::serde` wrappers so every //! `_blob` column uses one encoding path. Schema evolution is gated by the -//! refinery migration version — no per-blob revision tag. +//! refinery migration version — no per-blob revision tag, except the +//! `entry_format` / `profile_format` row stamps V021 added for the two +//! blobs that embed the widened `DashPayProfile` record (see +//! `identity_profile_encoding`). //! //! [`encode_outpoint`] / [`decode_outpoint`] encode `dashcore::OutPoint` //! the same way for the `outpoint` PK columns. The key is variable-width, diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs index dad012fd907..2c1baae8ed5 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs @@ -8,18 +8,18 @@ //! indexed queries. Round-trip pinned by //! `tests/integration/sqlite_dashpay_overlay_contract.rs`. //! -//! # …which is why the payment overlay is also PATCHED into `entry_blob` +//! # Profile and payment overlays are also folded into `entry_blob` //! -//! Because `load()` reads only the identity blob, a payment row that reached +//! Because `load()` reads only the identity blob, a profile or payment that reached //! the overlay table alone is a write that does not survive a restart. The //! wallet-event adapter is the single writer of swept sent-payment verdicts //! and has no other durable channel for them, so [`apply`] finishes by -//! folding each overlay row into the owning identity's `entry_blob`. +//! folding each overlay row into the owning identity's `entry_blob`, including +//! confirmed-absent profile tombstones. //! -//! The fold is a read-modify-write of ONLY the `(txid -> PaymentEntry)` keys -//! the overlay names, run inside the persister's own write transaction: -//! payments the overlay does not mention, and every other field of the -//! entry, are read back and written out unchanged. That is what distinguishes +//! The folds modify only the named profile or `(txid -> PaymentEntry)` keys +//! inside the persister's own write transaction. Payments the overlay does +//! not mention and every other field of the entry survive unchanged. That is what distinguishes //! it from shipping a whole `IdentityEntry` from the caller — a snapshot //! captured before the lock was released would wholesale replace the blob and //! silently drop any payment another writer committed in between @@ -45,10 +45,18 @@ use platform_wallet::wallet::platform_wallet::WalletId; use crate::sqlite::error::WalletStorageError; use crate::sqlite::schema::blob; use crate::sqlite::schema::blob::impl_persistable_blob; +use crate::sqlite::schema::identity_profile_encoding::decode_identity; // PUBLIC material only: DashPay overlay types reaching `_blob` columns. impl_persistable_blob!(DashPayProfile, PaymentEntry); +// `profile_blob` carries an encoding stamp (`profile_format`, V021): 0 is the +// pre-payment-address `DashPayProfile` shape, 1 the current one. Every write +// stamps 1; nothing in the crate reads the column back yet (see the module +// doc), so the stamped decoder is exported for hosts and for the day `load()` +// grows a reader. +pub use super::identity_profile_encoding::decode_profile; + /// Both tables are keyed by identity only; their FK to /// `identities(identity_id)` cascades via the `wallets → identities` chain. /// `wallet_id` feeds the precondition check only — no column. @@ -69,9 +77,10 @@ pub fn apply( let mut delete_stmt = tx.prepare_cached("DELETE FROM dashpay_profiles WHERE identity_id = ?1")?; let mut insert_stmt = tx.prepare_cached( - "INSERT INTO dashpay_profiles (identity_id, profile_blob) \ - VALUES (?1, ?2) \ - ON CONFLICT(identity_id) DO UPDATE SET profile_blob = excluded.profile_blob", + "INSERT INTO dashpay_profiles (identity_id, profile_blob, profile_format) \ + VALUES (?1, ?2, 1) \ + ON CONFLICT(identity_id) DO UPDATE SET \ + profile_blob = excluded.profile_blob, profile_format = 1", )?; for (identity_id, profile) in profiles { match profile { @@ -84,6 +93,7 @@ pub fn apply( } } } + patch_profiles_into_entry_blobs(tx, profiles)?; } } if let Some(payments) = payments { @@ -121,6 +131,11 @@ pub fn apply( /// order the two mean: the snapshot is the round's view of the identity, the /// overlay is the round's view of the payments that moved. /// +/// The row is decoded through its `entry_format` stamp (a pre-V021 row is +/// the legacy shape) and written back in the current shape stamped 1 in the +/// same statement, so a payment-only rewrite never leaves current bytes +/// under a legacy stamp or reads legacy bytes as the current record. +/// /// A missing `identities` row is not an error here. The FK would have /// rejected the overlay insert above, so by this point the row exists for /// every identity in `payments` unless it was deleted inside this same @@ -130,28 +145,30 @@ fn patch_payments_into_entry_blobs( payments: &BTreeMap>, ) -> Result<(), WalletStorageError> { let mut read = tx.prepare_cached( - "SELECT length(entry_blob), entry_blob FROM identities WHERE identity_id = ?1", + "SELECT length(entry_blob), entry_blob, entry_format FROM identities \ + WHERE identity_id = ?1", + )?; + let mut write = tx.prepare_cached( + "UPDATE identities SET entry_blob = ?2, entry_format = 1 WHERE identity_id = ?1", )?; - let mut write = - tx.prepare_cached("UPDATE identities SET entry_blob = ?2 WHERE identity_id = ?1")?; for (identity_id, by_tx) in payments { if by_tx.is_empty() { continue; } - let stored: Option<(i64, Vec)> = read + let stored: Option<(i64, Vec, i64)> = read .query_row(params![identity_id.as_slice()], |row| { - Ok((row.get(0)?, row.get(1)?)) + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) }) .map(Some) .or_else(|e| match e { rusqlite::Error::QueryReturnedNoRows => Ok(None), other => Err(other), })?; - let Some((len, payload)) = stored else { + let Some((len, payload, format)) = stored else { continue; }; blob::check_size(len)?; - let mut entry: IdentityEntry = blob::decode(&payload)?; + let mut entry: IdentityEntry = decode_identity(&payload, format)?; for (tx_id, row) in by_tx { entry.dashpay_payments.insert(tx_id.clone(), row.clone()); } @@ -160,3 +177,36 @@ fn patch_payments_into_entry_blobs( } Ok(()) } + +fn patch_profiles_into_entry_blobs( + tx: &Transaction<'_>, + profiles: &BTreeMap>, +) -> Result<(), WalletStorageError> { + let mut read = tx.prepare_cached( + "SELECT length(entry_blob), entry_blob, entry_format FROM identities \ + WHERE identity_id = ?1", + )?; + let mut write = tx.prepare_cached( + "UPDATE identities SET entry_blob = ?2, entry_format = 1 WHERE identity_id = ?1", + )?; + for (identity_id, profile) in profiles { + let stored: Option<(i64, Vec, i64)> = read + .query_row(params![identity_id.as_slice()], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) + }) + .map(Some) + .or_else(|e| match e { + rusqlite::Error::QueryReturnedNoRows => Ok(None), + other => Err(other), + })?; + let Some((len, payload, format)) = stored else { + continue; + }; + blob::check_size(len)?; + let mut entry: IdentityEntry = decode_identity(&payload, format)?; + entry.dashpay_profile = profile.clone(); + let patched = blob::encode(&entry)?; + write.execute(params![identity_id.as_slice(), patched])?; + } + Ok(()) +} diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs index d29c622f5eb..406ef862c7d 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs @@ -22,6 +22,11 @@ use crate::sqlite::schema::blob::impl_persistable_blob; // PUBLIC material only: identity snapshot reaching the `entry_blob` column. impl_persistable_blob!(IdentityEntry); +// `entry_blob` carries an encoding stamp (`entry_format`, V021): 0 is the +// pre-payment-address `IdentityEntry` shape, 1 the current one. Every write +// stamps 1; the stamped reader keeps rows written before V021 decodable. +pub use super::identity_profile_encoding::decode_identity; + /// Write the changeset's inserted / updated identities. /// /// The insert half of a two-part apply: [`apply_removals`] must run for @@ -49,12 +54,13 @@ pub fn apply_upserts( // upsert without erroring), preserving the resident blob and index. // `IS` is the NULL-safe match for the nullable column. let mut stmt = tx.prepare_cached( - "INSERT INTO identities (identity_id, wallet_id, identity_index, entry_blob) \ - VALUES (?1, ?2, ?3, ?4) \ + "INSERT INTO identities (identity_id, wallet_id, identity_index, entry_blob, entry_format) \ + VALUES (?1, ?2, ?3, ?4, 1) \ ON CONFLICT(identity_id) DO UPDATE SET \ wallet_id = COALESCE(identities.wallet_id, excluded.wallet_id), \ identity_index = excluded.identity_index, \ - entry_blob = excluded.entry_blob \ + entry_blob = excluded.entry_blob, \ + entry_format = 1 \ WHERE identities.wallet_id IS NULL OR identities.wallet_id IS excluded.wallet_id", )?; let wallet_id_param = wallet_id_to_param(wallet_id); @@ -81,7 +87,22 @@ pub fn apply_upserts( }); } } - let payload = blob::encode(entry)?; + let mut entry = entry.clone(); + if entry.dashpay_profile.is_none() { + let stored: Option<(i64, Vec, i64)> = tx + .query_row( + "SELECT length(entry_blob), entry_blob, entry_format FROM identities \ + WHERE identity_id = ?1 AND (wallet_id IS NULL OR wallet_id IS ?2)", + params![id.as_slice(), wallet_id_param], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .optional()?; + if let Some((len, payload, format)) = stored { + blob::check_size(len)?; + entry.dashpay_profile = decode_identity(&payload, format)?.dashpay_profile; + } + } + let payload = blob::encode(&entry)?; stmt.execute(params![ id.as_slice(), wallet_id_param, @@ -280,7 +301,7 @@ pub fn fetch( // the identity-id row can't leak through; sentinel matches orphan rows. let wallet_id_param = wallet_id_to_param(wallet_id); let mut stmt = conn.prepare( - "SELECT length(entry_blob), entry_blob FROM identities \ + "SELECT length(entry_blob), entry_blob, entry_format FROM identities \ WHERE identity_id = ?1 AND wallet_id IS ?2", )?; let mut rows = stmt.query(params![&identity_id[..], wallet_id_param])?; @@ -289,7 +310,7 @@ pub fn fetch( Some(row) => { blob::check_size(row.get::<_, i64>(0)?)?; let payload: Vec = row.get(1)?; - Ok(Some(blob::decode(&payload)?)) + Ok(Some(decode_identity(&payload, row.get(2)?)?)) } } } @@ -351,7 +372,7 @@ pub fn load_state_with_ctx( // unowned bucket. A plain `=` could not express the second case at all. let wallet_id_param = wallet_id_to_param(wallet_id); let mut stmt = conn.prepare( - "SELECT identity_id, length(entry_blob), entry_blob, identity_index \ + "SELECT identity_id, length(entry_blob), entry_blob, identity_index, entry_format \ FROM identities WHERE wallet_id IS ?1 ORDER BY identity_id", )?; // The ignored-senders TABLE is the authoritative ignore record (every @@ -366,7 +387,7 @@ pub fn load_state_with_ctx( blob::check_size(row.get::<_, i64>(1)?)?; let payload: Vec = row.get(2)?; let typed_identity_index: Option = row.get(3)?; - let entry: IdentityEntry = blob::decode(&payload)?; + let entry: IdentityEntry = decode_identity(&payload, row.get(4)?)?; // Cross-check the decoded blob against the typed columns it was // selected by (mirrors the accounts / identity_keys readers): the // blob must name the same identity, and its own wallet_id (when set) @@ -572,8 +593,9 @@ pub fn ensure_exists( let payload = blob::encode(&stub)?; let wallet_id_param = wallet_id_to_param(wallet_id); conn.execute( - "INSERT OR IGNORE INTO identities (identity_id, wallet_id, identity_index, entry_blob) \ - VALUES (?1, ?2, NULL, ?3)", + "INSERT OR IGNORE INTO identities \ + (identity_id, wallet_id, identity_index, entry_blob, entry_format) \ + VALUES (?1, ?2, NULL, ?3, 1)", params![&identity_id[..], wallet_id_param, payload], )?; Ok(()) diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/identity_profile_encoding.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/identity_profile_encoding.rs new file mode 100644 index 00000000000..1a392663409 --- /dev/null +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/identity_profile_encoding.rs @@ -0,0 +1,259 @@ +//! Frozen pre-V021 profile records, and the stamped decoders that route each +//! `identities.entry_blob` / `dashpay_profiles.profile_blob` row to the shape +//! it carries. Do not edit the legacy field order. +//! +//! `DashPayProfile` gained its payment addresses as trailing `Option` fields. +//! Under `bincode::serde` a struct is a fixed-arity positional record, so a +//! record written before the widening is never "short": the trailing fields +//! are simply absent, and decoding it against the current shape reads the +//! next field's bytes as an address. The row stamp (V021) is what says which +//! shape to decode; `serde(default)` on the new fields serves map formats +//! such as JSON only. +use super::blob; +use crate::sqlite::error::WalletStorageError; +use dpp::fee::Credits; +use dpp::prelude::{Identifier, Revision}; +use platform_wallet::changeset::IdentityEntry; +use platform_wallet::wallet::identity::types::block_time::BlockTime; +use platform_wallet::wallet::identity::PaymentEntry; +use platform_wallet::{ContactProfileEntry, DashPayProfile, DpnsNameInfo, IdentityStatus}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(serde::Serialize, serde::Deserialize)] +struct LegacyProfile { + display_name: Option, + bio: Option, + avatar_url: Option, + avatar_hash: Option<[u8; 32]>, + avatar_fingerprint: Option<[u8; 8]>, + public_message: Option, +} +impl From for DashPayProfile { + fn from(p: LegacyProfile) -> Self { + Self { + display_name: p.display_name, + bio: p.bio, + avatar_url: p.avatar_url, + avatar_hash: p.avatar_hash, + avatar_fingerprint: p.avatar_fingerprint, + public_message: p.public_message, + ..Default::default() + } + } +} +impl From for LegacyProfile { + fn from(p: DashPayProfile) -> Self { + Self { + display_name: p.display_name, + bio: p.bio, + avatar_url: p.avatar_url, + avatar_hash: p.avatar_hash, + avatar_fingerprint: p.avatar_fingerprint, + public_message: p.public_message, + } + } +} +#[derive(serde::Serialize, serde::Deserialize)] +struct LegacyContactProfile { + profile: Option, + checked_at_ms: u64, +} +#[derive(serde::Serialize, serde::Deserialize)] +struct LegacyIdentityEntry { + pub id: Identifier, + pub balance: Credits, + pub revision: Revision, + pub identity_index: Option, + pub last_updated_balance_block_time: Option, + pub last_synced_keys_block_time: Option, + pub dpns_names: Vec, + pub contested_dpns_names: Vec, + pub status: IdentityStatus, + pub wallet_id: Option<[u8; 32]>, + pub dashpay_profile: Option, + pub dashpay_payments: BTreeMap, + pub contact_profiles: BTreeMap, + pub ignored_senders: BTreeSet, +} +impl From for IdentityEntry { + fn from(old: LegacyIdentityEntry) -> Self { + IdentityEntry { + id: old.id, + balance: old.balance, + revision: old.revision, + identity_index: old.identity_index, + last_updated_balance_block_time: old.last_updated_balance_block_time, + last_synced_keys_block_time: old.last_synced_keys_block_time, + dpns_names: old.dpns_names, + contested_dpns_names: old.contested_dpns_names, + status: old.status, + wallet_id: old.wallet_id, + dashpay_profile: old.dashpay_profile.map(Into::into), + dashpay_payments: old.dashpay_payments, + contact_profiles: old + .contact_profiles + .into_iter() + .map(|(id, entry)| { + ( + id, + ContactProfileEntry { + profile: entry.profile.map(Into::into), + checked_at_ms: entry.checked_at_ms, + }, + ) + }) + .collect(), + ignored_senders: old.ignored_senders, + } + } +} +impl From for LegacyIdentityEntry { + fn from(entry: IdentityEntry) -> Self { + Self { + id: entry.id, + balance: entry.balance, + revision: entry.revision, + identity_index: entry.identity_index, + last_updated_balance_block_time: entry.last_updated_balance_block_time, + last_synced_keys_block_time: entry.last_synced_keys_block_time, + dpns_names: entry.dpns_names, + contested_dpns_names: entry.contested_dpns_names, + status: entry.status, + wallet_id: entry.wallet_id, + dashpay_profile: entry.dashpay_profile.map(Into::into), + dashpay_payments: entry.dashpay_payments, + contact_profiles: entry + .contact_profiles + .into_iter() + .map(|(id, entry)| { + ( + id, + LegacyContactProfile { + profile: entry.profile.map(Into::into), + checked_at_ms: entry.checked_at_ms, + }, + ) + }) + .collect(), + ignored_senders: entry.ignored_senders, + } + } +} + +// Test-only: production never writes the legacy shapes, but migration +// fixtures have to produce the bytes a pre-V021 writer produced. PUBLIC +// material only, like the current shapes they mirror. +#[cfg(any(test, feature = "__test-helpers"))] +super::blob::impl_persistable_blob!(LegacyProfile, LegacyIdentityEntry); + +/// The bytes a pre-V021 writer stored for `profile`: the record without the +/// payment-address fields. For fixtures of databases written before V021. +#[cfg(any(test, feature = "__test-helpers"))] +pub fn encode_legacy_profile(profile: &DashPayProfile) -> Result, WalletStorageError> { + blob::encode(&LegacyProfile::from(profile.clone())) +} + +/// The bytes a pre-V021 writer stored for `entry`: its own and its contacts' +/// profiles in the pre-payment-address shape. For fixtures of databases +/// written before V021. +#[cfg(any(test, feature = "__test-helpers"))] +pub fn encode_legacy_identity(entry: &IdentityEntry) -> Result, WalletStorageError> { + blob::encode(&LegacyIdentityEntry::from(entry.clone())) +} + +/// Decode a `dashpay_profiles.profile_blob` using its V021 `profile_format` +/// stamp: zero is the pre-address shape, one includes payment addresses. Never +/// fall back to the legacy shape after a current-format decoding error. +pub fn decode_profile(payload: &[u8], format: i64) -> Result { + match format { + 0 => blob::decode::(payload).map(Into::into), + 1 => blob::decode(payload), + _ => Err(WalletStorageError::blob_decode( + "unsupported profile encoding", + )), + } +} + +/// Decode an `identities.entry_blob` using its `entry_format` stamp, preserving +/// the pre-address owned and contact profile shapes for format zero. +pub fn decode_identity(payload: &[u8], format: i64) -> Result { + match format { + 1 => blob::decode(payload), + 0 => blob::decode::(payload).map(Into::into), + _ => Err(WalletStorageError::blob_decode( + "unsupported identity profile encoding", + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn old_profile() -> DashPayProfile { + DashPayProfile { + display_name: Some("Alice".into()), + bio: Some("hello".into()), + public_message: Some("hello".into()), + ..Default::default() + } + } + + #[test] + fn should_decode_standalone_profiles_by_format_without_fallback() { + let legacy = encode_legacy_profile(&old_profile()).unwrap(); + let mut profile = decode_profile(&legacy, 0).unwrap(); + assert_eq!(profile, old_profile()); + assert!(profile.core_payment_address.is_none()); + assert!(profile.platform_payment_address.is_none()); + assert!(profile.shielded_address.is_none()); + assert!(decode_profile(&legacy, 1).is_err()); + profile.shielded_address = Some(vec![9; 43]); + let current = blob::encode(&profile).unwrap(); + assert_eq!(decode_profile(¤t, 1).unwrap(), profile); + assert!(decode_profile(¤t, 0).is_err()); + assert!(decode_profile(¤t, 2).is_err()); + assert!(decode_profile(¤t[..current.len() - 1], 1).is_err()); + } + + /// The legacy identity record round-trips through the stamped decoder + /// with every field after the embedded profiles intact: the profile is + /// positional, so a shape mismatch would shift `dashpay_payments`, + /// `contact_profiles` and `ignored_senders`, not just drop an address. + #[test] + fn should_read_old_owned_and_contact_profiles_without_losing_following_fields() { + let id = Identifier::from([1; 32]); + let entry = IdentityEntry { + id, + balance: 123, + revision: 2, + identity_index: Some(0), + last_updated_balance_block_time: None, + last_synced_keys_block_time: None, + dpns_names: vec![], + contested_dpns_names: vec![], + status: IdentityStatus::Unknown, + wallet_id: Some([2; 32]), + dashpay_profile: Some(old_profile()), + dashpay_payments: BTreeMap::new(), + contact_profiles: [( + id, + ContactProfileEntry { + profile: Some(old_profile()), + checked_at_ms: 321, + }, + )] + .into(), + ignored_senders: [Identifier::from([3; 32])].into(), + }; + let legacy = encode_legacy_identity(&entry).unwrap(); + assert_eq!(decode_identity(&legacy, 0).unwrap(), entry); + // Current bytes carry three more `None`s per embedded profile. + let current = blob::encode(&entry).unwrap(); + assert_eq!(current.len(), legacy.len() + 6); + assert_eq!(decode_identity(¤t, 1).unwrap(), entry); + assert!(decode_identity(¤t[..current.len() - 1], 1).is_err()); + assert!(decode_identity(¤t, 2).is_err()); + assert!(decode_identity(&legacy, 2).is_err()); + } +} diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/mod.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/mod.rs index 88bff87e377..b3747c5713d 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/mod.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/mod.rs @@ -4,7 +4,10 @@ //! columns (heights, hashes, outpoints, flags); `_blob` columns carry the //! full sub-changeset entry via [`blob::encode`] / [`blob::decode`]. Schema //! evolution is gated by the refinery migration version — blobs carry no -//! inline revision tag. +//! inline revision tag. The two exceptions are the identity and DashPay +//! profile blobs, whose rows carry an encoding stamp column (V021) because +//! the positional `DashPayProfile` record grew payment addresses; see +//! [`identity_profile_encoding`]. pub mod accounts; pub mod asset_locks; @@ -16,6 +19,7 @@ pub mod dashpay; pub mod dpns_name_states; pub mod identities; pub mod identity_keys; +pub mod identity_profile_encoding; pub mod identity_scan_states; pub mod invitations; pub mod pending_contact_crypto; diff --git a/packages/rs-platform-wallet-storage/tests/integration/main.rs b/packages/rs-platform-wallet-storage/tests/integration/main.rs index 0f0a6c6f051..3a9ee008ccd 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/main.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/main.rs @@ -62,6 +62,7 @@ mod sqlite_open_version_gate; mod sqlite_permissions; mod sqlite_persist_roundtrip; mod sqlite_pool_reader; +mod sqlite_profile_address_encoding; mod sqlite_provider_key_accounts; mod sqlite_qa_identity_removal; mod sqlite_recovery_mode; diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_dashpay_overlay_contract.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_dashpay_overlay_contract.rs index 6b716cc9f35..fce9fb14dc5 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_dashpay_overlay_contract.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_dashpay_overlay_contract.rs @@ -9,9 +9,9 @@ //! tests pin both halves of that contract: //! //! 1. A `dashpay_*` write lands in the overlay tables (queryable directly). -//! 2. Writing ONLY the overlay (no identity blob carrying the same data) -//! does not corrupt `load()` — load succeeds and surfaces the wallet's -//! other state intact. +//! 2. Overlay-only writes fold into the canonical identity blob and survive load. +//! 3. Unknown scalar profile snapshots retain the canonical profile, while +//! explicit profile tombstones clear it. use crate::common; @@ -90,10 +90,7 @@ fn overlay_only_write_does_not_corrupt_load() { persister.store(w, overlay_cs).expect("store overlay"); persister.flush(w).expect("flush overlay"); - // The documented contract: load() reads DashPay from the identities - // blob (not the overlay table), so the overlay-only write neither - // appears in nor corrupts the loaded state. load() must still - // succeed and surface the wallet's core state. + // Loading the canonical blob must include the overlay and unrelated core state. let state = persister .load() .expect("load must succeed despite overlay-only write"); @@ -101,8 +98,101 @@ fn overlay_only_write_does_not_corrupt_load() { .wallets .get(&w) .expect("wallet present in loaded state"); + assert_eq!( + wallet.identity_manager.out_of_wallet_identities[&Identifier::from(identity)] + .dashpay() + .profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("bob") + ); assert_eq!( wallet.wallet_info.metadata.synced_height, 99, "core state must rehydrate intact alongside an unread overlay" ); } + +#[test] +fn should_preserve_profile_on_unknown_scalar_snapshot_and_apply_explicit_absence() { + use platform_wallet::changeset::{IdentityChangeSet, IdentityEntry, Merge}; + let (persister, _tmp, _path) = fresh_persister(); + let w = wid(0xC1); + let raw = [0xC2; 32]; + let id = Identifier::from(raw); + ensure_wallet_meta(&persister, &w); + ensure_identity(&persister, &raw, Some(&w)); + let apply_profile = |profile| { + persister + .store( + w, + PlatformWalletChangeSet { + dashpay_profiles: Some(BTreeMap::from([(id, profile)])), + ..Default::default() + }, + ) + .unwrap(); + persister.flush(w).unwrap(); + }; + apply_profile(Some(profile("Retained"))); + let state = persister.load().unwrap(); + let managed = &state.wallets[&w].identity_manager.out_of_wallet_identities[&id]; + assert_eq!( + managed + .dashpay() + .profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("Retained") + ); + let mut scalar = IdentityEntry::from_managed(managed); + scalar.dashpay_profile = None; + scalar.balance = 321; + let scalar_cs = IdentityChangeSet { + identities: BTreeMap::from([(id, scalar)]), + ..Default::default() + }; + persister.store(w, scalar_cs.clone().into()).unwrap(); + persister.flush(w).unwrap(); + let state = persister.load().unwrap(); + let managed = &state.wallets[&w].identity_manager.out_of_wallet_identities[&id]; + assert_eq!( + managed + .dashpay() + .profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("Retained") + ); + let mut cleared = PlatformWalletChangeSet { + dashpay_profiles: Some(BTreeMap::from([(id, None)])), + ..Default::default() + }; + cleared.merge(scalar_cs.into()); + persister.store(w, cleared).unwrap(); + persister.flush(w).unwrap(); + let state = persister.load().unwrap(); + let managed = &state.wallets[&w].identity_manager.out_of_wallet_identities[&id]; + assert!(managed.dashpay().profile.is_none()); + assert_eq!( + dpp::identity::accessors::IdentityGettersV0::balance(&managed.identity), + 321 + ); + apply_profile(Some(profile("Restored"))); + let state = persister.load().unwrap(); + assert_eq!( + state.wallets[&w].identity_manager.out_of_wallet_identities[&id] + .dashpay() + .profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("Restored") + ); +} diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_identity_index_uniqueness.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_identity_index_uniqueness.rs index 9021f02dc55..59d3c070432 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_identity_index_uniqueness.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_identity_index_uniqueness.rs @@ -15,6 +15,7 @@ use common::{ ensure_identity, ensure_wallet_meta, fresh_persister, fresh_persister_with_mode, wid, }; +use dpp::identity::accessors::IdentityGettersV0; use dpp::prelude::Identifier; use platform_wallet::changeset::{ IdentityChangeSet, IdentityEntry, PersistenceError, PersistenceErrorKind, @@ -558,6 +559,35 @@ fn a_buffered_removal_frees_its_slot_for_a_later_store() { assert!(!row_exists(&p, &iid(0x01))); } +/// Discovery re-slots an identity restored at a placeholder index into the +/// index its key derivation proved, and the new snapshot carries only the +/// changed `identity_index`. Buffered behind the old-slot snapshot, the +/// merged write must take the new index: otherwise the flush writes the +/// stale slot back and the freed slot refuses its rightful owner. +#[test] +fn a_buffered_reslot_moves_the_identity_and_frees_its_old_slot() { + let (p, _tmp, _path) = fresh_persister_with_mode(FlushMode::Manual); + let w = wid(0xBA); + ensure_wallet_meta(&p, &w); + p.store(w, identity_cs([identity_entry(0x01, Some(0))], [])) + .expect("placeholder snapshot at slot 0"); + p.store(w, identity_cs([identity_entry(0x01, Some(5))], [])) + .expect("adoption into the verified slot"); + p.store(w, identity_cs([identity_entry(0x02, Some(0))], [])) + .expect("the freed slot admits its rightful owner"); + + p.flush(w).expect("the merged changeset is consistent"); + assert_eq!(live_occupant(&p, &w, 5), Some([0x01; 32])); + assert_eq!(live_occupant(&p, &w, 0), Some([0x02; 32])); + + // A reopened persister reads the same placement back. + let state = p.load().expect("reload"); + let bucket = &state.wallets[&w].identity_manager.wallet_identities[&w]; + assert_eq!(bucket[&5].identity.id(), iid(0x01)); + assert_eq!(bucket[&5].identity_index, Some(5)); + assert_eq!(bucket[&0].identity.id(), iid(0x02)); +} + /// One wallet's rejected flush is one wallet's problem: `commit_writes` /// gives every dirty wallet its own transaction, so a neighbour's /// legitimate writes land in the same pass. diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs index 58cc3c18f3b..66e11696aae 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs @@ -677,6 +677,7 @@ fn tc012_dashpay_overlay_roundtrip() { avatar_hash: None, avatar_fingerprint: None, public_message: Some("public".into()), + ..Default::default() }; let payment = PaymentEntry::new_sent(Identifier::from([0x66; 32]), 7_500, Some("lunch".into())); diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs new file mode 100644 index 00000000000..a73bf23260e --- /dev/null +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs @@ -0,0 +1,335 @@ +#![allow(clippy::field_reassign_with_default)] + +//! A database written before V021 keeps its identity and DashPay profile rows +//! readable: the migration stamps the rows it finds 0, the stamped decoders +//! route them to the pre-payment-address record, and a rewrite stamps 1. +//! The fixture is written at V007 (the last published pre-rehydration +//! schema), so the whole V008 -> V021 chain runs over the legacy bytes. + +use std::collections::BTreeMap; + +use dpp::identity::accessors::IdentityGettersV0; +use dpp::prelude::Identifier; +use platform_wallet::changeset::{IdentityChangeSet, IdentityEntry}; +use platform_wallet::wallet::identity::PaymentEntry; +use platform_wallet::{ContactProfileEntry, DashPayProfile, IdentityStatus}; +use platform_wallet_storage::sqlite::schema::identity_profile_encoding::{ + encode_legacy_identity, encode_legacy_profile, +}; +use platform_wallet_storage::sqlite::schema::{blob, dashpay, identities}; +use platform_wallet_storage::sqlite::{decode_identity, decode_profile, migrations}; +use rusqlite::{params, Connection}; + +const WALLET_ID: [u8; 32] = [0x62; 32]; + +fn old_profile() -> DashPayProfile { + DashPayProfile { + display_name: Some("Alice".into()), + bio: Some("hello".into()), + public_message: Some("hello".into()), + ..Default::default() + } +} + +fn entry(id: Identifier) -> IdentityEntry { + IdentityEntry { + id, + balance: 123, + revision: 2, + identity_index: Some(0), + last_updated_balance_block_time: None, + last_synced_keys_block_time: None, + dpns_names: vec![], + contested_dpns_names: vec![], + status: IdentityStatus::Unknown, + wallet_id: Some(WALLET_ID), + dashpay_profile: Some(old_profile()), + dashpay_payments: BTreeMap::new(), + contact_profiles: [( + id, + ContactProfileEntry { + profile: Some(old_profile()), + checked_at_ms: 321, + }, + )] + .into(), + ignored_senders: [Identifier::from([3; 32])].into(), + } +} + +fn stamps(conn: &Connection) -> (i64, i64) { + let entry_format = conn + .query_row("SELECT entry_format FROM identities", [], |row| row.get(0)) + .unwrap(); + let profile_format = conn + .query_row("SELECT profile_format FROM dashpay_profiles", [], |row| { + row.get(0) + }) + .unwrap(); + (entry_format, profile_format) +} + +fn stored_profile(conn: &Connection) -> DashPayProfile { + let (payload, format): (Vec, i64) = conn + .query_row( + "SELECT profile_blob, profile_format FROM dashpay_profiles", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + decode_profile(&payload, format).unwrap() +} + +/// Rows a pre-V021 writer stored are stamped 0 by the migration and decode +/// to the pre-address shape through both readers; a rewrite stamps them 1 +/// and the new fields round-trip; an insert that omits the stamp is read as +/// the current shape. +#[test] +fn pre_v021_rows_stay_readable_and_rewrites_restamp() { + let id = Identifier::from([1; 32]); + let old = entry(id); + + let mut conn = Connection::open_in_memory().unwrap(); + conn.pragma_update(None, "foreign_keys", true).unwrap(); + migrations::runner() + .set_target(refinery::Target::Version(7)) + .run(&mut conn) + .unwrap(); + conn.execute( + "INSERT INTO wallet_metadata (wallet_id, network, birth_height) VALUES (?1, 'testnet', 0)", + params![WALLET_ID.as_slice()], + ) + .unwrap(); + conn.execute( + "INSERT INTO identities (identity_id, wallet_id, wallet_index, entry_blob, tombstoned) \ + VALUES (?1, ?2, 0, ?3, 0)", + params![ + id.as_slice(), + WALLET_ID.as_slice(), + encode_legacy_identity(&old).unwrap() + ], + ) + .unwrap(); + conn.execute( + "INSERT INTO dashpay_profiles (identity_id, profile_blob) VALUES (?1, ?2)", + params![ + id.as_slice(), + encode_legacy_profile(&old_profile()).unwrap() + ], + ) + .unwrap(); + + migrations::run(&mut conn).unwrap(); + + assert_eq!(stamps(&conn), (0, 0), "rows present at V021 are legacy"); + assert_eq!(stored_profile(&conn), old_profile()); + let restored = identities::fetch(&conn, &WALLET_ID, &id.to_buffer()) + .unwrap() + .unwrap(); + assert_eq!(restored, old); + assert!(restored + .dashpay_profile + .as_ref() + .unwrap() + .shielded_address + .is_none()); + // The reader the runtime restores from dispatches on the stamp too: a + // legacy row decoded against the current shape would fail this load. + let state = identities::load_state(&conn, &WALLET_ID).unwrap(); + let managed = &state.wallet_identities[&WALLET_ID][&0]; + assert_eq!(managed.identity.id(), id); + assert_eq!(managed.identity.balance(), 123); + + // Rewriting the rows through the live writers stamps them current. + let mut current = restored; + current.dashpay_profile.as_mut().unwrap().shielded_address = Some(vec![9; 43]); + let tx = conn.transaction().unwrap(); + identities::apply_upserts( + &tx, + &WALLET_ID, + &IdentityChangeSet { + identities: [(id, current.clone())].into(), + ..Default::default() + }, + ) + .unwrap(); + dashpay::apply( + &tx, + &WALLET_ID, + Some(&BTreeMap::from([(id, current.dashpay_profile.clone())])), + None, + ) + .unwrap(); + tx.commit().unwrap(); + assert_eq!(stamps(&conn), (1, 1)); + assert_eq!( + stored_profile(&conn), + current.dashpay_profile.clone().unwrap() + ); + assert_eq!( + identities::fetch(&conn, &WALLET_ID, &id.to_buffer()) + .unwrap() + .unwrap(), + current + ); + let encoded = blob::encode(¤t).unwrap(); + assert_eq!(decode_identity(&encoded, 1).unwrap(), current); + + // The stamp DEFAULT follows the writer: an insert that omits it reads as + // the current shape, so only rows the migration found are ever legacy. + let other = Identifier::from([7; 32]); + conn.execute( + "INSERT INTO identities (identity_id, wallet_id, identity_index, entry_blob) \ + VALUES (?1, ?2, 1, ?3)", + params![ + other.as_slice(), + WALLET_ID.as_slice(), + blob::encode(&IdentityEntry { + id: other, + identity_index: Some(1), + ..current.clone() + }) + .unwrap() + ], + ) + .unwrap(); + let format: i64 = conn + .query_row( + "SELECT entry_format FROM identities WHERE identity_id = ?1", + [other.as_slice()], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(format, 1); + assert_eq!( + identities::fetch(&conn, &WALLET_ID, &other.to_buffer()) + .unwrap() + .unwrap() + .dashpay_profile + .unwrap() + .shielded_address, + Some(vec![9; 43]) + ); +} + +/// A stamp no decoder knows is refused at the schema, not misread. +#[test] +fn unknown_stamp_is_rejected_by_the_check_constraint() { + let mut conn = Connection::open_in_memory().unwrap(); + migrations::run(&mut conn).unwrap(); + conn.execute( + "INSERT INTO wallets (wallet_id, network, birth_height) VALUES (?1, 'testnet', 0)", + params![WALLET_ID.as_slice()], + ) + .unwrap(); + let id = Identifier::from([4; 32]); + let err = conn + .execute( + "INSERT INTO identities (identity_id, wallet_id, identity_index, entry_blob, entry_format) \ + VALUES (?1, ?2, NULL, ?3, 2)", + params![id.as_slice(), WALLET_ID.as_slice(), blob::encode(&entry(id)).unwrap()], + ) + .unwrap_err(); + assert!(err.to_string().contains("CHECK"), "{err}"); +} + +/// Literal bytes of a pre-V021 `profile_blob`, written out by hand from the +/// `bincode::serde` standard encoding of the six-field record (no struct +/// declaration involved), so a reorder of the frozen legacy record cannot +/// regenerate the fixture and its decoder in step. Every field holds a +/// distinct value, so a positional shift misreads at least one of them. +#[test] +fn literal_pre_v021_profile_bytes_decode_positionally() { + let mut bytes = vec![0x01, 0x02, b'A', b'l']; // display_name: Some("Al") + bytes.extend([0x01, 0x01, b'b']); // bio: Some("b") + bytes.push(0x00); // avatar_url: None + bytes.push(0x01); // avatar_hash: Some([0x11; 32]) + bytes.extend([0x11; 32]); + bytes.push(0x01); // avatar_fingerprint: Some([0x22; 8]) + bytes.extend([0x22; 8]); + bytes.extend([0x01, 0x01, b'm']); // public_message: Some("m") + + let decoded = decode_profile(&bytes, 0).unwrap(); + assert_eq!( + decoded, + DashPayProfile { + display_name: Some("Al".into()), + bio: Some("b".into()), + avatar_url: None, + avatar_hash: Some([0x11; 32]), + avatar_fingerprint: Some([0x22; 8]), + public_message: Some("m".into()), + ..Default::default() + } + ); + // The legacy writer the migration fixture uses produces the same bytes. + assert_eq!(encode_legacy_profile(&decoded).unwrap(), bytes); + // Read as the current shape, the same row is not a valid record. + assert_ne!(decode_profile(&bytes, 1).ok(), Some(decoded)); +} + +/// A payment-only round (the `dashpay_payments_overlay` path) rewrites the +/// identity blob too. On a row the migration stamped 0 it must decode the +/// legacy record and write the current one stamped 1, so both identity +/// readers still see every profile field plus the new payment. +#[test] +fn payment_only_rewrite_of_a_legacy_identity_restamps_it() { + let id = Identifier::from([5; 32]); + let old = entry(id); + + let mut conn = Connection::open_in_memory().unwrap(); + conn.pragma_update(None, "foreign_keys", true).unwrap(); + migrations::runner() + .set_target(refinery::Target::Version(7)) + .run(&mut conn) + .unwrap(); + conn.execute( + "INSERT INTO wallet_metadata (wallet_id, network, birth_height) VALUES (?1, 'testnet', 0)", + params![WALLET_ID.as_slice()], + ) + .unwrap(); + conn.execute( + "INSERT INTO identities (identity_id, wallet_id, wallet_index, entry_blob, tombstoned) \ + VALUES (?1, ?2, 0, ?3, 0)", + params![ + id.as_slice(), + WALLET_ID.as_slice(), + encode_legacy_identity(&old).unwrap() + ], + ) + .unwrap(); + migrations::run(&mut conn).unwrap(); + let format = |conn: &Connection| -> i64 { + conn.query_row("SELECT entry_format FROM identities", [], |row| row.get(0)) + .unwrap() + }; + assert_eq!(format(&conn), 0); + + let payment = PaymentEntry::new_sent(Identifier::from([6; 32]), 42_000, Some("tip".into())); + let tx = conn.transaction().unwrap(); + dashpay::apply( + &tx, + &WALLET_ID, + None, + Some(&BTreeMap::from([( + id, + BTreeMap::from([("ab".repeat(32), payment.clone())]), + )])), + ) + .unwrap(); + tx.commit().unwrap(); + + assert_eq!(format(&conn), 1, "the rewritten blob is the current shape"); + let mut expected = old; + expected.dashpay_payments.insert("ab".repeat(32), payment); + assert_eq!( + identities::fetch(&conn, &WALLET_ID, &id.to_buffer()) + .unwrap() + .unwrap(), + expected + ); + let state = identities::load_state(&conn, &WALLET_ID).unwrap(); + let managed = &state.wallet_identities[&WALLET_ID][&0]; + assert_eq!(managed.identity.id(), id); + assert_eq!(managed.identity.balance(), 123); +} diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs index f1c5755c448..8c51cf7a0dc 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs @@ -15,13 +15,13 @@ use platform_wallet_storage::sqlite::{migrations as mig, schema::versions::Domai /// Golden `(version, name)` fingerprint of the frozen migration set. Bump /// deliberately only when adding/removing/renaming a migration file. const EXPECTED_ID_FINGERPRINT: &str = - "b1e10a6494cc31d24fabe4852477b3b93a2a98a7f310681b132ca8d9adef7311"; + "e6f2e947830f270bd68f96172be146ed627a3264981c6bce8a28d3c458668a91"; /// Golden content-level fingerprint over every migration's rendered SQL. /// Bump it only when ADDING a migration file; a body change on an already /// applied migration is a defect, not a golden to refresh. const EXPECTED_SQL_FINGERPRINT: &str = - "4490b15ba9de27bf5b30a47e462dc3b71c061a47f738a5240cdc89b3abc4ff43"; + "974e26e40c8b93c0ac148b2cbf3ef009d78ef3ec94fbf94cef91a2e82a4ec029"; /// The migrations merged `v4.2-dev` already ships. Refinery keys /// `refinery_schema_history` by version and validates an applied migration's diff --git a/packages/rs-platform-wallet/Cargo.toml b/packages/rs-platform-wallet/Cargo.toml index 0c0ee88abb2..d37ed44a144 100644 --- a/packages/rs-platform-wallet/Cargo.toml +++ b/packages/rs-platform-wallet/Cargo.toml @@ -58,6 +58,9 @@ zeroize = "1" # output is discarded there. log = "0.4" +# Profile metadata validation must also work without shielded spending support. +orchard = { git = "https://github.com/dashpay/orchard.git", tag = "dashified-0.14.1", default-features = false } + # Shielded pool (optional, behind `shielded` feature) grovedb-commitment-tree = { workspace = true, optional = true } # Direct `rusqlite` access so `FileBackedShieldedStore::open_path` can set diff --git a/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md b/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md new file mode 100644 index 00000000000..1a99880ed9d --- /dev/null +++ b/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md @@ -0,0 +1,108 @@ +# DashPay shielded tips + +DashPay profiles can publish a reusable Orchard receiving address. A payer resolves +DPNS to an identity, fetches its profile with proof verification, confirms the +recipient, and sends an ordinary shielded transfer. No contact request or payment +notification document is necessary. + +## Address format and updates + +`profile.shieldedAddress` contains 43 raw bytes: the 11-byte diversifier followed +by the 32-byte diversified transmission key. Text encoding, network prefix, and +checksum belong to the user interface. External addresses with any valid +diversifier are supported. The profile does not prove ownership of the address. + +`DashPayProfile` exposes `core_payment_address`, `platform_payment_address`, and +`shielded_address`. The transparent fields use their existing 21-byte storage +form. `ProfileUpdate` uses `PaymentAddressUpdate::Keep`, `Set(bytes)`, or `Remove` +for each address. An unrelated edit preserves all payment addresses. Clients +validate Orchard decoding before publication and payment; an invalid shielded +address does not prevent displaying the rest of the profile. + +Publication checks the connected chain's DashPay contract before submitting an +address field. A bundled schema alone does not demonstrate network activation. + +## Dedicated local accounts + +The wallet reserves ZIP-32 account indices `0x40000000..0x80000000` for DashPay +identities. A wallet-owned identity at derivation index `i` uses account +`0x40000000 + i`; identity indices outside the lower half are rejected by the +account helper. Ordinary account allocation must stay below `0x40000000`. Use +`shielded_identity_account_index` and `is_shielded_identity_account` instead of +duplicating these constants in applications. + +Call `PlatformWallet::prepare_shielded_identity_address(seed, identity_id, coordinator)` +to obtain the default address of this account. The helper binds its viewing keys +to the synchronization coordinator and flushes persistence before returning. It +does not publish the address; publication remains an explicit profile operation. +Repeated preparation derives the same account and address. An identity without a +wallet derivation index can publish an external address instead. + +Publish through `PlatformWallet::write_dashpay_profile`. A shielded address that is +one of this wallet's bound identity shielded addresses is published only if +preparation, in this session, proved with the seed that the identity holds the slot +selecting it, and the identity still holds that slot. Addresses from this wallet's +bound ordinary accounts are refused, including fresh diversified addresses; +addresses of another wallet remain allowed. Discovery can move an identity whose +keys derive at several indices, and a restored placeholder index proves nothing, so prepare the +address again after a restart or a move; preparation is idempotent. Preparation, +publication and tip sends hold a per-wallet placement lock that discovery, loading +and changeset apply take before moving an identity. An address already published +before a move keeps receiving into its old account until the profile is updated. + +Identity shielded accounts have distinct viewing keys. Hosts must exclude them from +ordinary receive, balance, and automatic spending choices, as the example apps do. +`shielded_balances()` returns all bound accounts separately, including identity +shielded accounts; it does not apply this policy. Spending a tip balance is an +explicit host action. +The generic shielded spend APIs (transfer, unshield, withdraw, top-up) still accept an +explicitly selected account and apply none of the tip-slot checks below; use +`send_shielded_tip` with a `ShieldedTipSource` for tips. +A published address is publicly associated with the profile; account separation +does not eliminate correlations introduced by later transfers or provide a +blanket guarantee against future cryptographic attacks. + +Address preparation requires an existing shielded bind. Bind the host's ordinary +accounts first; preparation preserves them while adding the dedicated account. + +## Restoration and address changes + +On seed restoration, discover the wallet's identities before binding and scanning +shielded accounts. Seed-backed `bind_shielded` adds each discovered identity's shielded +account even if the caller supplies only account zero. This does not depend on the +current profile: removal or replacement of a published address does not remove +received funds from recovery. After discovering more identities in an existing +session, bind again. Newly bound accounts start with their own scan watermark at +zero, so the next synchronization scans their history while retaining the shared +commitment tree and previously synchronized accounts. + +Seedless binding includes persisted identity shielded viewing keys, including +retired accounts. If a newly discovered identity's key is missing, it returns +`false` so the host can perform seed-backed binding. Address rotation within an +identity shielded account uses a new diversifier; the account viewing key detects +both old and new addresses. Removing +publication neither revokes old address copies nor stops their monitoring. + +An externally supplied address is not automatically owned by this wallet. Its +funds, viewing keys, and recovery belong to the external wallet. + +## Resolving and paying + +Use `wallet.identity().dashpay().resolve_shielded_tip(username)` to obtain a fresh +`ShieldedTipRecipient`. Display the resolved identity and address for confirmation. +`wallet.send_shielded_tip(...)` takes that confirmed recipient, re-resolves the +name and profile, and refuses payment if either changed. Its `ShieldedTipSource` +names what pays: `Identity(id)` spends that identity's shielded account, after the +seed proves the slot it holds; `Account(n)` spends an ordinary account, or the +identity shielded account of a slot that holds no identity (a retired identity's +funds). It never switches to a +transparent destination. This is a snapshot check: the submitted payment always +uses the address that was confirmed, even if the profile changes afterward. + +A tip send holds the wallet generation's payment gate through proving, persistence, +and broadcast. Removal waits for an admitted send to finish; a retained handle +from a removed or replaced generation cannot start another spend. + +Tips to a public profile address are anonymous from the receiver's perspective +unless the payer provides additional context. This feature does not implement +per-contact addresses or authenticated sender attribution. diff --git a/packages/rs-platform-wallet/src/changeset/changeset.rs b/packages/rs-platform-wallet/src/changeset/changeset.rs index 23d416973a3..ecfdac65e70 100644 --- a/packages/rs-platform-wallet/src/changeset/changeset.rs +++ b/packages/rs-platform-wallet/src/changeset/changeset.rs @@ -940,7 +940,8 @@ pub struct IdentityEntry { /// the wallet that owns this identity, if known. pub wallet_id: Option<[u8; 32]>, /// DashPay profile snapshot (display name, bio, avatar, public - /// message). `None` until the profile has been fetched or set. + /// message). `None` is unknown/no update; confirmed absence is carried + /// by `PlatformWalletChangeSet::dashpay_profiles`. pub dashpay_profile: Option, /// DashPay payment history keyed by transaction id (hex string). /// Mutations that don't touch payments still carry the current @@ -1131,9 +1132,10 @@ impl Merge for IdentityKeysChangeSet { /// /// `IdentityChangeSet::merge` does NOT resolve `identities` vs /// `removed` for the same key — both fields are extended -/// independently. Apply runs inserts before removes, so a merged -/// changeset that contains both an insert and a tombstone for the -/// same identity will end up "removed". Same hazard as +/// independently. Apply runs removes first and drops the snapshots of +/// removed identities, so a merged changeset that contains both an +/// insert and a tombstone for the same identity will end up "removed". +/// Same hazard as /// [`ContactChangeSet`]; same mitigation: every current emitter /// produces only one of {insert, tombstone} per key per mutation. #[derive(Debug, Clone, Default, PartialEq)] @@ -1172,12 +1174,16 @@ impl Merge for IdentityChangeSet { // equivalent. We use LWW for consistency with the // other scalars in this block. existing.wallet_id = entry.wallet_id; - // DashPay profile: last-write-wins. Same policy as - // every other Option scalar in this block — - // every mutation snapshot copies the current - // profile via `from_managed`, so LWW converges - // correctly within a single wallet. - existing.dashpay_profile = entry.dashpay_profile.clone(); + // `identity_index` follows the latest snapshot too. It is + // not immutable: discovery re-slots an identity restored + // at a placeholder index into the index its key derivation + // proved (`IdentityManager::adopt_into_wallet`). Keeping + // the first value would flush the stale slot and leave it + // occupied for the identity that legitimately owns it. + existing.identity_index = entry.identity_index; + if entry.dashpay_profile.is_some() { + existing.dashpay_profile = entry.dashpay_profile.clone(); + } // DPNS names: last-write-wins wholesale, same policy // as `contested_dpns_names` below. Every emitter // snapshots the complete current list via @@ -2349,9 +2355,9 @@ pub struct PlatformWalletChangeSet { pub token_balances: Option, /// DashPay profile overlays keyed by identity ID. Applied AFTER /// `identities` — updates the `dashpay_profile` field on existing - /// `ManagedIdentity` entries without touching other fields. Used - /// by the persister load path where only DashPay data is available - /// (the identity blob lives in the external `identity` table). + /// `ManagedIdentity` entries without touching other fields. A missing key + /// is no update; `Some(profile)` is present and `None` is confirmed absent. + /// Scalar identity snapshots with no profile do not carry this authority. /// Identities not in the wallet are silently skipped. pub dashpay_profiles: Option>>, /// DashPay payment history overlays keyed by identity ID. Same diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index 7b7112803f2..01bbe8cd05e 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -98,6 +98,28 @@ pub enum PlatformWalletError { #[error("Identity already exists: {0}")] IdentityAlreadyExists(Identifier), + /// A key derivation proved `identity_id` at `identity_index`, but this + /// wallet already holds a different identity in that slot. One of the two + /// records is stale; nothing was moved or persisted. + #[error( + "Identity {identity_id} is verified at index {identity_index}, but that slot holds \ + identity {occupant}" + )] + IdentityIndexOccupied { + identity_id: Identifier, + identity_index: u32, + occupant: Identifier, + }, + + #[error( + "Identity {identity_id} was created on chain but could not be registered locally: \ + {reason}; do not re-submit identity creation" + )] + IdentityCreatedButNotRegistered { + identity_id: Identifier, + reason: String, + }, + #[error("Identity not found: {0}")] IdentityNotFound(Identifier), diff --git a/packages/rs-platform-wallet/src/lib.rs b/packages/rs-platform-wallet/src/lib.rs index 13005d9c445..cfc89b4eee3 100644 --- a/packages/rs-platform-wallet/src/lib.rs +++ b/packages/rs-platform-wallet/src/lib.rs @@ -88,11 +88,12 @@ pub use wallet::identity::network::{ }; pub use wallet::identity::{ calculate_account_reference, derive_auto_accept_private_key, derive_contact_payment_address, - derive_contact_payment_addresses, derive_contact_xpub, pubkey_binds_expected_key_data, - unmask_account_reference, BlockTime, ContactProfileEntry, ContactRequest, ContactXpubData, - DashPayProfile, DashPayState, DpnsFetch, DpnsNameInfo, EstablishedContact, IdentityLocation, - IdentityManager, IdentityStatus, KeyStorage, ManagedIdentity, PrivateContact, PrivateKeyData, - ProfileUpdate, RegistrationIndex, DEFAULT_CONTACT_GAP_LIMIT, + derive_contact_payment_addresses, derive_contact_xpub, normalize_persisted_profile, + pubkey_binds_expected_key_data, unmask_account_reference, BlockTime, ContactProfileEntry, + ContactRequest, ContactXpubData, DashPayProfile, DashPayState, DpnsFetch, DpnsNameInfo, + EstablishedContact, IdentityLocation, IdentityManager, IdentityStatus, KeyStorage, + ManagedIdentity, PaymentAddressUpdate, PrivateContact, PrivateKeyData, ProfileUpdate, + RegistrationIndex, ShieldedTipRecipient, DEFAULT_CONTACT_GAP_LIMIT, }; pub use wallet::masternode_withdrawal::{ MasternodeWithdrawalKey, MasternodeWithdrawalKeys, MasternodeWithdrawalRequest, @@ -126,3 +127,13 @@ pub use key_wallet_manager; // the crate can pass it to `ManagedIdentity` mutation methods // (`set_dashpay_profile`, `record_dashpay_payment`, `add_identity`, …). pub use wallet::persister::WalletPersister; + +pub use wallet::identity::types::dashpay::profile::{ + valid_transparent_payment_address, validated_shielded_address, +}; + +#[cfg(feature = "shielded")] +pub use wallet::shielded::tips::{ + is_shielded_identity_account, shielded_identity_account_index, ShieldedTipSource, + SHIELDED_IDENTITY_ACCOUNT_BASE, +}; diff --git a/packages/rs-platform-wallet/src/manager/accessors.rs b/packages/rs-platform-wallet/src/manager/accessors.rs index b1389f98fe2..9cbbe257ad8 100644 --- a/packages/rs-platform-wallet/src/manager/accessors.rs +++ b/packages/rs-platform-wallet/src/manager/accessors.rs @@ -21,7 +21,7 @@ use crate::manager::platform_address_sync::PlatformAddressSyncManager; #[cfg(feature = "shielded")] use crate::manager::shielded_sync::ShieldedSyncManager; use crate::spv::SpvRuntime; -use crate::wallet::platform_wallet::WalletId; +use crate::wallet::platform_wallet::{WalletId, WalletManagerReader}; use crate::wallet::PlatformWallet; /// Result of [`PlatformWalletManager::provider_masternode_txs_blocking`]: @@ -1155,14 +1155,8 @@ impl PlatformWalletManager

{ /// and waiting on this lock inside that closure would stall /// `platform_wallet_manager_destroy` (a registry write) and, through /// parking_lot's writer preference, every other registry reader. - pub fn wallet_manager_arc( - &self, - ) -> Arc< - tokio::sync::RwLock< - key_wallet_manager::WalletManager, - >, - > { - Arc::clone(&self.wallet_manager) + pub fn wallet_manager_arc(&self) -> WalletManagerReader { + WalletManagerReader::new(Arc::clone(&self.wallet_manager)) } /// [`wallet_utxos_page`] under this manager's read lock. Blocking; diff --git a/packages/rs-platform-wallet/src/manager/load.rs b/packages/rs-platform-wallet/src/manager/load.rs index db5da2bd8ec..7a59138a48f 100644 --- a/packages/rs-platform-wallet/src/manager/load.rs +++ b/packages/rs-platform-wallet/src/manager/load.rs @@ -559,6 +559,12 @@ impl PlatformWalletManager

{ Arc::clone(&self.sync_fault), Arc::clone(&self.durable_cursors), ); + #[cfg(feature = "shielded")] + let platform_wallet = { + let mut wallet = platform_wallet; + wallet.shielded_coordinator = Some(Arc::clone(&self.shielded_coordinator)); + wallet + }; // Initialize the platform-address provider. If the snapshot // carried a slice for this wallet, restore it directly; diff --git a/packages/rs-platform-wallet/src/manager/wallet_lifecycle.rs b/packages/rs-platform-wallet/src/manager/wallet_lifecycle.rs index 466c6f5af35..ffec090956b 100644 --- a/packages/rs-platform-wallet/src/manager/wallet_lifecycle.rs +++ b/packages/rs-platform-wallet/src/manager/wallet_lifecycle.rs @@ -705,6 +705,12 @@ impl PlatformWalletManager

{ Arc::clone(&self.sync_fault), Arc::clone(&self.durable_cursors), ); + #[cfg(feature = "shielded")] + let platform_wallet = { + let mut wallet = platform_wallet; + wallet.shielded_coordinator = Some(Arc::clone(&self.shielded_coordinator)); + wallet + }; // Restore the platform-address provider from the slice read above — // the only area wired up today. `from_persisted` skips the live diff --git a/packages/rs-platform-wallet/src/wallet/apply.rs b/packages/rs-platform-wallet/src/wallet/apply.rs index 81512cad78a..ae23ea87e54 100644 --- a/packages/rs-platform-wallet/src/wallet/apply.rs +++ b/packages/rs-platform-wallet/src/wallet/apply.rs @@ -159,16 +159,22 @@ impl PlatformWalletInfo { removed, } = id_cs; - for (_id, entry) in identities { - self.identity_manager.apply_identity_entry(entry); - } // Best-effort removals across both buckets. Routed // through `remove_for_apply` so the manager's side-index // stays in lockstep with the buckets without us having to - // reach in and touch the index from out here. + // reach in and touch the index from out here. Removal wins over + // a same-batch snapshot, so removals go first and their + // snapshots are dropped: a removed identity's last placement + // must not hold a slot a surviving entry takes over. for removed_id in &removed { self.identity_manager.remove_for_apply(removed_id); } + self.identity_manager.apply_identity_entries( + identities + .into_iter() + .filter(|(id, _)| !removed.contains(id)) + .map(|(_, entry)| entry), + ); } // 2a'. Identity-scan verdict. Replayed rather than dropped: unlike the @@ -331,7 +337,7 @@ impl PlatformWalletInfo { if let Some(profiles) = dashpay_profiles { for (id, profile) in profiles { if let Some(managed) = self.identity_manager.managed_identity_mut(&id) { - *managed.dashpay_profile_mut() = profile; + managed.apply_dashpay_profile(profile); } } } @@ -1641,6 +1647,225 @@ mod tests { assert_eq!(restored.identity.revision(), 5); } + fn slotted_entry(id_byte: u8, wallet_id: Option<[u8; 32]>, index: u32) -> IdentityEntry { + let managed = ManagedIdentity::new(make_test_identity(id_byte, 0), index); + let mut entry = IdentityEntry::from_managed(&managed); + entry.wallet_id = wallet_id; + entry.identity_index = wallet_id.map(|_| index); + entry + } + + fn apply_entries( + info: &mut PlatformWalletInfo, + wallet: &mut Wallet, + entries: impl IntoIterator, + ) { + let mut cs = IdentityChangeSet::default(); + for entry in entries { + cs.identities.insert(entry.id, entry); + } + info.apply_changeset(wallet, wrap_id(cs)).expect("apply"); + } + + fn assert_slot(info: &PlatformWalletInfo, wallet_id: [u8; 32], index: u32, id_byte: u8) { + use dpp::identity::accessors::IdentityGettersV0; + let id = Identifier::from([id_byte; 32]); + let slotted = &info.identity_manager.wallet_identities[&wallet_id][&index]; + assert_eq!(slotted.identity.id(), id, "slot {index}"); + let found = info + .identity_manager + .managed_identity(&id) + .expect("present"); + assert_eq!(found.identity_index, Some(index)); + assert_eq!(found.wallet_id, Some(wallet_id)); + } + + /// Replaying a re-slot (A@0 → A@5) must move A, so a later B@0 takes the + /// freed slot instead of overwriting A — applied one by one or merged + /// into a batch that visits B (lower id) before A. + #[test] + fn apply_follows_identity_reslot_into_its_verified_index() { + let w = [0xAB; 32]; + for merged in [false, true] { + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + apply_entries(&mut info, &mut wallet, [slotted_entry(9, Some(w), 0)]); + if merged { + apply_entries( + &mut info, + &mut wallet, + [slotted_entry(9, Some(w), 5), slotted_entry(1, Some(w), 0)], + ); + } else { + apply_entries(&mut info, &mut wallet, [slotted_entry(9, Some(w), 5)]); + apply_entries(&mut info, &mut wallet, [slotted_entry(1, Some(w), 0)]); + } + assert_eq!(info.identity_manager.identity_count(), 2, "merged={merged}"); + assert_slot(&info, w, 5, 9); + assert_slot(&info, w, 0, 1); + } + } + + /// An observed identity adopted into the wallet replays into its slot. + #[test] + fn apply_promotes_an_observed_identity_into_the_wallet() { + let w = [0xAB; 32]; + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + apply_entries(&mut info, &mut wallet, [slotted_entry(9, None, 0)]); + apply_entries(&mut info, &mut wallet, [slotted_entry(9, Some(w), 3)]); + assert_eq!(info.identity_manager.identity_count(), 1); + assert_slot(&info, w, 3, 9); + } + + /// A new entry claiming a slot another identity still holds is skipped + /// rather than discarding the occupant. + #[test] + fn apply_does_not_insert_over_an_occupied_slot() { + let w = [0xAB; 32]; + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + apply_entries(&mut info, &mut wallet, [slotted_entry(9, Some(w), 0)]); + apply_entries(&mut info, &mut wallet, [slotted_entry(1, Some(w), 0)]); + assert_slot(&info, w, 0, 9); + assert!(info + .identity_manager + .managed_identity(&Identifier::from([1; 32])) + .is_none()); + } + + /// A batch removing an identity frees its slot for a new entry in the + /// same batch. + #[test] + fn apply_removal_frees_the_slot_for_a_same_batch_entry() { + let w = [0xAB; 32]; + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + apply_entries(&mut info, &mut wallet, [slotted_entry(9, Some(w), 3)]); + let mut cs = IdentityChangeSet::default(); + let entry = slotted_entry(1, Some(w), 3); + cs.identities.insert(entry.id, entry); + cs.removed.insert(Identifier::from([9; 32])); + info.apply_changeset(&mut wallet, wrap_id(cs)) + .expect("apply"); + assert_eq!(info.identity_manager.identity_count(), 1); + assert_slot(&info, w, 3, 1); + } + + /// Merge per-mutation changesets the way a Manual-flush buffer does. + fn merged(changesets: impl IntoIterator) -> IdentityChangeSet { + use crate::changeset::Merge; + let mut all = IdentityChangeSet::default(); + for cs in changesets { + all.merge(cs); + } + all + } + + fn snapshot(entry: IdentityEntry) -> IdentityChangeSet { + let mut cs = IdentityChangeSet::default(); + cs.identities.insert(entry.id, entry); + cs + } + + /// Replay a merged batch twice; both applications must reach the state + /// the mutations produced. + fn replay_twice( + seed: impl IntoIterator + Clone, + batch: IdentityChangeSet, + check: impl Fn(&PlatformWalletInfo), + ) { + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + apply_entries(&mut info, &mut wallet, seed); + for _ in 0..2 { + info.apply_changeset(&mut wallet, wrap_id(batch.clone())) + .expect("apply"); + check(&info); + } + } + + /// A moved to 5, then removed, then B added at 5: the merged batch keeps + /// A's snapshot beside its tombstone, which must not keep B out. + #[test] + fn should_place_an_entry_in_the_slot_of_a_removed_identity() { + let w = [0xAB; 32]; + let mut removal = IdentityChangeSet::default(); + removal.removed.insert(Identifier::from([9; 32])); + let batch = merged([ + snapshot(slotted_entry(9, Some(w), 5)), + removal, + snapshot(slotted_entry(1, Some(w), 5)), + ]); + replay_twice([slotted_entry(9, Some(w), 0)], batch, |info| { + assert_eq!(info.identity_manager.identity_count(), 1); + assert_slot(info, w, 5, 1); + }); + } + + /// A@0/B@1 swapped through free slot 2 merges into A@1/B@0, which replay + /// must install even though each move waits on the other. + #[test] + fn should_replay_a_merged_slot_swap() { + let w = [0xAB; 32]; + let batch = merged([ + snapshot(slotted_entry(9, Some(w), 2)), + snapshot(slotted_entry(1, Some(w), 0)), + snapshot(slotted_entry(9, Some(w), 1)), + ]); + replay_twice( + [slotted_entry(9, Some(w), 0), slotted_entry(1, Some(w), 1)], + batch, + |info| { + assert_eq!(info.identity_manager.identity_count(), 2); + assert_slot(info, w, 1, 9); + assert_slot(info, w, 0, 1); + assert!(info.identity_manager.out_of_wallet_identities.is_empty()); + }, + ); + } + + /// A move blocked by an identity the batch leaves in place keeps its slot. + #[test] + fn should_keep_a_move_blocked_by_a_stationary_identity_in_place() { + let w = [0xAB; 32]; + replay_twice( + [slotted_entry(9, Some(w), 0), slotted_entry(1, Some(w), 1)], + snapshot(slotted_entry(9, Some(w), 1)), + |info| { + assert_slot(info, w, 0, 9); + assert_slot(info, w, 1, 1); + }, + ); + } + + /// A swap whose slot a third entry also claims (an inconsistent batch) + /// is not staged, so no identity is stranded outside the wallet. + #[test] + fn should_not_stage_a_swap_whose_slot_is_claimed_twice() { + let w = [0xAB; 32]; + let batch = merged([ + snapshot(slotted_entry(1, Some(w), 1)), + snapshot(slotted_entry(3, Some(w), 0)), + snapshot(slotted_entry(2, Some(w), 0)), + ]); + replay_twice( + [ + slotted_entry(1, Some(w), 0), + slotted_entry(3, Some(w), 1), + slotted_entry(2, Some(w), 5), + ], + batch, + |info| { + assert_eq!(info.identity_manager.identity_count(), 3); + assert!(info.identity_manager.out_of_wallet_identities.is_empty()); + assert_slot(info, w, 0, 1); + assert_slot(info, w, 1, 3); + assert_slot(info, w, 5, 2); + }, + ); + } + /// A contact tombstone for a present (non-orphan) owner /// must drop the matching pending request. #[test] @@ -1703,6 +1928,8 @@ mod tests { avatar_hash: Some([0xaa; 32]), avatar_fingerprint: Some([0xbb; 8]), public_message: Some("hello world".into()), + shielded_address: Some(vec![0xcc; 43]), + ..Default::default() }; // Mutate A (persists internally via noop persister). @@ -1986,6 +2213,30 @@ mod tests { .apply_changeset(&mut wallet_b, wrap_id(id_cs)) .expect("apply"); + assert_eq!( + info_b + .identity_manager + .managed_identity(&id) + .unwrap() + .dashpay() + .profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("seed"), + "a scalar snapshot with no profile must preserve the retained profile" + ); + info_b + .apply_changeset( + &mut wallet_b, + PlatformWalletChangeSet { + dashpay_profiles: Some(BTreeMap::from([(id, None)])), + ..Default::default() + }, + ) + .expect("apply explicit profile absence"); + // Both wallets should have profile == None. assert_eq!( info_a @@ -2007,6 +2258,37 @@ mod tests { ); } + #[test] + fn apply_first_absent_profile_establishes_session_authority_for_observed_identity() { + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + let p = noop_persister(); + let id = Identifier::from([9; 32]); + info.identity_manager + .add_out_of_wallet_identity(make_test_identity(9, 1), &p) + .unwrap(); + assert!( + !info + .identity_manager + .managed_identity(&id) + .unwrap() + .dashpay() + .profile_checked + ); + info.apply_changeset( + &mut wallet, + PlatformWalletChangeSet { + dashpay_profiles: Some(BTreeMap::from([(id, None)])), + ..Default::default() + }, + ) + .unwrap(); + let managed = info.identity_manager.managed_identity(&id).unwrap(); + assert!(managed.dashpay().profile_checked); + assert!(managed.dashpay().profile.is_none()); + assert!(managed.identity_index.is_none()); + } + #[test] fn round_trip_double_apply_is_idempotent() { let wallet_a = build_test_wallet(); diff --git a/packages/rs-platform-wallet/src/wallet/identity/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/mod.rs index 37eb12adeff..c36c20e8336 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/mod.rs @@ -36,7 +36,8 @@ pub use state::{ }; pub use types::dashpay::profile::{calculate_avatar_hash, calculate_dhash_fingerprint}; pub use types::{ - ContactProfileEntry, ContactRequest, DashPayProfile, DashpayAddressMatch, DpnsFetch, - DpnsNameInfo, EstablishedContact, IdentityStatus, KeyStorage, PaymentDirection, PaymentEntry, - PaymentStatus, PrivateKeyData, ProfileUpdate, + normalize_persisted_profile, ContactProfileEntry, ContactRequest, DashPayProfile, + DashpayAddressMatch, DpnsFetch, DpnsNameInfo, EstablishedContact, IdentityStatus, KeyStorage, + PaymentAddressUpdate, PaymentDirection, PaymentEntry, PaymentStatus, PrivateKeyData, + ProfileUpdate, ShieldedTipRecipient, }; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs b/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs index 0e8596bed0a..854d5106a04 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs @@ -6,6 +6,7 @@ use key_wallet::bip32::ExtendedPrivKey; use crate::error::PlatformWalletError; use crate::wallet::identity::network::contact_requests::budget_spent; +use crate::wallet::identity::state::VerifiedPlacement; use crate::BlockTime; use super::*; @@ -440,25 +441,43 @@ impl IdentityWallet { // Acquire write lock to add/enrich the identity, then emit // every per-key breadcrumb in one batched changeset. + // Placement lock first; see `identity_placement`. + let placement_guard = self.identity_placement.write().await; let mut wm_guard = self.wallet_manager.write().await; - let info_guard = - wm_guard - .get_wallet_info_mut(&self.wallet_id) - .ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; - let is_new = info_guard.identity_manager.identity(&identity_id).is_none(); - if is_new { - // Stored below, with its verified keys, as one - // changeset. - info_guard.identity_manager.add_identity_unstored( - identity.clone(), - identity_index, - wallet_id, - )?; - } + let info_guard = self.current_wallet_info_mut(&mut wm_guard)?; + // The key hash at `identity_index` proved the index: add + // the identity there, or move an identity known from + // elsewhere into that slot (stored below, with its + // verified keys, as one changeset). A slot held by a different + // identity (whether the incoming one is new or known) + // means one of the two local records is stale. + // Skip this index without touching either identity, mark + // it unanswered so the next launch rescans, and keep + // walking: aborting here would also stop the stale + // record from reaching its own verified slot higher up + // the walk, which is what frees this one. + let is_new = match info_guard.identity_manager.place_verified_identity( + identity.clone(), + identity_index, + wallet_id, + ) { + Ok(placement) => placement == VerifiedPlacement::Added, + Err(e @ PlatformWalletError::IdentityIndexOccupied { .. }) => { + drop(wm_guard); + drop(placement_guard); + tracing::warn!( + index = identity_index, + error = %e, + "identity discovery: verified slot holds another identity; \ + leaving both untouched and rescanning later" + ); + tally.record_sighting(); + tally.record_conflict(identity_index); + identity_index += 1; + continue; + } + Err(e) => return Err(e), + }; if let Some(managed) = info_guard .identity_manager @@ -491,6 +510,7 @@ impl IdentityWallet { })?; } drop(wm_guard); + drop(placement_guard); if is_new { discovered.push(identity.clone()); @@ -592,14 +612,7 @@ impl IdentityWallet { match self.fetch_owned_dpns_names(identity_id, None).await { Ok((names, fetch)) => { let mut wm_guard = self.wallet_manager.write().await; - let info_guard = - wm_guard - .get_wallet_info_mut(&self.wallet_id) - .ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info_guard = self.current_wallet_info_mut(&mut wm_guard)?; if let Some(managed) = info_guard .identity_manager .managed_identity_mut(&identity_id) @@ -645,11 +658,11 @@ impl IdentityWallet { // own verdict instead would drop the gaps the fold carried forward. let recorded = { let mut wm = self.wallet_manager.write().await; - match wm.get_wallet_info_mut(&wallet_id) { - Some(info) => info + match self.current_wallet_info_mut(&mut wm) { + Ok(info) => info .identity_manager .record_identity_scan(wallet_id, verdict), - None => { + Err(_) => { tracing::warn!( wallet_id = %hex::encode(wallet_id), "identity scan finished for a wallet that is no longer managed; \ @@ -723,6 +736,9 @@ struct ScanTally { /// together, because to a later launch they are the same fact: an index /// nobody answered. aborted_at_index: Option, + /// Indices whose verified identity could not be placed because its slot + /// holds a different local identity. Unanswered for the verdict. + conflicted_indices: Vec, } impl ScanTally { @@ -763,16 +779,22 @@ impl ScanTally { self.aborted_at_index = Some(index); } + /// Platform answered at `index`, but the identity could not be placed + /// because its verified slot holds a different local identity. The index + /// counts as unanswered (so the verdict is incomplete and a later launch + /// rescans) without touching the probe counters: Platform did answer. + fn record_conflict(&mut self, index: u32) { + self.conflicted_indices.push(index); + } + /// Every index this scan did not answer, ascending — unanswered probes /// plus the index a local fault abandoned it at. fn unanswered_indices(&self) -> Vec { let mut indices = self.failed_indices.clone(); - if let Some(index) = self.aborted_at_index { - if !indices.contains(&index) { - indices.push(index); - indices.sort_unstable(); - } - } + indices.extend(self.aborted_at_index); + indices.extend(self.conflicted_indices.iter().copied()); + indices.sort_unstable(); + indices.dedup(); indices } @@ -1326,6 +1348,22 @@ mod tests { ); } + /// A verified identity whose slot holds another local identity is skipped, + /// not a fault: the walk goes on (the hit still resets the gap counter), + /// no probe counter moves, and the index is unanswered so the next launch + /// rescans instead of trusting a complete verdict. + #[test] + fn a_slot_conflict_keeps_walking_and_leaves_the_scan_incomplete() { + let mut tally = run_scan(5, [Ok(None), Ok(None)]); + tally.record_sighting(); + tally.record_conflict(2); + assert!(tally.should_continue(3), "the hit resets the gap counter"); + let verdict = tally.verdict(0, 3); + assert!(!verdict.complete); + assert_eq!(verdict.failed_indices, vec![2]); + assert_eq!(tally.failed_probes, 0, "Platform answered the probe"); + } + /// A local fault at an index that ALSO went unanswered is recorded once. #[test] fn an_abort_at_an_already_unanswered_index_is_not_duplicated() { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index fc346c8d038..48a8c383901 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -3946,6 +3946,7 @@ mod tests { document_erase_gate: Default::default(), dpns_operation_gate: Arc::new(tokio::sync::Mutex::new(())), dpns_sync_progress: Arc::new(std::sync::Mutex::new(BTreeMap::new())), + identity_placement: Arc::new(tokio::sync::RwLock::new(())), } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs index d89ea04eaee..a29cac1316e 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs @@ -536,6 +536,12 @@ pub struct IdentityWallet { /// the source rendered after process restart. pub(crate) dpns_sync_progress: Arc>>, + /// Orders moves of a wallet identity between slots (discovery, loading + /// and `PlatformWallet::apply` take it for writing) against operations + /// that act on the account a slot selects (tip preparation, tip sends and + /// tip address publication take it for reading). Taken before + /// `wallet_manager`. + pub(crate) identity_placement: Arc>, } // Manual `Debug`: the derive would require `B: Debug`, which is not part @@ -565,6 +571,7 @@ impl Clone for IdentityWallet { document_erase_gate: Arc::clone(&self.document_erase_gate), dpns_operation_gate: Arc::clone(&self.dpns_operation_gate), dpns_sync_progress: Arc::clone(&self.dpns_sync_progress), + identity_placement: Arc::clone(&self.identity_placement), } } } @@ -682,27 +689,6 @@ impl IdentityWallet { self.wallet_manager.read().await } - /// Get a write-lock handle to the shared [`WalletManager`]. - /// - /// Access wallet info via `wm.get_wallet_info_mut(&wallet_id)` on the - /// returned guard. This allows callers to mutate managed identities (e.g. - /// adding or updating identities from an external persistence layer). - pub async fn wallet_manager_write( - &self, - ) -> tokio::sync::RwLockWriteGuard<'_, WalletManager> { - self.wallet_manager.write().await - } - - /// Try to acquire a write-lock on the shared [`WalletManager`] without blocking. - /// - /// Returns `None` if the lock is currently held by another task. - /// Useful for synchronous callers that cannot await. - pub fn try_wallet_manager_write( - &self, - ) -> Option>> { - self.wallet_manager.try_write().ok() - } - /// The wallet ID for this identity wallet's underlying key material. pub fn wallet_id(&self) -> &WalletId { &self.wallet_id diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs index c0d63b5afe3..2a40cdd069d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs @@ -241,27 +241,27 @@ impl IdentityWallet { ) .await?; - // Add the identity to the manager and enrich it. + // Add the identity to the manager and enrich it. Placement lock + // first; see `identity_placement`. { + let _placement = self.identity_placement.write().await; let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; - if info.identity_manager.identity(&identity_id).is_none() { - // Stored below, with its verified keys, as one changeset. - info.identity_manager.add_identity_unstored( - identity.clone(), - identity_index, - wallet_id, - )?; - } + let info = self.current_wallet_info_mut(&mut wm)?; + // The probe at `identity_index` proved the index: add the identity + // there, or move an identity known from elsewhere into that slot; + // either is stored below, with its verified keys, as one changeset. + // A slot held by another identity refuses here, before status or + // keys are touched, so nothing contradictory is stored. + info.identity_manager.place_verified_identity( + identity.clone(), + identity_index, + wallet_id, + )?; if let Some(managed) = info.identity_manager.managed_identity_mut(&identity_id) { // Fold the freshly fetched on-chain state into an - // already-known identity too — the add above only runs for - // new ones, and without this a re-load kept serving the + // already-known identity too — the placement above only + // adds new ones, and without this a re-load kept serving the // stale key set (keys added from another device never // appeared, and contact requests referencing them failed // key-index validation). Same fold `refresh_identity` @@ -296,11 +296,7 @@ impl IdentityWallet { match self.fetch_owned_dpns_names(identity_id, None).await { Ok((names, fetch)) => { let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info = self.current_wallet_info_mut(&mut wm)?; if let Some(managed) = info.identity_manager.managed_identity_mut(&identity_id) { managed.apply_fetched_dpns_names(names, fetch, &self.persister); } @@ -412,11 +408,7 @@ impl IdentityWallet { match self.fetch_owned_dpns_names(identity_id, None).await { Ok((names, fetch)) => { let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info = self.current_wallet_info_mut(&mut wm)?; if let Some(managed) = info.identity_manager.managed_identity_mut(&identity_id) { managed.apply_fetched_dpns_names(names, fetch, &self.persister); @@ -477,11 +469,7 @@ impl IdentityWallet { // don't know the wallet index and cannot sign). { let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info = self.current_wallet_info_mut(&mut wm)?; info.identity_manager .add_out_of_wallet_identity(identity.clone(), &self.persister)?; } @@ -729,23 +717,13 @@ mod tests { } } - /// A load that finds an identity the wallet does not hold yet stores it - /// and its keys, each with the breadcrumb verified against the seed, as - /// one changeset. No snapshot of the identity or its keys reaches the - /// store ahead of the breadcrumbs, so a store that fails between two - /// writes cannot leave watch-only key rows behind. - #[tokio::test] - async fn should_store_a_newly_loaded_identity_with_its_keys_in_one_changeset() { - struct Events; - impl EventHandler for Events {} - impl PlatformEventHandler for Events {} - - const SEED: [u8; 64] = [7; 64]; - let network = Network::Testnet; - let master = ExtendedPrivKey::new_master(network, &SEED).unwrap(); - let identity_id = Identifier::from([0x5A; 32]); - // Registered at index 0 the way registration does it: MASTER, HIGH - // and CRITICAL auth keys at key ids 0..=2, all from the seed. + /// An identity registered at index 0 the way registration does it: + /// MASTER, HIGH and CRITICAL auth keys at key ids 0..=2, all from the seed. + fn registered_at_index_zero( + master: &ExtendedPrivKey, + network: Network, + identity_id: Identifier, + ) -> Identity { let levels = [ SecurityLevel::MASTER, SecurityLevel::HIGH, @@ -755,7 +733,7 @@ mod tests { .zip(levels) .map(|(key_id, security_level)| { let derived = - derive_ecdsa_identity_auth_keypair_from_master(&master, network, 0, key_id) + derive_ecdsa_identity_auth_keypair_from_master(master, network, 0, key_id) .unwrap(); let key: IdentityPublicKey = IdentityPublicKeyV0 { id: key_id, @@ -771,12 +749,30 @@ mod tests { (key_id, key) }) .collect(); - let on_chain = Identity::V0(IdentityV0 { + Identity::V0(IdentityV0 { id: identity_id, public_keys, balance: 1_000_000, revision: 1, - }); + }) + } + + /// A load that finds an identity the wallet does not hold yet stores it + /// and its keys, each with the breadcrumb verified against the seed, as + /// one changeset. No snapshot of the identity or its keys reaches the + /// store ahead of the breadcrumbs, so a store that fails between two + /// writes cannot leave watch-only key rows behind. + #[tokio::test] + async fn should_store_a_newly_loaded_identity_with_its_keys_in_one_changeset() { + struct Events; + impl EventHandler for Events {} + impl PlatformEventHandler for Events {} + + const SEED: [u8; 64] = [7; 64]; + let network = Network::Testnet; + let master = ExtendedPrivKey::new_master(network, &SEED).unwrap(); + let identity_id = Identifier::from([0x5A; 32]); + let on_chain = registered_at_index_zero(&master, network, identity_id); let mut sdk = dash_sdk::SdkBuilder::new_mock().build().unwrap(); let probe = @@ -843,4 +839,81 @@ mod tests { ); } } + + /// A load that proves the index of an identity already known out of + /// wallet adopts it into that slot, and the identity's snapshot (now + /// carrying the wallet and index) reaches the store in the same changeset + /// as its keys: placement itself stores nothing. + #[tokio::test] + async fn should_store_an_adopted_identity_at_its_proved_slot_with_its_keys() { + struct Events; + impl EventHandler for Events {} + impl PlatformEventHandler for Events {} + + const SEED: [u8; 64] = [7; 64]; + let network = Network::Testnet; + let master = ExtendedPrivKey::new_master(network, &SEED).unwrap(); + let identity_id = Identifier::from([0x5B; 32]); + let on_chain = registered_at_index_zero(&master, network, identity_id); + + let mut sdk = dash_sdk::SdkBuilder::new_mock().build().unwrap(); + let probe = + derive_load_probe_hash(ResolvedLoadKeyHashSource::Master(&master), network, 0).unwrap(); + sdk.mock() + .expect_fetch(PublicKeyHash(probe), Some(on_chain.clone())) + .await + .unwrap(); + let store = Arc::new(CapturingStore::default()); + let manager = PlatformWalletManager::new(Arc::new(sdk), store.clone(), Arc::new(Events)); + let wallet = manager + .create_wallet_from_seed_bytes( + network, + &SEED, + WalletAccountCreationOptions::Default, + Some(0), + ) + .await + .unwrap(); + let wallet_id = wallet.wallet_id(); + { + let identity = wallet.identity(); + let mut wm = identity.wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet_id) + .unwrap() + .identity_manager + .add_out_of_wallet_identity(on_chain, &identity.persister) + .unwrap(); + } + store.take(); + + wallet + .identity() + .load_identity_by_index_from_master(0, &master) + .await + .unwrap() + .expect("the identity at index 0 is found"); + + let stored = store.take(); + let identity_changesets: Vec<_> = stored + .iter() + .filter(|changeset| changeset.identities.is_some() || changeset.identity_keys.is_some()) + .collect(); + assert_eq!( + identity_changesets.len(), + 1, + "the adopted identity and its keys go out together: {identity_changesets:?}" + ); + let changeset = identity_changesets[0]; + let entry = &changeset + .identities + .as_ref() + .expect("the changeset carries the identity") + .identities[&identity_id]; + assert_eq!(entry.wallet_id, Some(wallet_id)); + assert_eq!(entry.identity_index, Some(0)); + assert!(changeset + .identity_keys + .as_ref() + .is_some_and(|keys| keys.upserts.len() == 3)); + } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs b/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs index 90591b4ab63..53092a5f078 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs @@ -13435,6 +13435,7 @@ mod tests { document_erase_gate: Arc::clone(&real.document_erase_gate), dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), + identity_placement: Arc::clone(&real.identity_placement), } } @@ -13478,6 +13479,7 @@ mod tests { document_erase_gate: Arc::clone(&real.document_erase_gate), dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), + identity_placement: Arc::clone(&real.identity_placement), } } @@ -13535,6 +13537,7 @@ mod tests { document_erase_gate: Arc::clone(&real.document_erase_gate), dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), + identity_placement: Arc::clone(&real.identity_placement), } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs index 3425470a24a..1780ea30e91 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs @@ -6795,7 +6795,7 @@ mod tests { &alice_crypto, )); let mut cx = Context::from_waker(Waker::noop()); - let wallet_manager = old.wallet_manager(); + let wallet_manager = &old.wallet_manager; let mut held = wallet_manager.write().await; let mut gated = false; for _ in 0..200 { @@ -9680,7 +9680,7 @@ mod tests { restore.as_mut().poll(&mut cx).is_pending(), "waits for the store" ); - let mut held_wallet = alice_wallet.wallet_manager().write().await; + let mut held_wallet = alice_wallet.wallet_manager.write().await; drop(held_store); // The restoration reads its journal snapshot, then waits for the wallet. assert!( @@ -9768,7 +9768,7 @@ mod tests { restore.as_mut().poll(&mut cx).is_pending(), "waits for the store" ); - let mut held_wallet = wallet.wallet_manager().write().await; + let mut held_wallet = wallet.wallet_manager.write().await; drop(held_store); // The restoration reads the redrive records, then waits for the // wallet before it opens the entry. @@ -9966,12 +9966,14 @@ mod tests { .await; let dir = tempfile::tempdir().expect("temporary shielded store"); let db_path = dir.path().join("tree.sqlite"); - let coordinator = Arc::new(NetworkShieldedCoordinator::new( - Arc::clone(&wallet.identity().sdk), - Network::Testnet, - db_path.clone(), - FileBackedShieldedStore::open_path(&db_path, 100).expect("the store"), - )); + manager + .configure_shielded(&db_path) + .await + .expect("configured"); + let coordinator = manager + .shielded_coordinator() + .await + .expect("the manager's coordinator"); // Bound, the coordinator holds the wallet's persister, on which it // notes the discharge. wallet @@ -12835,7 +12837,6 @@ mod tests { // The restart: the reply is not in the store and the host restores // nothing; only the bind can. - let after = coordinator_at(db_path); let restarted_manager = PlatformWalletManager::new( Arc::new(dashpay_sdk(&[&alice, &bob], vec![], PlatformVersion::latest(), None).await), kept, @@ -12890,6 +12891,14 @@ mod tests { "{public:?}" ); + restarted_manager + .configure_shielded(&db_path) + .await + .expect("configured"); + let after = restarted_manager + .shielded_coordinator() + .await + .expect("the manager's coordinator"); restarted .bind_shielded(&seed(BOB_PHRASE), &[0], &after) .await diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs index 14e82b28e91..e4a1de4490f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs @@ -22,8 +22,8 @@ use super::*; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::{ - calculate_avatar_hash, calculate_dhash_fingerprint, ContactProfileEntry, DashPayProfile, - ProfileUpdate, + calculate_avatar_hash, calculate_dhash_fingerprint, normalize_persisted_profile, + ContactProfileEntry, DashPayProfile, ProfileUpdate, }; // Profile documents require HIGH or CRITICAL authentication; MASTER is reserved @@ -55,11 +55,11 @@ impl DashPayView<'_, B> { /// /// Fetches through [`Sdk::get_profiles`](dash_sdk::Sdk::get_profiles) (`In` /// queries, not N+1; a failed fetch leaves the cache as is for the next - /// sweep), and persists only when the - /// fetched profile differs from the cached one — a `None` result clears the - /// cache only when a profile is currently stored (both arms guarded so a - /// no-change sweep writes nothing). Returns the number of identities whose - /// cached profile changed. + /// sweep), and persists when the fetched profile differs from the cached + /// one or establishes the first confirmed absence this session. Subsequent + /// unchanged results emit nothing. Returns the number of identities whose + /// profile state was updated. Results for a removed or replaced wallet + /// generation are discarded without changing state or persistence. pub async fn sync_profiles(&self) -> Result { // 1. Collect all managed identity IDs under a short read lock. let identity_ids: Vec = { @@ -99,18 +99,19 @@ impl DashPayView<'_, B> { .map(|id| (*id, found.get(id).cloned().flatten())) .collect(); - // 4. Under the write guard: persist-on-change only (mirror the - // None-arm's is_some guard for both directions). + // A first confirmed absence must emit a tombstone even on a cold cache. let mut changed = 0u32; let mut wm = self.wallet_manager.write().await; - let Some(info) = wm.get_wallet_info_mut(&self.wallet_id) else { + let Ok(info) = self.current_wallet_info_mut(&mut wm) else { return Ok(0); }; for (identity_id, profile) in fetched { let Some(managed) = info.identity_manager.managed_identity_mut(&identity_id) else { continue; }; - if managed.dashpay().profile == profile { + if (managed.dashpay().profile_checked || managed.dashpay().profile.is_some()) + && managed.dashpay().profile == profile + { continue; } managed.set_dashpay_profile(profile, &self.persister); @@ -139,7 +140,7 @@ impl DashPayView<'_, B> { /// All other behavior — avatar hashing, document construction, /// local cache update via the persister — is identical to the /// legacy variant. - pub async fn create_profile_with_external_signer( + pub(crate) async fn create_profile_with_external_signer( &self, identity_id: &Identifier, input: ProfileUpdate, @@ -150,6 +151,7 @@ impl DashPayView<'_, B> { { // 1. The DashPay data contract (process-wide cache). let dashpay_contract = super::dashpay_contract()?; + self.validate_payment_address_update(&input).await?; // 2. The profile fields, with avatar hashes computed from any raw bytes. let fields = profile_fields(input)?; @@ -200,7 +202,7 @@ impl DashPayView<'_, B> { /// /// Mirrors [`Self::update_profile`] but signing is routed through /// the supplied `&S: Signer`. - pub async fn update_profile_with_external_signer( + pub(crate) async fn update_profile_with_external_signer( &self, identity_id: &Identifier, input: ProfileUpdate, @@ -211,6 +213,7 @@ impl DashPayView<'_, B> { { // 1. The DashPay contract (process-wide cache). let dashpay_contract = super::dashpay_contract()?; + self.validate_payment_address_update(&input).await?; // 2. The profile fields; avatar hashes are computed only when new // bytes are provided. The SDK merges them onto the on-platform @@ -304,9 +307,22 @@ fn profile_fields(input: ProfileUpdate) -> Result [(&'static str, &crate::PaymentAddressUpdate); 3] { + [ + ("corePaymentAddress", &input.core_payment_address), + ("platformPaymentAddress", &input.platform_payment_address), + ("shieldedAddress", &input.shielded_address), + ] +} + /// Parse a profile document's property map into a [`DashPayProfile`]. /// Empty strings are normalized to `None`. `avatarHash`/`avatarFingerprint` /// are read via `as_bytes_slice` so both `Bytes` and the sized `Bytes32` @@ -329,14 +345,29 @@ fn profile_from_properties(props: &std::collections::BTreeMap) -> .and_then(|v: &Value| v.as_bytes_slice().ok()) .and_then(|bytes| <[u8; 8]>::try_from(bytes).ok()); - DashPayProfile { + normalize_persisted_profile(DashPayProfile { display_name: text("displayName"), bio: public_message.clone(), avatar_url: text("avatarUrl"), avatar_hash, avatar_fingerprint, public_message, - } + core_payment_address: props + .get("corePaymentAddress") + .and_then(|v| v.as_bytes_slice().ok()) + .filter(|bytes| crate::valid_transparent_payment_address(bytes)) + .map(|bytes| bytes.to_vec()), + platform_payment_address: props + .get("platformPaymentAddress") + .and_then(|v| v.as_bytes_slice().ok()) + .filter(|bytes| crate::valid_transparent_payment_address(bytes)) + .map(|bytes| bytes.to_vec()), + shielded_address: props + .get("shieldedAddress") + .and_then(|v| v.as_bytes_slice().ok()) + .and_then(crate::validated_shielded_address) + .map(|bytes| bytes.to_vec()), + }) } // --------------------------------------------------------------------------- @@ -405,6 +436,8 @@ impl DashPayView<'_, B> { /// are themselves managed identities are skipped (their own /// `dashpay_profile` is authoritative). Display-only: a failure never /// aborts the sweep. Returns the number of cache entries changed. + /// Results for a removed or replaced wallet generation are discarded + /// without changing state or persistence. /// /// Fetching pending senders' profiles is an accepted privacy cost: an /// observer could link the `$ownerId In [...]` query to our inbound set, @@ -498,7 +531,7 @@ impl DashPayView<'_, B> { let mut written = 0u32; { let mut wm = self.wallet_manager.write().await; - let Some(info) = wm.get_wallet_info_mut(&self.wallet_id) else { + let Ok(info) = self.current_wallet_info_mut(&mut wm) else { return Ok(0); }; for (owner_id, owner_results) in results { @@ -554,6 +587,9 @@ impl DashPayView<'_, B> { .await .map_err(PlatformWalletError::Sdk)?; + #[cfg(test)] + sync_generation_tests::after_fetch(&self.generation).await; + Ok(docs .into_iter() .map(|(owner, doc)| (owner, cacheable_profile(doc.properties()))) @@ -825,3 +861,878 @@ mod tests { assert!(cache[&id].profile.is_none()); } } + +impl DashPayView<'_, B> { + /// Fetch a fresh, proof-verified profile, bypassing the contact cache. + pub async fn fetch_profile( + &self, + identity_id: &Identifier, + ) -> Result, PlatformWalletError> { + let contract = super::dashpay_contract()?; + Ok(self + .sdk + .get_profiles(&contract, &[*identity_id]) + .await? + .remove(identity_id) + .map(|doc| profile_from_properties(doc.properties()))) + } + + /// Resolve the current DPNS owner and its current shielded tip address. + pub async fn resolve_shielded_tip( + &self, + username: &str, + ) -> Result { + let identity_id = self.sdk.resolve_dpns_name(username).await?.ok_or_else(|| { + PlatformWalletError::InvalidIdentityData("Username was not found".to_string()) + })?; + let address = self + .fetch_profile(&identity_id) + .await? + .and_then(|profile| profile.shielded_address) + .and_then(|bytes| crate::validated_shielded_address(&bytes)) + .ok_or_else(|| { + PlatformWalletError::InvalidIdentityData( + "This profile has no valid shielded tip address".to_string(), + ) + })?; + Ok(crate::ShieldedTipRecipient { + identity_id, + address, + }) + } + + async fn validate_payment_address_update( + &self, + input: &crate::ProfileUpdate, + ) -> Result<(), PlatformWalletError> { + use crate::PaymentAddressUpdate; + use dash_sdk::platform::Fetch; + use dpp::data_contract::accessors::v0::DataContractV0Getters; + use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; + use dpp::prelude::DataContract; + let updates = payment_address_updates(input); + if updates + .iter() + .all(|(_, patch)| !matches!(patch, PaymentAddressUpdate::Set(_))) + { + return Ok(()); + } + for (field, patch) in updates { + if let PaymentAddressUpdate::Set(bytes) = patch { + let valid = if field == "shieldedAddress" { + crate::validated_shielded_address(bytes).is_some() + } else { + crate::valid_transparent_payment_address(bytes) + }; + if !valid { + return Err(PlatformWalletError::InvalidIdentityData(format!( + "Invalid or unsupported {field}" + ))); + } + } + } + // The bundled latest schema does not prove the connected chain has + // activated it. Fetch the actual contract before submitting new fields. + let contract = DataContract::fetch( + &self.sdk, + dpp::data_contracts::SystemDataContract::Dashpay.id(), + ) + .await? + .ok_or_else(|| { + PlatformWalletError::InvalidIdentityData( + "DashPay contract is not available".to_string(), + ) + })?; + let profile = contract + .document_type_for_name("profile") + .map_err(|e| PlatformWalletError::InvalidIdentityData(e.to_string()))?; + for (field, patch) in updates { + if matches!(patch, PaymentAddressUpdate::Set(_)) + && !profile.properties().contains_key(field) + { + return Err(PlatformWalletError::InvalidIdentityData(format!( + "The connected network does not support {field} yet" + ))); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod address_patch_tests { + use super::*; + use crate::{PaymentAddressUpdate, ProfileUpdate}; + + #[tokio::test] + async fn should_allow_removal_without_contract_activation_but_reject_unsupported_set() { + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::version::PlatformVersion; + let mut sdk = dash_sdk::SdkBuilder::new_mock().build().unwrap(); + let contract = load_system_data_contract( + SystemDataContract::Dashpay, + PlatformVersion::get(13).unwrap(), + ) + .unwrap(); + sdk.mock() + .expect_fetch(SystemDataContract::Dashpay.id(), Some(contract)) + .await + .unwrap(); + let (wm, wallet_id, generation, _) = crate::test_support::funded_wallet_manager( + key_wallet::account::StandardAccountType::BIP44Account, + ) + .await; + let spv = Arc::new(crate::spv::SpvRuntime::new( + wm.clone(), + Arc::new(crate::events::PlatformEventManager::new(vec![])), + )); + let wallet = crate::PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wm, + generation, + Arc::new(tokio::sync::Notify::new()), + Arc::new(crate::wallet::persister::NoPlatformPersistence), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + let remove = ProfileUpdate { + display_name: Some("Alice II".into()), + core_payment_address: PaymentAddressUpdate::Remove, + platform_payment_address: PaymentAddressUpdate::Remove, + shielded_address: PaymentAddressUpdate::Remove, + ..Default::default() + }; + wallet + .identity() + .dashpay() + .validate_payment_address_update(&remove) + .await + .unwrap(); + let fields = profile_fields(remove).unwrap(); + assert_eq!(fields.display_name.as_deref(), Some("Alice II")); + assert_eq!(fields.core_payment_address, PaymentAddressUpdate::Remove); + assert_eq!( + fields.platform_payment_address, + PaymentAddressUpdate::Remove + ); + assert_eq!(fields.shielded_address, PaymentAddressUpdate::Remove); + // Removal must not bypass activation checks on a simultaneously set field. + let mixed = ProfileUpdate { + core_payment_address: PaymentAddressUpdate::Set(vec![0; 21]), + shielded_address: PaymentAddressUpdate::Remove, + ..Default::default() + }; + let error = wallet + .identity() + .dashpay() + .validate_payment_address_update(&mixed) + .await + .unwrap_err(); + assert!(error + .to_string() + .contains("does not support corePaymentAddress")); + } + + #[tokio::test] + async fn should_sync_address_only_profile_and_retain_it_in_snapshots() { + use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; + use dash_sdk::{platform::DocumentQuery, query_types::Documents}; + use dpp::document::DocumentV0; + use dpp::identity::IdentityV0; + use dpp::version::PlatformVersion; + + let owner = Identifier::from([0x61; 32]); + let key = orchard::keys::SpendingKey::from_bytes([42; 32]).unwrap(); + let raw = orchard::keys::FullViewingKey::from(&key) + .address_at(19u32, orchard::keys::Scope::External) + .to_raw_address_bytes(); + let contract = super::super::dashpay_contract().unwrap(); + let query = DocumentQuery::new(contract, "profile") + .unwrap() + .with_where(WhereClause { + field: "$ownerId".into(), + operator: WhereOperator::In, + value: Value::Array(vec![owner.into()]), + }) + .with_order_by(OrderClause { + field: "$ownerId".into(), + ascending: true, + }) + .with_limit(100); + let document = Document::V0(DocumentV0 { + id: Identifier::from([0x62; 32]), + owner_id: owner, + revision: Some(1), + properties: [("shieldedAddress".into(), Value::Bytes(raw.to_vec()))].into(), + ..Default::default() + }); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(key_wallet::Network::Testnet) + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch_many::( + query, + Some([(document.id(), Some(document))].into()), + ) + .await + .unwrap(); + let (wm, wallet_id, generation, _) = crate::test_support::funded_wallet_manager( + key_wallet::account::StandardAccountType::BIP44Account, + ) + .await; + let persister: Arc = + Arc::new(crate::wallet::persister::NoPlatformPersistence); + wm.write() + .await + .get_wallet_info_mut(&wallet_id) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id: owner, + public_keys: Default::default(), + balance: 0, + revision: 0, + }), + 0, + wallet_id, + &crate::wallet::persister::WalletPersister::new(wallet_id, persister.clone()), + ) + .unwrap(); + let spv = Arc::new(crate::spv::SpvRuntime::new( + wm.clone(), + Arc::new(crate::events::PlatformEventManager::new(vec![])), + )); + let wallet = crate::PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wm.clone(), + generation, + Arc::new(tokio::sync::Notify::new()), + persister, + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + assert_eq!( + wallet.identity().dashpay().sync_profiles().await.unwrap(), + 1 + ); + let manager = wm.read().await; + let managed = manager + .get_wallet_info(&wallet_id) + .unwrap() + .identity_manager + .managed_identity(&owner) + .unwrap(); + let snapshot = crate::changeset::IdentityEntry::from_managed(managed); + assert_eq!( + snapshot.dashpay_profile.unwrap().shielded_address, + Some(raw.to_vec()) + ); + } + + #[test] + fn should_ignore_invalid_addresses_without_losing_profile() { + let profile = profile_from_properties(&std::collections::BTreeMap::from([ + ("displayName".into(), Value::Text("Alice".into())), + ("shieldedAddress".into(), Value::Bytes(vec![255; 43])), + ("corePaymentAddress".into(), Value::Bytes(vec![255; 21])), + ])); + assert_eq!(profile.display_name.as_deref(), Some("Alice")); + assert!(profile.shielded_address.is_none()); + assert!(profile.core_payment_address.is_none()); + } + + #[cfg(feature = "shielded")] + #[test] + fn should_accept_external_addresses_with_nondefault_diversifiers() { + let keys = crate::wallet::shielded::OrchardKeySet::from_seed( + &[9; 64], + key_wallet::Network::Testnet, + 7, + ) + .unwrap(); + let raw = keys.address_at(19).to_raw_address_bytes(); + assert_ne!(raw, keys.default_address.to_raw_address_bytes()); + let profile = profile_from_properties(&std::collections::BTreeMap::from([( + "shieldedAddress".into(), + Value::Bytes(raw.to_vec()), + )])); + assert_eq!(profile.shielded_address, Some(raw.to_vec())); + assert!(crate::validated_shielded_address(&raw[..42]).is_none()); + } +} + +#[cfg(all(test, feature = "shielded"))] +mod tip_resolution_tests { + use super::*; + use crate::wallet::shielded::{ + CachedOrchardProver, FileBackedShieldedStore, NetworkShieldedCoordinator, OrchardKeySet, + }; + use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; + use dash_sdk::{platform::DocumentQuery, query_types::Documents, SdkBuilder}; + use dpp::{ + document::{Document, DocumentV0}, + system_data_contracts::{load_system_data_contract, SystemDataContract}, + version::PlatformVersion, + }; + + // Exercise both SDK queries through the real wallet API. No expectations + // permit a send/broadcast: a changed or invalid destination must stop first. + #[tokio::test] + async fn should_resolve_fresh_profiles_and_refuse_changed_tip_destinations() { + let original_owner = Identifier::from([1; 32]); + let new_owner = Identifier::from([2; 32]); + let keys = OrchardKeySet::from_seed(&[42; 64], key_wallet::Network::Testnet, 9).unwrap(); + let original_address = keys.default_address.to_raw_address_bytes(); + let changed_address = keys.address_at(7).to_raw_address_bytes(); + for (owner, address, expected_error) in [ + (original_owner, Some(original_address.to_vec()), "bound"), + ( + new_owner, + Some(original_address.to_vec()), + "recipient changed", + ), + ( + original_owner, + Some(changed_address.to_vec()), + "recipient changed", + ), + (original_owner, None, "no valid shielded tip address"), + ( + original_owner, + Some(vec![255; 43]), + "no valid shielded tip address", + ), + ] { + let dir = std::env::temp_dir().join(format!( + "tip-resolution-{}-{}", + std::process::id(), + rand::random::() + )); + std::fs::create_dir_all(&dir).unwrap(); + let mut sdk = SdkBuilder::new_mock() + .with_network(key_wallet::Network::Testnet) + .with_version(PlatformVersion::latest()) + .with_dump_dir(&dir) + .build() + .unwrap(); + let dpns = + load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()) + .unwrap(); + sdk.mock() + .expect_fetch(SystemDataContract::DPNS.id(), Some(dpns.clone())) + .await + .unwrap(); + let domain = Document::V0(DocumentV0 { + id: Identifier::from([3; 32]), + owner_id: owner, + revision: Some(1), + properties: [( + "records".into(), + Value::Map(vec![( + Value::Text("identity".into()), + Value::Identifier(owner.to_buffer()), + )]), + )] + .into(), + ..Default::default() + }); + let query = DocumentQuery { + data_contract: Arc::new(dpns), + document_type_name: "domain".into(), + where_clauses: vec![ + WhereClause { + field: "normalizedParentDomainName".into(), + operator: WhereOperator::Equal, + value: Value::Text("dash".into()), + }, + WhereClause { + field: "normalizedLabel".into(), + operator: WhereOperator::Equal, + value: Value::Text("a11ce".into()), + }, + ], + select: dash_sdk::drive::query::SelectProjection::documents(), + time_range_clauses: vec![], + integer_range_clauses: vec![], + group_by: vec![], + having: vec![], + order_by_clauses: vec![], + limit: 1, + offset: None, + start: None, + sub_queries: vec![], + }; + sdk.mock() + .expect_fetch_many::( + query, + Some([(domain.id(), Some(domain))].into()), + ) + .await + .unwrap(); + let profile = Document::V0(DocumentV0 { + id: Identifier::from([4; 32]), + owner_id: owner, + revision: Some(1), + properties: address + .map(|bytes| ("shieldedAddress".into(), Value::Bytes(bytes))) + .into_iter() + .collect(), + ..Default::default() + }); + // The `$ownerId In [owner]` query `Sdk::get_profiles` sends. + let contract = super::super::dashpay_contract().unwrap(); + let profile_query = DocumentQuery::new(contract, "profile") + .unwrap() + .with_where(WhereClause { + field: "$ownerId".into(), + operator: WhereOperator::In, + value: Value::Array(vec![owner.into()]), + }) + .with_order_by(OrderClause { + field: "$ownerId".into(), + ascending: true, + }) + .with_limit(100); + sdk.mock() + .expect_fetch_many::( + profile_query, + Some([(profile.id(), Some(profile))].into()), + ) + .await + .unwrap(); + let sdk = Arc::new(sdk); + let (wm, wallet_id, generation, _) = crate::test_support::funded_wallet_manager( + key_wallet::account::StandardAccountType::BIP44Account, + ) + .await; + let spv = Arc::new(crate::spv::SpvRuntime::new( + wm.clone(), + Arc::new(crate::events::PlatformEventManager::new(vec![])), + )); + let wallet = crate::PlatformWallet::new( + sdk.clone(), + wallet_id, + wm, + generation, + Arc::new(tokio::sync::Notify::new()), + Arc::new(crate::wallet::persister::NoPlatformPersistence), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + let path = dir.join("tree.sqlite"); + let store = FileBackedShieldedStore::open_path(&path, 100).unwrap(); + let coordinator = Arc::new(NetworkShieldedCoordinator::new( + sdk, + key_wallet::Network::Testnet, + path, + store, + )); + let confirmed = crate::ShieldedTipRecipient { + identity_id: original_owner, + address: original_address, + }; + let error = wallet + .send_shielded_tip( + &coordinator, + &[42; 64], + crate::ShieldedTipSource::Account(0), + "Alice.dash", + &confirmed, + 1000, + [0; 36], + &CachedOrchardProver::new(), + ) + .await + .unwrap_err(); + assert!( + error.to_string().contains(expected_error), + "expected {expected_error}, got {error}" + ); + drop(coordinator); + std::fs::remove_dir_all(dir).unwrap(); + } + } +} + +#[cfg(test)] +mod sync_generation_tests { + use super::*; + use crate::changeset::{ + ClientStartState, IdentityChangeSet, IdentityEntry, PersistenceError, + PlatformWalletChangeSet, PlatformWalletPersistence, + }; + use crate::test_support::NoopTestEventHandler; + use crate::wallet::core::WalletGeneration; + use crate::wallet::identity::ContactRequest; + use crate::wallet::platform_wallet::WalletId; + use crate::{PlatformWallet, PlatformWalletManager}; + use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; + use dash_sdk::{platform::DocumentQuery, query_types::Documents, SdkBuilder}; + use dpp::document::DocumentV0; + use dpp::identity::IdentityV0; + use dpp::version::PlatformVersion; + use key_wallet::{wallet::initialization::WalletAccountCreationOptions, Network}; + use std::collections::BTreeMap; + use std::sync::Mutex; + use std::time::Duration; + use tokio::sync::oneshot; + + type FetchPause = (oneshot::Sender<()>, oneshot::Receiver<()>); + static FETCH_PAUSES: Mutex> = Mutex::new(BTreeMap::new()); + + pub(super) async fn after_fetch(generation: &Arc) { + let pause = FETCH_PAUSES + .lock() + .unwrap() + .remove(&(Arc::as_ptr(generation) as usize)); + if let Some((reached, resume)) = pause { + reached.send(()).unwrap(); + resume.await.unwrap(); + } + } + + #[derive(Default)] + struct CapturingPersistence(Mutex>); + + impl PlatformWalletPersistence for CapturingPersistence { + fn store( + &self, + _: WalletId, + changeset: PlatformWalletChangeSet, + ) -> Result<(), PersistenceError> { + self.0.lock().unwrap().push(changeset); + Ok(()) + } + + fn flush(&self, _: WalletId) -> Result<(), PersistenceError> { + Ok(()) + } + + fn load(&self) -> Result { + Ok(ClientStartState::default()) + } + } + + async fn add_wallet( + manager: &PlatformWalletManager, + ) -> Arc { + manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap() + } + + async fn sync(wallet: &PlatformWallet, contacts: bool) -> u32 { + if contacts { + wallet + .identity() + .dashpay() + .sync_contact_profiles() + .await + .unwrap() + } else { + wallet.identity().dashpay().sync_profiles().await.unwrap() + } + } + + #[tokio::test] + async fn should_persist_first_observed_profile_absence_once_and_keep_overlay_across_scalars() { + use crate::changeset::Merge; + let owner = Identifier::from([0x61; 32]); + let query = DocumentQuery::new(dashpay_contract().unwrap(), "profile") + .unwrap() + .with_where(WhereClause { + field: "$ownerId".into(), + operator: WhereOperator::In, + value: Value::Array(vec![owner.into()]), + }) + .with_order_by(OrderClause { + field: "$ownerId".into(), + ascending: true, + }) + .with_limit(100); + let mut sdk = SdkBuilder::new_mock() + .with_network(Network::Testnet) + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch_many::( + query, + Some(Default::default()), + ) + .await + .unwrap(); + let persistence = Arc::new(CapturingPersistence::default()); + let manager = PlatformWalletManager::new( + Arc::new(sdk), + Arc::clone(&persistence), + Arc::new(NoopTestEventHandler), + ); + let wallet = add_wallet(&manager).await; + { + let mut state = wallet.state_mut().await.unwrap(); + state + .identity_manager + .add_out_of_wallet_identity( + Identity::V0(IdentityV0 { + id: owner, + public_keys: Default::default(), + balance: 123, + revision: 7, + }), + wallet.persister(), + ) + .unwrap(); + } + persistence.0.lock().unwrap().clear(); + assert_eq!(sync(&wallet, false).await, 1); + assert_eq!(sync(&wallet, false).await, 0); + let mut merged = { + let mut writes = persistence.0.lock().unwrap(); + assert_eq!(writes.len(), 1); + writes.pop().unwrap() + }; + assert_eq!( + merged.dashpay_profiles.as_ref().unwrap().get(&owner), + Some(&None) + ); + let scalar = merged.identities.clone().unwrap(); + let mut known = scalar.clone(); + known.identities.get_mut(&owner).unwrap().dashpay_profile = Some(DashPayProfile { + display_name: Some("Retained".into()), + ..Default::default() + }); + known.merge(scalar.clone()); + assert_eq!( + known.identities[&owner] + .dashpay_profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("Retained") + ); + merged.merge(scalar.into()); + assert_eq!( + merged.dashpay_profiles.as_ref().unwrap().get(&owner), + Some(&None) + ); + let state = wallet.state().await; + assert!( + state + .identity_manager + .managed_identity(&owner) + .unwrap() + .dashpay() + .profile_checked + ); + } + + async fn assert_delayed_sync_preserves_replacement(contacts: bool) { + for present in [true, false] { + let owner = Identifier::from([0x61; 32]); + let contact = Identifier::from([0x62; 32]); + let target = if contacts { contact } else { owner }; + let key = orchard::keys::SpendingKey::from_bytes([42; 32]).unwrap(); + let fvk = orchard::keys::FullViewingKey::from(&key); + let fetched_address = fvk + .address_at(19u32, orchard::keys::Scope::External) + .to_raw_address_bytes() + .to_vec(); + let restored_profile = DashPayProfile { + display_name: Some("Restored profile".into()), + shielded_address: Some( + fvk.address_at(20u32, orchard::keys::Scope::External) + .to_raw_address_bytes() + .to_vec(), + ), + ..Default::default() + }; + let contract = dashpay_contract().unwrap(); + let query = DocumentQuery::new(contract, "profile") + .unwrap() + .with_where(WhereClause { + field: "$ownerId".into(), + operator: WhereOperator::In, + value: Value::Array(vec![target.into()]), + }) + .with_order_by(OrderClause { + field: "$ownerId".into(), + ascending: true, + }) + .with_limit(100); + let document = Document::V0(DocumentV0 { + id: Identifier::from([0x63; 32]), + owner_id: target, + revision: Some(1), + properties: [( + "shieldedAddress".into(), + Value::Bytes(fetched_address.clone()), + )] + .into(), + ..Default::default() + }); + let docs: Documents = if present { + [(document.id(), Some(document))].into() + } else { + Default::default() + }; + let mut sdk = SdkBuilder::new_mock() + .with_network(Network::Testnet) + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch_many::(query, Some(docs)) + .await + .unwrap(); + let persistence = Arc::new(CapturingPersistence::default()); + let manager = PlatformWalletManager::new( + Arc::new(sdk), + Arc::clone(&persistence), + Arc::new(NoopTestEventHandler), + ); + let old = add_wallet(&manager).await; + let mut restored = { + let mut state = old.state_mut().await.unwrap(); + state + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id: owner, + public_keys: Default::default(), + balance: 123, + revision: 7, + }), + 0, + old.wallet_id(), + old.persister(), + ) + .unwrap(); + let managed = state.identity_manager.managed_identity_mut(&owner).unwrap(); + if contacts { + managed + .add_incoming_contact_request( + ContactRequest::new(contact, owner, 0, 0, 0, vec![], 0, 0), + old.persister(), + ) + .unwrap(); + } + IdentityEntry::from_managed(managed) + }; + restored.dashpay_profile = Some(restored_profile.clone()); + restored.contact_profiles.insert( + contact, + ContactProfileEntry { + profile: Some(restored_profile.clone()), + checked_at_ms: 42, + }, + ); + let (reached_tx, reached_rx) = oneshot::channel(); + let (resume_tx, resume_rx) = oneshot::channel(); + FETCH_PAUSES.lock().unwrap().insert( + Arc::as_ptr(&old.identity().generation) as usize, + (reached_tx, resume_rx), + ); + let syncing = { + let old = Arc::clone(&old); + tokio::spawn(async move { sync(&old, contacts).await }) + }; + tokio::time::timeout(Duration::from_secs(10), reached_rx) + .await + .unwrap() + .unwrap(); + tokio::time::timeout( + Duration::from_secs(10), + manager.remove_wallet(&old.wallet_id()), + ) + .await + .unwrap() + .unwrap(); + let current = add_wallet(&manager).await; + assert_eq!(old.wallet_id(), current.wallet_id()); + current + .apply( + IdentityChangeSet { + identities: [(owner, restored.clone())].into(), + ..Default::default() + } + .into(), + ) + .await + .unwrap(); + if contacts { + current + .state_mut() + .await + .unwrap() + .identity_manager + .managed_identity_mut(&owner) + .unwrap() + .add_incoming_contact_request( + ContactRequest::new(contact, owner, 0, 0, 0, vec![], 0, 0), + current.persister(), + ) + .unwrap(); + } + let before = persistence.0.lock().unwrap().len(); + resume_tx.send(()).unwrap(); + assert_eq!( + syncing.await.unwrap(), + 0, + "stale synchronization must be discarded" + ); + assert_eq!( + persistence.0.lock().unwrap().len(), + before, + "stale synchronization must not persist through its retained handle" + ); + { + let state = current.state().await; + let managed = state.identity_manager.managed_identity(&owner).unwrap(); + assert_eq!(IdentityEntry::from_managed(managed), restored); + } + assert_eq!( + sync(¤t, contacts).await, + 1, + "current generation can synchronize" + ); + assert!(persistence.0.lock().unwrap().len() > before); + let state = current.state().await; + let managed = state.identity_manager.managed_identity(&owner).unwrap(); + let profile = if contacts { + &managed.dashpay().contact_profiles[&contact].profile + } else { + &managed.dashpay().profile + }; + assert_eq!( + profile.as_ref().and_then(|p| p.shielded_address.as_ref()), + present.then_some(&fetched_address) + ); + } + } + + #[tokio::test] + async fn should_discard_delayed_own_profile_sync_after_wallet_replacement() { + assert_delayed_sync_preserves_replacement(false).await; + } + + #[tokio::test] + async fn should_discard_delayed_contact_profile_sync_after_wallet_replacement() { + assert_delayed_sync_preserves_replacement(true).await; + } +} diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/dashpay.rs b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/dashpay.rs index a9b1fdeca06..498b50bd9d5 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/dashpay.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/dashpay.rs @@ -249,6 +249,9 @@ pub struct DashPayState { /// profile has been fetched or set. pub profile: Option, + /// Session-only authority: a successful fetch or explicit update checked this profile. + pub(crate) profile_checked: bool, + /// DashPay payment history keyed by transaction id (hex string). /// Each entry records a single Dash payment to or from a contact /// identity, with direction, amount, memo, and status. diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs index bc960262ea9..c091e156289 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs @@ -4,7 +4,7 @@ use super::key_storage::{DpnsFetch, DpnsNameInfo, IdentityStatus}; use super::ManagedIdentity; use crate::changeset::{ IdentityChangeSet, IdentityEntry, IdentityKeyEntry, IdentityKeysChangeSet, KeyWithBreadcrumb, - PersistenceError, + PersistenceError, PlatformWalletChangeSet, }; use crate::wallet::persister::WalletPersister; use crate::BlockTime; @@ -133,10 +133,15 @@ impl ManagedIdentity { profile: Option, persister: &WalletPersister, ) { - self.dashpay.profile = profile; - let cs = self.snapshot_changeset(); - if let Err(e) = persister.store(cs.into()) { - tracing::error!("Failed to persist changeset: {}", e); + let previous = std::mem::replace(&mut self.dashpay.profile, profile.clone()); + let mut cs: PlatformWalletChangeSet = self.snapshot_changeset().into(); + cs.dashpay_profiles = Some(BTreeMap::from([(self.id(), profile)])); + match persister.store(cs) { + Ok(()) => self.dashpay.profile_checked = true, + Err(e) => { + self.dashpay.profile = previous; + tracing::error!("Failed to persist changeset: {}", e); + } } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/mod.rs index c11f1e91f8a..cc4fd32590a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/mod.rs @@ -20,6 +20,7 @@ pub use crate::wallet::identity::types::key_storage::{ self, DpnsFetch, DpnsNameInfo, IdentityStatus, KeyStorage, PrivateKeyData, }; +use crate::wallet::identity::DashPayProfile; use dpp::identity::Identity; /// A managed identity that combines an Identity with wallet-specific metadata. @@ -117,6 +118,12 @@ impl ManagedIdentity { &mut self.dashpay.profile } + /// Apply an authoritative profile overlay without emitting another write. + pub(crate) fn apply_dashpay_profile(&mut self, profile: Option) { + self.dashpay.profile = profile; + self.dashpay.profile_checked = true; + } + /// Mutable access to the DashPay payment-history cache. /// /// Replay/restore surface: bypasses persistence and the diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs b/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs index 03f8ed10004..16be8b01bae 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs @@ -36,7 +36,10 @@ impl IdentityManager { /// /// Idempotent: applying the same entry twice produces the same state /// as applying it once. If the identity already exists in either - /// bucket, the scalar fields are updated in place; balance/revision + /// bucket, it first moves to the wallet slot the entry carries (a + /// re-slot by [`Self::adopt_into_wallet`]) unless another identity + /// holds that slot (placement follows the latest entry applied, as in + /// `IdentityChangeSet::merge`), and the scalar fields are updated; balance/revision /// are gated on `entry.revision >= existing.identity.revision()` /// matching the merge policy on `IdentityChangeSet`. DPNS labels and /// contested DPNS labels are complete canonical snapshots and are @@ -46,6 +49,20 @@ impl IdentityManager { let id = entry.id; + // Follow a re-slot (placeholder index 0 to its verified index, or an + // observed identity adopted into the wallet) before updating in place. + if self.identity(&id).is_some() { + if let Some((wallet_id, index)) = entry.wallet_id.zip(entry.identity_index) { + if let Err(error) = self.adopt_into_wallet(&id, wallet_id, index) { + tracing::warn!( + identity = %id, + %error, + "keeping identity at its current slot during apply", + ); + } + } + } + // Updating an existing identity — find it across both buckets. if let Some(existing) = self.locate_mut(&id) { if entry.revision >= existing.identity.revision() { @@ -57,7 +74,9 @@ impl IdentityManager { } existing.last_synced_keys_block_time = entry.last_synced_keys_block_time; existing.status = entry.status; - *existing.dashpay_profile_mut() = entry.dashpay_profile; + if let Some(profile) = entry.dashpay_profile { + existing.apply_dashpay_profile(Some(profile)); + } // DPNS names: wholesale assign, matching the changeset's // last-write-wins merge — entries carry the complete list // (snapshotted via `from_managed`), and a sold/transferred @@ -107,6 +126,18 @@ impl IdentityManager { ); return; }; + // Inserting would discard the occupant while its reverse-index + // entry kept pointing here. + if let Some(occupant) = self.slot_holder(&wallet_id, registration_index) { + tracing::warn!( + identity = %id, + %occupant, + wallet_id = %hex::encode(wallet_id), + registration_index, + "skipping wallet-owned identity entry whose slot is occupied during apply", + ); + return; + } let mut managed = ManagedIdentity::new(identity, registration_index); managed.last_updated_balance_block_time = entry.last_updated_balance_block_time; @@ -162,6 +193,116 @@ impl IdentityManager { } } + /// Restore a batch of entries independently of their order. Known + /// identities are applied first, each deferred while its target slot is + /// still held by another identity that the batch moves out, and new ones + /// are inserted last: a re-slot A@0 → A@5 frees slot 0 for a new B@0 + /// whichever entry is visited first. Moves that only wait on each other + /// (A@0/B@1 becoming A@1/B@0) are staged out of the wallet and then + /// placed; a move blocked by an identity that stays put is applied in + /// place. + pub(crate) fn apply_identity_entries( + &mut self, + entries: impl IntoIterator, + ) { + let (mut pending, fresh): (Vec<_>, Vec<_>) = entries + .into_iter() + .partition(|entry| self.identity(&entry.id).is_some()); + while !pending.is_empty() { + let (blocked, ready): (Vec<_>, Vec<_>) = pending + .into_iter() + .partition(|entry| self.blocker(entry).is_some()); + let progressed = !ready.is_empty(); + for entry in ready { + self.apply_identity_entry(entry); + } + pending = blocked; + if !progressed { + let cycle = self.cycle_members(&pending); + if cycle.is_empty() { + break; + } + for id in &cycle { + self.stage_out_of_wallet(id); + } + } + } + for entry in pending.into_iter().chain(fresh) { + self.apply_identity_entry(entry); + } + } + + /// The other identity holding the slot `entry` places its identity in. + fn blocker(&self, entry: &IdentityEntry) -> Option { + entry + .wallet_id + .zip(entry.identity_index) + .and_then(|(wallet_id, index)| self.slot_holder(&wallet_id, index)) + .filter(|holder| *holder != entry.id) + } + + /// Blocked moves on a closed cycle: following blockers through the other + /// blocked moves leads back to the start. Empty when another blocked move + /// waits on a cycle member: that slot is claimed twice (only an + /// inconsistent batch does this), and staging could strand the loser + /// outside the wallet. + fn cycle_members(&self, pending: &[IdentityEntry]) -> Vec { + let blockers: BTreeMap = pending + .iter() + .filter_map(|entry| Some((entry.id, self.blocker(entry)?))) + .collect(); + let cycle: Vec = blockers + .keys() + .copied() + .filter(|start| { + let mut current = *start; + for _ in 0..blockers.len() { + match blockers.get(¤t) { + Some(next) if next == start => return true, + Some(next) => current = *next, + None => return false, + } + } + false + }) + .collect(); + let contested = blockers + .iter() + .any(|(id, blocker)| !cycle.contains(id) && cycle.contains(blocker)); + if contested { + Vec::new() + } else { + cycle + } + } + + /// Park an in-wallet identity in the observed bucket, freeing its slot; + /// applying its entry then adopts it back into its target slot. + fn stage_out_of_wallet(&mut self, identity_id: &Identifier) { + let Some(IdentityLocation::InWallet { + wallet_id, + registration_index, + }) = self.location_index().get(identity_id).copied() + else { + return; + }; + if let Some(managed) = self + .wallet_identities + .get_mut(&wallet_id) + .and_then(|bucket| bucket.remove(®istration_index)) + { + self.out_of_wallet_identities.insert(*identity_id, managed); + self.location_index_insert(*identity_id, IdentityLocation::OutOfWallet); + } + } + + fn slot_holder(&self, wallet_id: &[u8; 32], index: u32) -> Option { + self.wallet_identities + .get(wallet_id) + .and_then(|bucket| bucket.get(&index)) + .map(|occupant| occupant.identity.id()) + } + /// Restore a single [`IdentityKeyEntry`] onto the matching /// `ManagedIdentity`. /// diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs b/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs index 294e836f9d8..e6618d9211d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs @@ -4,7 +4,9 @@ //! Every mutation here persists a corresponding //! [`IdentityChangeSet`](crate::changeset::IdentityChangeSet) via //! the supplied [`WalletPersister`], except -//! [`IdentityManager::add_identity_unstored`], whose caller stores. +//! [`IdentityManager::add_identity_unstored`], +//! [`IdentityManager::place_verified_identity`] and +//! [`IdentityManager::adopt_into_wallet`], whose callers store. use super::{IdentityLocation, IdentityManager}; use crate::changeset::{IdentityChangeSet, IdentityEntry, PlatformWalletChangeSet}; @@ -16,6 +18,15 @@ use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::Identity; use dpp::prelude::Identifier; +/// How [`IdentityManager::place_verified_identity`] placed an identity. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum VerifiedPlacement { + /// Newly added to the wallet bucket. + Added, + /// Already known; moved into (or confirmed at) the verified slot. + Adopted, +} + impl IdentityManager { /// Create a new identity manager pub fn new() -> Self { @@ -31,7 +42,10 @@ impl IdentityManager { /// onto the value at insert time. /// /// Errors if an identity with the same id already exists in either - /// bucket. + /// bucket, or with [`PlatformWalletError::IdentityIndexOccupied`] if the + /// slot already holds a different identity (inserting would silently + /// discard the occupant while its reverse-index entry kept pointing at + /// the slot). Nothing is changed or persisted on either error. /// /// Persists the resulting changeset via `persister` and returns `()`. pub fn add_identity( @@ -90,6 +104,17 @@ impl IdentityManager { if self.identity(&identity_id).is_some() { return Err(PlatformWalletError::IdentityAlreadyExists(identity_id)); } + if let Some(occupant) = self + .wallet_identities + .get(&wallet_id) + .and_then(|bucket| bucket.get(&identity_index)) + { + return Err(PlatformWalletError::IdentityIndexOccupied { + identity_id, + identity_index, + occupant: occupant.identity.id(), + }); + } let mut managed_identity = ManagedIdentity::new(identity, identity_index); // Denormalize the bucket keys onto the value so callers that @@ -142,6 +167,103 @@ impl IdentityManager { } } + /// Place an identity a key derivation just proved at `identity_index` in + /// `wallet_id`'s bucket: add it when unknown, otherwise move it into that + /// slot (see [`Self::adopt_into_wallet`]). Identity load and discovery both + /// go through here before they touch status or keys, so a refused + /// placement changes nothing. Like [`Self::add_identity_unstored`] it + /// does not persist: the caller stores the identity's snapshot with its + /// verified keys as one changeset. + pub(crate) fn place_verified_identity( + &mut self, + identity: Identity, + identity_index: u32, + wallet_id: WalletId, + ) -> Result { + let identity_id = identity.id(); + if self.identity(&identity_id).is_none() { + self.add_identity_unstored(identity, identity_index, wallet_id)?; + Ok(VerifiedPlacement::Added) + } else { + self.adopt_into_wallet(&identity_id, wallet_id, identity_index)?; + Ok(VerifiedPlacement::Adopted) + } + } + + /// Move an already-known identity into `wallet_id`'s bucket at the + /// `identity_index` a key derivation just proved for it. + /// + /// Identity load and discovery find identities by deriving this wallet's + /// MASTER key at an index, so the index they report is verified. An + /// identity first seen another way (observed out-of-wallet, or restored + /// with a host placeholder index) must take that verified slot rather than + /// just gaining a `wallet_id`: an index-less wallet identity is persisted + /// without its index, and hosts that cannot store "unknown" restore it as + /// index 0, which per-identity derivations (the dedicated tip account) + /// would then attribute to identity 0. + /// + /// Does not persist; the caller's following snapshot write carries the + /// updated `wallet_id` / `identity_index`. Fails with + /// [`PlatformWalletError::IdentityIndexOccupied`], changing nothing, when + /// the slot already holds a different identity. + /// Live-wallet callers hold `identity_placement` before the manager write + /// lock so a tip operation keeps its verified source slot until it finishes. + pub(crate) fn adopt_into_wallet( + &mut self, + identity_id: &Identifier, + wallet_id: WalletId, + identity_index: u32, + ) -> Result<(), PlatformWalletError> { + let target = IdentityLocation::InWallet { + wallet_id, + registration_index: identity_index, + }; + let current = self + .location_index() + .get(identity_id) + .copied() + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; + if current != target { + if let Some(other) = self + .wallet_identities + .get(&wallet_id) + .and_then(|bucket| bucket.get(&identity_index)) + .filter(|other| other.identity.id() != *identity_id) + { + return Err(PlatformWalletError::IdentityIndexOccupied { + identity_id: *identity_id, + identity_index, + occupant: other.identity.id(), + }); + } + let managed = match current { + IdentityLocation::OutOfWallet => self.out_of_wallet_identities.remove(identity_id), + IdentityLocation::InWallet { + wallet_id, + registration_index, + } => self + .wallet_identities + .get_mut(&wallet_id) + .and_then(|bucket| bucket.remove(®istration_index)), + } + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; + self.wallet_identities + .entry(wallet_id) + .or_default() + .insert(identity_index, managed); + self.location_index_insert(*identity_id, target); + } + if let Some(managed) = self + .wallet_identities + .get_mut(&wallet_id) + .and_then(|bucket| bucket.get_mut(&identity_index)) + { + managed.wallet_id = Some(wallet_id); + managed.identity_index = Some(identity_index); + } + Ok(()) + } + /// Add an identity to the out-of-wallet (observed read-only) bucket. /// /// There is no separate `WatchedIdentity` type; observed identities diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs index 236f259e4b2..c58b49a9943 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs @@ -29,6 +29,7 @@ mod accessors; mod apply; mod lifecycle; +pub(crate) use lifecycle::VerifiedPlacement; use super::managed_identity::ManagedIdentity; use crate::changeset::{IdentityManagerStartState, IdentityScanStateEntry}; @@ -230,6 +231,7 @@ impl IdentityManager { #[cfg(test)] mod tests { use super::*; + use crate::error::PlatformWalletError; use crate::wallet::persister::{NoPlatformPersistence, WalletPersister}; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::Identity; @@ -277,6 +279,172 @@ mod tests { assert_eq!(manager.highest_registration_index(&wallet_id), Some(0)); } + #[derive(Default)] + struct CountingPersistence { + stores: std::sync::atomic::AtomicUsize, + } + impl crate::changeset::PlatformWalletPersistence for CountingPersistence { + fn store( + &self, + _wallet_id: WalletId, + _changeset: crate::changeset::PlatformWalletChangeSet, + ) -> Result<(), crate::changeset::PersistenceError> { + self.stores + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(()) + } + fn flush(&self, _wallet_id: WalletId) -> Result<(), crate::changeset::PersistenceError> { + Ok(()) + } + fn load( + &self, + ) -> Result + { + Ok(Default::default()) + } + } + + /// Load and discovery prove an index by derivation and place the identity + /// through `place_verified_identity` before touching status or keys. An + /// identity already known (observed, or restored at a placeholder slot) + /// moves into the verified slot as `Adopted`, which discovery does not + /// report as newly discovered. A slot held by a different identity is a + /// typed refusal that changes and persists nothing. + #[test] + fn verified_placement_adopts_known_identities_and_refuses_occupied_slots() { + use std::sync::atomic::Ordering; + let mut manager = IdentityManager::new(); + let wallet_id: WalletId = [9u8; 32]; + let counter = Arc::new(CountingPersistence::default()); + let p = WalletPersister::new(wallet_id, Arc::clone(&counter) as _); + + let fresh = Identifier::from([5u8; 32]); + assert_eq!( + manager + .place_verified_identity(create_test_identity(fresh), 2, wallet_id) + .unwrap(), + VerifiedPlacement::Added + ); + + // Promotion of an observed identity: no new id is reported. + let observed = Identifier::from([1u8; 32]); + manager + .add_out_of_wallet_identity(create_test_identity(observed), &p) + .unwrap(); + assert_eq!( + manager + .place_verified_identity(create_test_identity(observed), 4, wallet_id) + .unwrap(), + VerifiedPlacement::Adopted + ); + assert!(manager.out_of_wallet_identities.is_empty()); + let managed = manager.identity(&observed).expect("present"); + assert_eq!(managed.identity_index, Some(4)); + assert_eq!(managed.wallet_id, Some(wallet_id)); + assert_eq!(manager.identity_index(&observed), Some(4)); + + // A host-placeholder slot 0 is corrected to the verified index. + let placeholder = Identifier::from([2u8; 32]); + manager + .add_identity(create_test_identity(placeholder), 0, wallet_id, &p) + .unwrap(); + manager + .adopt_into_wallet(&placeholder, wallet_id, 7) + .unwrap(); + let bucket = &manager.wallet_identities[&wallet_id]; + assert!(!bucket.contains_key(&0)); + assert_eq!(bucket[&7].identity.id(), placeholder); + assert_eq!(manager.identity_index(&placeholder), Some(7)); + // Already in place: a no-op success. + manager + .adopt_into_wallet(&placeholder, wallet_id, 7) + .unwrap(); + + // Never evict a different identity from the target slot, and persist + // nothing on the refusal. + let other = Identifier::from([3u8; 32]); + manager + .add_out_of_wallet_identity(create_test_identity(other), &p) + .unwrap(); + let stores_before = counter.stores.load(Ordering::SeqCst); + let refused = manager.place_verified_identity(create_test_identity(other), 7, wallet_id); + assert!( + matches!( + refused, + Err(PlatformWalletError::IdentityIndexOccupied { + identity_id, + identity_index: 7, + occupant, + }) if identity_id == other && occupant == placeholder + ), + "{refused:?}" + ); + assert_eq!(counter.stores.load(Ordering::SeqCst), stores_before); + assert_eq!(manager.identity_index(&other), None); + assert!(manager.identity(&other).unwrap().wallet_id.is_none()); + assert_eq!(manager.identity_index(&placeholder), Some(7)); + assert!(matches!( + manager.adopt_into_wallet(&Identifier::from([4u8; 32]), wallet_id, 9), + Err(PlatformWalletError::IdentityNotFound(_)) + )); + } + + /// An unknown identity verified at a slot that already holds a different + /// identity (a restored placeholder, say) must not overwrite it: the + /// occupant's state would be discarded while its reverse-index entry kept + /// resolving to the newcomer. Refused with the typed error, changing and + /// persisting nothing, through `add_identity` and the shared placement. + #[test] + fn an_unknown_identity_cannot_take_an_occupied_slot() { + use std::sync::atomic::Ordering; + let mut manager = IdentityManager::new(); + let wallet_id: WalletId = [9u8; 32]; + let counter = Arc::new(CountingPersistence::default()); + let p = WalletPersister::new(wallet_id, Arc::clone(&counter) as _); + + let occupant = Identifier::from([0xB0; 32]); + manager + .add_identity(create_test_identity(occupant), 0, wallet_id, &p) + .unwrap(); + let newcomer = Identifier::from([0xA0; 32]); + let stores_before = counter.stores.load(Ordering::SeqCst); + + for attempt in [ + manager.add_identity(create_test_identity(newcomer), 0, wallet_id, &p), + manager + .place_verified_identity(create_test_identity(newcomer), 0, wallet_id) + .map(|_| ()), + ] { + assert!( + matches!( + attempt, + Err(PlatformWalletError::IdentityIndexOccupied { + identity_id, + identity_index: 0, + occupant: held, + }) if identity_id == newcomer && held == occupant + ), + "{attempt:?}" + ); + } + + assert_eq!(counter.stores.load(Ordering::SeqCst), stores_before); + assert_eq!( + manager.identity(&occupant).map(|m| m.identity.id()), + Some(occupant) + ); + assert!(manager.identity(&newcomer).is_none()); + assert_eq!(manager.identity_index(&occupant), Some(0)); + let bucket = &manager.wallet_identities[&wallet_id]; + assert_eq!(bucket.len(), 1); + assert_eq!(bucket[&0].identity.id(), occupant); + // A free slot is still fine. + manager + .add_identity(create_test_identity(newcomer), 1, wallet_id, &p) + .unwrap(); + assert_eq!(manager.identity_index(&newcomer), Some(1)); + } + #[test] fn test_add_out_of_wallet_identity() { let mut manager = IdentityManager::new(); diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs index 05f321ec6ef..d63a9845254 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs @@ -12,3 +12,4 @@ pub use managed_identity::{BlockTime, DashPayState, ManagedIdentity, PrivateCont pub use manager::IdentityLocation; pub use manager::IdentityManager; pub use manager::RegistrationIndex; +pub(crate) use manager::VerifiedPlacement; diff --git a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs index 339520651d7..5443b88508a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs @@ -9,6 +9,6 @@ pub use contact_request::ContactRequest; pub use established_contact::EstablishedContact; pub use payment::{DashpayAddressMatch, PaymentDirection, PaymentEntry, PaymentStatus}; pub use profile::{ - calculate_avatar_hash, calculate_dhash_fingerprint, ContactProfileEntry, DashPayProfile, - ProfileUpdate, + calculate_avatar_hash, calculate_dhash_fingerprint, normalize_persisted_profile, + ContactProfileEntry, DashPayProfile, PaymentAddressUpdate, ProfileUpdate, ShieldedTipRecipient, }; diff --git a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs index ab661278f99..03cfdec8a1f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs @@ -37,6 +37,61 @@ pub struct DashPayProfile { pub avatar_fingerprint: Option<[u8; 8]>, /// Public message broadcast to contacts. pub public_message: Option, + /// Core P2PKH/P2SH storage address (type byte plus HASH160, 21 bytes). + /// The address defaults support map formats such as JSON. Positional + /// bincode records require the storage layer's versioned legacy decoder. + #[cfg_attr(feature = "serde", serde(default))] + pub core_payment_address: Option>, + /// Platform P2PKH/P2SH storage address (21 bytes). + #[cfg_attr(feature = "serde", serde(default))] + pub platform_payment_address: Option>, + /// Complete raw Orchard address (11-byte diversifier + 32-byte pk_d). + #[cfg_attr(feature = "serde", serde(default))] + pub shielded_address: Option>, +} + +/// Normalize profile data loaded from a host-owned persistence row. +/// +/// Persistence adapters only marshal the row into this model; acceptance of +/// payment-address bytes belongs to platform-wallet so restore policy cannot +/// drift between FFI, JNI, Swift, and native callers. +pub fn normalize_persisted_profile(mut profile: DashPayProfile) -> DashPayProfile { + profile.avatar_url = profile + .avatar_url + .filter(|url| !url.is_empty() && url.len() <= 2048 && url.starts_with("https://")); + profile.core_payment_address = profile + .core_payment_address + .filter(|address| valid_transparent_payment_address(address)); + profile.platform_payment_address = profile + .platform_payment_address + .filter(|address| valid_transparent_payment_address(address)); + profile.shielded_address = profile + .shielded_address + .and_then(|address| validated_shielded_address(&address).map(|address| address.to_vec())); + profile +} + +#[cfg(test)] +mod normalize_tests { + use super::*; + + #[test] + fn normalize_persisted_profile_drops_invalid_addresses() { + let profile = normalize_persisted_profile(DashPayProfile { + avatar_url: Some("http://example.com/avatar.png".to_string()), + core_payment_address: Some(vec![5; 21]), + platform_payment_address: Some(vec![1; 20]), + shielded_address: Some(vec![0xff; 43]), + display_name: Some("Alice".to_string()), + ..Default::default() + }); + + assert_eq!(profile.display_name.as_deref(), Some("Alice")); + assert_eq!(profile.avatar_url, None); + assert_eq!(profile.core_payment_address, None); + assert_eq!(profile.platform_payment_address, None); + assert_eq!(profile.shielded_address, None); + } } /// A cached **contact** profile, keyed by the contact's identity id on the @@ -79,6 +134,31 @@ pub struct ProfileUpdate { /// includes them in the document, then drops the bytes. /// `None` = no avatar / remove avatar. pub avatar_bytes: Option>, + pub core_payment_address: PaymentAddressUpdate, + pub platform_payment_address: PaymentAddressUpdate, + pub shielded_address: PaymentAddressUpdate, +} + +/// Explicit patch semantics: omission must never remove a published address. +pub use dash_sdk::platform::dashpay::PaymentAddressUpdate; + +/// Recipient shown at confirmation. Re-resolve before sending and compare both +/// fields so a changed DPNS owner or profile cannot silently redirect a tip. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ShieldedTipRecipient { + pub identity_id: dpp::prelude::Identifier, + pub address: [u8; 43], +} + +/// Validate public Orchard address metadata independently of spending support. +pub fn validated_shielded_address(bytes: &[u8]) -> Option<[u8; 43]> { + let raw: [u8; 43] = bytes.try_into().ok()?; + Option::::from(orchard::Address::from_raw_address_bytes(&raw)).map(|_| raw) +} + +/// Storage-form transparent address validation, matching the DashPay trigger. +pub fn valid_transparent_payment_address(bytes: &[u8]) -> bool { + bytes.len() == 21 && matches!(bytes.first(), Some(0x00 | 0x01)) } /// Compute SHA-256 hash of image bytes (DIP-15 `avatarHash` field). diff --git a/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs index c6623c5a8b2..a098e5f85fd 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs @@ -11,7 +11,8 @@ pub mod key_storage; pub use block_time::BlockTime; pub use dashpay::{ - ContactProfileEntry, ContactRequest, DashPayProfile, DashpayAddressMatch, EstablishedContact, - PaymentDirection, PaymentEntry, PaymentStatus, ProfileUpdate, + normalize_persisted_profile, ContactProfileEntry, ContactRequest, DashPayProfile, + DashpayAddressMatch, EstablishedContact, PaymentAddressUpdate, PaymentDirection, PaymentEntry, + PaymentStatus, ProfileUpdate, ShieldedTipRecipient, }; pub use key_storage::{DpnsFetch, DpnsNameInfo, IdentityStatus, KeyStorage, PrivateKeyData}; diff --git a/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs b/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs index c44e8f14a2c..74e12808593 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs @@ -1428,7 +1428,7 @@ mod tests { let (manager, wallet_id) = test_platform_wallet_manager().await; let wallet = manager.get_wallet(&wallet_id).await.expect("wallet handle"); let signer = - fund_test_platform_wallet(wallet.wallet_manager(), &wallet_id, 10_000_000).await; + fund_test_platform_wallet(&wallet.wallet_manager, &wallet_id, 10_000_000).await; let address = wallet .platform() .next_unused_receive_address(PlatformPaymentAccountKey { @@ -1477,7 +1477,7 @@ mod tests { let (manager, wallet_id) = test_platform_wallet_manager().await; let wallet = manager.get_wallet(&wallet_id).await.expect("wallet handle"); let signer = - fund_test_platform_wallet(wallet.wallet_manager(), &wallet_id, 10_000_000).await; + fund_test_platform_wallet(&wallet.wallet_manager, &wallet_id, 10_000_000).await; let address = wallet .platform() .next_unused_receive_address(PlatformPaymentAccountKey { diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 8a7edc96b0b..9f3263167b7 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -38,9 +38,14 @@ use crate::changeset::{ ClientStartState, PersistenceError, PlatformWalletChangeSet, PlatformWalletPersistence, }; use crate::error::PlatformWalletError; +#[cfg(feature = "shielded")] +use crate::validated_shielded_address; +use crate::{DashPayProfile, PaymentAddressUpdate, ProfileUpdate}; use dash_sdk::platform::transition::put_settings::PutSettings; use dpp::address_funds::PlatformAddress; use dpp::fee::Credits; +#[cfg(feature = "shielded")] +use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey}; use dpp::prelude::Identifier; @@ -55,6 +60,7 @@ use { super::shielded::store::{ PendingRedrive, PrivateContactPayment, PrivatePaymentEntry, PrivatePaymentRecord, }, + super::shielded::tips::PreparedTipAccount, super::shielded::{ FileBackedShieldedStore, NetworkShieldedCoordinator, OrchardKeySet, ShieldedStore, }, @@ -384,6 +390,7 @@ pub struct PlatformWallet { wallet_id: WalletId, pub(crate) sdk: Arc, pub(crate) wallet_manager: Arc>>, + wallet_manager_reader: WalletManagerReader, // Sub-wallets that hold a broadcaster are monomorphized with // `SpvBroadcaster` — the only production broadcaster in use. // Swapping this out to another broadcaster is a three-line flip @@ -434,6 +441,23 @@ pub struct PlatformWallet { /// wallet handles share the one lock. #[cfg(feature = "shielded")] pub(crate) shield_guard: Arc>, + /// Serializes changes to the bound shielded account set. A bind + /// replaces the registration with the accounts it was given, so a + /// caller that reads the current set and binds an augmented copy (tip + /// preparation) must not interleave with another bind, or the other + /// bind's ordinary accounts are dropped and their live state purged. + /// Taken at the top of every bind entry point and by + /// `shielded_add_account`, before `shield_guard`. + #[cfg(feature = "shielded")] + pub(crate) shielded_config_lock: Arc>, + /// The tip account each identity's address was last prepared for in + /// this session, after its slot was proved with the seed. Publication + /// of a wallet tip address requires it, so an address is published only + /// for the identity and slot it was prepared for, and invalidated by a + /// coordinator Clear. `Arc` so cloned wallet handles share it. + #[cfg(feature = "shielded")] + pub(crate) prepared_tip_accounts: + Arc>>, /// Set once this wallet has been removed from the manager, to stop /// a handle that outlives the removal from binding shielded state /// back onto the coordinator. Callers resolve an @@ -453,6 +477,12 @@ pub struct PlatformWallet { /// handles share them. #[cfg(feature = "shielded")] private_payment_restores: Arc>, + /// The manager-owned network coordinator slot. Wallet operations resolve + /// the configured coordinator through this slot so callers cannot pair a + /// wallet with a different same-network coordinator. + #[cfg(feature = "shielded")] + pub(crate) shielded_coordinator: + Option>>>>, } impl PlatformWallet { @@ -505,9 +535,9 @@ impl PlatformWallet { Arc::clone(&self.sdk) } - /// Get a reference to the shared wallet manager lock. - pub fn wallet_manager(&self) -> &Arc>> { - &self.wallet_manager + /// Read the shared wallet manager. Mutations use [`Self::state_mut`]. + pub fn wallet_manager(&self) -> &WalletManagerReader { + &self.wallet_manager_reader } /// Get the lock-free balance for UI reads. @@ -542,11 +572,18 @@ impl PlatformWallet { /// Write-lock the wallet manager and return a guard that derefs to this /// wallet's `PlatformWalletInfo` (with `DerefMut`). - pub async fn state_mut(&self) -> WalletStateWriteGuard<'_> { - WalletStateWriteGuard { - guard: self.wallet_manager.write().await, + /// Holds the identity-placement write lock first, so replacing the manager + /// or removing/re-adding an identity cannot race a tip operation. + /// Returns `WalletNotFound` if this handle's generation is no longer current. + pub async fn state_mut(&self) -> Result, PlatformWalletError> { + let placement = self.identity.identity_placement.write().await; + let mut guard = self.wallet_manager.write().await; + self.identity.current_wallet_info_mut(&mut guard)?; + Ok(WalletStateWriteGuard { + guard, wallet_id: self.wallet_id, - } + _placement: placement, + }) } /// Blocking read-lock. @@ -559,15 +596,21 @@ impl PlatformWallet { /// Blocking write-lock. /// + /// Holds identity placement before wallet state, like [`Self::state_mut`]. /// Uses `tokio::sync::RwLock::blocking_write` — must NOT be /// called from within a tokio async context. Exists so sync /// callers (e.g. SPV-driven transaction processing) can reach /// mutation methods that require the wallet-manager write lock. - pub fn state_mut_blocking(&self) -> WalletStateWriteGuard<'_> { - WalletStateWriteGuard { - guard: self.wallet_manager.blocking_write(), + /// Returns `WalletNotFound` if this handle's generation is no longer current. + pub fn state_mut_blocking(&self) -> Result, PlatformWalletError> { + let placement = self.identity.identity_placement.blocking_write(); + let mut guard = self.wallet_manager.blocking_write(); + self.identity.current_wallet_info_mut(&mut guard)?; + Ok(WalletStateWriteGuard { + guard, wallet_id: self.wallet_id, - } + _placement: placement, + }) } // ----------------------------------------------------------------- @@ -724,16 +767,18 @@ impl PlatformWallet { } /// Non-blocking write-lock. Returns `None` if the lock is currently - /// held by any reader or writer. Same safety properties as + /// held by any reader or writer, identity placement is in use, or this handle's + /// generation is no longer current. Same safety properties as /// [`try_state`]: never panics, never blocks. pub fn try_state_mut(&self) -> Option> { - self.wallet_manager - .try_write() - .ok() - .map(|guard| WalletStateWriteGuard { - guard, - wallet_id: self.wallet_id, - }) + let placement = self.identity.identity_placement.try_write().ok()?; + let mut guard = self.wallet_manager.try_write().ok()?; + self.identity.current_wallet_info_mut(&mut guard).ok()?; + Some(WalletStateWriteGuard { + guard, + wallet_id: self.wallet_id, + _placement: placement, + }) } /// Construct a PlatformWallet from a WalletManager that already contains @@ -752,6 +797,36 @@ impl PlatformWallet { broadcaster: Arc, sync_fault: Arc, durable_cursors: crate::changeset::DurableCursors, + ) -> Self { + Self::new_with_coordinator_slot( + sdk, + wallet_id, + wallet_manager, + generation, + lock_notify, + persister, + broadcaster, + sync_fault, + durable_cursors, + #[cfg(feature = "shielded")] + None, + ) + } + + #[allow(clippy::too_many_arguments)] + pub(crate) fn new_with_coordinator_slot( + sdk: Arc, + wallet_id: WalletId, + wallet_manager: Arc>>, + generation: Arc, + lock_notify: Arc, + persister: Arc, + broadcaster: Arc, + sync_fault: Arc, + durable_cursors: crate::changeset::DurableCursors, + #[cfg(feature = "shielded")] shielded_coordinator: Option< + Arc>>>, + >, ) -> Self { // Build the per-wallet persister handle once and share it with // the sub-wallets that need to queue their own changesets @@ -809,6 +884,7 @@ impl PlatformWallet { document_erase_gate: Default::default(), dpns_operation_gate: Arc::new(tokio::sync::Mutex::new(())), dpns_sync_progress: Arc::new(std::sync::Mutex::new(BTreeMap::new())), + identity_placement: Arc::new(tokio::sync::RwLock::new(())), }; let platform = PlatformAddressWallet::new( @@ -822,6 +898,7 @@ impl PlatformWallet { Self { wallet_id, sdk, + wallet_manager_reader: WalletManagerReader::new(Arc::clone(&wallet_manager)), wallet_manager, core, identity, @@ -834,10 +911,45 @@ impl PlatformWallet { #[cfg(feature = "shielded")] shield_guard: Arc::new(tokio::sync::Mutex::new(())), #[cfg(feature = "shielded")] + shielded_config_lock: Arc::new(tokio::sync::Mutex::new(())), + #[cfg(feature = "shielded")] + prepared_tip_accounts: Arc::new(std::sync::Mutex::new(BTreeMap::new())), + #[cfg(feature = "shielded")] shielded_detached: Arc::new(std::sync::atomic::AtomicBool::new(false)), #[cfg(feature = "shielded")] private_payment_restores: Arc::default(), + #[cfg(feature = "shielded")] + shielded_coordinator, + } + } + + #[cfg(feature = "shielded")] + pub(crate) async fn resolve_shielded_coordinator( + &self, + supplied: &Arc, + ) -> Result, PlatformWalletError> { + if supplied.network() != self.network() { + return Err(PlatformWalletError::InvalidParameter(format!( + "the shielded coordinator is for {:?}, this wallet for {:?}", + supplied.network(), + self.network(), + ))); + } + if let Some(slot) = &self.shielded_coordinator { + let configured = slot.read().await.clone().ok_or_else(|| { + PlatformWalletError::ShieldedStoreError( + "shielded support is not configured on this wallet manager".to_string(), + ) + })?; + if !Arc::ptr_eq(&configured, supplied) { + return Err(PlatformWalletError::InvalidParameter( + "the supplied shielded coordinator is not owned by this wallet manager" + .to_string(), + )); + } + return Ok(configured); } + Ok(Arc::clone(supplied)) } /// Bind a shielded (Orchard) sub-wallet to this `PlatformWallet`. @@ -872,6 +984,24 @@ impl PlatformWallet { seed: &[u8], accounts: &[u32], coordinator: &Arc, + ) -> Result<(), PlatformWalletError> { + let coordinator = self.resolve_shielded_coordinator(coordinator).await?; + // Fence generation teardown across attachment validation, host + // viewing-key persistence, and coordinator/handle installation. + let _lifecycle = self.core().generation_payment_guard().await; + let _config = self.shielded_config_lock.lock().await; + self.bind_shielded_locked_unfenced(seed, accounts, &coordinator) + .await + } + + /// [`Self::bind_shielded`] for a caller already holding + /// `shielded_config_lock` and the generation lifecycle guard. + #[cfg(feature = "shielded")] + pub(crate) async fn bind_shielded_locked_unfenced( + &self, + seed: &[u8], + accounts: &[u32], + coordinator: &Arc, ) -> Result<(), PlatformWalletError> { use super::shielded::{AccountViewingKeys, OrchardKeySet, SubwalletId}; let required = crate::changeset::PersistenceCapabilities::SHIELDED_FVK_RESTART; @@ -898,12 +1028,29 @@ impl PlatformWallet { // snapshot predates a Clear. let snapshot_generation = coordinator.clear_generation(); let network = self.sdk.network; + let mut accounts: std::collections::BTreeSet = accounts.iter().copied().collect(); + accounts.extend(self.discovered_tip_accounts().await?); + // Keep retired tip accounts scanning, including identities removed from + // the local manager after their address was published. + let start = self + .persister + .load() + .map_err(|e| PlatformWalletError::Persistence(e.to_string()))?; + accounts.extend( + start + .shielded + .viewing_keys + .keys() + .filter(|id| { + id.wallet_id == self.wallet_id + && super::shielded::is_shielded_identity_account(id.account_index) + }) + .map(|id| id.account_index), + ); let mut account_views: std::collections::BTreeMap = std::collections::BTreeMap::new(); - for &account in accounts { - // `accounts` may contain duplicates; the BTreeMap - // dedups by definition. The full keyset (with its - // `SpendAuthorizingKey`) is dropped at the end of + for &account in &accounts { + // The full keyset (with its `SpendAuthorizingKey`) is dropped at the end of // this iteration — only the viewing half survives. let ks = OrchardKeySet::from_seed(seed, network, account)?; account_views.insert(account, ks.viewing_keys()); @@ -921,11 +1068,6 @@ impl PlatformWallet { // treat it like the malformed-row case below: surface it rather // than silently mixing two keys' state. The recovery is a // shielded Clear, which drops both sides at once. - let start = self.persister.load().map_err(|e| { - PlatformWalletError::ShieldedBuildError(format!( - "persister load failed while binding shielded viewing keys: {e}" - )) - })?; for (account, views) in &account_views { let id = SubwalletId::new(self.wallet_id, *account); if let Some(persisted) = start.shielded.viewing_keys.get(&id) { @@ -990,6 +1132,11 @@ impl PlatformWallet { coordinator: &Arc, ) -> Result { use super::shielded::{AccountViewingKeys, SubwalletId}; + let coordinator = self.resolve_shielded_coordinator(coordinator).await?; + // Keep the generation alive from attachment validation through the + // persisted snapshot read and coordinator/handle installation. + let _lifecycle = self.core().generation_payment_guard().await; + let _config = self.shielded_config_lock.lock().await; let required = crate::changeset::PersistenceCapabilities::SHIELDED_FVK_RESTART; let capabilities = self.persister.persistence_capabilities(); if !capabilities.contains(required) { @@ -1015,9 +1162,25 @@ impl PlatformWallet { "persister load failed while rebinding shielded viewing keys: {e}" )) })?; + let mut accounts: std::collections::BTreeSet = accounts.iter().copied().collect(); + // Newly discovered identities require their tip accounts too. Missing + // FVKs must trigger seed-backed binding: skipping them would report a + // successful restart while silently omitting recoverable tip history. + accounts.extend(self.discovered_tip_accounts().await?); + accounts.extend( + start + .shielded + .viewing_keys + .keys() + .filter(|id| { + id.wallet_id == self.wallet_id + && super::shielded::is_shielded_identity_account(id.account_index) + }) + .map(|id| id.account_index), + ); let mut account_views: std::collections::BTreeMap = std::collections::BTreeMap::new(); - for &account in accounts { + for &account in &accounts { let id = SubwalletId::new(self.wallet_id, account); let Some(fvk_bytes) = start.shielded.viewing_keys.get(&id) else { return Ok(false); @@ -1032,7 +1195,7 @@ impl PlatformWallet { } // Hand the already-loaded snapshot to the install step so the // restore doesn't pay a second full persister load. - self.install_shielded_views(account_views, coordinator, start, snapshot_generation) + self.install_shielded_views(account_views, &coordinator, start, snapshot_generation) .await?; Ok(true) } @@ -1288,6 +1451,12 @@ impl PlatformWallet { missing.bits(), ))); } + // Serialized with the binds: tip preparation rebinds a snapshot of + // the account set, which would drop an account inserted mid-way. + // The lifecycle gate spans attachment validation through host + // persistence and the final handle mutation. + let _lifecycle = self.core().generation_payment_guard().await; + let _config = self.shielded_config_lock.lock().await; self.ensure_shielded_attached()?; // Everything that calls into the host — the snapshot read below // and the viewing-key write further down — stays OUTSIDE the key @@ -2215,8 +2384,9 @@ impl PlatformWallet { /// local `IdentityManager`; on a successful broadcast the proof-verified identity is registered /// there (mirroring `register_from_addresses`) so the host persister emits the /// `IdentityChangeSet` / `IdentityKeysChangeSet` that creates the app's identity row. A failed - /// registration after a successful broadcast is logged and swallowed — the identity already - /// exists on chain, so the next sync heals the local row. Returns the new identity's id. + /// registration after a successful broadcast returns + /// [`PlatformWalletError::IdentityCreatedButNotRegistered`], carrying the created identity's + /// id. Creation must not be re-submitted in that case. #[cfg(feature = "shielded")] #[allow(clippy::too_many_arguments)] pub async fn shielded_identity_create_from_pool( @@ -2238,6 +2408,23 @@ impl PlatformWallet { P: dpp::shielded::builder::OrchardProver, IS: dpp::identity::signer::Signer + Send + Sync, { + { + let wm = self.wallet_manager.read().await; + let info = wm + .get_wallet_info(&self.wallet_id) + .ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id)))?; + if let Some(occupant) = info + .identity_manager + .wallet_identities + .get(&self.wallet_id) + .and_then(|identities| identities.get(&identity_index)) + { + return Err(PlatformWalletError::InvalidIdentityData(format!( + "Cannot create an identity at index {identity_index}: the slot holds identity {}", + occupant.identity.id() + ))); + } + } let (identity_id, identity) = { // Scope the transient keyset so its spend authority is dropped before we take the // wallet-manager write lock below — it's only needed for the spend, not for the @@ -2262,36 +2449,22 @@ impl PlatformWallet { // Register the proof-verified identity in the local manager at its HD slot, exactly like // `register_from_addresses`' Step 3 — this drives the host persister's // `IdentityChangeSet` / `IdentityKeysChangeSet` emit so the app's identity row is created. - // The broadcast already succeeded; a registration failure here (e.g. the slot is already - // occupied locally) is logged and swallowed rather than surfaced as an error, since the - // identity exists on chain and the next sync heals the local view. { let mut wm = self.wallet_manager.write().await; - match wm.get_wallet_info_mut(&self.wallet_id) { - Some(info) => { - if let Err(e) = info.identity_manager.add_identity( - identity, - identity_index, - self.wallet_id, - &self.persister, - ) { - tracing::warn!( - identity_index, - error = %e, - "IdentityCreateFromShieldedPool broadcast succeeded but registering the \ - identity in the local manager failed; the on-chain identity exists and \ - the next sync will heal the local row" - ); - } + let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { + PlatformWalletError::IdentityCreatedButNotRegistered { + identity_id, + reason: "wallet was removed from the manager".to_string(), } - None => { - tracing::warn!( - identity_index, - "IdentityCreateFromShieldedPool broadcast succeeded but the wallet info was \ - not found in the manager; skipping local registration (heals on next sync)" - ); - } - } + })?; + info.identity_manager + .add_identity(identity, identity_index, self.wallet_id, &self.persister) + .map_err( + |error| PlatformWalletError::IdentityCreatedButNotRegistered { + identity_id, + reason: error.to_string(), + }, + )?; } Ok(identity_id) @@ -2810,8 +2983,8 @@ impl PlatformWallet { /// `Wallet::add_account`. /// /// Returns [`ApplyError::WalletNotFound`](crate::wallet::ApplyError::WalletNotFound) - /// if the wallet has been removed from the manager between handle - /// acquisition and this call. + /// if this handle's wallet has been removed or replaced in the manager + /// between handle acquisition and this call. /// /// Consumes the changeset by value — `apply_changeset` drains /// every map straight into the wallet maps with no clones. @@ -2832,10 +3005,18 @@ impl PlatformWallet { }); { + // An identity entry can move an identity to another slot. + // Placement lock first; see `identity_placement`. + let _placement = if changeset.identities.is_some() { + Some(self.identity.identity_placement.write().await) + } else { + None + }; let mut wm = self.wallet_manager.write().await; - let (wallet, info) = wm - .get_wallet_mut_and_info_mut(&self.wallet_id) - .ok_or(crate::wallet::ApplyError::WalletNotFound(self.wallet_id))?; + let (wallet, info) = self + .identity + .current_wallet_and_info_mut(&mut wm) + .map_err(|_| crate::wallet::ApplyError::WalletNotFound(self.wallet_id))?; info.apply_changeset(wallet, changeset)?; } @@ -2895,6 +3076,7 @@ impl Clone for PlatformWallet { wallet_id: self.wallet_id, sdk: self.sdk.clone(), wallet_manager: self.wallet_manager.clone(), + wallet_manager_reader: self.wallet_manager_reader.clone(), core: self.core.clone(), identity: self.identity.clone(), platform: self.platform.clone(), @@ -2906,9 +3088,85 @@ impl Clone for PlatformWallet { #[cfg(feature = "shielded")] shield_guard: self.shield_guard.clone(), #[cfg(feature = "shielded")] + shielded_config_lock: self.shielded_config_lock.clone(), + #[cfg(feature = "shielded")] + prepared_tip_accounts: self.prepared_tip_accounts.clone(), + #[cfg(feature = "shielded")] shielded_detached: self.shielded_detached.clone(), #[cfg(feature = "shielded")] private_payment_restores: self.private_payment_restores.clone(), + #[cfg(feature = "shielded")] + shielded_coordinator: self.shielded_coordinator.clone(), + } + } +} + +impl PlatformWallet { + /// Create (`create`) or update `identity_id`'s DashPay profile. A + /// shielded address that is one of this wallet's dedicated tip addresses + /// must have been prepared for this identity at the slot it holds, and + /// the placement lock is held through a write that sets one, so the slot + /// cannot change before it lands. Wallet removal waits for the complete + /// write; removed or replaced wallet handles cannot publish. + pub async fn write_dashpay_profile( + &self, + identity_id: &Identifier, + input: ProfileUpdate, + signer: &S, + create: bool, + ) -> Result + where + S: Signer + Send + Sync, + { + let _lifecycle = self.core().generation_payment_guard().await; + if !self.core().is_current_generation().await { + return Err(PlatformWalletError::WalletNotFound(hex::encode( + self.wallet_id(), + ))); + } + let sets_shielded = matches!(input.shielded_address, PaymentAddressUpdate::Set(_)); + #[cfg(not(feature = "shielded"))] + if sets_shielded { + return Err(PlatformWalletError::InvalidIdentityData( + "Shielded address publication requires shielded support".to_string(), + )); + } + #[cfg(feature = "shielded")] + let prepared_coordinator = if sets_shielded { + self.prepared_tip_accounts + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(identity_id) + .and_then(PreparedTipAccount::coordinator) + } else { + None + }; + #[cfg(feature = "shielded")] + let _coordinator_operation = match prepared_coordinator.as_ref() { + Some(coordinator) => Some(coordinator.operation_guard().await), + None => None, + }; + let _placement = if sets_shielded { + Some(self.identity.identity_placement.read().await) + } else { + None + }; + #[cfg(feature = "shielded")] + if let PaymentAddressUpdate::Set(bytes) = &input.shielded_address { + if let Some(address) = validated_shielded_address(bytes) { + self.check_tip_address_publication(identity_id, &address) + .await?; + } + } + let dashpay = self.identity.dashpay(); + if create { + dashpay + .create_profile_with_external_signer(identity_id, input, signer) + .await + } else { + dashpay + .update_profile_with_external_signer(identity_id, input, signer) + .await } } } @@ -2925,6 +3183,40 @@ impl std::fmt::Debug for PlatformWallet { // Wallet state guard types — lock WalletManager, deref to PlatformWalletInfo // --------------------------------------------------------------------------- +/// Shared read access without exposing an unlocked identity-placement mutation path. +/// Use [`PlatformWallet::state_mut`] to change a live wallet's state. +/// +/// ```compile_fail +/// async fn bypass(reader: &platform_wallet::wallet::platform_wallet::WalletManagerReader) { +/// reader.write().await; +/// } +/// ``` +#[derive(Clone)] +pub struct WalletManagerReader { + inner: Arc>>, +} + +impl WalletManagerReader { + pub(crate) fn new(inner: Arc>>) -> Self { + Self { inner } + } + + pub async fn read(&self) -> RwLockReadGuard<'_, WalletManager> { + self.inner.read().await + } + + pub fn blocking_read(&self) -> RwLockReadGuard<'_, WalletManager> { + self.inner.blocking_read() + } + + pub fn try_read( + &self, + ) -> Result>, tokio::sync::TryLockError> + { + self.inner.try_read() + } +} + /// Read guard that locks `WalletManager` and derefs to this wallet's /// `PlatformWalletInfo`. Also provides `.wallet()` for key material access. pub struct WalletStateReadGuard<'a> { @@ -2955,6 +3247,7 @@ impl Deref for WalletStateReadGuard<'_> { pub struct WalletStateWriteGuard<'a> { guard: RwLockWriteGuard<'a, WalletManager>, wallet_id: WalletId, + _placement: RwLockWriteGuard<'a, ()>, } impl<'a> WalletStateWriteGuard<'a> { @@ -3507,6 +3800,127 @@ fn check_recipient_hrp( Ok(()) } +#[cfg(test)] +mod state_generation_tests { + use super::*; + use crate::events::{EventHandler, PlatformEventHandler}; + use crate::wallet::persister::NoPlatformPersistence; + use crate::PlatformWalletManager; + use dashcore::Network; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + + struct NoopEvents; + impl EventHandler for NoopEvents {} + impl PlatformEventHandler for NoopEvents {} + + #[cfg(not(feature = "shielded"))] + #[tokio::test] + async fn should_reject_shielded_profile_addresses_without_shielded_support() { + let manager = PlatformWalletManager::new( + Arc::new(dash_sdk::Sdk::new_mock()), + Arc::new(NoPlatformPersistence), + Arc::new(NoopEvents), + ); + let wallet = manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + let signer = simple_signer::signer::SimpleSigner::default(); + let result = wallet + .write_dashpay_profile( + &Identifier::from([7; 32]), + ProfileUpdate { + shielded_address: PaymentAddressUpdate::Set(vec![0; 43]), + ..Default::default() + }, + &signer, + false, + ) + .await; + assert!(matches!( + result, + Err(PlatformWalletError::InvalidIdentityData(message)) + if message.contains("requires shielded support") + )); + } + + #[tokio::test] + async fn should_reject_mutations_from_a_removed_wallet_generation() { + async fn assert_profile_write_refused(wallet: &PlatformWallet) { + let signer = simple_signer::signer::SimpleSigner::default(); + for create in [true, false] { + assert!(matches!( + wallet + .write_dashpay_profile( + &Identifier::default(), + ProfileUpdate::default(), + &signer, + create, + ) + .await, + Err(PlatformWalletError::WalletNotFound(_)) + )); + } + } + + let manager = PlatformWalletManager::new( + Arc::new(dash_sdk::Sdk::new_mock()), + Arc::new(NoPlatformPersistence), + Arc::new(NoopEvents), + ); + let old = manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + let id = old.wallet_id(); + manager.remove_wallet(&id).await.unwrap(); + assert_profile_write_refused(&old).await; + assert!(matches!( + old.state_mut().await, + Err(PlatformWalletError::WalletNotFound(_)) + )); + let current = manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + assert_eq!(current.wallet_id(), id); + assert_profile_write_refused(&old).await; + assert!(matches!( + old.state_mut().await, + Err(PlatformWalletError::WalletNotFound(_)) + )); + assert!(old.try_state_mut().is_none()); + let blocking_old = Arc::clone(&old); + assert!(tokio::task::spawn_blocking(move || matches!( + blocking_old.state_mut_blocking(), + Err(PlatformWalletError::WalletNotFound(_)) + )) + .await + .unwrap()); + assert!( + matches!(old.apply(PlatformWalletChangeSet::default()).await, + Err(crate::wallet::ApplyError::WalletNotFound(wallet_id)) if wallet_id == id) + ); + assert!(current.state_mut().await.is_ok()); + assert!(current.try_state_mut().is_some()); + } +} + #[cfg(all(test, feature = "shielded"))] mod private_contact_request_redrive_tests { use super::*; diff --git a/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs b/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs index e224586420b..69386a16905 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs @@ -251,6 +251,11 @@ pub struct NetworkShieldedCoordinator { /// other way round. lifecycle: tokio::sync::Mutex<()>, + /// Clear waits for operations that bind/flush viewing keys or spend from + /// extracted notes. Separate from `lifecycle`, which bind takes internally. + /// Lock order: `operation_admission` → `lifecycle` → `store`. + operation_admission: RwLock<()>, + /// Wallets whose per-subwallet store state has been successfully /// hydrated from the host's persisted snapshot this session /// (`restore_for_wallet` completed without error after the @@ -420,6 +425,7 @@ impl NetworkShieldedCoordinator { progress_handler: std::sync::Mutex::new(None), tree_progress_handler: std::sync::Mutex::new(None), lifecycle: tokio::sync::Mutex::new(()), + operation_admission: RwLock::new(()), hydrated: RwLock::new(std::collections::BTreeSet::new()), clear_generation: std::sync::atomic::AtomicU64::new(0), } @@ -679,6 +685,12 @@ impl NetworkShieldedCoordinator { } } + /// Acquire before wallet placement/configuration locks; retain through persistence + /// and the operation result so Clear cannot delete state while it is still in use. + pub(crate) async fn operation_guard(&self) -> tokio::sync::RwLockReadGuard<'_, ()> { + self.operation_admission.read().await + } + /// [`register_wallet`](Self::register_wallet)'s body, with the /// lifecycle mutex already held by the caller's transaction. async fn register_locked( @@ -1222,6 +1234,7 @@ impl NetworkShieldedCoordinator { /// stays populated, and the next cold resync would gate-skip every /// re-downloaded position against the stale `tree_size`. pub async fn clear(&self) -> Result<(), crate::error::PlatformWalletError> { + let _operations = self.operation_admission.write().await; // Held across the whole Clear, store reset included, so no bind // install can be halfway through its transaction here: one that // already registered would otherwise restore its pre-Clear diff --git a/packages/rs-platform-wallet/src/wallet/shielded/mod.rs b/packages/rs-platform-wallet/src/wallet/shielded/mod.rs index a535e52fff4..9f4f49c2de0 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/mod.rs @@ -52,6 +52,11 @@ pub mod prover; pub mod seed_pool; pub mod store; pub mod sync; +pub mod tips; +pub use tips::{ + is_shielded_identity_account, shielded_identity_account_index, ShieldedTipSource, + SHIELDED_IDENTITY_ACCOUNT_BASE, +}; #[cfg(test)] mod viewing_key_bind_tests; #[cfg(test)] diff --git a/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs index 6cdb39536f8..e1fdd622497 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs @@ -281,3 +281,33 @@ fn shield_memo_round_trips_through_ovk_recovery() { "the OVK-recovered memo must decode back to the original text" ); } + +#[test] +fn should_restore_tip_notes_without_exposing_personal_notes_to_tip_viewing_key() { + use crate::wallet::shielded::shielded_identity_account_index; + let seed = [0x67; 64]; + let tip_index = shielded_identity_account_index(0).unwrap(); + let tips = OrchardKeySet::from_seed(&seed, Network::Testnet, tip_index).unwrap(); + let restored = OrchardKeySet::from_seed(&seed, Network::Testnet, tip_index).unwrap(); + let personal = OrchardKeySet::from_seed(&seed, Network::Testnet, 0).unwrap(); + // Rotation is just another address of the dedicated account. Both remain + // discoverable without a saved diversifier index or a current profile. + for recipient in [tips.default_address, tips.address_at(17)] { + let wire = make_own_ovk_wire_note( + recipient, + tips.outgoing_viewing_key.clone(), + 123_456, + [0; 36], + ); + assert!(try_decrypt_note_with_memo(&restored.prepared_ivk(), &wire).is_some()); + assert!(try_decrypt_note_with_memo(&personal.prepared_ivk(), &wire).is_none()); + } + let personal_wire = make_own_ovk_wire_note( + personal.default_address, + personal.outgoing_viewing_key.clone(), + 456_789, + [0; 36], + ); + assert!(try_decrypt_note_with_memo(&tips.prepared_ivk(), &personal_wire).is_none()); + assert!(try_recover_outgoing_note(&tips.outgoing_viewing_key, &personal_wire).is_none()); +} diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs new file mode 100644 index 00000000000..2a4a1a54f18 --- /dev/null +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -0,0 +1,524 @@ +//! Dedicated DashPay identity shielded accounts. Account selection is wallet policy, not +//! consensus: external Orchard addresses remain valid profile values. +//! +//! Reserve the upper half of the ZIP-32 account space for identities. A wallet-owned +//! identity at index i uses account 0x40000000 + i. Ordinary accounts use the +//! lower half. This mapping never depends on a username, the current profile, +//! or local allocation history: identity discovery followed by shielded bind +//! reconstructs it even after publication was removed. Address rotation uses +//! another diversifier in the same account, so all old addresses remain covered. + +use super::NetworkShieldedCoordinator; +use crate::wallet::platform_wallet::PlatformWallet; +use crate::{PlatformWalletError, ShieldedTipRecipient}; +use dpp::identity::accessors::IdentityGettersV0; +use dpp::prelude::Identifier; +use grovedb_commitment_tree::PaymentAddress; +use orchard::keys::Scope; +use std::sync::{Arc, PoisonError, Weak}; + +pub(crate) struct PreparedTipAccount { + account: u32, + coordinator: Weak, + clear_generation: u64, +} + +impl PreparedTipAccount { + pub(crate) fn coordinator(&self) -> Option> { + self.coordinator.upgrade() + } +} + +pub const SHIELDED_IDENTITY_ACCOUNT_BASE: u32 = 0x4000_0000; + +pub fn shielded_identity_account_index(identity_index: u32) -> Result { + if identity_index >= SHIELDED_IDENTITY_ACCOUNT_BASE { + return Err(PlatformWalletError::ShieldedKeyDerivation( + "Identity index exceeds the identity shielded account range".to_string(), + )); + } + Ok(SHIELDED_IDENTITY_ACCOUNT_BASE + identity_index) +} + +pub fn is_shielded_identity_account(account: u32) -> bool { + (SHIELDED_IDENTITY_ACCOUNT_BASE..0x8000_0000).contains(&account) +} + +/// The account a tip is paid from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ShieldedTipSource { + /// The identity's dedicated tip account, at the slot the seed proves the + /// identity holds when the notes are selected. + Identity(Identifier), + /// An explicit account: an ordinary account, or the tip account of a slot + /// that holds no identity (a retired identity's funds). A slot that holds + /// an identity is spent through [`Self::Identity`] instead. + Account(u32), +} + +/// Prove `identity_index` with the seed: the identity must carry the MASTER +/// authentication key this wallet derives at that index (the key discovery and +/// registration both use). Fails closed when no key matches, including when +/// no public keys were restored. +fn verify_identity_index( + seed: &[u8], + network: key_wallet::Network, + identity_index: u32, + identity: &dpp::identity::Identity, +) -> Result<(), PlatformWalletError> { + use crate::wallet::identity::network::{ + derive_identity_auth_key_hash_from_master, MASTER_KEY_INDEX, + }; + use dpp::identity::identity_public_key::methods::hash::IdentityPublicKeyHashMethodsV0; + + let master = key_wallet::bip32::ExtendedPrivKey::new_master(network, seed) + .map_err(|e| PlatformWalletError::ShieldedKeyDerivation(e.to_string()))?; + let expected = derive_identity_auth_key_hash_from_master( + &master, + network, + identity_index, + MASTER_KEY_INDEX, + )?; + let verified = identity + .public_keys() + .values() + .any(|key| key.public_key_hash().ok() == Some(expected)); + if verified { + Ok(()) + } else { + Err(PlatformWalletError::InvalidIdentityData(format!( + "Identity index {identity_index} is not verified for this wallet; \ + rediscover the identity before using its tip account" + ))) + } +} + +impl PlatformWallet { + pub(crate) async fn discovered_tip_accounts(&self) -> Result, PlatformWalletError> { + let wm = self.wallet_manager.read().await; + let info = wm + .get_wallet_info(&self.wallet_id()) + .ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id())))?; + // An identity outside this convention can still use ordinary accounts + // or publish an external address; it must not block wallet-wide sync. + Ok(info + .identity_manager + .managed_identities() + .filter(|identity| identity.wallet_id == Some(self.wallet_id())) + .filter_map(|identity| identity.identity_index) + .filter_map(|index| shielded_identity_account_index(index).ok()) + .collect()) + } + + /// Prepare a dedicated receiving account without publishing anything. Full + /// bind persists its viewing key and registers it with the coordinator before + /// callers can publish the returned address. Repeated calls are idempotent. + /// Requires an existing shielded bind so preparing a tip account cannot + /// silently replace the host's ordinary account configuration. + pub async fn prepare_shielded_identity_address( + &self, + seed: &[u8], + identity_id: &Identifier, + coordinator: &Arc, + ) -> Result<[u8; 43], PlatformWalletError> { + let coordinator = self.resolve_shielded_coordinator(coordinator).await?; + // Do not publish a key from a mis-associated mnemonic. A first bind + // has no persisted FVK against which to detect a wrong seed. + let root = key_wallet::wallet::root_extended_keys::RootExtendedPrivKey::new_master(seed) + .map_err(|e| PlatformWalletError::ShieldedKeyDerivation(e.to_string()))?; + let public = root.to_root_extended_pub_key(); + drop(root); + let scoped_id = key_wallet::Wallet::compute_wallet_id_from_root_extended_pub_key( + &public, + Some(self.sdk.network), + ); + let legacy_id = + key_wallet::Wallet::compute_wallet_id_from_root_extended_pub_key(&public, None); + if self.wallet_id() != scoped_id && self.wallet_id() != legacy_id { + return Err(PlatformWalletError::ShieldedKeyDerivation( + "The supplied seed does not belong to this wallet".to_string(), + )); + } + let _lifecycle = self.core().generation_payment_guard().await; + if !self.core().is_current_generation().await { + return Err(PlatformWalletError::WalletNotFound(hex::encode( + self.wallet_id(), + ))); + } + let clear_generation = coordinator.clear_generation(); + let _operation = coordinator.operation_guard().await; + if coordinator.clear_generation() != clear_generation { + return Err(PlatformWalletError::ShieldedNotBound); + } + // Held until the address is returned, so the identity cannot move to + // another slot between the check below and the bind of the account + // that slot selects. Publication rechecks it (see + // `check_tip_address_publication`) because the slot can still change + // before the host publishes. + let _placement = self.identity.identity_placement.read().await; + let account = self.verified_tip_account(seed, identity_id).await?; + // Read the bound set and bind the augmented copy as one step: a bind + // replaces the registration, so another bind landing in between + // would have its ordinary accounts dropped by this stale snapshot. + let _config = self.shielded_config_lock.lock().await; + let mut accounts = self.shielded_account_indices().await; + if accounts.is_empty() { + return Err(PlatformWalletError::ShieldedNotBound); + } + #[cfg(test)] + test_hooks::after_snapshot(self).await; + accounts.push(account); + self.bind_shielded_locked_unfenced(seed, &accounts, &coordinator) + .await?; + #[cfg(test)] + test_hooks::after_bind(self).await; + self.persister() + .flush() + .map_err(|e| PlatformWalletError::Persistence(e.to_string()))?; + let address = self + .shielded_default_address(account) + .await + .ok_or(PlatformWalletError::ShieldedNotBound)?; + if coordinator.clear_generation() != clear_generation { + return Err(PlatformWalletError::ShieldedNotBound); + } + self.prepared_tip_accounts + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert( + *identity_id, + PreparedTipAccount { + account, + coordinator: Arc::downgrade(&coordinator), + clear_generation, + }, + ); + Ok(address) + } + + /// The tip account of a wallet-owned identity's slot, proved with the + /// seed. A restored index is metadata, and hosts that cannot represent + /// "unknown" restore a placeholder 0 for wallet-attached identities, so + /// the seed must reproduce the identity's MASTER key at the recorded index + /// before the account that index selects is used for it. + async fn verified_tip_account( + &self, + seed: &[u8], + identity_id: &Identifier, + ) -> Result { + let wm = self.wallet_manager.read().await; + let info = wm + .get_wallet_info(&self.wallet_id()) + .ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id())))?; + let identity = info + .identity_manager + .managed_identity(identity_id) + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; + if identity.wallet_id != Some(self.wallet_id()) { + return Err(PlatformWalletError::InvalidIdentityData( + "Tip account requires a wallet-owned identity".to_string(), + )); + } + let index = identity.identity_index.ok_or_else(|| { + PlatformWalletError::InvalidIdentityData( + "Tip account requires a recoverable identity index".to_string(), + ) + })?; + verify_identity_index(seed, self.sdk.network, index, &identity.identity)?; + shielded_identity_account_index(index) + } + + /// The account `source` spends. An identity spends the tip account of + /// the slot the seed proves it holds. An explicit tip account is refused + /// while its slot holds an identity: the user chose that identity's + /// account by its number, and the identity in the slot may not be the one + /// they meant. + pub(crate) async fn tip_source_account( + &self, + seed: &[u8], + source: ShieldedTipSource, + ) -> Result { + match source { + ShieldedTipSource::Identity(identity_id) => { + self.verified_tip_account(seed, &identity_id).await + } + ShieldedTipSource::Account(account) if is_shielded_identity_account(account) => { + let wm = self.wallet_manager.read().await; + let info = wm.get_wallet_info(&self.wallet_id()).ok_or_else(|| { + PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id())) + })?; + let occupant = info + .identity_manager + .wallet_identities + .get(&self.wallet_id()) + .and_then(|bucket| bucket.get(&(account - SHIELDED_IDENTITY_ACCOUNT_BASE))); + match occupant { + Some(owner) => Err(PlatformWalletError::InvalidIdentityData(format!( + "Account {account} is the tip account of identity {}; \ + send from that identity instead", + owner.identity.id() + ))), + None => Ok(account), + } + } + ShieldedTipSource::Account(account) => Ok(account), + } + } + + /// Refuse to publish one of this wallet's shielded addresses unless + /// preparation, in this session, proved with the seed that `identity_id` + /// holds the slot selecting that account, and the identity still holds + /// it. Discovery can move an identity whose keys derive at several + /// indices, and a restored placeholder index is not proof of a slot. + /// Ordinary accounts and internal-scope identity addresses cannot be published; + /// this wallet scans external receiving addresses. Addresses of other wallets are + /// the owner's choice. Only bound accounts are recognised; preparation binds the + /// account it hands out. Callers hold the placement lock through the + /// profile write. + pub(crate) async fn check_tip_address_publication( + &self, + identity_id: &Identifier, + address: &[u8; 43], + ) -> Result<(), PlatformWalletError> { + let Some(address) = + Option::::from(PaymentAddress::from_raw_address_bytes(address)) + else { + return Ok(()); + }; + let owning_account = { + let keys = self.shielded_keys.read().await; + keys.as_ref().and_then(|keys| { + keys.iter().find_map(|(account, views)| { + views + .full_viewing_key + .scope_for_address(&address) + .map(|scope| (*account, scope)) + }) + }) + }; + let Some((owning_account, scope)) = owning_account else { + return Ok(()); + }; + if !is_shielded_identity_account(owning_account) { + return Err(PlatformWalletError::InvalidIdentityData( + "An address from this wallet's ordinary shielded accounts cannot be published \ + in an identity profile" + .to_string(), + )); + } + if matches!(scope, Scope::Internal) { + return Err(PlatformWalletError::InvalidIdentityData( + "Only external receiving addresses from this wallet can be published \ + in an identity profile" + .to_string(), + )); + } + let prepared = self + .prepared_tip_accounts + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(identity_id) + .is_some_and(|prepared| { + prepared.account == owning_account + && prepared.coordinator.upgrade().is_some_and(|coordinator| { + coordinator.clear_generation() == prepared.clear_generation + }) + }); + let wm = self.wallet_manager.read().await; + let current = wm + .get_wallet_info(&self.wallet_id()) + .and_then(|info| info.identity_manager.managed_identity(identity_id)) + .filter(|identity| identity.wallet_id == Some(self.wallet_id())) + .and_then(|identity| identity.identity_index) + .and_then(|index| shielded_identity_account_index(index).ok()); + if prepared && current == Some(owning_account) { + Ok(()) + } else { + Err(PlatformWalletError::InvalidIdentityData( + "This tip address was not prepared for the identity's current tip account; \ + prepare the identity's tip address again" + .to_string(), + )) + } + } + + /// Send only to the identity/address pair that the user confirmed. A changed + /// name owner or profile requires a new confirmation; there is no fallback to + /// a transparent rail. Network changes after this check cannot change the + /// destination, which remains the explicitly confirmed raw address. + /// + /// The source is checked before anything is resolved or proved, and the + /// placement lock is held through the spend, so an identity's tip is paid + /// from the account of the slot it holds when its notes are selected. + #[allow(clippy::too_many_arguments)] + pub async fn send_shielded_tip( + &self, + coordinator: &Arc, + seed: &[u8], + source: ShieldedTipSource, + username: &str, + expected_recipient: &ShieldedTipRecipient, + amount: u64, + memo: [u8; 36], + prover: P, + ) -> Result<(), PlatformWalletError> { + let coordinator = self.resolve_shielded_coordinator(coordinator).await?; + { + let _placement = self.identity.identity_placement.read().await; + self.tip_source_account(seed, source).await?; + } + let current = self + .identity() + .dashpay() + .resolve_shielded_tip(username) + .await?; + if current != *expected_recipient { + return Err(PlatformWalletError::InvalidIdentityData( + "The tip recipient changed; review and confirm the payment again".to_string(), + )); + } + let _lifecycle = self.core().generation_payment_guard().await; + if !self.core().is_current_generation().await { + return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode( + self.wallet_id(), + ))); + } + let _operation = coordinator.operation_guard().await; + let _placement = self.identity.identity_placement.read().await; + let account = self.tip_source_account(seed, source).await?; + #[cfg(test)] + test_hooks::before_spend(self).await; + self.shielded_transfer_to( + &coordinator, + seed, + account, + ¤t.address, + amount, + memo, + prover, + ) + .await + } +} + +/// Test-only pause point between tip preparation's account snapshot and +/// its bind, keyed by wallet instance (shared by its clones) so parallel +/// tests built from the same mnemonic do not interfere. +#[cfg(test)] +pub(crate) mod test_hooks { + use super::PlatformWallet; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + use tokio::sync::oneshot; + + type Hook = (oneshot::Sender<()>, oneshot::Receiver<()>); + #[derive(Clone, Copy, PartialEq, Eq, Hash)] + enum Stage { + Snapshot, + Bound, + Spend, + } + static HOOKS: Mutex>> = Mutex::new(None); + + fn key(wallet: &PlatformWallet) -> usize { + Arc::as_ptr(&wallet.shielded_config_lock) as usize + } + + fn pause( + wallet: &PlatformWallet, + stage: Stage, + ) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { + let (reached_tx, reached_rx) = oneshot::channel(); + let (resume_tx, resume_rx) = oneshot::channel(); + HOOKS + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .insert((key(wallet), stage), (reached_tx, resume_rx)); + (reached_rx, resume_tx) + } + + async fn reach(wallet: &PlatformWallet, stage: Stage) { + let hook = HOOKS + .lock() + .unwrap() + .as_mut() + .and_then(|hooks| hooks.remove(&(key(wallet), stage))); + if let Some((reached, resume)) = hook { + let _ = reached.send(()); + let _ = resume.await; + } + } + + pub(crate) fn pause_after_snapshot( + wallet: &PlatformWallet, + ) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { + pause(wallet, Stage::Snapshot) + } + + pub(crate) async fn after_snapshot(wallet: &PlatformWallet) { + reach(wallet, Stage::Snapshot).await; + } + + pub(crate) fn pause_after_bind( + wallet: &PlatformWallet, + ) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { + pause(wallet, Stage::Bound) + } + + pub(crate) async fn after_bind(wallet: &PlatformWallet) { + reach(wallet, Stage::Bound).await; + } + + pub(crate) fn pause_before_spend( + wallet: &PlatformWallet, + ) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { + pause(wallet, Stage::Spend) + } + + pub(crate) async fn before_spend(wallet: &PlatformWallet) { + reach(wallet, Stage::Spend).await; + } +} + +#[cfg(test)] +mod tests { + use super::super::OrchardKeySet; + use super::*; + use key_wallet::Network; + + #[test] + fn should_derive_distinct_recoverable_tip_accounts() { + let seed = [42u8; 64]; + let ordinary = OrchardKeySet::from_seed(&seed, Network::Testnet, 0).unwrap(); + let index = shielded_identity_account_index(0).unwrap(); + let tip = OrchardKeySet::from_seed(&seed, Network::Testnet, index).unwrap(); + let restored = OrchardKeySet::from_seed( + &seed, + Network::Testnet, + shielded_identity_account_index(0).unwrap(), + ) + .unwrap(); + let other = OrchardKeySet::from_seed( + &seed, + Network::Testnet, + shielded_identity_account_index(1).unwrap(), + ) + .unwrap(); + assert_ne!( + ordinary.full_viewing_key.to_bytes(), + tip.full_viewing_key.to_bytes() + ); + assert_ne!( + tip.default_address.to_raw_address_bytes(), + other.default_address.to_raw_address_bytes() + ); + assert_eq!( + tip.full_viewing_key.to_bytes(), + restored.full_viewing_key.to_bytes() + ); + assert!(!is_shielded_identity_account(0)); + assert!(is_shielded_identity_account(index)); + assert!(shielded_identity_account_index(SHIELDED_IDENTITY_ACCOUNT_BASE).is_err()); + } +} diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index 0f2b2cadada..770f20ec431 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -15,6 +15,7 @@ use std::sync::{Arc, Mutex}; use dashcore::Network; use key_wallet::account::StandardAccountType; +use orchard::keys::Scope; use crate::changeset::PersistenceError; use crate::changeset::PlatformWalletPersistence; @@ -38,6 +39,8 @@ use crate::wallet::shielded::{ #[derive(Default)] struct CapturingPersistence { stored: Mutex>, + durability_events: Mutex>, + fail_flush: std::sync::atomic::AtomicBool, serve: Mutex>>, serve_subwallets: Mutex>, load_calls: Mutex, @@ -112,11 +115,18 @@ impl PlatformWalletPersistence for CapturingPersistence { _wallet_id: WalletId, changeset: PlatformWalletChangeSet, ) -> Result<(), PersistenceError> { + self.durability_events.lock().unwrap().push("store"); self.stored.lock().expect("stored lock").push(changeset); Ok(()) } fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> { + self.durability_events.lock().unwrap().push("flush"); + if self.fail_flush.load(std::sync::atomic::Ordering::SeqCst) { + return Err(PersistenceError::backend(std::io::Error::other( + "injected flush failure", + ))); + } Ok(()) } @@ -175,7 +185,12 @@ where { let (wallet_manager, wallet_id, balance, _signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; - let sdk = Arc::new(dash_sdk::Sdk::new_mock()); + let sdk = Arc::new( + dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .build() + .unwrap(), + ); let spv = Arc::new(crate::spv::SpvRuntime::new( Arc::clone(&wallet_manager), Arc::new(crate::events::PlatformEventManager::new(Vec::new())), @@ -1162,3 +1177,1766 @@ async fn fresh_address_and_own_check_follow_the_bound_account() { ); assert_eq!(wallet.is_own_shielded_address(1, &fresh).await, None); } + +/// A profile is not a recovery record. Identity discovery alone must restore +/// the reserved account, even when the owner removed the tip address entirely. +/// The MASTER authentication key this seed derives for `identity_index` on +/// testnet, as an identity public-key map: what discovery and registration +/// leave on a wallet-owned identity, and what tip preparation verifies. +fn seed_master_key( + seed: &[u8], + identity_index: u32, +) -> BTreeMap { + use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::identity::{IdentityPublicKey, KeyType, Purpose, SecurityLevel}; + use dpp::platform_value::BinaryData; + let master = key_wallet::bip32::ExtendedPrivKey::new_master(Network::Testnet, seed).unwrap(); + let derived = crate::wallet::identity::network::derive_ecdsa_identity_auth_keypair_from_master( + &master, + Network::Testnet, + identity_index, + crate::wallet::identity::network::MASTER_KEY_INDEX, + ) + .unwrap(); + BTreeMap::from([( + 0, + IdentityPublicKey::V0(IdentityPublicKeyV0 { + id: 0, + purpose: Purpose::AUTHENTICATION, + security_level: SecurityLevel::MASTER, + contract_bounds: None, + key_type: KeyType::ECDSA_SECP256K1, + read_only: false, + data: BinaryData::new(derived.public_key.to_vec()), + disabled_at: None, + }), + )]) +} + +/// A signer for writes that must be refused before anything is signed. +#[derive(Debug)] +struct NoSigner; + +#[async_trait::async_trait] +impl dpp::identity::signer::Signer for NoSigner { + async fn sign( + &self, + _key: &dpp::identity::IdentityPublicKey, + _data: &[u8], + ) -> Result { + unreachable!("the write is refused before signing") + } + + async fn sign_create_witness( + &self, + _key: &dpp::identity::IdentityPublicKey, + _data: &[u8], + ) -> Result { + unreachable!("the write is refused before signing") + } + + fn can_sign_with(&self, _key: &dpp::identity::IdentityPublicKey) -> bool { + false + } +} + +/// Cold reload of a host that cannot store "index unknown": a wallet-attached +/// identity whose index was lost comes back at placeholder slot 0 while +/// identity 0's tip account (and its funds) is retained and bound. Tip +/// preparation must refuse it instead of handing out identity 0's address, +/// and must accept it once rediscovery proves its real index. +#[tokio::test] +async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified() { + use crate::shielded_identity_account_index; + use dpp::identity::{Identity, IdentityV0}; + use dpp::prelude::Identifier; + let phrase = crate::test_support::MESSAGE_SIGNING_TEST_MNEMONIC; + let seed = key_wallet::Mnemonic::from_phrase(phrase) + .unwrap() + .to_seed(""); + let (wallet_manager, wallet_id, _, _) = + crate::test_support::mnemonic_wallet_manager(phrase).await; + let generation = wallet_manager + .read() + .await + .get_wallet_info(&wallet_id) + .unwrap() + .generation + .clone(); + let spv = Arc::new(crate::spv::SpvRuntime::new( + Arc::clone(&wallet_manager), + Arc::new(crate::events::PlatformEventManager::new(Vec::new())), + )); + let sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .build() + .unwrap(); + let persister = Arc::new(CapturingPersistence::default()); + let wallet = PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wallet_manager, + generation, + Arc::new(tokio::sync::Notify::new()), + persister.clone(), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + // Restored at the host's placeholder 0, but its keys are identity 5's. + let id = Identifier::from([0x55; 32]); + { + let mut wm = wallet.wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id, + public_keys: seed_master_key(&seed[..], 5), + balance: 0, + revision: 0, + }), + 0, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } + let coordinator = coordinator_at(&temp_dir("tips_placeholder_index")); + let identity_zero_tips = shielded_identity_account_index(0).unwrap(); + wallet + .bind_shielded(&seed[..], &[0, identity_zero_tips], &coordinator) + .await + .unwrap(); + let identity_zero_address = wallet + .shielded_default_address(identity_zero_tips) + .await + .unwrap(); + + let refused = wallet + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) + .await; + assert!( + matches!(refused, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not verified")), + "{refused:?}" + ); + // A send from this identity selects the same recorded index, so it is + // refused too, before any network resolution or proving; and identity + // 0's tip account cannot be spent by number while a slot-0 identity + // holds it. + let recipient = crate::ShieldedTipRecipient { + identity_id: Identifier::from([0x77; 32]), + address: [0; 43], + }; + let spend = |source: crate::ShieldedTipSource| { + let wallet = wallet.clone(); + let coordinator = Arc::clone(&coordinator); + let recipient = recipient.clone(); + let seed = seed.clone(); + async move { + wallet + .send_shielded_tip( + &coordinator, + &seed[..], + source, + "recipient.dash", + &recipient, + 1_000, + [0; 36], + &super::CachedOrchardProver::new(), + ) + .await + } + }; + let refused_with = |result: &Result<(), crate::PlatformWalletError>, reason: &str| matches!(result, Err(crate::PlatformWalletError::InvalidIdentityData(msg)) if msg.contains(reason)); + // Nor can it publish identity 0's tip address as its own: the profile + // write refuses it before signing or any network call. + let published = wallet + .write_dashpay_profile( + &id, + crate::ProfileUpdate { + shielded_address: crate::PaymentAddressUpdate::Set(identity_zero_address.to_vec()), + ..Default::default() + }, + &NoSigner, + false, + ) + .await + .map(|_| ()); + assert!( + refused_with(&published, "not prepared for"), + "{published:?}" + ); + let refused_spend = spend(crate::ShieldedTipSource::Identity(id)).await; + assert!( + refused_with(&refused_spend, "not verified"), + "{refused_spend:?}" + ); + let by_number = spend(crate::ShieldedTipSource::Account(identity_zero_tips)).await; + assert!( + refused_with(&by_number, "send from that identity"), + "{by_number:?}" + ); + + // Rediscovery proves index 5 and re-slots the identity. + { + let mut wm = wallet.wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .adopt_into_wallet(&id, wallet.wallet_id(), 5) + .unwrap(); + } + let address = wallet + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) + .await + .unwrap(); + assert_ne!(address, identity_zero_address); + assert_eq!( + wallet + .shielded_default_address(shielded_identity_account_index(5).unwrap()) + .await + .unwrap(), + address + ); + assert_eq!( + wallet + .tip_source_account(&seed[..], crate::ShieldedTipSource::Identity(id)) + .await + .unwrap(), + shielded_identity_account_index(5).unwrap() + ); + // The identity now passes the source check (the mock SDK then fails the + // recipient lookup). Slot 0 is empty, so its account is spendable by + // number as a retired identity's; slot 5's is not. + for source in [ + crate::ShieldedTipSource::Identity(id), + crate::ShieldedTipSource::Account(identity_zero_tips), + ] { + let passed = spend(source).await; + assert!( + !matches!( + passed, + Err(crate::PlatformWalletError::InvalidIdentityData(_)) + ), + "{source:?}: {passed:?}" + ); + } + let own_by_number = spend(crate::ShieldedTipSource::Account( + shielded_identity_account_index(5).unwrap(), + )) + .await; + assert!( + refused_with(&own_by_number, "send from that identity"), + "{own_by_number:?}" + ); +} + +#[tokio::test] +async fn should_restore_tip_account_from_identity_discovery_and_register_for_sync() { + use crate::shielded_identity_account_index; + use dpp::identity::{Identity, IdentityV0}; + use dpp::prelude::Identifier; + let phrase = crate::test_support::MESSAGE_SIGNING_TEST_MNEMONIC; + let seed = key_wallet::Mnemonic::from_phrase(phrase) + .unwrap() + .to_seed(""); + let id = Identifier::from([0x33; 32]); + let account = shielded_identity_account_index(3).unwrap(); + let mut original = None; + for session in 0..2 { + let persister = Arc::new(CapturingPersistence::default()); + let (wallet_manager, wallet_id, _, _) = + crate::test_support::mnemonic_wallet_manager(phrase).await; + let generation = wallet_manager + .read() + .await + .get_wallet_info(&wallet_id) + .unwrap() + .generation + .clone(); + let spv = Arc::new(crate::spv::SpvRuntime::new( + Arc::clone(&wallet_manager), + Arc::new(crate::events::PlatformEventManager::new(Vec::new())), + )); + let sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .build() + .unwrap(); + let wallet = PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wallet_manager, + generation, + Arc::new(tokio::sync::Notify::new()), + persister.clone(), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + { + let mut wm = wallet.wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id, + public_keys: seed_master_key(&seed[..], 3), + balance: 0, + revision: 0, + }), + 3, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } + { + let mut wm = wallet.wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id: Identifier::from([0x44; 32]), + public_keys: BTreeMap::new(), + balance: 0, + revision: 0, + }), + crate::SHIELDED_IDENTITY_ACCOUNT_BASE, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } + let coordinator = coordinator_at(&temp_dir(&format!("tips_restore_{session}"))); + // Fresh database, no viewing keys, no published profile, and caller + // only knows about ordinary account zero. + assert!(!wallet + .bind_shielded_from_persisted(&[0], &coordinator) + .await + .unwrap()); + // Upgrading an existing wallet can leave account zero persisted while + // identity discovery introduces a tip account without an FVK. Seedless + // success here would suppress the host's seed fallback and lose scans + // for that identity's tip history. + let ordinary = super::OrchardKeySet::from_seed(&seed[..], Network::Testnet, 0).unwrap(); + persister.serve_viewing_keys(BTreeMap::from([( + SubwalletId::new(wallet.wallet_id(), 0), + ordinary.full_viewing_key.to_bytes().to_vec(), + )])); + assert!(!wallet + .bind_shielded_from_persisted(&[0], &coordinator) + .await + .unwrap()); + assert!(!wallet.is_shielded_bound().await); + assert!(wallet + .prepare_shielded_identity_address(&[0x11; 64], &id, &coordinator) + .await + .is_err()); + assert!(matches!( + wallet + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) + .await, + Err(crate::PlatformWalletError::ShieldedNotBound) + )); + assert!(!wallet.is_shielded_bound().await); + assert!(persister.captured_viewing_keys().is_empty()); + assert!(coordinator.registered_subwallets().await.is_empty()); + wallet + .bind_shielded(&seed[..], &[0], &coordinator) + .await + .unwrap(); + assert!(coordinator + .registered_subwallets() + .await + .contains(&SubwalletId::new(wallet.wallet_id(), account))); + assert!(wallet + .prepare_shielded_identity_address(&[0x11; 64], &id, &coordinator) + .await + .is_err()); + // A queued FVK is insufficient: no publishable address may escape a + // failed durability barrier, even though bind installed keys in memory. + persister.durability_events.lock().unwrap().clear(); + persister + .fail_flush + .store(true, std::sync::atomic::Ordering::SeqCst); + assert!(matches!( + wallet + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) + .await, + Err(crate::PlatformWalletError::Persistence(_)) + )); + assert_eq!( + *persister.durability_events.lock().unwrap(), + ["store", "flush"] + ); + assert!(wallet.shielded_default_address(account).await.is_some()); + persister + .fail_flush + .store(false, std::sync::atomic::Ordering::SeqCst); + persister.durability_events.lock().unwrap().clear(); + let address = wallet + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) + .await + .unwrap(); + assert!(wallet + .prepare_shielded_identity_address( + &seed[..], + &Identifier::from([0x44; 32]), + &coordinator + ) + .await + .is_err()); + assert_eq!( + *persister.durability_events.lock().unwrap(), + ["store", "flush"] + ); + assert_ne!(wallet.shielded_default_address(0).await.unwrap(), address); + assert_eq!( + wallet + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) + .await + .unwrap(), + address + ); + assert!(persister + .captured_viewing_keys() + .contains_key(&SubwalletId::new(wallet.wallet_id(), account))); + if let Some(first) = original { + assert_eq!(first, address); + } else { + original = Some(address); + } + } +} + +#[tokio::test] +async fn should_rebind_retired_tip_accounts_without_profile_or_identity() { + let seed = [0x42; 64]; + let account = crate::shielded_identity_account_index(7).unwrap(); + let persister = Arc::new(CapturingPersistence::default()); + let wallet = platform_wallet_with(Arc::clone(&persister)).await; + let keys = super::OrchardKeySet::from_seed(&seed[..], Network::Testnet, account).unwrap(); + let ordinary = super::OrchardKeySet::from_seed(&seed[..], Network::Testnet, 0).unwrap(); + persister.serve_viewing_keys(BTreeMap::from([ + ( + SubwalletId::new(wallet.wallet_id(), 0), + ordinary.full_viewing_key.to_bytes().to_vec(), + ), + ( + SubwalletId::new(wallet.wallet_id(), account), + keys.full_viewing_key.to_bytes().to_vec(), + ), + ])); + let coordinator = coordinator_at(&temp_dir("retired_tips")); + assert!(wallet + .bind_shielded_from_persisted(&[0], &coordinator) + .await + .unwrap()); + assert_eq!( + wallet.shielded_default_address(account).await.unwrap(), + keys.default_address.to_raw_address_bytes() + ); + assert!(coordinator + .registered_subwallets() + .await + .contains(&SubwalletId::new(wallet.wallet_id(), account))); +} + +/// A host rebind passes only ordinary accounts (FFI and host SDKs cap the +/// request at 64 entries); Rust adds every persisted tip account itself. With +/// more than 64 tip accounts on record, a `[0]` request must still bind them +/// all, both seedlessly and from the seed, and the resulting +/// `shielded_account_indices` snapshot exceeds the request cap, which is why +/// hosts must not echo it back as a bind request. +#[tokio::test] +async fn should_bind_more_than_64_persisted_tip_accounts_from_an_ordinary_request() { + let seed = [0x42; 64]; + let tips: Vec = (0..70) + .map(|index| crate::shielded_identity_account_index(index).unwrap()) + .collect(); + for (tag, seeded) in [("many_tips_persisted", false), ("many_tips_seeded", true)] { + let persister = Arc::new(CapturingPersistence::default()); + let wallet = platform_wallet_with(Arc::clone(&persister)).await; + let mut rows = BTreeMap::new(); + for &account in std::iter::once(&0).chain(tips.iter()) { + let keys = + super::OrchardKeySet::from_seed(&seed[..], wallet.sdk().network, account).unwrap(); + rows.insert( + SubwalletId::new(wallet.wallet_id(), account), + keys.full_viewing_key.to_bytes().to_vec(), + ); + } + persister.serve_viewing_keys(rows); + let coordinator = coordinator_at(&temp_dir(tag)); + if seeded { + wallet + .bind_shielded(&seed[..], &[0], &coordinator) + .await + .unwrap(); + } else { + assert!(wallet + .bind_shielded_from_persisted(&[0], &coordinator) + .await + .unwrap()); + } + let bound = wallet.shielded_account_indices().await; + assert_eq!(bound.len(), 71, "{tag}"); + assert!( + bound.len() > 64, + "{tag}: the snapshot exceeds the request cap" + ); + let ordinary: Vec = bound + .iter() + .copied() + .filter(|&account| !super::is_shielded_identity_account(account)) + .collect(); + assert_eq!(ordinary, vec![0], "{tag}"); + let registered = coordinator.registered_subwallets().await; + for &account in &tips { + assert!( + registered.contains(&SubwalletId::new(wallet.wallet_id(), account)), + "{tag}: tip account {account} registered for sync" + ); + } + } +} + +/// A wallet bound to account 0 whose identity at index 2 can prepare a tip +/// address, for racing preparation against other account-set writers. +async fn tip_race_fixture( + tag: &str, +) -> ( + PlatformWallet, + [u8; 64], + dpp::prelude::Identifier, + Arc, +) { + use dpp::identity::{Identity, IdentityV0}; + use dpp::prelude::Identifier; + let phrase = crate::test_support::MESSAGE_SIGNING_TEST_MNEMONIC; + let seed = key_wallet::Mnemonic::from_phrase(phrase) + .unwrap() + .to_seed(""); + let (wallet_manager, wallet_id, _, _) = + crate::test_support::mnemonic_wallet_manager(phrase).await; + let generation = wallet_manager + .read() + .await + .get_wallet_info(&wallet_id) + .unwrap() + .generation + .clone(); + let spv = Arc::new(crate::spv::SpvRuntime::new( + Arc::clone(&wallet_manager), + Arc::new(crate::events::PlatformEventManager::new(Vec::new())), + )); + let mock_dir = temp_dir(tag); + std::fs::create_dir_all(&mock_dir).unwrap(); + let sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .with_dump_dir(&mock_dir) + .with_version(dpp::version::PlatformVersion::latest()) + .build() + .unwrap(); + let persister = Arc::new(CapturingPersistence::default()); + let wallet = PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wallet_manager, + generation, + Arc::new(tokio::sync::Notify::new()), + persister.clone(), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + let id = Identifier::from([0x66; 32]); + { + let mut wm = wallet.wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id, + public_keys: seed_master_key(&seed[..], 2), + balance: 0, + revision: 0, + }), + 2, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } + let coordinator = coordinator_at(&temp_dir(tag)); + wallet + .bind_shielded(&seed[..], &[0], &coordinator) + .await + .unwrap(); + (wallet, *seed, id, coordinator) +} + +/// Pause tip preparation right after its account snapshot, run `writer` +/// against the same wallet, and require the writer to wait for preparation. +async fn race_tip_preparation( + wallet: &PlatformWallet, + seed: [u8; 64], + id: dpp::prelude::Identifier, + coordinator: &Arc, + writer: F, +) where + F: FnOnce(PlatformWallet) -> Fut, + Fut: std::future::Future> + Send + 'static, +{ + let (reached, resume) = super::tips::test_hooks::pause_after_snapshot(wallet); + let preparing = { + let wallet = wallet.clone(); + let coordinator = Arc::clone(coordinator); + tokio::spawn(async move { + wallet + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) + .await + }) + }; + reached.await.expect("preparation reached its snapshot"); + let mut writing = tokio::spawn(writer(wallet.clone())); + // Unserialized, the writer finishes now and the resumed preparation then + // rebinds its stale {0} plus the tip account, dropping account 1. + let finished_early = + tokio::time::timeout(std::time::Duration::from_millis(500), &mut writing).await; + assert!( + finished_early.is_err(), + "an account-set writer must wait for tip preparation's read-modify-write" + ); + resume.send(()).unwrap(); + preparing.await.unwrap().expect("tip address prepared"); + writing.await.unwrap().expect("account-set writer succeeds"); +} + +/// Tip preparation reads the bound account set and binds it plus the tip +/// account. A bind of ordinary accounts landing between those two steps must +/// not be undone by the stale snapshot: preparation is paused right after its +/// snapshot while another task binds accounts 0 and 1, and account 1 must +/// still be bound and registered once both finish. +#[tokio::test] +async fn should_keep_an_ordinary_account_bound_during_tip_preparation() { + use crate::shielded_identity_account_index; + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_concurrent_bind").await; + let tip = shielded_identity_account_index(2).unwrap(); + let bind_coordinator = Arc::clone(&coordinator); + race_tip_preparation(&wallet, seed, id, &coordinator, move |wallet| async move { + wallet + .bind_shielded(&seed[..], &[0, 1], &bind_coordinator) + .await + }) + .await; + + let bound = wallet.shielded_account_indices().await; + for account in [0, 1, tip] { + assert!( + bound.contains(&account), + "account {account} bound: {bound:?}" + ); + } + let registered = coordinator.registered_subwallets().await; + for account in [0, 1, tip] { + assert!( + registered.contains(&SubwalletId::new(wallet.wallet_id(), account)), + "account {account} registered" + ); + } +} + +/// `shielded_add_account` writes the same account set, so it must not land +/// between preparation's snapshot and its bind either, or that bind replaces +/// the key map without the added account. +#[tokio::test] +async fn should_keep_an_added_account_during_tip_preparation() { + use crate::shielded_identity_account_index; + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_concurrent_add").await; + let tip = shielded_identity_account_index(2).unwrap(); + race_tip_preparation(&wallet, seed, id, &coordinator, move |wallet| async move { + wallet.shielded_add_account(&seed[..], 1).await + }) + .await; + + let bound = wallet.shielded_account_indices().await; + for account in [0, 1, tip] { + assert!( + bound.contains(&account), + "account {account} bound: {bound:?}" + ); + } +} + +/// Discovery can move an identity whose keys derive at two indices between +/// their slots. Preparation holds the placement lock from its slot check to +/// its return, so a move waits for it; the address it returned then names the +/// old slot's account, and publishing that address for the moved identity is +/// refused until its address is prepared again. Other wallets' addresses stay +/// publishable. +#[tokio::test] +async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stale_address() { + use crate::shielded_identity_account_index; + use dpp::identity::accessors::IdentityGettersV0; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_placement_move").await; + { + let mut wm = wallet.wallet_manager.write().await; + let managed = wm + .get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .managed_identity_mut(&id) + .unwrap(); + let mut second = seed_master_key(&seed[..], 7).remove(&0).unwrap(); + second.set_id(1); + managed.identity.add_public_key(second); + } + + let (reached, resume) = super::tips::test_hooks::pause_after_snapshot(&wallet); + let preparing = { + let wallet = wallet.clone(); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + wallet + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) + .await + }) + }; + reached.await.expect("preparation reached its snapshot"); + // The move discovery and loading make, under the lock they take. + let mut moving = { + let wallet = wallet.clone(); + tokio::spawn(async move { + let _placement = wallet.identity.identity_placement.write().await; + let mut wm = wallet.wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .adopt_into_wallet(&id, wallet.wallet_id(), 7) + }) + }; + let moved_early = + tokio::time::timeout(std::time::Duration::from_millis(500), &mut moving).await; + assert!( + moved_early.is_err(), + "an identity move must wait for tip preparation to return" + ); + resume.send(()).unwrap(); + let stale = preparing.await.unwrap().expect("tip address prepared"); + assert_eq!( + Some(stale), + wallet + .shielded_default_address(shielded_identity_account_index(2).unwrap()) + .await + ); + moving.await.unwrap().expect("identity moved to slot 7"); + + let refused = wallet.check_tip_address_publication(&id, &stale).await; + assert!( + matches!(refused, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not prepared for")), + "{refused:?}" + ); + let fresh = wallet + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) + .await + .unwrap(); + assert_ne!(fresh, stale); + let external = super::OrchardKeySet::from_seed( + &[9; 64], + Network::Testnet, + shielded_identity_account_index(2).unwrap(), + ) + .unwrap() + .default_address + .to_raw_address_bytes(); + for address in [fresh, external] { + wallet + .check_tip_address_publication(&id, &address) + .await + .expect("publishable"); + } +} + +#[tokio::test] +async fn should_reject_ordinary_account_profile_addresses_at_every_diversifier() { + let (wallet, seed, id, coordinator) = tip_race_fixture("identity_profile_privacy").await; + let other_account = crate::shielded_identity_account_index(7).unwrap(); + wallet + .bind_shielded(&seed, &[0, 1, other_account], &coordinator) + .await + .unwrap(); + let prepared = wallet + .prepare_shielded_identity_address(&seed, &id, &coordinator) + .await + .unwrap(); + for account in [0, 1] { + let keys = OrchardKeySet::from_seed(&seed, Network::Testnet, account).unwrap(); + for address in [ + keys.default_address, + keys.address_at(17), + keys.full_viewing_key.address_at(3u32, Scope::Internal), + ] { + let error = wallet + .check_tip_address_publication(&id, &address.to_raw_address_bytes()) + .await + .unwrap_err(); + assert!( + matches!(error, crate::PlatformWalletError::InvalidIdentityData(ref message) if message.contains("ordinary shielded accounts")), + "{error:?}" + ); + } + } + let other = wallet + .shielded_default_address(other_account) + .await + .unwrap(); + assert!(wallet + .check_tip_address_publication(&id, &other) + .await + .is_err()); + let own = OrchardKeySet::from_seed( + &seed, + Network::Testnet, + crate::shielded_identity_account_index(2).unwrap(), + ) + .unwrap(); + for index in [0u32, 17] { + let address = own.full_viewing_key.address_at(index, Scope::Internal); + let error = wallet + .check_tip_address_publication(&id, &address.to_raw_address_bytes()) + .await + .unwrap_err(); + assert!( + matches!(error, crate::PlatformWalletError::InvalidIdentityData(ref message) if message.contains("external receiving addresses")), + "{error:?}" + ); + } + let external = OrchardKeySet::from_seed(&[9; 64], Network::Testnet, 0).unwrap(); + for address in [ + prepared, + own.address_at(17).to_raw_address_bytes(), + external.default_address.to_raw_address_bytes(), + external.address_at(17).to_raw_address_bytes(), + external + .full_viewing_key + .address_at(17u32, Scope::Internal) + .to_raw_address_bytes(), + ] { + wallet + .check_tip_address_publication(&id, &address) + .await + .unwrap(); + } +} + +#[tokio::test] +async fn should_require_fresh_tip_preparation_after_clear_even_after_rebind() { + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_clear").await; + let address = wallet + .prepare_shielded_identity_address(&seed, &id, &coordinator) + .await + .unwrap(); + wallet + .check_tip_address_publication(&id, &address) + .await + .unwrap(); + + coordinator.clear().await.unwrap(); + assert!(wallet + .check_tip_address_publication(&id, &address) + .await + .is_err()); + wallet + .bind_shielded(&seed, &[0], &coordinator) + .await + .unwrap(); + assert!(wallet + .check_tip_address_publication(&id, &address) + .await + .is_err()); + + assert_eq!( + wallet + .prepare_shielded_identity_address(&seed, &id, &coordinator) + .await + .unwrap(), + address + ); + wallet + .check_tip_address_publication(&id, &address) + .await + .unwrap(); +} + +#[tokio::test] +async fn should_refuse_shielded_identity_creation_at_an_occupied_slot_before_deriving_or_spending() +{ + let (wallet, _, occupant, coordinator) = tip_race_fixture("tips_occupied_creation").await; + let error = wallet + .shielded_identity_create_from_pool( + &coordinator, + &[], + 0, + 2, + vec![], + 0, + dpp::address_funds::PlatformAddress::P2pkh([0x11; 20]), + &NoSigner, + &super::CachedOrchardProver::new(), + ) + .await + .unwrap_err(); + assert!( + matches!(error, crate::PlatformWalletError::InvalidIdentityData(ref message) + if message.contains("index 2") && message.contains(&format!("{occupant}"))), + "{error:?}" + ); +} + +async fn mock_tip_recipient(wallet: &PlatformWallet) -> crate::ShieldedTipRecipient { + use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; + use dash_sdk::{platform::DocumentQuery, query_types::Documents}; + use dpp::document::{Document, DocumentV0, DocumentV0Getters}; + use dpp::platform_value::Value; + use dpp::prelude::Identifier; + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::version::PlatformVersion; + + let recipient = Identifier::from([0x77; 32]); + let address = OrchardKeySet::from_seed(&[9; 64], Network::Testnet, 0) + .unwrap() + .default_address + .to_raw_address_bytes(); + let mut sdk = wallet.sdk().clone(); + let dpns = + load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()).unwrap(); + sdk.mock() + .expect_fetch(SystemDataContract::DPNS.id(), Some(dpns.clone())) + .await + .unwrap(); + let domain = Document::V0(DocumentV0 { + id: Identifier::from([3; 32]), + owner_id: recipient, + revision: Some(1), + properties: [( + "records".into(), + Value::Map(vec![( + Value::Text("identity".into()), + Value::Identifier(recipient.to_buffer()), + )]), + )] + .into(), + ..Default::default() + }); + let query = DocumentQuery::new(dpns, "domain") + .unwrap() + .with_where(WhereClause { + field: "normalizedParentDomainName".into(), + operator: WhereOperator::Equal, + value: Value::Text("dash".into()), + }) + .with_where(WhereClause { + field: "normalizedLabel".into(), + operator: WhereOperator::Equal, + value: Value::Text("a11ce".into()), + }) + .with_limit(1); + sdk.mock() + .expect_fetch_many::( + query, + Some([(domain.id(), Some(domain))].into()), + ) + .await + .unwrap(); + let profile = Document::V0(DocumentV0 { + id: Identifier::from([4; 32]), + owner_id: recipient, + revision: Some(1), + properties: [("shieldedAddress".into(), Value::Bytes(address.to_vec()))].into(), + ..Default::default() + }); + let query = DocumentQuery::new( + crate::wallet::identity::network::dashpay_contract().unwrap(), + "profile", + ) + .unwrap() + .with_where(WhereClause { + field: "$ownerId".into(), + operator: WhereOperator::In, + value: Value::Array(vec![recipient.into()]), + }) + .with_order_by(OrderClause { + field: "$ownerId".into(), + ascending: true, + }) + .with_limit(100); + sdk.mock() + .expect_fetch_many::( + query, + Some([(profile.id(), Some(profile))].into()), + ) + .await + .unwrap(); + + crate::ShieldedTipRecipient { + identity_id: recipient, + address, + } +} + +#[tokio::test] +async fn should_order_public_identity_manager_replacement_after_tip_spending() { + use futures::FutureExt; + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_public_mutation").await; + let recipient = mock_tip_recipient(&wallet).await; + let (reached, resume) = super::tips::test_hooks::pause_before_spend(&wallet); + let mut sending = { + let wallet = wallet.clone(); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + wallet + .send_shielded_tip( + &coordinator, + &seed, + crate::ShieldedTipSource::Identity(id), + "Alice.dash", + &recipient, + 0, + [0; 36], + &super::CachedOrchardProver::new(), + ) + .await + }) + }; + tokio::time::timeout(std::time::Duration::from_secs(5), async { + tokio::select! { + result = reached => result.unwrap(), + result = &mut sending => panic!("tip send stopped before source validation: {result:?}"), + } + }) + .await + .expect("tip send reached source validation"); + assert!( + wallet.try_state_mut().is_none(), + "public writes must respect placement" + ); + let mut replacing = Box::pin(wallet.state_mut()); + assert!( + replacing.as_mut().now_or_never().is_none(), + "replacement must wait for the send" + ); + resume.send(()).unwrap(); + let error = sending.await.unwrap().unwrap_err(); + assert!( + matches!(error, crate::PlatformWalletError::ShieldedBuildError(ref message) if message.starts_with("amount must be > 0")), + "{error:?}" + ); + let mut state = replacing.await.unwrap(); + let mut replacement = state.identity_manager.clone(); + let identity = replacement + .remove_identity(&id, wallet.persister()) + .unwrap(); + replacement + .add_identity(identity, 7, wallet.wallet_id(), wallet.persister()) + .unwrap(); + state.identity_manager = replacement; + assert_eq!(state.identity_manager.identity_index(&id), Some(7)); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn should_order_blocking_public_state_mutation_against_identity_placement() { + let (wallet, _, id, _) = tip_race_fixture("tips_blocking_public_mutation").await; + let placement = wallet.identity.identity_placement.read().await; + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let mut writing = { + let wallet = wallet.clone(); + tokio::task::spawn_blocking(move || { + started_tx.send(()).unwrap(); + let mut state = wallet.state_mut_blocking().unwrap(); + let identity = state + .identity_manager + .remove_identity(&id, wallet.persister()) + .unwrap(); + state + .identity_manager + .add_identity(identity, 7, wallet.wallet_id(), wallet.persister()) + .unwrap(); + }) + }; + started_rx.await.unwrap(); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(500), &mut writing) + .await + .is_err() + ); + drop(placement); + writing.await.unwrap(); + assert_eq!( + wallet.state().await.identity_manager.identity_index(&id), + Some(7) + ); +} + +mod tip_lifecycle_tests { + use super::*; + use crate::events::{EventHandler, PlatformEventHandler}; + use crate::wallet::shielded::CachedOrchardProver; + use crate::{PlatformWalletManager, ShieldedTipSource}; + use dash_sdk::query_types::{NoParamQuery, ShieldedAnchors}; + use dpp::shielded::builder::OrchardProver; + use futures::FutureExt; + use grovedb_commitment_tree::{ + ExtractedNoteCommitment, Note, NoteValue, ProvingKey, RandomSeed, Rho, + }; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + use std::panic::AssertUnwindSafe; + use std::time::Duration; + use tokio::sync::oneshot; + + const SEED: [u8; 64] = [0x42; 64]; + + struct NoopEvents; + impl EventHandler for NoopEvents {} + impl PlatformEventHandler for NoopEvents {} + + async fn fixture() -> ( + tempfile::TempDir, + Arc>, + Arc, + Arc, + ) { + let dir = tempfile::tempdir().unwrap(); + let sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .with_version(dpp::version::PlatformVersion::latest()) + .with_dump_dir(dir.path()) + .build() + .unwrap(); + let manager = Arc::new(PlatformWalletManager::new( + Arc::new(sdk), + Arc::new(CapturingPersistence::default()), + Arc::new(NoopEvents), + )); + let wallet = add_wallet(&manager).await; + manager + .configure_shielded(dir.path().join("tree.sqlite")) + .await + .unwrap(); + let coordinator = manager.shielded_coordinator().await.unwrap(); + wallet + .bind_shielded(&SEED, &[0], &coordinator) + .await + .unwrap(); + (dir, manager, wallet, coordinator) + } + + async fn add_wallet( + manager: &PlatformWalletManager, + ) -> Arc { + manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &SEED, + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap() + } + + async fn assert_preparation_precedes_host_deletion(clear: bool) { + use dpp::identity::{Identity, IdentityV0}; + use dpp::prelude::Identifier; + + let (_dir, manager, wallet, coordinator) = fixture().await; + let identity_id = Identifier::from([0x66; 32]); + wallet + .wallet_manager + .write() + .await + .get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id: identity_id, + public_keys: seed_master_key(&SEED, 2), + balance: 0, + revision: 0, + }), + 2, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + let (reached, resume) = super::super::tips::test_hooks::pause_after_bind(&wallet); + let preparing = { + let wallet = Arc::clone(&wallet); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + wallet + .prepare_shielded_identity_address(&SEED, &identity_id, &coordinator) + .await + }) + }; + tokio::time::timeout(Duration::from_secs(10), reached) + .await + .unwrap() + .unwrap(); + assert_eq!( + manager.persister.durability_events.lock().unwrap().last(), + Some(&"store") + ); + let mut deleting = { + let manager = Arc::clone(&manager); + let wallet_id = wallet.wallet_id(); + tokio::spawn(async move { + if clear { + manager.clear_shielded().await.unwrap(); + } else { + manager.remove_wallet(&wallet_id).await.unwrap(); + } + manager.persister.stored.lock().unwrap().clear(); + manager + .persister + .durability_events + .lock() + .unwrap() + .push("host deletion"); + }) + }; + let early = tokio::time::timeout(Duration::from_millis(500), &mut deleting).await; + resume.send(()).unwrap(); + let address = preparing.await.unwrap().unwrap(); + assert!(early.is_err(), "teardown must wait for the post-bind flush"); + deleting.await.unwrap(); + let events = manager.persister.durability_events.lock().unwrap().clone(); + assert_eq!(&events[events.len() - 2..], &["flush", "host deletion"]); + assert!(manager.persister.captured_viewing_keys().is_empty()); + if clear { + assert!(wallet + .check_tip_address_publication(&identity_id, &address) + .await + .is_err()); + } else { + let current = add_wallet(&manager).await; + assert_eq!(current.wallet_id(), wallet.wallet_id()); + let after_create = manager.persister.durability_events.lock().unwrap().len(); + assert!(matches!( + wallet + .prepare_shielded_identity_address(&SEED, &identity_id, &coordinator) + .await, + Err(crate::PlatformWalletError::WalletNotFound(_)) + )); + assert_eq!( + manager.persister.durability_events.lock().unwrap().len(), + after_create + ); + } + } + + #[tokio::test] + async fn should_finish_tip_preparation_persistence_before_clear_and_host_deletion() { + assert_preparation_precedes_host_deletion(true).await; + } + + #[tokio::test] + async fn should_finish_tip_preparation_persistence_before_removal_and_host_deletion() { + assert_preparation_precedes_host_deletion(false).await; + } + + #[derive(Debug)] + struct PausedProfileSigner { + reached: Mutex>>, + resume: Mutex>, + } + + #[async_trait::async_trait] + impl dpp::identity::signer::Signer for PausedProfileSigner { + async fn sign( + &self, + _: &dpp::identity::IdentityPublicKey, + _: &[u8], + ) -> Result { + panic!("the unavailable signer must prevent publication") + } + + async fn sign_create_witness( + &self, + _: &dpp::identity::IdentityPublicKey, + _: &[u8], + ) -> Result { + panic!("profile publication must not create a witness") + } + + fn can_sign_with(&self, _: &dpp::identity::IdentityPublicKey) -> bool { + self.reached + .lock() + .unwrap() + .take() + .unwrap() + .send(()) + .unwrap(); + self.resume + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .unwrap(); + false + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn should_fence_profile_publication_against_wallet_replacement() { + use crate::wallet::identity::network::dashpay_contract; + use crate::{PaymentAddressUpdate, PlatformWalletError, ProfileUpdate}; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + use dpp::identity::{Identity, IdentityV0, SecurityLevel}; + use dpp::prelude::Identifier; + use dpp::system_data_contracts::SystemDataContract; + + for create in [true, false] { + let (_dir, manager, wallet, coordinator) = fixture().await; + let identity_id = Identifier::from([0x66; 32]); + let mut public_keys = seed_master_key(&SEED, 2); + let mut signing_key = public_keys[&0].clone(); + signing_key.set_id(1); + signing_key.set_security_level(SecurityLevel::CRITICAL); + public_keys.insert(1, signing_key); + wallet + .state_mut() + .await + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id: identity_id, + public_keys, + balance: 0, + revision: 0, + }), + 2, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + let address = wallet + .prepare_shielded_identity_address(&SEED, &identity_id, &coordinator) + .await + .unwrap(); + let input = ProfileUpdate { + shielded_address: PaymentAddressUpdate::Set(address.to_vec()), + ..Default::default() + }; + let mut sdk = wallet.sdk().clone(); + sdk.mock() + .expect_fetch( + SystemDataContract::Dashpay.id(), + Some(dashpay_contract().unwrap().as_ref().clone()), + ) + .await + .unwrap(); + let (reached_tx, reached_rx) = oneshot::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let signer = PausedProfileSigner { + reached: Mutex::new(Some(reached_tx)), + resume: Mutex::new(resume_rx), + }; + let before = manager.persister.stored_count(); + let publishing = { + let wallet = Arc::clone(&wallet); + let input = input.clone(); + tokio::spawn(async move { + wallet + .write_dashpay_profile(&identity_id, input, &signer, create) + .await + }) + }; + tokio::time::timeout(Duration::from_secs(10), reached_rx) + .await + .unwrap() + .unwrap(); + let mut replacing = { + let manager = Arc::clone(&manager); + let wallet_id = wallet.wallet_id(); + tokio::spawn(async move { + manager.remove_wallet(&wallet_id).await.unwrap(); + add_wallet(&manager).await + }) + }; + let early = tokio::time::timeout(Duration::from_millis(500), &mut replacing).await; + resume_tx.send(()).unwrap(); + let error = publishing.await.unwrap().unwrap_err(); + assert!( + error.to_string().contains("unavailable to signer"), + "{error}" + ); + assert!(early.is_err(), "removal must wait for profile publication"); + let current = replacing.await.unwrap(); + assert_eq!(wallet.wallet_id(), current.wallet_id()); + assert!(current.core().is_current_generation().await); + assert!(manager.persister.stored.lock().unwrap()[before..] + .iter() + .all(|changes| changes.dashpay_profiles.is_none())); + let after_replacement = manager.persister.stored_count(); + for stale_input in [input, ProfileUpdate::default()] { + assert!(matches!( + wallet + .write_dashpay_profile(&identity_id, stale_input, &NoSigner, create) + .await, + Err(PlatformWalletError::WalletNotFound(_)) + )); + } + assert_eq!(manager.persister.stored_count(), after_replacement); + assert!(current + .state() + .await + .identity_manager + .managed_identity(&identity_id) + .is_none()); + } + } + + struct PausedProver { + reached: Mutex>>, + resume: Mutex>, + } + + impl OrchardProver for PausedProver { + fn proving_key(&self) -> &ProvingKey { + self.reached + .lock() + .unwrap() + .take() + .unwrap() + .send(()) + .unwrap(); + self.resume + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .unwrap(); + panic!("stop the proof after checking the teardown fence") + } + } + + async fn fund(wallet: &PlatformWallet, coordinator: &NetworkShieldedCoordinator, account: u32) { + let keys = OrchardKeySet::from_seed(&SEED, Network::Testnet, account).unwrap(); + let rho = Rho::from_bytes(&[1; 32]).into_option().unwrap(); + let rseed = RandomSeed::from_bytes([2; 32], &rho).into_option().unwrap(); + let note = Note::from_parts( + keys.default_address, + NoteValue::from_raw(1_000_000_000_000), + rho, + rseed, + ) + .into_option() + .unwrap(); + let mut note_data = Vec::new(); + note_data.extend_from_slice(¬e.recipient().to_raw_address_bytes()); + note_data.extend_from_slice(¬e.value().inner().to_le_bytes()); + note_data.extend_from_slice(¬e.rho().to_bytes()); + note_data.extend_from_slice(note.rseed().as_bytes()); + let note = ShieldedNote { + position: 0, + cmx: ExtractedNoteCommitment::from(note.commitment()).to_bytes(), + nullifier: note.nullifier(&keys.full_viewing_key).to_bytes(), + block_height: 1, + is_spent: false, + value: note.value().inner(), + note_data, + }; + let mut store = coordinator.store().write().await; + store.append_commitment(¬e.cmx, true).unwrap(); + store.checkpoint_tree(1).unwrap(); + store + .save_note(SubwalletId::new(wallet.wallet_id(), account), ¬e) + .unwrap(); + let anchor = store.tree_anchor().unwrap(); + drop(store); + let mut sdk = wallet.sdk().clone(); + sdk.mock() + .expect_fetch(NoParamQuery {}, Some(ShieldedAnchors(vec![anchor]))) + .await + .unwrap(); + sdk.mock().set_response_height_of::(10); + } + + async fn assert_teardown_waits_for_tip_proving(clear: bool) { + let (_dir, manager, wallet, coordinator) = fixture().await; + let recipient = mock_tip_recipient(&wallet).await; + fund(&wallet, &coordinator, 0).await; + let (reached_tx, reached_rx) = oneshot::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let prover = PausedProver { + reached: Mutex::new(Some(reached_tx)), + resume: Mutex::new(resume_rx), + }; + let sending = { + let wallet = Arc::clone(&wallet); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + AssertUnwindSafe(wallet.send_shielded_tip( + &coordinator, + &SEED, + ShieldedTipSource::Account(0), + "Alice.dash", + &recipient, + 100_000_000_000, + [0; 36], + prover, + )) + .catch_unwind() + .await + }) + }; + tokio::time::timeout(Duration::from_secs(10), reached_rx) + .await + .unwrap() + .unwrap(); + let wallet_id = wallet.wallet_id(); + let mut removing = { + let manager = Arc::clone(&manager); + tokio::spawn(async move { + if clear { + manager.clear_shielded().await.unwrap(); + } else { + manager.remove_wallet(&wallet_id).await.unwrap(); + } + manager.persister.stored.lock().unwrap().clear(); + manager + .persister + .durability_events + .lock() + .unwrap() + .push("host deletion"); + }) + }; + let early = tokio::time::timeout(Duration::from_millis(500), &mut removing).await; + resume_tx.send(()).unwrap(); + assert!( + sending.await.unwrap().is_err(), + "the prover stops at the test boundary" + ); + assert!(early.is_err(), "teardown must wait for proving"); + removing.await.unwrap(); + assert_eq!(wallet.core().is_current_generation().await, clear); + assert_eq!( + manager.persister.durability_events.lock().unwrap().last(), + Some(&"host deletion") + ); + assert_eq!(manager.persister.stored_count(), 0); + let store = coordinator.store().read().await; + let id = SubwalletId::new(wallet_id, 0); + assert!(store.get_all_notes(id).unwrap().is_empty()); + assert!(store.get_activity_ids(id).unwrap().is_empty()); + assert!(store.pending_redrives(id).unwrap().is_empty()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn should_hold_removal_until_tip_proving_returns() { + assert_teardown_waits_for_tip_proving(false).await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn should_hold_clear_until_tip_proving_returns() { + assert_teardown_waits_for_tip_proving(true).await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn should_refuse_stale_mutations_while_replacement_tip_source_is_locked() { + use crate::changeset::IdentityChangeSet; + use crate::wallet::identity::network::{ + derive_identity_auth_key_hash_from_master, IdentityDiscoveryOptions, MASTER_KEY_INDEX, + }; + use dash_sdk::platform::types::identity::PublicKeyHash; + use dpp::identity::{Identity, IdentityV0}; + use dpp::prelude::Identifier; + + let (_dir, manager, old, coordinator) = fixture().await; + manager.remove_wallet(&old.wallet_id()).await.unwrap(); + let current = add_wallet(&manager).await; + let identity_id = Identifier::from([0x66; 32]); + let identity = Identity::V0(IdentityV0 { + id: identity_id, + public_keys: seed_master_key(&SEED, 2), + balance: 0, + revision: 0, + }); + current + .state_mut() + .await + .unwrap() + .identity_manager + .add_identity( + identity.clone(), + 2, + current.wallet_id(), + current.persister(), + ) + .unwrap(); + current + .bind_shielded(&SEED, &[0], &coordinator) + .await + .unwrap(); + current + .prepare_shielded_identity_address(&SEED, &identity_id, &coordinator) + .await + .unwrap(); + fund( + ¤t, + &coordinator, + crate::shielded_identity_account_index(2).unwrap(), + ) + .await; + let recipient = mock_tip_recipient(¤t).await; + let master = + key_wallet::bip32::ExtendedPrivKey::new_master(Network::Testnet, &SEED).unwrap(); + let probe = derive_identity_auth_key_hash_from_master( + &master, + Network::Testnet, + 2, + MASTER_KEY_INDEX, + ) + .unwrap(); + let mut sdk = old.sdk().clone(); + sdk.mock() + .expect_fetch(PublicKeyHash(probe), Some(identity)) + .await + .unwrap(); + + let (reached, resume) = super::super::tips::test_hooks::pause_before_spend(¤t); + let (proof_reached_tx, proof_reached) = oneshot::channel(); + let (proof_resume_tx, proof_resume_rx) = std::sync::mpsc::channel(); + proof_resume_tx.send(()).unwrap(); + let prover = PausedProver { + reached: Mutex::new(Some(proof_reached_tx)), + resume: Mutex::new(proof_resume_rx), + }; + let sending = { + let current = Arc::clone(¤t); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + AssertUnwindSafe(current.send_shielded_tip( + &coordinator, + &SEED, + ShieldedTipSource::Identity(identity_id), + "Alice.dash", + &recipient, + 100_000_000_000, + [0; 36], + prover, + )) + .catch_unwind() + .await + }) + }; + tokio::time::timeout(Duration::from_secs(10), reached) + .await + .unwrap() + .unwrap(); + assert!( + current.try_state_mut().is_none(), + "the live placement gate is held" + ); + let before = manager.persister.stored_count(); + assert!(matches!( + old.state_mut().await, + Err(crate::PlatformWalletError::WalletNotFound(_)) + )); + assert!(old.try_state_mut().is_none()); + let blocking_old = Arc::clone(&old); + assert!(tokio::task::spawn_blocking(move || matches!( + blocking_old.state_mut_blocking(), + Err(crate::PlatformWalletError::WalletNotFound(_)) + )) + .await + .unwrap()); + let changeset = PlatformWalletChangeSet { + identities: Some(IdentityChangeSet { + removed: [identity_id].into(), + ..Default::default() + }), + ..Default::default() + }; + assert!(matches!( + old.apply(changeset).await, + Err(crate::wallet::ApplyError::WalletNotFound(_)) + )); + assert!(matches!( + old.identity() + .load_identity_by_index_from_master(2, &master) + .await, + Err(crate::PlatformWalletError::WalletNotFound(_)) + )); + assert!(matches!( + old.identity() + .discover_from_master( + IdentityDiscoveryOptions { + start_index: Some(2), + gap_limit: 1 + }, + &master, + ) + .await, + Err(crate::PlatformWalletError::WalletNotFound(_)) + )); + assert_eq!(manager.persister.stored_count(), before); + assert_eq!( + current + .state() + .await + .identity_manager + .identity_index(&identity_id), + Some(2) + ); + resume.send(()).unwrap(); + proof_reached.await.unwrap(); + assert!( + sending.await.unwrap().is_err(), + "the funded transfer reached the test prover" + ); + } + + #[tokio::test] + async fn should_refuse_tip_sends_from_a_removed_generation_after_same_id_recreation() { + let (_dir, manager, old, coordinator) = fixture().await; + let recipient = mock_tip_recipient(&old).await; + let wallet_id = old.wallet_id(); + manager.remove_wallet(&wallet_id).await.unwrap(); + let current = add_wallet(&manager).await; + assert_eq!(current.wallet_id(), wallet_id); + assert!(current.core().is_current_generation().await); + let result = old + .send_shielded_tip( + &coordinator, + &SEED, + ShieldedTipSource::Account(0), + "Alice.dash", + &recipient, + 1, + [0; 36], + &CachedOrchardProver::new(), + ) + .await; + assert!( + matches!( + result, + Err(crate::PlatformWalletError::WalletRemovedBeforeSend(_)) + ), + "{result:?}" + ); + let store = coordinator.store().read().await; + let id = SubwalletId::new(wallet_id, 0); + assert!(store.get_all_notes(id).unwrap().is_empty()); + assert!(store.get_activity_ids(id).unwrap().is_empty()); + assert!(store.pending_redrives(id).unwrap().is_empty()); + } +} diff --git a/packages/rs-sdk/src/platform/dashpay/mod.rs b/packages/rs-sdk/src/platform/dashpay/mod.rs index 83352890a63..b987c03cf8f 100644 --- a/packages/rs-sdk/src/platform/dashpay/mod.rs +++ b/packages/rs-sdk/src/platform/dashpay/mod.rs @@ -35,7 +35,7 @@ pub use private_contact_request::{ PRIVATE_CONTACT_REQUEST_AUTO_ACCEPT_PROOF_MIN_LEN, PRIVATE_CONTACT_REQUEST_DOCUMENT_TYPE_NAME, PRIVATE_CONTACT_REQUEST_SHIELDED_ADDRESS_LEN, PRIVATE_CONTACT_REQUEST_SIGNING_KEY_TYPES, }; -pub use profile::ProfileFields; +pub use profile::{PaymentAddressUpdate, ProfileFields}; use crate::{Error, Sdk}; use dpp::prelude::Identifier; diff --git a/packages/rs-sdk/src/platform/dashpay/profile.rs b/packages/rs-sdk/src/platform/dashpay/profile.rs index e0469af7f03..406cab5c048 100644 --- a/packages/rs-sdk/src/platform/dashpay/profile.rs +++ b/packages/rs-sdk/src/platform/dashpay/profile.rs @@ -35,13 +35,16 @@ const PROFILE_DOCUMENT_TYPE: &str = "profile"; /// cardinality cap, which is also the document-query limit. pub(crate) const MAX_PROFILE_OWNERS_PER_QUERY: usize = 100; -/// The profile fields a caller sets. `None` leaves the field alone on -/// [`Sdk::update_profile`] and omits it on [`Sdk::create_profile`]. +/// The profile fields a caller sets. `None` (or [`PaymentAddressUpdate::Keep`]) +/// leaves the field alone on [`Sdk::update_profile`] and omits it on +/// [`Sdk::create_profile`]. /// /// `avatar_hash` and `avatar_fingerprint` are computed by the caller from the /// avatar image bytes. An update that changes `avatar_url` must set both hashes -/// with it, and an update sets the two hashes together. A field cannot be -/// cleared. +/// with it, and an update sets the two hashes together. Only the payment +/// addresses can be cleared, through [`PaymentAddressUpdate::Remove`]. Address +/// bytes are sent as given; Platform enforces their length, and decoding them +/// (a transparent address type, an Orchard address) is the caller's check. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ProfileFields { /// Display name (1 to 25 chars per DIP-15) @@ -54,6 +57,25 @@ pub struct ProfileFields { pub avatar_hash: Option<[u8; 32]>, /// dHash perceptual fingerprint of the avatar image pub avatar_fingerprint: Option<[u8; 8]>, + /// `corePaymentAddress`: version byte and HASH160 + pub core_payment_address: PaymentAddressUpdate, + /// `platformPaymentAddress`: version byte and HASH160 + pub platform_payment_address: PaymentAddressUpdate, + /// `shieldedAddress`: raw 43-byte Orchard address + pub shielded_address: PaymentAddressUpdate, +} + +/// A change to one profile payment address. The default leaves a published +/// address alone, so omitting the field never removes it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum PaymentAddressUpdate { + /// Leave the address as it is + #[default] + Keep, + /// Publish these address bytes + Set(Vec), + /// Remove the published address + Remove, } impl ProfileFields { @@ -78,6 +100,21 @@ impl ProfileFields { Value::Bytes(fingerprint.to_vec()), ); } + for (field, update) in [ + ("corePaymentAddress", self.core_payment_address), + ("platformPaymentAddress", self.platform_payment_address), + ("shieldedAddress", self.shielded_address), + ] { + match update { + PaymentAddressUpdate::Keep => {} + PaymentAddressUpdate::Set(bytes) => { + properties.insert(field.to_string(), Value::Bytes(bytes)); + } + PaymentAddressUpdate::Remove => { + properties.remove(field); + } + } + } properties } } @@ -438,6 +475,71 @@ mod tests { ); } + /// Each payment address is kept, replaced or removed on its own, and an + /// update that names none of them keeps all three. + #[test] + fn should_keep_replace_and_remove_payment_addresses_independently() { + let (id, owner) = (Identifier::new([0xD2; 32]), Identifier::new([0x0F; 32])); + let contract = dashpay_contract(); + let original = ProfileFields { + display_name: Some("Alice".into()), + core_payment_address: PaymentAddressUpdate::Set(vec![0; 21]), + platform_payment_address: PaymentAddressUpdate::Set(vec![1; 21]), + shielded_address: PaymentAddressUpdate::Set(vec![2; 43]), + ..Default::default() + } + .overlay(BTreeMap::new()); + let existing = profile_document(id, owner, original.clone(), Some(1)); + + let renamed = ProfileFields { + display_name: Some("Alice II".into()), + ..Default::default() + }; + let renamed = replacement_document(&existing, renamed, &contract).unwrap(); + for field in [ + "corePaymentAddress", + "platformPaymentAddress", + "shieldedAddress", + ] { + assert_eq!( + renamed.properties().get(field).map(Value::to_bytes), + original.get(field).map(Value::to_bytes), + "{field}" + ); + } + + let changed = ProfileFields { + shielded_address: PaymentAddressUpdate::Set(vec![3; 43]), + core_payment_address: PaymentAddressUpdate::Remove, + ..Default::default() + }; + let changed = replacement_document(&renamed, changed, &contract).unwrap(); + let merged = changed.properties(); + assert!(!merged.contains_key("corePaymentAddress")); + assert_eq!( + merged.get("platformPaymentAddress").map(Value::to_bytes), + Some(Ok(vec![1; 21])) + ); + assert_eq!( + merged.get("shieldedAddress").map(Value::to_bytes), + Some(Ok(vec![3; 43])) + ); + assert_eq!(text(merged, "displayName"), Some("Alice II")); + } + + /// Removing an address on create just leaves it out. + #[test] + fn should_omit_a_removed_payment_address_on_create() { + let fields = ProfileFields { + display_name: Some("Alice".into()), + shielded_address: PaymentAddressUpdate::Remove, + ..Default::default() + }; + let properties = fields.overlay(BTreeMap::new()); + assert_eq!(properties.len(), 1); + assert_eq!(text(&properties, "displayName"), Some("Alice")); + } + /// A supplied avatar hash and fingerprint replace the existing ones. #[test] fn should_replace_the_avatar_when_supplied() { diff --git a/packages/rs-unified-sdk-jni/src/dashpay.rs b/packages/rs-unified-sdk-jni/src/dashpay.rs index b240a4f261a..ae5fabe16de 100644 --- a/packages/rs-unified-sdk-jni/src/dashpay.rs +++ b/packages/rs-unified-sdk-jni/src/dashpay.rs @@ -661,6 +661,12 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_DashpayNative_createO avatar_bytes: JByteArray, do_create: jboolean, signer_handle: jlong, + core_action: jint, + core_address: JByteArray, + platform_action: jint, + platform_address: JByteArray, + shielded_action: jint, + shielded_address: JByteArray, ) -> jstring { guard(&mut env, ptr::null_mut(), |env| { let Some(id) = read_id32(env, &identity_id, "identityId") else { @@ -691,9 +697,34 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_DashpayNative_createO } }; + let address_bytes = [&core_address, &platform_address, &shielded_address] + .into_iter() + .map(|address| { + if address.is_null() { + Ok(Vec::new()) + } else { + env.convert_byte_array(address) + } + }) + .collect::, _>>(); + let address_bytes = match address_bytes { + Ok(bytes) => bytes, + Err(_) => { + crate::support::throw_sdk_exception(env, 1, "Unreadable payment address"); + return ptr::null_mut(); + } + }; + let actions = [core_action, platform_action, shielded_action]; + let updates: [_; 3] = std::array::from_fn(|index| { + platform_wallet_ffi::dashpay_profile::PaymentAddressUpdateFFI { + action: actions[index] as u32, + bytes: address_bytes[index].as_ptr(), + len: address_bytes[index].len(), + } + }); let mut profile = DashPayProfileFFI::empty(); let result = unsafe { - platform_wallet_ffi::platform_wallet_create_or_update_dashpay_profile_with_signer( + platform_wallet_ffi::platform_wallet_create_or_update_dashpay_profile_with_addresses_with_signer( wallet_handle as Handle, id.as_ptr(), display.as_ref().map_or(ptr::null(), |c| c.as_ptr()), @@ -701,6 +732,9 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_DashpayNative_createO url.as_ref().map_or(ptr::null(), |c| c.as_ptr()), avatar.as_ref().map_or(ptr::null(), |v| v.as_ptr()), avatar.as_ref().map_or(0, |v| v.len()), + &updates[0], + &updates[1], + &updates[2], do_create != 0, signer_handle as *mut SignerHandle, &mut profile as *mut DashPayProfileFFI, diff --git a/packages/rs-unified-sdk-jni/src/funding.rs b/packages/rs-unified-sdk-jni/src/funding.rs index 1c7bff45acc..e32ce7a43bb 100644 --- a/packages/rs-unified-sdk-jni/src/funding.rs +++ b/packages/rs-unified-sdk-jni/src/funding.rs @@ -1259,3 +1259,174 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_shielde let _ = take_pwffi_error(env, result); }) } + +/// Dedicated identity shielded account preparation; returns the complete raw Orchard address. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_prepareShieldedIdentityAddress( + mut env: JNIEnv, + _class: JClass, + manager: jlong, + wallet_id: JByteArray, + resolver: jlong, + identity_id: JByteArray, +) -> jni::sys::jbyteArray { + guard(&mut env, ptr::null_mut(), |env| { + let Some(wid) = read_id32(env, &wallet_id, "walletId") else { + return ptr::null_mut(); + }; + let Some(id) = read_id32(env, &identity_id, "identityId") else { + return ptr::null_mut(); + }; + let mut address = [0; 43]; + let result = unsafe { + platform_wallet_ffi::platform_wallet_manager_prepare_shielded_identity_address( + manager as Handle, + wid.as_ptr(), + resolver as *mut MnemonicResolverHandle, + id.as_ptr(), + address.as_mut_ptr(), + ) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + env.byte_array_from_slice(&address) + .map(|a| a.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + +/// Current verified recipient: 32-byte identity ID followed by 43-byte address. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_resolveShieldedTip( + mut env: JNIEnv, + _class: JClass, + wallet: jlong, + username: JString, +) -> jni::sys::jbyteArray { + guard(&mut env, ptr::null_mut(), |env| { + let username = match read_cstring_opt(env, &username, "username") { + Ok(Some(name)) => name, + _ => { + throw_sdk_exception(env, 1, "username is required"); + return ptr::null_mut(); + } + }; + let mut recipient = [0; 75]; + let result = unsafe { + platform_wallet_ffi::platform_wallet_resolve_shielded_tip( + wallet as Handle, + username.as_ptr(), + recipient.as_mut_ptr(), + recipient.as_mut_ptr().add(32), + ) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + env.byte_array_from_slice(&recipient) + .map(|a| a.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + +/// Revalidates the confirmed recipient before spending. A non-null +/// `source_identity_id` spends that identity's dedicated tip account and +/// `source_account` is ignored; otherwise `source_account` is spent. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_sendShieldedTip( + mut env: JNIEnv, + _class: JClass, + manager: jlong, + wallet_id: JByteArray, + resolver: jlong, + source_identity_id: JByteArray, + source_account: jint, + username: JString, + expected_id: JByteArray, + expected_address: JByteArray, + amount: jlong, + memo: JString, +) { + guard(&mut env, (), |env| { + if source_account < 0 || amount <= 0 { + throw_sdk_exception(env, 1, "Invalid account or amount"); + return; + } + let Some(wid) = read_id32(env, &wallet_id, "walletId") else { + return; + }; + let source = if source_identity_id.is_null() { + platform_wallet_ffi::ShieldedTipSourceFFI { + kind: platform_wallet_ffi::SHIELDED_TIP_SOURCE_ACCOUNT, + identity_id: [0; 32], + account: source_account as u32, + } + } else { + let Some(identity_id) = read_id32(env, &source_identity_id, "sourceIdentityId") else { + return; + }; + platform_wallet_ffi::ShieldedTipSourceFFI { + kind: platform_wallet_ffi::SHIELDED_TIP_SOURCE_IDENTITY, + identity_id, + account: 0, + } + }; + let Some(id) = read_id32(env, &expected_id, "expectedIdentityId") else { + return; + }; + let Some(address) = read_recipient43(env, &expected_address) else { + return; + }; + let username = match read_cstring_opt(env, &username, "username") { + Ok(Some(name)) => name, + _ => { + throw_sdk_exception(env, 1, "username is required"); + return; + } + }; + let memo = match read_cstring_opt(env, &memo, "memo") { + Ok(value) => value, + Err(()) => return, + }; + let result = unsafe { + platform_wallet_ffi::platform_wallet_manager_send_shielded_tip( + manager as Handle, + wid.as_ptr(), + resolver as *mut MnemonicResolverHandle, + &source, + username.as_ptr(), + id.as_ptr(), + address.as_ptr(), + amount as u64, + memo.as_ref().map_or(ptr::null(), |m| m.as_ptr()), + ) + }; + let _ = take_pwffi_error(env, result); + }) +} + +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_identityAccountIndex( + mut env: JNIEnv, + _class: JClass, + identity_index: jint, +) -> jint { + guard(&mut env, -1, |env| { + if identity_index < 0 { + throw_sdk_exception(env, 1, "identity index must be non-negative"); + return -1; + } + let mut account = 0; + let result = unsafe { + platform_wallet_ffi::platform_wallet_shielded_identity_account_index( + identity_index as u32, + &mut account, + ) + }; + if take_pwffi_error(env, result) { + return -1; + } + account as jint + }) +} diff --git a/packages/rs-unified-sdk-jni/src/persistence.rs b/packages/rs-unified-sdk-jni/src/persistence.rs index 86a38c3329e..5803d268265 100644 --- a/packages/rs-unified-sdk-jni/src/persistence.rs +++ b/packages/rs-unified-sdk-jni/src/persistence.rs @@ -53,11 +53,11 @@ use jni::sys::jstring; use jni::JNIEnv; use platform_wallet_ffi::{ AccountAddressPoolFFI, AccountChangeSetFFI, AccountSpecFFI, AddressBalanceEntryFFI, - AssetLockEntryFFI, ContactIgnoredSenderFFI, ContactProfileRestoreEntryFFI, ContactRequestFFI, - ContactRequestRemovalFFI, CoreAddressEntryFFI, DashPayBackfillCoveredContactFFI, - DpnsNameStateFFI, IdentityEntryFFI, IdentityKeyEntryFFI, IdentityKeyRemovalFFI, - IdentityKeyRestoreFFI, IdentityRestoreEntryFFI, InvitationEntryFFI, OutPointFFI, - PaymentRestoreEntryFFI, PersistenceCallbacks, PersistenceCallbacksExtension, + AssetLockEntryFFI, ContactIgnoredSenderFFI, ContactProfileRestoreEntryFFI, + ContactProfileRowFFI, ContactRequestFFI, ContactRequestRemovalFFI, CoreAddressEntryFFI, + DashPayBackfillCoveredContactFFI, DpnsNameStateFFI, IdentityEntryFFI, IdentityKeyEntryFFI, + IdentityKeyRemovalFFI, IdentityKeyRestoreFFI, IdentityRestoreEntryFFI, InvitationEntryFFI, + OutPointFFI, PaymentRestoreEntryFFI, PersistenceCallbacks, PersistenceCallbacksExtension, PlatformAddressFFI, PrivateContactRequestsPositionFFI, PrivateShieldedAddressFFI, ProviderSpecialTxRestoreEntryFFI, SpentOutPointFFI, SweepBatchFFI, TokenBalanceRemovalFFI, TokenBalanceUpsertFFI, TransactionRecordFFI, UnresolvedAssetLockTxRecordFFI, UtxoEntryFFI, @@ -226,6 +226,12 @@ pub(crate) fn build_vtable(context: *mut c_void) -> PersistenceCallbacks { /// publication fails closed. pub(crate) fn build_extension(env: &mut JNIEnv, bridge: &JObject) -> PersistenceCallbacksExtension { extension_for(BridgeOverrides { + dashpay_profiles: bridge_overrides( + env, + bridge, + "onPersistDashpayProfile", + PERSIST_DASHPAY_PROFILE_DESCRIPTOR, + ), sweeps: bridge_overrides( env, bridge, @@ -328,6 +334,7 @@ struct BridgeOverrides { /// vouches for the contact requests read before it, which an inherited /// no-op contact upsert never keeps. private_contact_scan_state: bool, + dashpay_profiles: bool, } /// The extension slots wired for a bridge with `overrides` (see @@ -335,6 +342,9 @@ struct BridgeOverrides { fn extension_for(overrides: BridgeOverrides) -> PersistenceCallbacksExtension { PersistenceCallbacksExtension { on_persist_dpns_name_states_fn: Some(tramp_persist_dpns_name_states), + on_persist_dashpay_profiles_fn: overrides + .dashpay_profiles + .then_some(tramp_persist_dashpay_profiles), on_persist_wallet_changeset_sweeps_fn: if overrides.sweeps { Some(tramp_persist_wallet_changeset_sweeps) } else { @@ -1739,13 +1749,28 @@ unsafe fn persist_identity_upsert( let public_message = cstr_opt(env, e.dashpay_profile_public_message)?; let avatar_hash = env.byte_array_from_slice(&e.dashpay_profile_avatar_hash)?; let avatar_fp = env.byte_array_from_slice(&e.dashpay_profile_avatar_fingerprint)?; + let core_payment_address = if e.dashpay_profile_core_payment_address_present { + JObject::from(env.byte_array_from_slice(&e.dashpay_profile_core_payment_address)?) + } else { + JObject::null() + }; + let platform_payment_address = if e.dashpay_profile_platform_payment_address_present { + JObject::from(env.byte_array_from_slice(&e.dashpay_profile_platform_payment_address)?) + } else { + JObject::null() + }; + let shielded_address = if e.dashpay_profile_shielded_address_present { + JObject::from(env.byte_array_from_slice(&e.dashpay_profile_shielded_address)?) + } else { + JObject::null() + }; let code = env .call_method( bridge, "onPersistIdentityUpsert", "([B[BJJZIBZ[B[Ljava/lang/String;[JZLjava/lang/String;Ljava/lang/String;\ - Ljava/lang/String;[BZ[BZLjava/lang/String;)I", + Ljava/lang/String;[BZ[BZLjava/lang/String;[B[B[B)I", &[ wid.into(), (&identity_id).into(), @@ -1767,6 +1792,9 @@ unsafe fn persist_identity_upsert( (&avatar_fp).into(), JValue::Bool(e.dashpay_profile_avatar_fingerprint_present as u8), (&public_message).into(), + (&core_payment_address).into(), + (&platform_payment_address).into(), + (&shielded_address).into(), ], )? .i()?; @@ -1790,11 +1818,26 @@ unsafe fn persist_identity_upsert( let public_message = cstr_opt(env, row.public_message)?; let avatar_hash = env.byte_array_from_slice(&row.avatar_hash)?; let avatar_fp = env.byte_array_from_slice(&row.avatar_fingerprint)?; + let core_payment_address = if row.core_payment_address_present { + JObject::from(env.byte_array_from_slice(&row.core_payment_address)?) + } else { + JObject::null() + }; + let platform_payment_address = if row.platform_payment_address_present { + JObject::from(env.byte_array_from_slice(&row.platform_payment_address)?) + } else { + JObject::null() + }; + let shielded_address = if row.shielded_address_present { + JObject::from(env.byte_array_from_slice(&row.shielded_address)?) + } else { + JObject::null() + }; env.call_method( bridge, "onPersistContactProfileDelta", "([B[B[BZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;\ - [BZ[BZLjava/lang/String;J)I", + [BZ[BZLjava/lang/String;J[B[B[B)I", &[ wid.into(), (&identity_id).into(), @@ -1809,6 +1852,9 @@ unsafe fn persist_identity_upsert( JValue::Bool(row.avatar_fingerprint_present as u8), (&public_message).into(), JValue::Long(row.checked_at_ms as i64), + (&core_payment_address).into(), + (&platform_payment_address).into(), + (&shielded_address).into(), ], )? .i() @@ -1820,6 +1866,72 @@ unsafe fn persist_identity_upsert( Ok(0) } +const PERSIST_DASHPAY_PROFILE_DESCRIPTOR: &str = + "([B[BZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[BZ[BZLjava/lang/String;[B[B[B)I"; + +unsafe extern "C" fn tramp_persist_dashpay_profiles( + context: *mut c_void, + wallet_id: *const u8, + rows_ptr: *const ContactProfileRowFFI, + rows_count: usize, +) -> i32 { + with_bridge(context, |env, bridge| { + let wid = id32(env, wallet_id)?; + for row in slice_or_empty(rows_ptr, rows_count) { + let code = env.with_local_frame(16, |env| { + let contact_id = env.byte_array_from_slice(&row.contact_id)?; + let display = cstr_opt(env, row.display_name)?; + let bio = cstr_opt(env, row.bio)?; + let avatar_url = cstr_opt(env, row.avatar_url)?; + let public_message = cstr_opt(env, row.public_message)?; + let avatar_hash = env.byte_array_from_slice(&row.avatar_hash)?; + let avatar_fp = env.byte_array_from_slice(&row.avatar_fingerprint)?; + let core_payment_address = if row.core_payment_address_present { + JObject::from(env.byte_array_from_slice(&row.core_payment_address)?) + } else { + JObject::null() + }; + let platform_payment_address = if row.platform_payment_address_present { + JObject::from(env.byte_array_from_slice(&row.platform_payment_address)?) + } else { + JObject::null() + }; + let shielded_address = if row.shielded_address_present { + JObject::from(env.byte_array_from_slice(&row.shielded_address)?) + } else { + JObject::null() + }; + env.call_method( + bridge, + "onPersistDashpayProfile", + PERSIST_DASHPAY_PROFILE_DESCRIPTOR, + &[ + (&wid).into(), + (&contact_id).into(), + JValue::Bool(row.is_present as u8), + (&display).into(), + (&bio).into(), + (&avatar_url).into(), + (&avatar_hash).into(), + JValue::Bool(row.avatar_hash_present as u8), + (&avatar_fp).into(), + JValue::Bool(row.avatar_fingerprint_present as u8), + (&public_message).into(), + (&core_payment_address).into(), + (&platform_payment_address).into(), + (&shielded_address).into(), + ], + )? + .i() + })?; + if code != 0 { + return Ok(code); + } + } + Ok(0) + }) +} + // ── Identity keys ───────────────────────────────────────────────────── unsafe extern "C" fn tramp_persist_identity_keys( @@ -2667,6 +2779,7 @@ struct IdentityRestoreStaged { ignored_senders: Vec<[u8; 32]>, payments: Vec, contact_profiles: Vec, + dashpay_profile: Option, } /// Staged DashPay payment-history row: FFI struct with `txid` / `memo` @@ -2695,6 +2808,21 @@ struct ContactProfileRestoreStaged { public_message: Option, } +fn seal_profile(profile: ContactProfileRestoreStaged) -> ContactProfileRestoreEntryFFI { + let ContactProfileRestoreStaged { + mut row, + display_name, + bio, + avatar_url, + public_message, + } = profile; + row.display_name = opt_cstring_into_raw(display_name); + row.bio = opt_cstring_into_raw(bio); + row.avatar_url = opt_cstring_into_raw(avatar_url); + row.public_message = opt_cstring_into_raw(public_message); + row +} + /// Staged DashPay contact-restore row: FFI struct with every pointer /// field still null / 0 until sealed, plus the owned buffers that back /// them. Mirrors the Swift `buildIdentityRestoreBuffer` contact block: @@ -2888,6 +3016,7 @@ fn seal_wallet_entries(staged: Vec) -> Vec = keys .into_iter() @@ -2960,26 +3089,12 @@ fn seal_wallet_entries(staged: Vec) -> Vec = - contact_profiles - .into_iter() - .map( - |ContactProfileRestoreStaged { - mut row, - display_name, - bio, - avatar_url, - public_message, - }| { - row.display_name = opt_cstring_into_raw(display_name); - row.bio = opt_cstring_into_raw(bio); - row.avatar_url = opt_cstring_into_raw(avatar_url); - row.public_message = - opt_cstring_into_raw(public_message); - row - }, - ) - .collect(); + contact_profiles.into_iter().map(seal_profile).collect(); (entry.contact_profiles, entry.contact_profiles_count) = vec_into_raw(contact_profiles); entry @@ -3845,6 +3960,18 @@ fn build_identity_restore( contact_profiles.push(cp); } + let owned_profile = env + .get_field( + holder, + "dashpayProfile", + "Lorg/dashfoundation/dashsdk/ffi/ContactProfileRestoreData;", + )? + .l()?; + let dashpay_profile = if owned_profile.is_null() { + None + } else { + Some(build_contact_profile_restore(env, &owned_profile)?) + }; let entry = IdentityRestoreEntryFFI { identity_id, balance, @@ -3865,6 +3992,7 @@ fn build_identity_restore( ignored_senders_count: 0, contact_profiles: ptr::null(), contact_profiles_count: 0, + dashpay_profile: ptr::null(), }; Ok(IdentityRestoreStaged { entry, @@ -3873,6 +4001,7 @@ fn build_identity_restore( ignored_senders, payments, contact_profiles, + dashpay_profile, }) } @@ -3941,6 +4070,24 @@ fn build_contact_profile_restore( Err(_) => ([0u8; 8], false), }; + let bytes = read_bytes_field_vec(env, holder, "corePaymentAddress")?; + let (core_payment_address, core_payment_address_present) = + match <[u8; 21]>::try_from(bytes.as_slice()) { + Ok(value) => (value, true), + Err(_) => ([0; 21], false), + }; + let bytes = read_bytes_field_vec(env, holder, "platformPaymentAddress")?; + let (platform_payment_address, platform_payment_address_present) = + match <[u8; 21]>::try_from(bytes.as_slice()) { + Ok(value) => (value, true), + Err(_) => ([0; 21], false), + }; + let bytes = read_bytes_field_vec(env, holder, "shieldedAddress")?; + let (shielded_address, shielded_address_present) = match <[u8; 43]>::try_from(bytes.as_slice()) + { + Ok(value) => (value, true), + Err(_) => ([0; 43], false), + }; Ok(ContactProfileRestoreStaged { row: ContactProfileRestoreEntryFFI { contact_id, @@ -3951,6 +4098,12 @@ fn build_contact_profile_restore( avatar_hash_present, avatar_fingerprint, avatar_fingerprint_present, + core_payment_address, + core_payment_address_present, + platform_payment_address, + platform_payment_address_present, + shielded_address, + shielded_address_present, public_message: ptr::null(), checked_at_ms, }, @@ -4307,6 +4460,16 @@ unsafe extern "C" fn tramp_load_wallet_list_free( e.identities_count, )); for ident in idents.iter() { + if !ident.dashpay_profile.is_null() { + let profile = Box::from_raw( + ident.dashpay_profile as *mut ContactProfileRestoreEntryFFI, + ); + free_raw_cstring(profile.display_name); + free_raw_cstring(profile.bio); + free_raw_cstring(profile.avatar_url); + free_raw_cstring(profile.public_message); + } + if !ident.keys.is_null() && ident.keys_count > 0 { let keys: Box<[IdentityKeyRestoreFFI]> = Box::from_raw(std::ptr::slice_from_raw_parts_mut( @@ -5185,6 +5348,10 @@ fn read_bytes_field_vec( /// [`nativeVerifyPersistenceBridgeDescriptors`] resolves the whole table up /// front instead; keep this table in sync with the `call_method` sites. const BRIDGE_METHOD_TABLE: &[(&str, &str)] = &[ + ( + "onPersistDashpayProfile", + PERSIST_DASHPAY_PROFILE_DESCRIPTOR, + ), ("persistenceCapabilitiesVersion", "()I"), ("persistenceCapabilitiesBits", "()J"), ("onChangesetBegin", "([B)I"), @@ -5253,13 +5420,13 @@ const BRIDGE_METHOD_TABLE: &[(&str, &str)] = &[ ( "onPersistIdentityUpsert", "([B[BJJZIBZ[B[Ljava/lang/String;[JZLjava/lang/String;Ljava/lang/String;\ - Ljava/lang/String;[BZ[BZLjava/lang/String;)I", + Ljava/lang/String;[BZ[BZLjava/lang/String;[B[B[B)I", ), ("onPersistIdentityRemoval", "([B[B)I"), ( "onPersistContactProfileDelta", "([B[B[BZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;\ - [BZ[BZLjava/lang/String;J)I", + [BZ[BZLjava/lang/String;J[B[B[B)I", ), ("onPersistIdentityKeyUpsert", IDENTITY_KEY_UPSERT_DESCRIPTOR), ("onPersistIdentityKeyRemoval", "([B[BI)I"), @@ -5473,6 +5640,7 @@ mod tests { header, backfill, private_contact_scan_state: false, + dashpay_profiles: false, }); assert_eq!( extension.on_persist_wallet_dashpay_backfill_fn.is_some(), @@ -5485,6 +5653,7 @@ mod tests { header: false, backfill: false, private_contact_scan_state: false, + dashpay_profiles: false, }); assert!(sweeps_only.on_persist_wallet_changeset_sweeps_fn.is_some()); assert!(sweeps_only.on_persist_wallet_dashpay_backfill_fn.is_none()); @@ -5502,6 +5671,7 @@ mod tests { header: false, backfill: false, private_contact_scan_state: wired, + dashpay_profiles: false, }); assert_eq!( extension.on_persist_private_contact_scan_state_fn.is_some(), @@ -5648,6 +5818,47 @@ mod tests { assert!(jint_height(u32::MAX).is_err()); } + #[test] + fn should_negotiate_only_overridden_dashpay_profile_callback_and_match_descriptor() { + let names = [ + "[B", + "[B", + "boolean", + "java.lang.String", + "java.lang.String", + "java.lang.String", + "[B", + "boolean", + "[B", + "boolean", + "java.lang.String", + "[B", + "[B", + "[B", + ] + .into_iter() + .map(str::to_owned) + .collect::>(); + assert_eq!( + method_descriptor(&names, "int"), + PERSIST_DASHPAY_PROFILE_DESCRIPTOR + ); + assert!(BRIDGE_METHOD_TABLE.contains(&( + "onPersistDashpayProfile", + PERSIST_DASHPAY_PROFILE_DESCRIPTOR + ))); + for wired in [false, true] { + let extension = extension_for(BridgeOverrides { + sweeps: false, + header: false, + backfill: false, + private_contact_scan_state: false, + dashpay_profiles: wired, + }); + assert_eq!(extension.on_persist_dashpay_profiles_fn.is_some(), wired); + } + } + #[test] fn sweeps_callback_descriptor_ships_flat_arrays_and_an_explicit_height_pair() { // walletId, packed txids + count, winner, packed released outpoints diff --git a/packages/rs-unified-sdk-jni/src/tokens.rs b/packages/rs-unified-sdk-jni/src/tokens.rs index 438c10a45cf..7616e3be820 100644 --- a/packages/rs-unified-sdk-jni/src/tokens.rs +++ b/packages/rs-unified-sdk-jni/src/tokens.rs @@ -1583,6 +1583,42 @@ pub(crate) fn profile_to_json(profile: &DashPayProfileFFI) -> String { .collect(); fields.push(format!("\"avatarFingerprint\":{}", json_string(&hex))); } + if profile.core_payment_address_is_some { + fields.push(format!( + "\"corePaymentAddress\":{}", + json_string( + &profile + .core_payment_address + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ) + )); + } + if profile.platform_payment_address_is_some { + fields.push(format!( + "\"platformPaymentAddress\":{}", + json_string( + &profile + .platform_payment_address + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ) + )); + } + if profile.shielded_address_is_some { + fields.push(format!( + "\"shieldedAddress\":{}", + json_string( + &profile + .shielded_address + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ) + )); + } format!("{{{}}}", fields.join(",")) } @@ -2082,7 +2118,19 @@ mod tests { profile.avatar_hash[31] = 0x01; profile.avatar_fingerprint_is_some = true; profile.avatar_fingerprint = [0x10, 0x20, 0, 0, 0, 0, 0, 0xFF]; + profile.core_payment_address_is_some = true; + profile.core_payment_address = [1; 21]; + profile.platform_payment_address_is_some = true; + profile.platform_payment_address = [2; 21]; + profile.shielded_address_is_some = true; + profile.shielded_address = [3; 43]; let json = profile_to_json(&profile); + assert!(json.contains(&format!("\"corePaymentAddress\":\"{}\"", "01".repeat(21)))); + assert!(json.contains(&format!( + "\"platformPaymentAddress\":\"{}\"", + "02".repeat(21) + ))); + assert!(json.contains(&format!("\"shieldedAddress\":\"{}\"", "03".repeat(43)))); // 32-byte hash: 0xAB … 0x01 → "ab" prefix, "01" suffix (64 hex chars). assert!(json.contains("\"avatarHash\":\"ab"), "got {json}"); assert!(json.contains("01\""), "hash suffix; got {json}"); diff --git a/packages/swift-sdk/SCHEMA_RELEASES.md b/packages/swift-sdk/SCHEMA_RELEASES.md index bc9c7f29453..7c6213f711a 100644 --- a/packages/swift-sdk/SCHEMA_RELEASES.md +++ b/packages/swift-sdk/SCHEMA_RELEASES.md @@ -4,8 +4,13 @@ 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. 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. +model checksum match the observed App Store 9.0.2 database. App Store schemas +3.0.0 and 4.0.0 are published; `DashSchemaV3` and `DashSchemaV4` are bound to +`DashSchemaSnapshotV3` and `DashSchemaSnapshotV4`. Active models are V5, which +adds the optional asset-lock shielded funding recipient, private contact request +scan positions and private shielded addresses, and the +`PersistentDashpayPaymentAddresses` entity. Published V4 retains its optional +asset-lock operation id. 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 @@ -15,26 +20,23 @@ 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 +The main migration plan is historical V2 → V3 → V4 → V5. Accepted V1 has a separate +V1 → V3 → V4 → V5 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 published V3 snapshot exactly, entity hashes and checksum alike; any other +store labelled `2.0.0` is `unsupported-v2` and fails closed. 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`, `published-v3-to-v4`, `published-v4-to-v5`, -`labelled-current-v5`, `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 +`labelled-current-v5`, `ordinary-current-plan` or, from the bridge, +`legacy-v1-bridge-to-v3` (each route continues through the registered stages to +the live version). 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`); `3.0.0`, `4.0.0` and `5.0.0` labels take 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. @@ -138,9 +140,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 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 +Keep the bridge for installations that skip the V3 app release. `DashSchemaV3` +is bound to its released snapshot, and the bridge keeps it as its fixed target +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. diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacyStoreSQLite.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacyStoreSQLite.swift index cad4a7bab20..1214428de61 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacyStoreSQLite.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacyStoreSQLite.swift @@ -215,18 +215,52 @@ enum DashLegacyStoreSQLite { } for (name, table) in before.tables { guard let next = after.tables[name] else { throw Failure.unsupported("Migration removed table \(name)") } - let names = table.columns.keys.sorted() - for name in names { - guard let nextColumn = next.columns[name], nextColumn.declaredType == table.columns[name]?.declaredType else { + // Compare columns by entity name, not ordinal: adding an entity + // renumbers the ones sorted after it, which renames generated + // columns such as `Z13TOKENBALANCES` to `Z14TOKENBALANCES`. + let oldColumns = try ordinalKeyedColumns(table, entities: before.entities) + let newColumns = try ordinalKeyedColumns(next, entities: after.entities) + let keys = oldColumns.keys.sorted() + for key in keys { + guard let nextColumn = newColumns[key], nextColumn.declaredType == oldColumns[key]?.declaredType else { throw Failure.unsupported("Migration removed or converted a column in \(table.actual)") } } - let oldDigest = try rowsDigest(old, table: table, names: names, entities: before.entities) - let newDigest = try rowsDigest(new, table: next, names: names, entities: after.entities) + let oldDigest = try rowsDigest(old, table: table, names: keys.compactMap { oldColumns[$0]?.normalized }, + entities: before.entities) + let newDigest = try rowsDigest(new, table: next, names: keys.compactMap { newColumns[$0]?.normalized }, + entities: after.entities) guard oldDigest == newDigest else { throw Failure.unsupported("Migration changed existing data in \(name)") } } } + /// Re-key a table's columns so the entity ordinal Core Data embeds in a + /// generated column name (`Z`, e.g. a to-many inverse's + /// foreign key) is replaced by the entity's name. Attribute columns are + /// `Z` plus a property name, which cannot start with a digit, so only + /// generated columns match. Used for cross-store comparison only: the + /// persisted recovery evidence keeps `layout`'s keys unchanged so journals + /// written by earlier builds still verify. + private static func ordinalKeyedColumns(_ table: Table, entities: [Int64: String]) throws -> [String: Column] { + var keyed: [String: Column] = [:] + for (name, column) in table.columns { + var key = name + if name.hasPrefix("Z"), !name.hasPrefix("Z_") { + let suffix = name.dropFirst() + let digits = suffix.prefix(while: { $0.isNumber }) + if !digits.isEmpty { + guard let number = Int64(digits), let entity = entities[number] else { + throw Failure.unsupported("Unknown entity ordinal in column \(table.actual)") + } + key = "Z{" + entity + "}" + suffix.dropFirst(digits.count) + } + } + guard keyed[key] == nil else { throw Failure.unsupported("Ambiguous Core Data column name") } + keyed[key] = column + } + return keyed + } + private static func layout(_ connection: Connection) throws -> Layout { var entities: [Int64: String] = [:] try connection.query("SELECT Z_ENT, Z_NAME FROM Z_PRIMARYKEY") { diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift index d41f20aba2a..985f4cb7656 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift @@ -96,7 +96,8 @@ public enum DashModelContainer { PersistentTrackedMasternode.self, PersistentIdentityBalanceMetadata.self, PersistentPrivateContactRequestsPosition.self, - PersistentPrivateShieldedAddress.self + PersistentPrivateShieldedAddress.self, + PersistentDashpayPaymentAddresses.self ] } @@ -399,6 +400,8 @@ public enum DashSchemaV4: VersionedSchema { /// Current schema: an asset lock records the optional Orchard recipient of its /// shielded funding, and the private contact request sync keeps its scan state /// (each identity's read position and its private contacts' shielded addresses). +/// DashPay payment addresses are stored in their own entity, leaving the +/// published profile entities unchanged. public enum DashSchemaV5: VersionedSchema { public static var versionIdentifier: Schema.Version { Schema.Version(5, 0, 0) } public static var models: [any PersistentModel.Type] { DashModelContainer.modelTypes } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayContactProfile.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayContactProfile.swift index 3106c69cc04..5bbbf4173b3 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayContactProfile.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayContactProfile.swift @@ -11,7 +11,7 @@ import SwiftData /// without re-fetching on every launch. The cache is /// relationship-independent — it serves established contacts, pending /// incoming-request senders, and (later) ignored senders from one table, -/// matching the Rust map. It holds **only the five public profile +/// matching the Rust map. It holds **only the public profile /// fields** parsed from the on-chain `profile` document; it must never /// receive anything derived from the encrypted `contactInfo` path. /// @@ -176,3 +176,16 @@ extension PersistentDashpayContactProfile { } } } + +// Address metadata is stored separately so released profile/identity relationships +// retain their SwiftData schema identity across upgrades. +extension PersistentDashpayContactProfile { + private var paymentAddresses: PersistentDashpayPaymentAddresses? { + guard let modelContext else { return nil } + return try? PersistentDashpayPaymentAddresses.fetch(in: modelContext, networkRaw: networkRaw, + ownerIdentityId: ownerIdentityId, profileIdentityId: contactIdentityId) + } + public var corePaymentAddress: Data? { paymentAddresses?.corePaymentAddress } + public var platformPaymentAddress: Data? { paymentAddresses?.platformPaymentAddress } + public var shieldedAddress: Data? { paymentAddresses?.shieldedAddress } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayPaymentAddresses.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayPaymentAddresses.swift new file mode 100644 index 00000000000..3bf115ecba2 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayPaymentAddresses.swift @@ -0,0 +1,63 @@ +import Foundation +import SwiftData + +/// Raw payment addresses for an owned or cached contact profile. Keeping this +/// metadata independent preserves the released profile/identity relationship schema. +@Model +public final class PersistentDashpayPaymentAddresses { + #Unique([\.networkRaw, \.ownerIdentityId, \.profileIdentityId]) + + public var networkRaw: UInt32 + public var ownerIdentityId: Data + public var profileIdentityId: Data + public var corePaymentAddress: Data? + public var platformPaymentAddress: Data? + public var shieldedAddress: Data? + + public init(networkRaw: UInt32, ownerIdentityId: Data, profileIdentityId: Data, + corePaymentAddress: Data? = nil, platformPaymentAddress: Data? = nil, + shieldedAddress: Data? = nil) { + self.networkRaw = networkRaw + self.ownerIdentityId = ownerIdentityId + self.profileIdentityId = profileIdentityId + self.corePaymentAddress = corePaymentAddress + self.platformPaymentAddress = platformPaymentAddress + self.shieldedAddress = shieldedAddress + } + + static func fetch(in context: ModelContext, networkRaw: UInt32, + ownerIdentityId: Data, profileIdentityId: Data, fetcher: any ModelFetching = LiveModelFetcher()) throws -> PersistentDashpayPaymentAddresses? { + let query = FetchDescriptor(predicate: #Predicate { + $0.networkRaw == networkRaw && $0.ownerIdentityId == ownerIdentityId && $0.profileIdentityId == profileIdentityId + }) + return try fetcher.fetch(query, in: context).first + } + + /// Called within the persister's transaction; empty metadata removes the row. + static func replace(in context: ModelContext, networkRaw: UInt32, + ownerIdentityId: Data, profileIdentityId: Data, + core: Data?, platform: Data?, shielded: Data?, + fetcher: any ModelFetching = LiveModelFetcher()) throws { + let existing = try fetch(in: context, networkRaw: networkRaw, + ownerIdentityId: ownerIdentityId, profileIdentityId: profileIdentityId, fetcher: fetcher) + if core == nil && platform == nil && shielded == nil { + if let existing { context.delete(existing) } + return + } + let row = existing ?? PersistentDashpayPaymentAddresses(networkRaw: networkRaw, + ownerIdentityId: ownerIdentityId, profileIdentityId: profileIdentityId) + row.corePaymentAddress = core + row.platformPaymentAddress = platform + row.shieldedAddress = shielded + if existing == nil { context.insert(row) } + } + + /// Delete every address row an identity owns (its own profile's and its + /// cached contacts'). Rows are keyed by id, not by relationship, so any + /// path that deletes an identity outside the persistence handler must call this. + public static func removeOwned(in context: ModelContext, networkRaw: UInt32, ownerIdentityId: Data) throws { + try context.delete(model: PersistentDashpayPaymentAddresses.self, where: #Predicate { + $0.networkRaw == networkRaw && $0.ownerIdentityId == ownerIdentityId + }) + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayProfile.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayProfile.swift index 3e6eb2dd126..f0cdf470a70 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayProfile.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayProfile.swift @@ -128,3 +128,16 @@ extension PersistentDashpayProfile { } } } + +// Address metadata is stored separately so released profile/identity relationships +// retain their SwiftData schema identity across upgrades. +extension PersistentDashpayProfile { + private var paymentAddresses: PersistentDashpayPaymentAddresses? { + guard let modelContext else { return nil } + return try? PersistentDashpayPaymentAddresses.fetch(in: modelContext, networkRaw: networkRaw, + ownerIdentityId: identity.identityId, profileIdentityId: identity.identityId) + } + public var corePaymentAddress: Data? { paymentAddresses?.corePaymentAddress } + public var platformPaymentAddress: Data? { paymentAddresses?.platformPaymentAddress } + public var shieldedAddress: Data? { paymentAddresses?.shieldedAddress } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift index df7543d756c..e95cdc03478 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift @@ -460,12 +460,18 @@ extension PersistentIdentity { return true } + /// Throws, deleting nothing, when the owner's payment-address rows cannot + /// be removed: they reference their owner by id only, so no relationship + /// cascade reaches them, and deleting the identity without them would + /// strand rows a later restore could pick up. @discardableResult public static func remove( in context: ModelContext, identityId: Data - ) -> Bool { + ) throws -> Bool { guard let row = fetch(in: context, identityId: identityId) else { return false } + try PersistentDashpayPaymentAddresses.removeOwned( + in: context, networkRaw: row.networkRaw, ownerIdentityId: identityId) context.delete(row) return true } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DashPayProfile.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DashPayProfile.swift index e7208cbe53b..5b9f17eb610 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DashPayProfile.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DashPayProfile.swift @@ -26,19 +26,33 @@ public struct DashPayProfile: Sendable, Equatable { /// Perceptual dHash (8 bytes / 64 bits) of the avatar. Present /// whenever the on-chain document carried an `avatarFingerprint`. public let avatarFingerprint: Data? + /// Core address storage encoding: type byte followed by HASH160 (21 bytes). + public let corePaymentAddress: Data? + /// Platform address storage encoding: type byte followed by HASH160 (21 bytes). + public let platformPaymentAddress: Data? + /// Complete raw Orchard address: diversifier (11 bytes) and public key (32 bytes). + public let shieldedAddress: Data? + public init( displayName: String? = nil, publicMessage: String? = nil, avatarUrl: String? = nil, avatarHash: Data? = nil, - avatarFingerprint: Data? = nil + avatarFingerprint: Data? = nil, + corePaymentAddress: Data? = nil, + platformPaymentAddress: Data? = nil, + shieldedAddress: Data? = nil ) { self.displayName = displayName self.publicMessage = publicMessage self.avatarUrl = avatarUrl self.avatarHash = avatarHash self.avatarFingerprint = avatarFingerprint + self.corePaymentAddress = corePaymentAddress + self.platformPaymentAddress = platformPaymentAddress + self.shieldedAddress = shieldedAddress + } /// Copy a `DashPayProfileFFI` into a Swift-owned value. The @@ -55,12 +69,16 @@ public struct DashPayProfile: Sendable, Equatable { self.avatarFingerprint = ffi.avatar_fingerprint_is_some ? Data(fromTuple8: ffi.avatar_fingerprint) : nil + self.corePaymentAddress = ffi.core_payment_address_is_some ? Swift.withUnsafeBytes(of: ffi.core_payment_address) { Data($0) } : nil + self.platformPaymentAddress = ffi.platform_payment_address_is_some ? Swift.withUnsafeBytes(of: ffi.platform_payment_address) { Data($0) } : nil + self.shieldedAddress = ffi.shielded_address_is_some ? Swift.withUnsafeBytes(of: ffi.shielded_address) { Data($0) } : nil + } } /// Input for `ManagedPlatformWallet.createDashPayProfile` / -/// `updateDashPayProfile`. Every field is optional; fields left as -/// `nil` are simply omitted from the outgoing document. +/// `updateDashPayProfile`. Optional text/avatar fields left as `nil` +/// are omitted. Payment addresses explicitly distinguish keep, set, and remove. /// /// `avatarBytes` is the raw image payload pre-downloaded by the app /// layer. When provided, platform-wallet computes the SHA-256 hash @@ -71,17 +89,28 @@ public struct DashPayProfileUpdate: Sendable { public var publicMessage: String? public var avatarUrl: String? public var avatarBytes: Data? + public var corePaymentAddress: DashPayPaymentAddressUpdate + public var platformPaymentAddress: DashPayPaymentAddressUpdate + public var shieldedAddress: DashPayPaymentAddressUpdate + public init( displayName: String? = nil, publicMessage: String? = nil, avatarUrl: String? = nil, - avatarBytes: Data? = nil + avatarBytes: Data? = nil, + corePaymentAddress: DashPayPaymentAddressUpdate = .keep, + platformPaymentAddress: DashPayPaymentAddressUpdate = .keep, + shieldedAddress: DashPayPaymentAddressUpdate = .keep ) { self.displayName = displayName self.publicMessage = publicMessage self.avatarUrl = avatarUrl self.avatarBytes = avatarBytes + self.corePaymentAddress = corePaymentAddress + self.platformPaymentAddress = platformPaymentAddress + self.shieldedAddress = shieldedAddress + } } @@ -122,3 +151,24 @@ private extension Data { self = Swift.withUnsafeBytes(of: &value) { Data($0) } } } + +/// Explicit operation on a payment address property. +public enum DashPayPaymentAddressUpdate: Sendable, Equatable { + case keep + case set(Data) + case remove + + func withFFI(_ body: (UnsafePointer) throws -> T) rethrows -> T { + let action: UInt32 + let data: Data + switch self { + case .keep: action = 0; data = Data() + case .set(let bytes): action = 1; data = bytes + case .remove: action = 2; data = Data() + } + return try data.withUnsafeBytes { bytes in + var value = PaymentAddressUpdateFFI(action: action, bytes: bytes.baseAddress?.assumingMemoryBound(to: UInt8.self), len: UInt(data.count)) + return try withUnsafePointer(to: &value, body) + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index dd76967b2b2..fdbdd513f80 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -3559,8 +3559,9 @@ extension ManagedPlatformWallet { // Rust holds a `passUnretained` ctx pointer to it via `signerHandle`, // so a bare `_ = signer` keepalive can be released under -O before the // call returns. `withExtendedLifetime` keeps ARC holding it for the - // call's duration (matches the other *_with_signer wrappers). - let result: PlatformWalletFFIResult = withExtendedLifetime(signer) { + // call's duration (matches the other *_with_signer wrappers). The + // wallet is pinned the same way: its `deinit` destroys `handle`. + let result: PlatformWalletFFIResult = withExtendedLifetime((self, signer)) { idBytes.withUnsafeBufferPointer { idBp -> PlatformWalletFFIResult in let idPtr = idBp.baseAddress! @@ -3569,37 +3570,19 @@ extension ManagedPlatformWallet { publicMessage, avatarUrl ) { namePtr, msgPtr, urlPtr -> PlatformWalletFFIResult in - let bytes = avatarBytes ?? Data() - if let avatarBytes, !avatarBytes.isEmpty { - return avatarBytes.withUnsafeBytes { rawBuf -> PlatformWalletFFIResult in - let bytesPtr = rawBuf.baseAddress?.assumingMemoryBound(to: UInt8.self) - return platform_wallet_create_or_update_dashpay_profile_with_signer( - handle, - idPtr, - namePtr, - msgPtr, - urlPtr, - bytesPtr, - UInt(avatarBytes.count), - doCreate, - signerHandle, - &outProfile - ) + return update.corePaymentAddress.withFFI { core in + update.platformPaymentAddress.withFFI { platform in + update.shieldedAddress.withFFI { shielded in + (avatarBytes ?? Data()).withUnsafeBytes { bytes in + platform_wallet_create_or_update_dashpay_profile_with_addresses_with_signer( + handle, idPtr, namePtr, msgPtr, urlPtr, + bytes.baseAddress?.assumingMemoryBound(to: UInt8.self), + UInt(bytes.count), core, platform, shielded, + doCreate, signerHandle, &outProfile + ) + } + } } - } else { - _ = bytes - return platform_wallet_create_or_update_dashpay_profile_with_signer( - handle, - idPtr, - namePtr, - msgPtr, - urlPtr, - nil, - 0, - doCreate, - signerHandle, - &outProfile - ) } } } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index 5befbfc41ec..ed884920dd9 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -194,6 +194,23 @@ extension PlatformWalletManager { currentShieldedTreeTotal = total } + /// Effective engine account set, including automatically discovered tip accounts. + public func shieldedAccountIndices(walletId: Data) throws -> [UInt32] { + guard isConfigured, handle != NULL_HANDLE, walletId.count == 32 else { + throw PlatformWalletError.invalidParameter("Configured manager and 32-byte walletId required") + } + var indices: UnsafeMutablePointer? + var count: UInt = 0 + try walletId.withUnsafeBytes { bytes in + try platform_wallet_manager_shielded_account_indices( + handle, bytes.bindMemory(to: UInt8.self).baseAddress!, &indices, &count + ).check() + } + defer { platform_wallet_manager_free_shielded_account_indices(indices, count) } + guard let indices else { return [] } + return Array(UnsafeBufferPointer(start: indices, count: Int(count))) + } + /// Bind `walletId`'s multi-account shielded sub-wallet to the /// `PlatformWallet` — from viewing keys the persister already /// holds when possible, deriving from the mnemonic only when it @@ -1672,3 +1689,123 @@ func shieldedTreeProgressCallback( ) } } + +public struct ShieldedTipRecipient: Sendable, Equatable { + public let identityId: Data + public let address: Data +} + +/// The account a shielded tip is paid from. Rust decides which account an +/// identity's source selects, from the slot the wallet seed proves it holds. +public enum ShieldedTipSource: Sendable, Equatable { + /// The identity's dedicated tip account. + case identity(Data) + /// An ordinary account, or the tip account of a retired identity. + case account(UInt32) + + var ffi: ShieldedTipSourceFFI? { + var value = ShieldedTipSourceFFI() + switch self { + case .identity(let identityId): + guard identityId.count == 32 else { return nil } + value.kind = UInt32(SHIELDED_TIP_SOURCE_IDENTITY) + identityId.withUnsafeBytes { src in + Swift.withUnsafeMutableBytes(of: &value.identity_id) { dst in + dst.copyMemory(from: src) + } + } + case .account(let account): + value.kind = UInt32(SHIELDED_TIP_SOURCE_ACCOUNT) + value.account = account + } + return value + } +} + +extension ManagedPlatformWallet { + /// Fetch and verify the current DPNS identity and shielded tip address. + public func resolveShieldedTip(username: String) async throws -> ShieldedTipRecipient { + // `deinit` destroys `handle`, so the wallet stays alive for the native call. + return try await Task.detached(priority: .userInitiated) { [self] in + try withExtendedLifetime(self) { + var identityId = [UInt8](repeating: 0, count: 32) + var address = [UInt8](repeating: 0, count: 43) + try username.withCString { + try platform_wallet_resolve_shielded_tip(handle, $0, &identityId, &address).check() + } + return ShieldedTipRecipient(identityId: Data(identityId), address: Data(address)) + } + }.value + } +} + +extension PlatformWalletManager { + /// Prepare the identity's dedicated shielded account. Publication is a separate profile update. + public func prepareShieldedIdentityAddress(walletId: Data, identityId: Data, resolver: MnemonicResolver) async throws -> Data { + guard walletId.count == 32, identityId.count == 32, let resolverHandle = resolver.handle else { + throw PlatformWalletError.invalidParameter("Expected wallet/identity IDs and mnemonic resolver") + } + // Admitted, so `shutdown()` waits for this call before destroying the handle. + try admitNativeOp("prepareShieldedIdentityAddress") + defer { finishNativeOp() } + let handle = self.handle + return try await Task.detached(priority: .userInitiated) { + try withExtendedLifetime(resolver) { + var address = [UInt8](repeating: 0, count: 43) + try walletId.withUnsafeBytes { wallet in + try identityId.withUnsafeBytes { identity in + try platform_wallet_manager_prepare_shielded_identity_address( + handle, wallet.baseAddress!.assumingMemoryBound(to: UInt8.self), resolverHandle, + identity.baseAddress!.assumingMemoryBound(to: UInt8.self), &address + ).check() + } + } + return Data(address) + } + }.value + } + + /// Recheck the confirmed recipient before building and broadcasting the payment. + public func sendShieldedTip(walletId: Data, resolver: MnemonicResolver, source: ShieldedTipSource, + username: String, recipient: ShieldedTipRecipient, amount: UInt64) async throws { + guard walletId.count == 32, recipient.identityId.count == 32, recipient.address.count == 43, + let sourceFFI = source.ffi, let resolverHandle = resolver.handle else { + throw PlatformWalletError.invalidParameter("Invalid shielded tip source, recipient or wallet") + } + try admitNativeOp("sendShieldedTip") + defer { finishNativeOp() } + let handle = self.handle + try await Task.detached(priority: .userInitiated) { + var source = sourceFFI + try withExtendedLifetime(resolver) { + try walletId.withUnsafeBytes { wallet in + try recipient.identityId.withUnsafeBytes { identity in + try recipient.address.withUnsafeBytes { address in + try username.withCString { name in + try platform_wallet_manager_send_shielded_tip( + handle, wallet.baseAddress!.assumingMemoryBound(to: UInt8.self), resolverHandle, + &source, name, identity.baseAddress!.assumingMemoryBound(to: UInt8.self), + address.baseAddress!.assumingMemoryBound(to: UInt8.self), amount, nil + ).check() + } + } + } + } + } + }.value + } +} + +extension PlatformWalletManager { + public static func shieldedIdentityAccountIndex(identityIndex: UInt32) throws -> UInt32 { + var account: UInt32 = 0 + try platform_wallet_shielded_identity_account_index(identityIndex, &account).check() + return account + } +} + +extension PlatformWalletManager { + public static func isShieldedIdentityAccount(_ account: UInt32) -> Bool { + platform_wallet_is_shielded_identity_account(account) + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index 3a3568ec2f2..4d71913608a 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -3395,6 +3395,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { extensionCallbacks.struct_size = UInt(MemoryLayout.size) extensionCallbacks.version = UInt32(PLATFORM_WALLET_PERSISTENCE_CALLBACKS_EXTENSION_VERSION) extensionCallbacks.reserved = 0 + extensionCallbacks.on_persist_dashpay_profiles_fn = persistDashpayProfilesCallback extensionCallbacks.on_persist_dpns_name_states_fn = persistDpnsNameStatesCallback extensionCallbacks.on_persist_tracked_masternodes_fn = persistTrackedMasternodesCallback extensionCallbacks.on_load_tracked_masternodes_fn = loadTrackedMasternodesCallback @@ -3728,12 +3729,14 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// were dropped from the Rust side — the former moved to the UI /// layer, the latter is now derived from /// `IdentityManager.highestRegistrationIndex(...)` at read time. + @discardableResult func persistIdentities( walletId: Data, upserts: [IdentityEntrySnapshot], removed: [Data] - ) { + ) -> Bool { onQueue { + do { for entry in upserts { let identityId = entry.identityId let descriptor = FetchDescriptor( @@ -3814,20 +3817,8 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { names: entry.dpnsNames ) - // Upsert the DashPay profile cache for this identity. - // - // Gated on `entry.dashpayProfile != nil` — a `nil` - // snapshot mirrors the FFI's - // `dashpay_profile_present == false`, which the Rust - // `IdentityChangeSet::merge` policy treats as "no - // update" (NOT delete). DashPay doesn't expose a - // user-driven "delete profile" today; if it ever does, - // the removal must arrive via a separate signal so we - // know it's intentional. Match the dpns-name handling - // shape: a missing snapshot leaves any existing row - // intact. if let profile = entry.dashpayProfile { - upsertDashpayProfile(identityRow: row, profile: profile) + try upsertDashpayProfile(identityRow: row, profile: profile) } // Upsert the cached contact-profile rows for this identity. @@ -3839,7 +3830,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // contact simply MISSING from this flush is "no update" (not a // delete). An empty array leaves any existing rows intact. if !entry.contactProfiles.isEmpty { - upsertDashpayContactProfiles( + try upsertDashpayContactProfiles( identityRow: row, profiles: entry.contactProfiles ) @@ -3895,15 +3886,70 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { let descriptor = FetchDescriptor( predicate: #Predicate { $0.identityId == identityId } ) - if let existing = try? backgroundContext.fetch(descriptor).first { + // A failed fetch fails the changeset rather than reading as an + // absent row, which would strand the identity and its sidecar. + if let existing = try backgroundContext.fetch(descriptor).first { + try PersistentDashpayPaymentAddresses.removeOwned(in: backgroundContext, + networkRaw: existing.networkRaw, ownerIdentityId: identityId) backgroundContext.delete(existing) } } // No save() — bracketed by changesetBegin/End. + return true + } catch { + SDKLogger.event("persistence_profile_addresses_failed", category: .persistence, + severity: .error, error: error) + return false + } } // onQueue } + @discardableResult + func persistDashpayProfiles(walletId: Data, profiles: [DashpayProfileOverlaySnapshot]) -> Bool { + onQueue { + do { + let walletDescriptor = FetchDescriptor( + predicate: PersistentWallet.predicate(walletId: walletId) + ) + let wallet = try modelFetcher.fetch(walletDescriptor, in: backgroundContext).first + guard let networkRaw = wallet?.networkRaw ?? network?.rawValue else { + return false + } + for overlay in profiles { + let identityId = overlay.identityId + let descriptor = FetchDescriptor( + predicate: #Predicate { $0.identityId == identityId && $0.networkRaw == networkRaw } + ) + guard let row = try modelFetcher.fetch(descriptor, in: backgroundContext).first else { + return false + } + if let profile = overlay.profile { + try upsertDashpayProfile(identityRow: row, profile: profile) + } else { + // Resolve the profile so SwiftData can snapshot it during rollback. + let profileDescriptor = FetchDescriptor( + predicate: #Predicate { + $0.identity.identityId == identityId && $0.networkRaw == networkRaw + } + ) + let existing = try modelFetcher.fetch(profileDescriptor, in: backgroundContext).first + try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, + networkRaw: row.networkRaw, ownerIdentityId: row.identityId, + profileIdentityId: row.identityId, core: nil, platform: nil, shielded: nil, + fetcher: modelFetcher) + if let existing { backgroundContext.delete(existing) } + } + } + return true + } catch { + SDKLogger.event("persistence_profile_overlay_failed", category: .persistence, + severity: .error, error: error) + return false + } + } + } + /// Upsert a `PersistentDPNSName` row for every label the FFI /// identity entry carried. Rows are keyed on /// `(networkRaw, normalizedParentDomainName, normalizedLabel)`, @@ -4087,7 +4133,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { private func upsertDashpayProfile( identityRow: PersistentIdentity, profile: DashpayProfileSnapshot - ) { + ) throws { if let existing = identityRow.dashpayProfile { // Field-level refresh. Every column is overwritten on // every flush — the FFI snapshot is authoritative for @@ -4102,6 +4148,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { existing.avatarUrl = profile.avatarUrl existing.avatarHash = profile.avatarHash existing.avatarFingerprint = profile.avatarFingerprint + existing.lastUpdated = Date() } else { let row = PersistentDashpayProfile( @@ -4119,6 +4166,10 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // `PersistentIdentity.dashpayProfile`, so we don't need // to assign `identityRow.dashpayProfile = row` here. } + try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, + networkRaw: identityRow.networkRaw, ownerIdentityId: identityRow.identityId, + profileIdentityId: identityRow.identityId, core: profile.corePaymentAddress, + platform: profile.platformPaymentAddress, shielded: profile.shieldedAddress, fetcher: modelFetcher) } /// Upsert one `PersistentDashpayContactProfile` row per cached @@ -4148,7 +4199,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { private func upsertDashpayContactProfiles( identityRow: PersistentIdentity, profiles: [ContactProfileSnapshot] - ) { + ) throws { let ownerIdentityId = identityRow.identityId for profile in profiles { let contactIdentityId = profile.contactIdentityId @@ -4159,9 +4210,12 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { ) ) guard profile.isPresent else { + try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, + networkRaw: identityRow.networkRaw, ownerIdentityId: ownerIdentityId, + profileIdentityId: contactIdentityId, core: nil, platform: nil, shielded: nil, fetcher: modelFetcher) // Confirmed-absent: delete the stale row if one exists; a // never-persisted contact is a no-op. - if let existing = try? backgroundContext.fetch(descriptor).first { + if let existing = try modelFetcher.fetch(descriptor, in: backgroundContext).first { backgroundContext.delete(existing) } continue @@ -4173,6 +4227,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { existing.avatarUrl = profile.avatarUrl existing.avatarHash = profile.avatarHash existing.avatarFingerprint = profile.avatarFingerprint + existing.checkedAtMs = profile.checkedAtMs existing.lastUpdated = Date() } else { @@ -4192,6 +4247,10 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // collection from the `inverse:` declaration on // `PersistentIdentity.contactProfiles`. } + try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, + networkRaw: identityRow.networkRaw, ownerIdentityId: ownerIdentityId, + profileIdentityId: contactIdentityId, core: profile.corePaymentAddress, + platform: profile.platformPaymentAddress, shielded: profile.shieldedAddress, fetcher: modelFetcher) } } @@ -5457,6 +5516,11 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { let contactProfiles: [ContactProfileSnapshot] } + struct DashpayProfileOverlaySnapshot { + let identityId: Data + let profile: DashpayProfileSnapshot? + } + /// Owned snapshot of one `ContactProfileRowFFI` — the contact's /// identity id, the five public profile fields, and the /// `checked_at_ms` self-heal timestamp. Decouples every contained @@ -5481,6 +5545,9 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// 8-byte DHash perceptual fingerprint. `nil` when the source /// `avatar_fingerprint_present == false`. let avatarFingerprint: Data? + var corePaymentAddress: Data? = nil + var platformPaymentAddress: Data? = nil + var shieldedAddress: Data? = nil /// Wall-clock ms of the last fetch attempt on the Rust side /// (`ContactProfileEntry.checked_at_ms`). let checkedAtMs: UInt64 @@ -5504,6 +5571,9 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// `avatarFingerprint`). `nil` when the source /// `avatar_fingerprint_present == false`. let avatarFingerprint: Data? + var corePaymentAddress: Data? = nil + var platformPaymentAddress: Data? = nil + var shieldedAddress: Data? = nil } /// Swift-side snapshot of `IdentityKeyEntryFFI` — public-key @@ -7057,6 +7127,8 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // that their problematic cascade children are // gone from the store. for identity in identitiesToDelete { + try PersistentDashpayPaymentAddresses.removeOwned(in: backgroundContext, + networkRaw: identity.networkRaw, ownerIdentityId: identity.identityId) backgroundContext.delete(identity) } try backgroundContext.save() @@ -7602,6 +7674,16 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } } + let paymentAddressRows: [PersistentDashpayPaymentAddresses] + do { + paymentAddressRows = try modelFetcher.fetch(FetchDescriptor(), in: backgroundContext) + } catch { + SDKLogger.event("persistence_profile_addresses_load_failed", category: .persistence, + severity: .error, error: error) + return (nil, 0, true) + } + let addressesByOwner = Dictionary(grouping: paymentAddressRows, by: \.ownerIdentityId) + // Allocate `entriesPtr` and the `LoadAllocation` here — past // the fallible SwiftData fetch above — so an early-error path // doesn't leak the entries buffer (LoadAllocation only gets @@ -7756,6 +7838,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } let identitiesBuffer = buildIdentityRestoreBuffer( identities: sortedIdentities, + addressesByOwner: addressesByOwner, allocation: allocation ) @@ -8767,6 +8850,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { private func buildIdentityRestoreBuffer( identities: [PersistentIdentity], + addressesByOwner: [Data: [PersistentDashpayPaymentAddresses]], allocation: LoadAllocation ) -> UnsafeMutablePointer? { if identities.isEmpty { @@ -9099,6 +9183,62 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // under a wrong key (matching the abort-on-corrupt convention the // UTXO restore uses). Filtering up front also keeps the fixed- // capacity buffer fully initialized so the count stays exact. + let addressRows = (addressesByOwner[identity.identityId] ?? []).filter { $0.networkRaw == identity.networkRaw } + if let profile = identity.dashpayProfile { + let addresses = addressRows.first { $0.profileIdentityId == identity.identityId } + var row = ContactProfileRestoreEntryFFI() + copyBytes(identity.identityId, into: &row.contact_id) + if let displayName = profile.displayName, !displayName.isEmpty { + row.display_name = UnsafePointer( + duplicateCString(displayName, allocation: allocation)) + } + if let bio = profile.bio, !bio.isEmpty { + row.bio = UnsafePointer( + duplicateCString(bio, allocation: allocation)) + } + if let avatarUrl = profile.avatarUrl, !avatarUrl.isEmpty { + row.avatar_url = UnsafePointer( + duplicateCString(avatarUrl, allocation: allocation)) + } + if let publicMessage = profile.publicMessage, !publicMessage.isEmpty { + row.public_message = UnsafePointer( + duplicateCString(publicMessage, allocation: allocation)) + } + // Gate the byte arrays on presence — an absent hash / + // fingerprint must round-trip as `_present == false`, + // not as an all-zero value (which Rust would otherwise + // restore as a real `Some([0u8; N])`). + if let avatarHash = profile.avatarHash, avatarHash.count == 32 { + copyBytes(avatarHash, into: &row.avatar_hash) + row.avatar_hash_present = true + } else { + row.avatar_hash_present = false + } + if let address = addresses?.corePaymentAddress, address.count == 21 { + copyBytes(address, into: &row.core_payment_address) + row.core_payment_address_present = true + } + if let address = addresses?.platformPaymentAddress, address.count == 21 { + copyBytes(address, into: &row.platform_payment_address) + row.platform_payment_address_present = true + } + if let address = addresses?.shieldedAddress, address.count == 43 { + copyBytes(address, into: &row.shielded_address) + row.shielded_address_present = true + } + if let avatarFingerprint = profile.avatarFingerprint, + avatarFingerprint.count == 8 { + copyBytes(avatarFingerprint, into: &row.avatar_fingerprint) + row.avatar_fingerprint_present = true + } else { + row.avatar_fingerprint_present = false + } + let own = UnsafeMutablePointer.allocate(capacity: 1) + own.initialize(to: row) + entry.dashpay_profile = UnsafePointer(own) + allocation.contactProfileArrays.append((own, 1)) + } + let contactProfileRows = identity.contactProfiles.filter { $0.contactIdentityId.count == 32 } @@ -9110,6 +9250,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { capacity: contactProfileRows.count ) for (c, profile) in contactProfileRows.enumerated() { + let addresses = addressRows.first { $0.profileIdentityId == profile.contactIdentityId } var row = ContactProfileRestoreEntryFFI() copyBytes(profile.contactIdentityId, into: &row.contact_id) if let displayName = profile.displayName, !displayName.isEmpty { @@ -9138,6 +9279,18 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } else { row.avatar_hash_present = false } + if let address = addresses?.corePaymentAddress, address.count == 21 { + copyBytes(address, into: &row.core_payment_address) + row.core_payment_address_present = true + } + if let address = addresses?.platformPaymentAddress, address.count == 21 { + copyBytes(address, into: &row.platform_payment_address) + row.platform_payment_address_present = true + } + if let address = addresses?.shieldedAddress, address.count == 43 { + copyBytes(address, into: &row.shielded_address) + row.shielded_address_present = true + } if let avatarFingerprint = profile.avatarFingerprint, avatarFingerprint.count == 8 { copyBytes(avatarFingerprint, into: &row.avatar_fingerprint) @@ -10408,6 +10561,36 @@ private func persistAccountAddressPoolsCallback( return allOk ? 0 : 1 } +private func persistDashpayProfilesCallback( + context: UnsafeMutableRawPointer?, + walletIdPtr: UnsafePointer?, + rowsPtr: UnsafePointer?, + rowsCount: UInt +) -> Int32 { + guard let context, let walletIdPtr else { return 1 } + guard rowsCount == 0 || rowsPtr != nil else { return 1 } + let handler = Unmanaged.fromOpaque(context).takeUnretainedValue() + var profiles: [PlatformWalletPersistenceHandler.DashpayProfileOverlaySnapshot] = [] + if let rowsPtr { + for index in 0.. Predicate { + #Predicate { + $0.walletId == walletId && $0.accountIndex == 0 && $0.isSpent == false + } + } + var body: some View { // Snapshot Core balance once per render — `coreBalance` goes // through a blocking FFI call (`accountBalances(for:)`); the @@ -486,7 +492,7 @@ struct SendTransactionView: View { .reduce(0) { $0 + $1.confirmed } } - /// Per-wallet shielded balance: sum of THIS wallet's unspent + /// Account-0 shielded balance: sum of THIS wallet's unspent /// `PersistentShieldedNote` values (Rust pushes note rows via the /// shielded persister). Reads SwiftData rather than the /// single-mirror `shieldedService.shieldedBalance`, so the shielded diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletKeyHealthSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletKeyHealthSheet.swift index 15004a1158b..344df016871 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletKeyHealthSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletKeyHealthSheet.swift @@ -418,6 +418,9 @@ enum WalletKeyHealthChecker { for cr in Array(identity.contactRequests) { modelContext.delete(cr) } + // Payment-address rows are keyed by owner id; no cascade reaches them. + try PersistentDashpayPaymentAddresses.removeOwned( + in: modelContext, networkRaw: identity.networkRaw, ownerIdentityId: identity.identityId) try modelContext.save() // PHASE 2: delete the identity itself. Its problematic diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift index 5c5d8974477..cf4c3084c19 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift @@ -248,7 +248,7 @@ struct CreateIdentityView: View { @Query(sort: [SortDescriptor(\PersistentAssetLock.updatedAt, order: .reverse)]) private var allAssetLocks: [PersistentAssetLock] - /// All wallets' unspent shielded notes. The shielded funding + /// All wallets' unspent account-0 shielded notes. The shielded funding /// picker spans multiple wallets, so this uses the all-wallets /// predicate and `shieldedPoolBalance(for:)` scopes by walletId in /// memory — a single-walletId `@Query` couldn't serve every row @@ -256,9 +256,15 @@ struct CreateIdentityView: View { /// `modelContext.fetch`) makes the funding option and denomination /// list update live: rows arriving while this sheet is open /// re-render the view. - @Query(filter: PersistentShieldedNote.unspentPredicate) + @Query(filter: CreateIdentityView.shieldedFundingPredicate) private var unspentShieldedNotes: [PersistentShieldedNote] + static var shieldedFundingPredicate: Predicate { + #Predicate { + $0.accountIndex == 0 && $0.isSpent == false + } + } + // MARK: - Selection state /// The source wallet selection. `nil` encodes "pick nothing yet"; @@ -1820,8 +1826,8 @@ struct CreateIdentityView: View { && shieldedFallbackAddressBytes(for: walletId) != nil } - /// Per-wallet shielded pool balance: sum of `walletId`'s unspent - /// `PersistentShieldedNote` values, filtered in memory from the + /// Per-wallet shielded funding balance: sum of `walletId`'s unspent + /// account-0 `PersistentShieldedNote` values, filtered in memory from the /// `unspentShieldedNotes` `@Query` (rather than the single-mirror /// `shieldedService.shieldedBalance`). Correct for ANY loaded /// wallet, not just the mirror's `firstWallet`. diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift index d5565d27f42..eabeadd9ed3 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift @@ -62,6 +62,13 @@ struct StorageExplorerView: View { ) { DashpayContactProfileStorageListView(network: network) } + modelRow( + "DashPay Payment Addresses", + icon: "qrcode", + type: PersistentDashpayPaymentAddresses.self + ) { + DashpayPaymentAddressesStorageListView(network: network) + } modelRow( "DashPay Payments", icon: "arrow.left.arrow.right.circle", @@ -303,6 +310,7 @@ struct StorageExplorerView: View { directCount(PersistentDashpayProfile.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDashpayContactRequest.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDashpayContactProfile.self, predicate: #Predicate { $0.networkRaw == raw }) + directCount(PersistentDashpayPaymentAddresses.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDashpayPayment.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDashpayIgnoredSender.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentPrivateContactRequestsPosition.self, predicate: #Predicate { $0.networkRaw == raw }) diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift index fb8ff7e41bb..f38b1a855d6 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift @@ -569,6 +569,40 @@ struct DashpayContactProfileStorageListView: View { } } +// MARK: - PersistentDashpayPaymentAddresses + +struct DashpayPaymentAddressesStorageListView: View { + let network: Network + @Query private var records: [PersistentDashpayPaymentAddresses] + + private var filtered: [PersistentDashpayPaymentAddresses] { + records.filter { $0.networkRaw == network.rawValue } + } + + var body: some View { + let visible = filtered + List(visible) { record in + NavigationLink(destination: DashpayPaymentAddressesStorageDetailView(record: record)) { + VStack(alignment: .leading, spacing: 4) { + Text(record.profileIdentityId.toHexString()) + .font(.body).lineLimit(1).truncationMode(.middle) + Text("Owner: \(record.ownerIdentityId.toHexString())") + .font(.caption) + .foregroundColor(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + } + } + .navigationTitle("Payment Addresses (\(visible.count))") + .overlay { + if visible.isEmpty { + ContentUnavailableView("No Records", systemImage: "qrcode") + } + } + } +} + // MARK: - PersistentDashpayContactRequest /// Storage-explorer list of every DashPay contact-request row. diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift index 4b2b4e0a471..f1757fff639 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift @@ -414,6 +414,29 @@ struct DashpayContactProfileStorageDetailView: View { } } +// MARK: - PersistentDashpayPaymentAddresses + +struct DashpayPaymentAddressesStorageDetailView: View { + let record: PersistentDashpayPaymentAddresses + + var body: some View { + Form { + Section("Profile") { + FieldRow(label: "Network", value: Network(rawValue: record.networkRaw)?.displayName ?? String(record.networkRaw)) + FieldRow(label: "Owner ID (Hex)", value: hexString(record.ownerIdentityId)) + FieldRow(label: "Profile ID (Hex)", value: hexString(record.profileIdentityId)) + } + Section("Payment Addresses (Hex)") { + FieldRow(label: "Core (21 B)", value: record.corePaymentAddress.map(hexString) ?? "—") + FieldRow(label: "Platform (21 B)", value: record.platformPaymentAddress.map(hexString) ?? "—") + FieldRow(label: "Shielded (43 B)", value: record.shieldedAddress.map(hexString) ?? "—") + } + } + .navigationTitle("Payment Addresses") + .navigationBarTitleDisplayMode(.inline) + } +} + // MARK: - PersistentDashpayPayment /// Detail view for one DashPay payment-history row. Read-only dump diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift index 188e698c789..14038d24625 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift @@ -63,15 +63,92 @@ final class PersistentShieldedNotePredicateTests: XCTestCase { ) } + func testShieldedSendHasNoSourceBalanceForTipOnlyWallet() throws { + let container = try DashModelContainer.createInMemory() + let context = ModelContext(container) + let wallet = walletId(0xAA) + context.insert(makeNote(walletId: wallet, accountIndex: 0x4000_0000, + nullifier: 0x01, isSpent: false, value: 900)) + try context.save() + + let notes = try context.fetch(FetchDescriptor( + predicate: SendTransactionView.shieldedSourcePredicate(walletId: wallet) + )) + XCTAssertTrue(notes.isEmpty) + XCTAssertEqual(notes.reduce(UInt64(0)) { $0 + $1.value }, 0) + } + + func testShieldedSendSourceBalanceIncludesOnlyUnspentAccountZeroInSelectedWallet() throws { + let container = try DashModelContainer.createInMemory() + let context = ModelContext(container) + let wallet = walletId(0xAA) + context.insert(makeNote(walletId: wallet, nullifier: 0x01, isSpent: false, value: 100)) + context.insert(makeNote(walletId: wallet, nullifier: 0x02, isSpent: false, value: 50)) + context.insert(makeNote(walletId: wallet, nullifier: 0x03, isSpent: true, value: 999)) + context.insert(makeNote(walletId: wallet, accountIndex: 1, + nullifier: 0x04, isSpent: false, value: 200)) + context.insert(makeNote(walletId: wallet, accountIndex: 0x4000_0000, + nullifier: 0x05, isSpent: false, value: 900)) + context.insert(makeNote(walletId: walletId(0xBB), + nullifier: 0x06, isSpent: false, value: 300)) + try context.save() + + let notes = try context.fetch(FetchDescriptor( + predicate: SendTransactionView.shieldedSourcePredicate(walletId: wallet) + )) + XCTAssertEqual(notes.count, 2) + XCTAssertEqual(notes.reduce(UInt64(0)) { $0 + $1.value }, 150) + } + + func testIdentityFundingHasNoSourceBalanceForTipOnlyWallet() throws { + let container = try DashModelContainer.createInMemory() + let context = ModelContext(container) + let wallet = walletId(0xAA) + context.insert(makeNote(walletId: wallet, accountIndex: 0x4000_0000, + nullifier: 0x01, isSpent: false, value: 900)) + try context.save() + + let notes = try context.fetch(FetchDescriptor( + predicate: CreateIdentityView.shieldedFundingPredicate + )) + XCTAssertTrue(notes.isEmpty) + XCTAssertEqual(notes.reduce(UInt64(0)) { $0 + $1.value }, 0) + } + + func testIdentityFundingBalanceIncludesOnlyUnspentAccountZeroInSelectedWallet() throws { + let container = try DashModelContainer.createInMemory() + let context = ModelContext(container) + let wallet = walletId(0xAA) + let otherWallet = walletId(0xBB) + context.insert(makeNote(walletId: wallet, nullifier: 0x01, isSpent: false, value: 100)) + context.insert(makeNote(walletId: wallet, nullifier: 0x02, isSpent: false, value: 50)) + context.insert(makeNote(walletId: wallet, nullifier: 0x03, isSpent: true, value: 999)) + context.insert(makeNote(walletId: wallet, accountIndex: 1, + nullifier: 0x04, isSpent: false, value: 200)) + context.insert(makeNote(walletId: wallet, accountIndex: 0x4000_0000, + nullifier: 0x05, isSpent: false, value: 900)) + context.insert(makeNote(walletId: otherWallet, + nullifier: 0x06, isSpent: false, value: 300)) + try context.save() + + let notes = try context.fetch(FetchDescriptor( + predicate: CreateIdentityView.shieldedFundingPredicate + )) + XCTAssertEqual(notes.count, 3) + XCTAssertEqual(notes.filter { $0.walletId == wallet }.reduce(UInt64(0)) { $0 + $1.value }, 150) + XCTAssertEqual(notes.filter { $0.walletId == otherWallet }.reduce(UInt64(0)) { $0 + $1.value }, 300) + } + private func makeNote( walletId: Data, + accountIndex: UInt32 = 0, nullifier: UInt8, isSpent: Bool, value: UInt64 ) -> PersistentShieldedNote { PersistentShieldedNote( walletId: walletId, - accountIndex: 0, + accountIndex: accountIndex, position: 0, cmx: Data(repeating: 0, count: 32), nullifier: Data(repeating: nullifier, count: 32), diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift index b07ad5a84f2..a90a4035082 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift @@ -794,6 +794,61 @@ final class DashLegacySchemaMigrationTests: XCTestCase { } } + /// Adding an entity renumbers every entity sorted after it, and Core Data + /// embeds the ordinal in generated column names (`Z13TOKENBALANCES` on the + /// token-balance table becomes `Z14TOKENBALANCES` once V5 adds + /// `PersistentDashpayPaymentAddresses` ahead of `PersistentIdentity`). The + /// validator must follow the entity name, while a dropped or converted + /// column is still rejected. + func testValidatorFollowsEntityRenumberingInGeneratedColumnNames() throws { + let fixture = try XCTUnwrap(Bundle.module.url( + forResource: "dash-v1", withExtension: "store", subdirectory: "Fixtures/SchemaStores")) + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let before = directory.appendingPathComponent("before.store") + try FileManager.default.copyItem(at: fixture, to: before) + + func renumbered(_ name: String, tail: String) throws -> URL { + let url = directory.appendingPathComponent(name) + try FileManager.default.copyItem(at: fixture, to: url) + let connection = try DashLegacyStoreSQLite.Connection(url, writable: true) + var tables: [String] = [] + try connection.query(""" + SELECT m.name FROM sqlite_master m WHERE m.type='table' AND m.name <> 'Z_PRIMARYKEY' + AND EXISTS (SELECT 1 FROM pragma_table_info(m.name) WHERE name='Z_ENT') + """) { tables.append(String(cString: sqlite3_column_text($0, 0))) } + var sql = """ + BEGIN; + UPDATE Z_PRIMARYKEY SET Z_ENT = Z_ENT + 1000 WHERE Z_ENT >= 8; + UPDATE Z_PRIMARYKEY SET Z_ENT = Z_ENT - 999 WHERE Z_ENT >= 1000; + INSERT INTO Z_PRIMARYKEY (Z_ENT, Z_NAME, Z_SUPER, Z_MAX) + VALUES (8, 'PersistentDashpayPaymentAddresses', 0, 0); + ALTER TABLE Z_1INVOLVEDTRANSACTIONS RENAME COLUMN Z_31INVOLVEDTRANSACTIONS TO Z_32INVOLVEDTRANSACTIONS; + """ + for table in tables { sql += "UPDATE \(table) SET Z_ENT = Z_ENT + 1 WHERE Z_ENT >= 8;\n" } + sql += tail + "\nCOMMIT;" + try connection.execute(sql) + return url + } + + XCTAssertNoThrow(try DashLegacyStoreSQLite.validatePreservation(from: before, to: try renumbered( + "renamed.store", + tail: "ALTER TABLE ZPERSISTENTTOKENBALANCE RENAME COLUMN Z13TOKENBALANCES TO Z14TOKENBALANCES;"))) + let dropIndex = "DROP INDEX IF EXISTS ZPERSISTENTTOKENBALANCE_Z13TOKENBALANCES_INDEX;" + let drop = "ALTER TABLE ZPERSISTENTTOKENBALANCE DROP COLUMN Z13TOKENBALANCES;" + for (name, tail) in [ + ("dropped.store", dropIndex + drop), + ("converted.store", dropIndex + drop + + "ALTER TABLE ZPERSISTENTTOKENBALANCE ADD COLUMN Z14TOKENBALANCES VARCHAR;"), + ] { + let candidate = try renumbered(name, tail: tail) + XCTAssertThrowsError( + try DashLegacyStoreSQLite.validatePreservation(from: before, to: candidate), + name) + } + } + func testValidatorRejectsColumnTypeChangesAndPreservesTypedValues() throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift index 94ee9120cf3..0eeac2b1f1f 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift @@ -627,11 +627,34 @@ final class DashModelMigrationTests: XCTestCase { func testV3AddsKeyColumnsWithoutChangingTheFrozenBaseline() throws { let baseline = Schema(versionedSchema: DashSchemaV1.self) let live = Schema(versionedSchema: DashSchemaV3.self) + // V3 is the published snapshot; the live types must still carry the columns. + let current = DashModelContainer.schema let oldKey = try XCTUnwrap(baseline.entities.first { $0.name == "PersistentPublicKey" }) let newKey = try XCTUnwrap(live.entities.first { $0.name == "PersistentPublicKey" }) + let currentKey = try XCTUnwrap(current.entities.first { $0.name == "PersistentPublicKey" }) for column in ["totalBudget", "expiresAt", "contractBoundsKind"] { XCTAssertNil(oldKey.attributesByName[column]) XCTAssertNotNil(newKey.attributesByName[column]) + XCTAssertNotNil(currentKey.attributesByName[column]) + } + } + + /// V5 adds payment-address and private-contact entities. Payment addresses + /// live in their own table, preserving the published V4 profile columns. + func testV5AddsPaymentAddressesAndPrivateContactEntitiesToPublishedV4() throws { + let v4 = Schema(versionedSchema: DashSchemaV4.self) + let current = DashModelContainer.schema + XCTAssertEqual( + Set(current.entities.map(\.name)).subtracting(v4.entities.map(\.name)), + ["PersistentDashpayPaymentAddresses", "PersistentPrivateContactRequestsPosition", + "PersistentPrivateShieldedAddress"]) + XCTAssertEqual(Set(v4.entities.map(\.name)).subtracting(current.entities.map(\.name)), []) + for name in ["PersistentDashpayProfile", "PersistentDashpayContactProfile"] { + let published = try XCTUnwrap(v4.entities.first { $0.name == name }) + let live = try XCTUnwrap(current.entities.first { $0.name == name }) + XCTAssertEqual( + live.attributesByName.keys.sorted(), published.attributesByName.keys.sorted(), + "\(name): V5 adds no column; addresses live in their own entity") } } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift index 84e538c521a..c6116430525 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift @@ -120,14 +120,15 @@ final class DashPayContactPersistenceTests: XCTestCase { /// Apply one identity persister round carrying only the given contact /// profiles for the fixture owner — the seam `upsertDashpayContactProfiles` /// runs under. + @discardableResult private func applyContactProfiles( _ profiles: [PlatformWalletPersistenceHandler.ContactProfileSnapshot] - ) { + ) -> Bool { // Bracket the round like the FFI does: `endChangeset` is the only // atomic `save()`, so a bare `persistIdentities` would stage the writes // without committing them. handler.beginChangeset(walletId: walletId) - handler.persistIdentities( + let success = handler.persistIdentities( walletId: walletId, upserts: [ PlatformWalletPersistenceHandler.IdentityEntrySnapshot( @@ -145,7 +146,282 @@ final class DashPayContactPersistenceTests: XCTestCase { ], removed: [] ) - handler.endChangeset(walletId: walletId, success: true) + return handler.endChangeset(walletId: walletId, success: success) + } + + func testContactPaymentAddressesAreReplacedAndRemovedTogetherWithProfile() throws { + let shielded = Data(repeating: 0x33, count: 43) + applyContactProfiles([.init( + contactIdentityId: contactId, isPresent: true, displayName: "Tips", bio: nil, + publicMessage: nil, avatarUrl: nil, avatarHash: nil, avatarFingerprint: nil, + corePaymentAddress: Data(repeating: 1, count: 21), + platformPaymentAddress: Data(repeating: 2, count: 21), + shieldedAddress: shielded, checkedAtMs: 1)]) + let first = try XCTUnwrap(fetchContactProfileRows().first) + XCTAssertEqual(first.shieldedAddress, shielded) + XCTAssertEqual(first.corePaymentAddress, Data(repeating: 1, count: 21)) + XCTAssertEqual(first.platformPaymentAddress, Data(repeating: 2, count: 21)) + applyContactProfiles([.init( + contactIdentityId: contactId, isPresent: true, displayName: "Tips", bio: nil, + publicMessage: nil, avatarUrl: nil, avatarHash: nil, avatarFingerprint: nil, + checkedAtMs: 2)]) + let replaced = try XCTUnwrap(fetchContactProfileRows().first) + XCTAssertNil(replaced.shieldedAddress) + XCTAssertNil(replaced.corePaymentAddress) + XCTAssertNil(replaced.platformPaymentAddress) + } + + func testPaymentAddressReadFailureRejectsProfilePersistenceRound() throws { + handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet, + modelFetcher: PaymentAddressReadFailure()) + let saved = applyContactProfiles([.init(contactIdentityId: contactId, isPresent: true, + displayName: "Must roll back", bio: nil, publicMessage: nil, avatarUrl: nil, + avatarHash: nil, avatarFingerprint: nil, shieldedAddress: Data(repeating: 3, count: 43), + checkedAtMs: 1)]) + XCTAssertFalse(saved) + XCTAssertTrue(try fetchContactProfileRows().isEmpty) + } + + func testContactProfileReadFailureRollsBackTombstoneAddressesAndIdentityChanges() throws { + let shielded = Data(repeating: 3, count: 43) + XCTAssertTrue(applyContactProfiles([.init( + contactIdentityId: contactId, isPresent: true, displayName: "Keep profile", + bio: nil, publicMessage: nil, avatarUrl: nil, avatarHash: nil, + avatarFingerprint: nil, shieldedAddress: shielded, checkedAtMs: 1)])) + let context = ModelContext(container) + let owner = try XCTUnwrap(context.fetch(FetchDescriptor()).first) + owner.balance = 321 + owner.revision = 5 + try context.save() + + handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet, + modelFetcher: ContactProfileReadFailure()) + XCTAssertFalse(applyContactProfiles([.init( + contactIdentityId: contactId, isPresent: false, displayName: nil, + bio: nil, publicMessage: nil, avatarUrl: nil, avatarHash: nil, + avatarFingerprint: nil, checkedAtMs: 2)])) + + let restored = ModelContext(container) + let profile = try XCTUnwrap(restored.fetch( + FetchDescriptor()).first) + XCTAssertEqual(profile.displayName, "Keep profile") + let addresses = try restored.fetch(FetchDescriptor()) + XCTAssertEqual(addresses.count, 1) + XCTAssertEqual(addresses.first?.shieldedAddress, shielded) + let restoredOwner = try XCTUnwrap(restored.fetch(FetchDescriptor()).first) + XCTAssertEqual(restoredOwner.balance, 321) + XCTAssertEqual(restoredOwner.revision, 5) + } + + func testPaymentAddressReadFailureRejectsWalletRestore() throws { + let context = ModelContext(container) + let wallet = PersistentWallet(walletId: walletId, network: .testnet) + context.insert(wallet) + let account = PersistentAccount(wallet: wallet, accountType: 0, accountIndex: 0, accountTypeName: "standard") + account.accountExtendedPubKeyBytes = Data(repeating: 0xEE, count: 78) + context.insert(account) + try context.save() + handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet, + modelFetcher: PaymentAddressReadFailure()) + let (entries, count, errored) = handler.loadWalletList() + XCTAssertTrue(errored) + XCTAssertNil(entries) + XCTAssertEqual(count, 0) + } + + func testOwnedProfilePaymentAddressesSurviveRestoreBuffer() throws { + let context = ModelContext(container) + let wallet = PersistentWallet(walletId: walletId, network: .testnet) + context.insert(wallet) + let account = PersistentAccount(wallet: wallet, accountType: 0, accountIndex: 0, accountTypeName: "standard") + account.accountExtendedPubKeyBytes = Data(repeating: 0xEE, count: 78) + context.insert(account) + let owner = try XCTUnwrap(context.fetch(FetchDescriptor()).first) + owner.wallet = wallet + context.insert(PersistentDashpayProfile(identity: owner, displayName: "Tip recipient")) + try PersistentDashpayPaymentAddresses.replace(in: context, networkRaw: Network.testnet.rawValue, + ownerIdentityId: ownerId, profileIdentityId: ownerId, core: Data(repeating: 1, count: 21), + platform: Data(repeating: 2, count: 21), shielded: Data(repeating: 3, count: 43)) + try context.save() + + let (entries, count, errored) = handler.loadWalletList() + XCTAssertFalse(errored) + XCTAssertEqual(count, 1) + let buffer = try XCTUnwrap(entries) + defer { handler.loadWalletListFree(entries: UnsafeRawPointer(buffer)) } + let restored = try XCTUnwrap(buffer[0].identities?[0].dashpay_profile).pointee + XCTAssertEqual(restored.display_name.map { String(cString: $0) }, "Tip recipient") + XCTAssertTrue(restored.core_payment_address_present) + XCTAssertTrue(restored.platform_payment_address_present) + XCTAssertTrue(restored.shielded_address_present) + XCTAssertEqual(Swift.withUnsafeBytes(of: restored.shielded_address) { Data($0) }, Data(repeating: 3, count: 43)) + } + + func testOwnedProfileExplicitAbsenceIsNotRestored() throws { + // `sync_profiles` clears a profile deleted on Platform; the cached + // row must not be hydrated back on the next cold start. + let context = ModelContext(container) + let wallet = PersistentWallet(walletId: walletId, network: .testnet) + context.insert(wallet) + let account = PersistentAccount(wallet: wallet, accountType: 0, accountIndex: 0, accountTypeName: "standard") + account.accountExtendedPubKeyBytes = Data(repeating: 0xEE, count: 78) + context.insert(account) + try context.save() + + func persist(_ profile: PlatformWalletPersistenceHandler.DashpayProfileSnapshot?) { + handler.beginChangeset(walletId: walletId) + let success = handler.persistIdentities(walletId: walletId, upserts: [.init( + identityId: ownerId, balance: 0, revision: 0, identityIndex: 0, label: nil, status: 0, + walletId: walletId, dpnsNames: [], dashpayProfile: profile, contactProfiles: [])], + removed: []) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: success)) + } + persist(.init(displayName: "Tip recipient", bio: nil, publicMessage: nil, avatarUrl: nil, + avatarHash: nil, avatarFingerprint: nil, shieldedAddress: Data(repeating: 3, count: 43))) + XCTAssertEqual(try ModelContext(container).fetchCount(FetchDescriptor()), 1) + persist(nil) + XCTAssertEqual(try ModelContext(container).fetchCount(FetchDescriptor()), 1) + XCTAssertEqual(try ModelContext(container).fetchCount(FetchDescriptor()), 1) + handler.beginChangeset(walletId: walletId) + let cleared = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: ownerId, profile: nil)]) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: cleared)) + + let reader = ModelContext(container) + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 0) + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 0) + let (entries, count, errored) = handler.loadWalletList() + XCTAssertFalse(errored) + XCTAssertEqual(count, 1) + let buffer = try XCTUnwrap(entries) + defer { handler.loadWalletListFree(entries: UnsafeRawPointer(buffer)) } + XCTAssertNil(try XCTUnwrap(buffer[0].identities)[0].dashpay_profile) + } + + func testProfileOverlayRequiresIdentityNetworkToMatchCallbackWallet() throws { + let otherWalletId = Data(repeating: 0xBB, count: 32) + let context = ModelContext(container) + context.insert(PersistentWallet(walletId: otherWalletId, network: .devnet)) + try context.save() + + handler.beginChangeset(walletId: otherWalletId) + let stored = handler.persistDashpayProfiles(walletId: otherWalletId, profiles: [ + .init(identityId: ownerId, profile: .init( + displayName: "Wrong network", bio: nil, publicMessage: nil, avatarUrl: nil, + avatarHash: nil, avatarFingerprint: nil, shieldedAddress: nil + )) + ]) + XCTAssertFalse(stored) + XCTAssertFalse(handler.endChangeset(walletId: otherWalletId, success: stored)) + + let reader = ModelContext(container) + XCTAssertTrue(try reader.fetch(FetchDescriptor()).isEmpty) + } + + func testObservedProfileSurvivesAdoptionAndExplicitCallbackCanRemoveIt() throws { + let callbacks = handler.makePersistenceCallbacksExtension() + let persist = try XCTUnwrap(callbacks.on_persist_dashpay_profiles_fn) + let context = Unmanaged.passUnretained(handler!).toOpaque() + var row = ContactProfileRowFFI() + row.contact_id = Self.tuple32(ownerId) + row.is_present = true + row.shielded_address_present = true + withUnsafeMutableBytes(of: &row.shielded_address) { $0.copyBytes(from: Data(repeating: 3, count: 43)) } + handler.beginChangeset(walletId: walletId) + let stored = "Observed profile".withCString { name in + row.display_name = name + return walletId.withUnsafeBytes { wallet in + withUnsafePointer(to: &row) { persist(context, wallet.bindMemory(to: UInt8.self).baseAddress, $0, 1) } + } + } + row.display_name = nil + XCTAssertEqual(stored, 0) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: stored == 0)) + for index in [nil, UInt32(0)] { + handler.beginChangeset(walletId: walletId) + let kept = handler.persistIdentities(walletId: walletId, upserts: [.init( + identityId: ownerId, balance: 42, revision: 1, identityIndex: index, + label: nil, status: 0, walletId: walletId, dpnsNames: [], dashpayProfile: nil, + contactProfiles: [])], removed: []) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: kept)) + let reader = ModelContext(container) + XCTAssertEqual(try reader.fetch(FetchDescriptor()).first?.displayName, "Observed profile") + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 1) + } + // A tombstone is authoritative even after placement changes back to observed. + handler.beginChangeset(walletId: walletId) + let observed = handler.persistIdentities(walletId: walletId, upserts: [.init( + identityId: ownerId, balance: 42, revision: 1, identityIndex: nil, + label: nil, status: 0, walletId: walletId, dpnsNames: [], dashpayProfile: nil, + contactProfiles: [])], removed: []) + row.is_present = false + let cleared = walletId.withUnsafeBytes { wallet in + withUnsafePointer(to: &row) { persist(context, wallet.bindMemory(to: UInt8.self).baseAddress, $0, 1) } + } + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: observed && cleared == 0)) + let reader = ModelContext(container) + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 0) + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 0) + } + + func testExplicitProfileAbsenceAddressFailureRollsBackProfileAndScalarUpdate() throws { + handler.beginChangeset(walletId: walletId) + let profile = PlatformWalletPersistenceHandler.DashpayProfileSnapshot( + displayName: "Keep me", bio: nil, publicMessage: nil, avatarUrl: nil, + avatarHash: nil, avatarFingerprint: nil, shieldedAddress: Data(repeating: 3, count: 43)) + let stored = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: ownerId, profile: profile)]) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: stored)) + handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet, + modelFetcher: PaymentAddressReadFailure()) + handler.beginChangeset(walletId: walletId) + let updated = handler.persistIdentities(walletId: walletId, upserts: [.init( + identityId: ownerId, balance: 999, revision: 4, identityIndex: nil, + label: nil, status: 0, walletId: walletId, dpnsNames: [], dashpayProfile: nil, + contactProfiles: [])], removed: []) + let cleared = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: ownerId, profile: nil)]) + XCTAssertTrue(updated) + XCTAssertFalse(cleared) + XCTAssertFalse(handler.endChangeset(walletId: walletId, success: updated && cleared)) + let reader = ModelContext(container) + XCTAssertEqual(try reader.fetch(FetchDescriptor()).first?.displayName, "Keep me") + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 1) + XCTAssertEqual(try reader.fetch(FetchDescriptor()).first?.balance, 0) + } + + func testExplicitProfileAbsenceLaterCallbackFailureRollsBackDeletionAndScalarUpdate() throws { + handler.beginChangeset(walletId: walletId) + let profile = PlatformWalletPersistenceHandler.DashpayProfileSnapshot( + displayName: "Keep me", bio: nil, publicMessage: nil, avatarUrl: nil, + avatarHash: nil, avatarFingerprint: nil, shieldedAddress: Data(repeating: 3, count: 43)) + let stored = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: ownerId, profile: profile)]) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: stored)) + handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet) + + handler.beginChangeset(walletId: walletId) + let updated = handler.persistIdentities(walletId: walletId, upserts: [.init( + identityId: ownerId, balance: 999, revision: 4, identityIndex: nil, + label: nil, status: 0, walletId: walletId, dpnsNames: [], dashpayProfile: nil, + contactProfiles: [])], removed: []) + let cleared = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: ownerId, profile: nil)]) + let laterCallback = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: contactId, profile: nil)]) + XCTAssertTrue(updated) + XCTAssertTrue(cleared) + XCTAssertFalse(laterCallback) + XCTAssertFalse(handler.endChangeset(walletId: walletId, success: updated && cleared && laterCallback)) + + let reader = ModelContext(container) + let restoredProfile = try XCTUnwrap(reader.fetch(FetchDescriptor()).first) + XCTAssertEqual(restoredProfile.displayName, "Keep me") + let addresses = try XCTUnwrap(reader.fetch(FetchDescriptor()).first) + XCTAssertEqual(addresses.shieldedAddress, Data(repeating: 3, count: 43)) + let restoredIdentity = try XCTUnwrap(reader.fetch(FetchDescriptor()).first) + XCTAssertEqual(restoredIdentity.balance, 0) + XCTAssertEqual(restoredIdentity.revision, 0) } // MARK: Contact-profile tombstone delete @@ -1195,3 +1471,19 @@ final class DashPayPaymentFFIMarshallingTests: XCTestCase { XCTAssertEqual(payment.txid, "") } } + +private struct PaymentAddressReadFailure: ModelFetching { + struct ReadError: Error {} + func fetch(_ descriptor: FetchDescriptor, in context: ModelContext) throws -> [T] { + if T.self == PersistentDashpayPaymentAddresses.self { throw ReadError() } + return try context.fetch(descriptor) + } +} + +private struct ContactProfileReadFailure: ModelFetching { + struct ReadError: Error {} + func fetch(_ descriptor: FetchDescriptor, in context: ModelContext) throws -> [T] { + if T.self == PersistentDashpayContactProfile.self { throw ReadError() } + return try context.fetch(descriptor) + } +} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedAccountSnapshotTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedAccountSnapshotTests.swift new file mode 100644 index 00000000000..56598d8dabc --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedAccountSnapshotTests.swift @@ -0,0 +1,24 @@ +import XCTest +@testable import SwiftDashSDK + +@MainActor +final class ShieldedAccountSnapshotTests: XCTestCase { + /// Identity discovery can precede configureShielded. Reading the current + /// account set must still succeed so the service can perform the first bind. + func testUnconfiguredShieldedWalletReturnsEmptySnapshot() async throws { + let sdk = try SDK(network: .testnet) + let manager = try PlatformWalletManager(sdk: sdk) + do { + let wallet = try await manager.createWallet( + mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", + network: .testnet, + createDefaultAccounts: false) + XCTAssertEqual(try manager.shieldedAccountIndices(walletId: wallet.walletId), []) + XCTAssertThrowsError(try manager.shieldedAccountIndices(walletId: Data(repeating: 0x71, count: 32))) + await manager.shutdown() + } catch { + await manager.shutdown() + throw error + } + } +} diff --git a/packages/swift-sdk/schema-models.json b/packages/swift-sdk/schema-models.json index b7714b9657d..4bb7a6198fd 100644 --- a/packages/swift-sdk/schema-models.json +++ b/packages/swift-sdk/schema-models.json @@ -38,7 +38,8 @@ "PersistentTrackedMasternode": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTrackedMasternode.swift", "PersistentIdentityBalanceMetadata": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentityBalanceMetadata.swift", "PersistentPrivateContactRequestsPosition": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateContactRequestsPosition.swift", - "PersistentPrivateShieldedAddress": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateShieldedAddress.swift" + "PersistentPrivateShieldedAddress": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateShieldedAddress.swift", + "PersistentDashpayPaymentAddresses": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayPaymentAddresses.swift" }, "value_types": [ { diff --git a/scripts/check-storage-explorer.sh b/scripts/check-storage-explorer.sh index 55e150dc9d3..3f21948187c 100755 --- a/scripts/check-storage-explorer.sh +++ b/scripts/check-storage-explorer.sh @@ -16,13 +16,12 @@ DETAIL_VIEWS="$REPO_ROOT/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/View errors=0 -# Extract model type names from DashModelContainer.modelTypes array. +# Extract model type names from the current schema's model list and its +# shared declarations: modelTypes -> v3ModelTypes -> allModelTypes. # Matches lines like "PersistentFoo.self," and extracts "PersistentFoo". -# Scoped to the body of the `modelTypes` computed property so other -# `.self` references in the file (e.g. `migrationPlan: -# DashMigrationPlan.self` passed to ModelContainer) aren't mistaken -# for SwiftData models. -model_types=$(awk '/var modelTypes/{flag=1} flag{print} flag && /^ \}/{flag=0}' "$CONTAINER" \ +# Scope the scan to these declarations so frozen schema substitutions and +# unrelated references (e.g. DashMigrationPlan.self) aren't treated as models. +model_types=$(awk '/static func allModelTypes\(|static var (v3ModelTypes|modelTypes):/{flag=1} flag{print} flag && /^ \}/{flag=0}' "$CONTAINER" \ | grep -oE '[A-Z][A-Za-z0-9]+\.self' \ | sed 's/\.self//' \ | sort -u) @@ -53,7 +52,7 @@ fi # Check each model type is referenced in the explorer top-level view. echo "=== Checking StorageExplorerView.swift ===" for model in $model_types; do - if ! grep -q "$model" "$EXPLORER"; then + if ! grep -qw "$model" "$EXPLORER"; then echo " MISSING: $model not referenced in StorageExplorerView.swift" errors=$((errors + 1)) else @@ -66,7 +65,7 @@ echo "" # containing @Query of the model type). echo "=== Checking StorageModelListViews.swift ===" for model in $model_types; do - if ! grep -q "$model" "$LIST_VIEWS"; then + if ! grep -qw "$model" "$LIST_VIEWS"; then echo " MISSING: $model has no list view in StorageModelListViews.swift" errors=$((errors + 1)) else @@ -78,7 +77,7 @@ echo "" # Check each model type has a detail view. echo "=== Checking StorageRecordDetailViews.swift ===" for model in $model_types; do - if ! grep -q "$model" "$DETAIL_VIEWS"; then + if ! grep -qw "$model" "$DETAIL_VIEWS"; then echo " MISSING: $model has no detail view in StorageRecordDetailViews.swift" errors=$((errors + 1)) else