@bsv/expo-wallet-toolbox 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +311 -0
- package/README.md +52 -1
- package/assets/sounds/vault-deposit.wav +0 -0
- package/assets/sounds/vault-withdraw.wav +0 -0
- package/core/config.tsx +21 -18
- package/core/context/VaultContext.tsx +8 -11
- package/core/context/WalletConnectionContext.tsx +137 -52
- package/core/context/WalletContext.tsx +413 -23
- package/core/hooks/useConfirmationSound.ts +14 -8
- package/core/i18n/translations.tsx +3368 -952
- package/core/index.ts +107 -14
- package/core/localpay/build.ts +674 -37
- package/core/localpay/codec.ts +68 -5
- package/core/localpay/pending.ts +240 -22
- package/core/localpay/settlementAck.ts +149 -0
- package/core/localpay/types.ts +14 -1
- package/core/localpay/verify.ts +118 -69
- package/core/mandala/abortGuard.ts +134 -0
- package/core/mandala/basketMigration.ts +166 -0
- package/core/mandala/bundle.ts +244 -0
- package/core/mandala/createRuntime.ts +2437 -0
- package/core/mandala/drain.ts +670 -0
- package/core/mandala/permissionModule.ts +642 -0
- package/core/mandala/resendTransfer.ts +175 -0
- package/core/mandala/runtime.ts +357 -0
- package/core/mandala/settlementStore.ts +412 -0
- package/core/mandala/types.ts +290 -0
- package/core/offline/cancelParked.ts +94 -1
- package/core/offline/payerHold.ts +152 -12
- package/core/offline/tokenFrames.ts +197 -0
- package/core/parsePeerPayURI.ts +70 -17
- package/core/pay/rails/address.ts +51 -3
- package/core/pay/rails/handle.ts +88 -9
- package/core/pay/rails/index.ts +16 -6
- package/core/pay/rails/nearby.ts +114 -4
- package/core/services/capWalletArgs.ts +8 -9
- package/core/services/externalOrigin.ts +39 -0
- package/core/services/vault/VaultKeyService.ts +912 -251
- package/core/services/vault/ceremony.ts +435 -367
- package/core/services/vault/ceremonyHost.ts +27 -21
- package/core/services/vault/devMock.ts +30 -7
- package/core/services/vault/driver.ts +95 -41
- package/core/services/vault/guard.ts +514 -56
- package/core/services/vault/hardwareLease.ts +22 -0
- package/core/services/vault/mockYubiKey.ts +258 -90
- package/core/services/vault/pivReset.ts +145 -0
- package/core/services/vault/r1comb.ts +976 -0
- package/core/services/vault/session.ts +93 -26
- package/core/services/vault/transfers.ts +2617 -747
- package/core/services/vault/types.ts +100 -43
- package/core/services/vault/vaultStore.ts +991 -74
- package/core/services/walletConnectionValidation.ts +293 -0
- package/core/services/walletServiceConfig.ts +19 -24
- package/core/storage/StorageExpoSQLite.ts +382 -56
- package/core/storage/dbImage.ts +48 -0
- package/core/storage/methods/findSql.ts +0 -54
- package/core/storage/methods/listOutputsSql.ts +7 -3
- package/core/storage/methods/offlineActions.ts +15 -0
- package/core/storage/methods/processOfflineActions.ts +263 -6
- package/core/storage/methods/walletBalanceSql.ts +16 -4
- package/core/storage/schema/createTables.ts +123 -0
- package/core/storage/sqlUpdateValue.ts +24 -0
- package/core/toolboxConfig.ts +240 -0
- package/core/walletRepair/runWalletCheck.ts +19 -2
- package/package.json +25 -24
- package/ui/components/QRScanner.tsx +1 -1
- package/ui/components/pay/AdmissionNotice.tsx +99 -0
- package/ui/components/pay/AssetPicker.tsx +184 -0
- package/ui/components/pay/AvailableBalance.tsx +33 -2
- package/ui/components/pay/HandleReceive.tsx +213 -50
- package/ui/components/pay/NearbyFlow.tsx +616 -69
- package/ui/components/pay/PayForm.tsx +73 -8
- package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
- package/ui/components/pay/RecipientField.tsx +49 -4
- package/ui/components/pay/RequestHub.tsx +68 -8
- package/ui/components/pay/ResultBanner.tsx +41 -4
- package/ui/components/pay/UniversalSend.tsx +534 -30
- package/ui/components/pay/tokenSendCopy.ts +116 -0
- package/ui/components/pay/useRecipientInput.ts +36 -7
- package/ui/components/ui/PermissionSheet.tsx +65 -4
- package/ui/components/ui/Sheet.tsx +9 -2
- package/ui/components/vault/EnrollWizard.tsx +1432 -488
- package/ui/components/vault/KeyChooser.tsx +96 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
- package/ui/components/vault/vaultErrorCopy.ts +145 -0
- package/ui/components/wallet/ActivityRow.tsx +101 -17
- package/ui/components/wallet/AmountInput.tsx +77 -25
- package/ui/components/wallet/AssetAmount.tsx +95 -0
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
- package/ui/components/wallet/tokenEviction.ts +65 -0
- package/ui/hooks/useExportWalletData.ts +39 -0
- package/ui/hooks/useMandala.ts +303 -0
- package/ui/hooks/useVaultBalance.ts +105 -7
- package/ui/hooks/useVaultCoverage.ts +52 -0
- package/ui/importDatabases.ts +7 -3
- package/ui/index.ts +50 -7
- package/ui/screens/ConnectionsScreen.tsx +46 -29
- package/ui/screens/PairScreen.tsx +12 -12
- package/ui/screens/PayScreen.tsx +130 -10
- package/ui/screens/SettingsScreen.tsx +18 -9
- package/ui/screens/VaultScreen.tsx +925 -171
- package/ui/screens/VaultTransferScreen.tsx +376 -123
- package/ui/screens/WalletCheckScreen.tsx +10 -1
- package/ui/screens/WalletConfigScreen.tsx +42 -20
- package/ui/screens/WalletHomeScreen.tsx +417 -86
- package/ui/screens/homeBadges.ts +9 -1
- package/ui/screens/tokenRowTitle.ts +68 -0
- package/ui/tokenFormat.ts +108 -0
- package/ui/tokenSeen.ts +75 -0
- package/ui/tokenStatus.ts +79 -0
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/services/vault/k1.ts +0 -75
- package/core/services/vault/sealing.ts +0 -84
- package/core/services/vault/vaultDerivation.ts +0 -152
- package/core/services/vault/vaultPassphrase.ts +0 -287
- package/ui/components/vault/PassphraseField.tsx +0 -306
- package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
- package/ui/screens/VaultRecoverScreen.tsx +0 -226
|
@@ -6,13 +6,11 @@ import {
|
|
|
6
6
|
buildFindSql,
|
|
7
7
|
columnsExcluding,
|
|
8
8
|
rangeReadSql,
|
|
9
|
-
RELEASE_STALE_VAULT_STAGING_SPENTBY_SQL,
|
|
10
|
-
RELEASE_STRANDED_VAULT_STAGING_SQL,
|
|
11
9
|
spendingReferencesSql,
|
|
12
10
|
splitOutpoint
|
|
13
11
|
} from './methods/findSql'
|
|
14
12
|
import { scrubHistoryJson } from './methods/historyNotes'
|
|
15
|
-
import { sqlBindValue } from './sqlUpdateValue'
|
|
13
|
+
import { BYTE_COLUMNS, bytesForColumn, sqlBindValue } from './sqlUpdateValue'
|
|
16
14
|
import { StorageError, storageErrorFromSqlite } from './errors'
|
|
17
15
|
import {
|
|
18
16
|
RECLAIM_CANDIDATES_SQL,
|
|
@@ -48,6 +46,8 @@ import type {
|
|
|
48
46
|
PurgeParams,
|
|
49
47
|
PurgeResults,
|
|
50
48
|
RequestSyncChunkArgs,
|
|
49
|
+
StorageProcessActionArgs,
|
|
50
|
+
StorageProcessActionResults,
|
|
51
51
|
SyncChunk,
|
|
52
52
|
TrxToken
|
|
53
53
|
} from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
|
|
@@ -72,8 +72,8 @@ import type {
|
|
|
72
72
|
TableUser
|
|
73
73
|
} from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
|
|
74
74
|
import type { ListActionsResult, ListOutputsResult, Validation, WalletLoggerInterface } from '@bsv/sdk'
|
|
75
|
-
import { Beef } from '@bsv/sdk'
|
|
76
|
-
import
|
|
75
|
+
import { Beef, Transaction } from '@bsv/sdk'
|
|
76
|
+
import { EntityProvenTxReq } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/entities'
|
|
77
77
|
import type { PostReqsToNetworkResult } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/attemptToPostReqsToNetwork'
|
|
78
78
|
import { listActionsSql } from './methods/listActionsSql'
|
|
79
79
|
import { listOutputsSql } from './methods/listOutputsSql'
|
|
@@ -94,12 +94,30 @@ import {
|
|
|
94
94
|
import { buildOfflineHoldResult, groupOfflineHolds } from '../offline/hold'
|
|
95
95
|
import { getOnline } from '../net/online'
|
|
96
96
|
import { TaskSendOffline } from '../monitor/TaskSendOffline'
|
|
97
|
+
import { isR1CLockingScript } from '../services/vault/guard'
|
|
97
98
|
|
|
98
99
|
export interface StorageExpoSQLiteOptions extends StorageProviderOptions {
|
|
99
100
|
databaseName?: string
|
|
100
101
|
identityKey?: string
|
|
101
102
|
}
|
|
102
103
|
|
|
104
|
+
/** What `repairSettledTokenTransaction` actually changed, for the caller's log. */
|
|
105
|
+
export interface TokenTransactionRepair {
|
|
106
|
+
txid: string
|
|
107
|
+
/** Transaction rows moved back to 'unproven'. */
|
|
108
|
+
transactionIds: number[]
|
|
109
|
+
/** Their statuses before the repair — 'failed', in the case this exists for. */
|
|
110
|
+
wasTxStatuses: string[]
|
|
111
|
+
/** The request's status before the repair, or undefined when there was none. */
|
|
112
|
+
wasReqStatus?: string
|
|
113
|
+
/** Coins this transaction spends that were wrongly spendable and are now spent. */
|
|
114
|
+
inputsMarkedSpent: number
|
|
115
|
+
/** This transaction's own outputs (change included) restored to spendable. */
|
|
116
|
+
outputsMadeSpendable: number
|
|
117
|
+
/** True when the request had gone and was rebuilt from the raw transaction. */
|
|
118
|
+
reqCreated: boolean
|
|
119
|
+
}
|
|
120
|
+
|
|
103
121
|
/** Per-connection wait before a lock contention becomes "database is locked". */
|
|
104
122
|
export const BUSY_TIMEOUT_MS = 5000
|
|
105
123
|
|
|
@@ -135,6 +153,25 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
135
153
|
this.dbName = options.databaseName || `wallet-${keySuffix}-${this.chain}net.db`
|
|
136
154
|
}
|
|
137
155
|
|
|
156
|
+
/**
|
|
157
|
+
* Final Vault authorization check for explicit transaction inputs.
|
|
158
|
+
*
|
|
159
|
+
* The toolbox invokes this only after it has resolved the immutable source
|
|
160
|
+
* locking script from authenticated local storage or verified BEEF. This is
|
|
161
|
+
* the database-side backstop for history-scan races: even if an R1C output
|
|
162
|
+
* appears between an external guard scan and createAction, the reservation
|
|
163
|
+
* cannot proceed without the host-derived internal-admin marker.
|
|
164
|
+
*/
|
|
165
|
+
async validateResolvedActionInput(
|
|
166
|
+
vargs: { __bsvVaultAdminAuthorized?: boolean },
|
|
167
|
+
input: { lockingScript?: { toHex(): string } }
|
|
168
|
+
): Promise<void> {
|
|
169
|
+
const lockingScript = input.lockingScript?.toHex()
|
|
170
|
+
if (lockingScript && isR1CLockingScript(lockingScript) && vargs.__bsvVaultAdminAuthorized !== true) {
|
|
171
|
+
throw new Error('Vault R1C inputs require internal wallet authorization')
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
138
175
|
// ============================================================================
|
|
139
176
|
// Infrastructure methods
|
|
140
177
|
// ============================================================================
|
|
@@ -398,7 +435,9 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
398
435
|
}
|
|
399
436
|
for (const key of Object.keys(v)) {
|
|
400
437
|
const val = v[key]
|
|
401
|
-
if (
|
|
438
|
+
if (BYTE_COLUMNS.has(key)) {
|
|
439
|
+
v[key] = bytesForColumn(key, val)
|
|
440
|
+
} else if (Array.isArray(val) && (val.length === 0 || Number.isInteger(val[0]))) {
|
|
402
441
|
v[key] = Uint8Array.from(val)
|
|
403
442
|
} else if (val === null) {
|
|
404
443
|
v[key] = undefined
|
|
@@ -435,7 +474,9 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
435
474
|
}
|
|
436
475
|
for (const key of Object.keys(v)) {
|
|
437
476
|
const val = v[key]
|
|
438
|
-
if (
|
|
477
|
+
if (BYTE_COLUMNS.has(key)) {
|
|
478
|
+
v[key] = bytesForColumn(key, val)
|
|
479
|
+
} else if (Array.isArray(val) && (val.length === 0 || Number.isInteger(val[0]))) {
|
|
439
480
|
v[key] = Uint8Array.from(val)
|
|
440
481
|
} else if (val === null) {
|
|
441
482
|
v[key] = undefined
|
|
@@ -1363,7 +1404,7 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1363
1404
|
* getSyncChunk reads to build a backup chunk.
|
|
1364
1405
|
*/
|
|
1365
1406
|
async getProvenTxsForUser(args: FindForUserSincePagedArgs): Promise<TableProvenTx[]> {
|
|
1366
|
-
const db = this.getDB()
|
|
1407
|
+
const db = this.getDB(args.trx)
|
|
1367
1408
|
let query = `SELECT pt.* FROM proven_txs pt
|
|
1368
1409
|
WHERE EXISTS (SELECT 1 FROM transactions t WHERE t.provenTxId = pt.provenTxId AND t.userId = ?)`
|
|
1369
1410
|
const params: any[] = [args.userId]
|
|
@@ -1381,7 +1422,7 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1381
1422
|
}
|
|
1382
1423
|
|
|
1383
1424
|
async getProvenTxReqsForUser(args: FindForUserSincePagedArgs): Promise<TableProvenTxReq[]> {
|
|
1384
|
-
const db = this.getDB()
|
|
1425
|
+
const db = this.getDB(args.trx)
|
|
1385
1426
|
let query = `SELECT ptr.* FROM proven_tx_reqs ptr
|
|
1386
1427
|
WHERE EXISTS (SELECT 1 FROM transactions t WHERE t.txid = ptr.txid AND t.userId = ?)`
|
|
1387
1428
|
const params: any[] = [args.userId]
|
|
@@ -1399,7 +1440,7 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1399
1440
|
}
|
|
1400
1441
|
|
|
1401
1442
|
async getTxLabelMapsForUser(args: FindForUserSincePagedArgs): Promise<TableTxLabelMap[]> {
|
|
1402
|
-
const db = this.getDB()
|
|
1443
|
+
const db = this.getDB(args.trx)
|
|
1403
1444
|
let query = `SELECT tlm.* FROM tx_labels_map tlm
|
|
1404
1445
|
WHERE EXISTS (SELECT 1 FROM tx_labels tl WHERE tl.txLabelId = tlm.txLabelId AND tl.userId = ?)`
|
|
1405
1446
|
const params: any[] = [args.userId]
|
|
@@ -1417,7 +1458,7 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1417
1458
|
}
|
|
1418
1459
|
|
|
1419
1460
|
async getOutputTagMapsForUser(args: FindForUserSincePagedArgs): Promise<TableOutputTagMap[]> {
|
|
1420
|
-
const db = this.getDB()
|
|
1461
|
+
const db = this.getDB(args.trx)
|
|
1421
1462
|
let query = `SELECT otm.* FROM output_tags_map otm
|
|
1422
1463
|
WHERE EXISTS (SELECT 1 FROM output_tags ot WHERE ot.outputTagId = otm.outputTagId AND ot.userId = ?)`
|
|
1423
1464
|
const params: any[] = [args.userId]
|
|
@@ -1520,41 +1561,6 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1520
1561
|
.map(r => ({ reference: r.reference as string, status: r.status as string }))
|
|
1521
1562
|
}
|
|
1522
1563
|
|
|
1523
|
-
/**
|
|
1524
|
-
* Release every input a definitively-invalid vault deposit tx2 still holds.
|
|
1525
|
-
* Returns how many outputs were made spendable again.
|
|
1526
|
-
*
|
|
1527
|
-
* The shape being healed (production, 2026-08-21): tx2 was rejected by every
|
|
1528
|
-
* broadcaster (proven_tx_reqs.status = 'invalid', transactions.status =
|
|
1529
|
-
* 'failed'), the toolbox's own release of its inputs was then OVERRIDDEN by
|
|
1530
|
-
* markStaleInputsAsSpent — which asked the indexers about tx1's staging
|
|
1531
|
-
* output seconds after tx1 broadcast, and indexer lag said "not a UTXO" —
|
|
1532
|
-
* and abortAction cannot help because 'failed' is in its unAbortable list.
|
|
1533
|
-
* The staging coin (and any change the toolbox pulled in as extra funding)
|
|
1534
|
-
* sits spendable=0 forever while it is live on chain.
|
|
1535
|
-
*
|
|
1536
|
-
* The predicate is deliberately narrow, every clause load-bearing:
|
|
1537
|
-
* - spentBy transaction has status 'failed' AND its proven_tx_req is
|
|
1538
|
-
* 'invalid' — the network REJECTED the spender outright; it can never be
|
|
1539
|
-
* mined, so releasing its inputs cannot enable a real double-spend. A
|
|
1540
|
-
* 'failed' tx without an 'invalid' req (e.g. a broadcast that timed out
|
|
1541
|
-
* but may have propagated) is NOT touched.
|
|
1542
|
-
* - the spender carries the 'vault-deposit' label — this heal exists for
|
|
1543
|
-
* the deposit flow and must not reinterpret failures of anything else.
|
|
1544
|
-
*/
|
|
1545
|
-
async releaseVaultStagingStrandedByInvalidTx(): Promise<number> {
|
|
1546
|
-
if (!this.isAvailable()) await this.makeAvailable()
|
|
1547
|
-
const r = await this.getDB().runAsync(RELEASE_STRANDED_VAULT_STAGING_SQL, [])
|
|
1548
|
-
// The other arm: coins already spendable=1 but with a stale spentBy still
|
|
1549
|
-
// naming the failed spender (updateOutput's spentBy: undefined is dropped
|
|
1550
|
-
// by sqlUpdate). createAction refuses those with WERR_REVIEW_ACTIONS, so
|
|
1551
|
-
// they are just as stuck as the spendable=0 arm until cleared.
|
|
1552
|
-
const r2 = await this.getDB().runAsync(RELEASE_STALE_VAULT_STAGING_SPENTBY_SQL, [])
|
|
1553
|
-
const released = (r?.changes ?? 0) + (r2?.changes ?? 0)
|
|
1554
|
-
if (released > 0) console.log('[vault] released %d output(s) stranded by invalid deposit tx', released)
|
|
1555
|
-
return released
|
|
1556
|
-
}
|
|
1557
|
-
|
|
1558
1564
|
/** Size of the database file on disk, or null when it cannot be read. */
|
|
1559
1565
|
async databaseFileBytes(): Promise<number | null> {
|
|
1560
1566
|
try {
|
|
@@ -1850,6 +1856,141 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1850
1856
|
}, args.trx)
|
|
1851
1857
|
}
|
|
1852
1858
|
|
|
1859
|
+
/**
|
|
1860
|
+
* Put a token transaction the wallet wrongly failed back into a live state,
|
|
1861
|
+
* for a caller that has independently established the transaction IS on chain.
|
|
1862
|
+
*
|
|
1863
|
+
* WHY THIS EXISTS RATHER THAN A CALL INTO THE TOOLBOX. Every sanctioned
|
|
1864
|
+
* un-fail path in `@bsv/wallet-toolbox-mobile` is gated on something this case
|
|
1865
|
+
* cannot supply:
|
|
1866
|
+
*
|
|
1867
|
+
* · `updateTransactionStatus` refuses outright — "A 'failed' transaction may
|
|
1868
|
+
* not be un-failed by this method" (`StorageProvider.js`), and `reviewStatus`
|
|
1869
|
+
* only ever moves rows TOWARDS failed.
|
|
1870
|
+
* · `TaskUnFail` is the real recovery path, but its entry point demands
|
|
1871
|
+
* `services.getMerklePath(txid)` first and returns the req to `'invalid'`
|
|
1872
|
+
* when there is none. A transaction the overlay broadcast seconds ago has
|
|
1873
|
+
* no merkle path and will not have one for ten minutes, which is precisely
|
|
1874
|
+
* the window in which the wallet's own bookkeeping is wrong and its coins
|
|
1875
|
+
* are wrongly spendable.
|
|
1876
|
+
* · `unfailTransactionsForProof` — the body TaskUnFail delegates to — is the
|
|
1877
|
+
* right SHAPE (tx to 'unproven', inputs to spent, req to 'unmined'), and
|
|
1878
|
+
* the steps below are deliberately identical to it, EXCEPT that it decides
|
|
1879
|
+
* each of this transaction's own outputs by `services.isUtxo(output)`. For
|
|
1880
|
+
* a tx broadcast moments ago that probe answers "not a utxo" from services
|
|
1881
|
+
* that have not seen it yet, which would leave the change permanently
|
|
1882
|
+
* unspendable — the opposite of the repair.
|
|
1883
|
+
*
|
|
1884
|
+
* So the steps are written out here, through the provider's own CRUD methods
|
|
1885
|
+
* (`updateTransaction`/`updateOutput`/`updateProvenTxReq`), and never as raw
|
|
1886
|
+
* SQL over the tables. What it does, in one write transaction:
|
|
1887
|
+
*
|
|
1888
|
+
* 1. every transaction row for `txid` that is not already `'completed'`
|
|
1889
|
+
* goes to `'unproven'` — broadcast, awaiting proof;
|
|
1890
|
+
* 2. every input the raw transaction spends that is one of THIS user's
|
|
1891
|
+
* outputs goes back to `spendable: false, spentBy: <this transaction>`.
|
|
1892
|
+
* This is the money-safety step: `updateTransactionStatus('failed')`
|
|
1893
|
+
* released those coins, and they are spent on chain;
|
|
1894
|
+
* 3. this transaction's own outputs go back to `spendable: true`, except any
|
|
1895
|
+
* a different transaction has since spent (`spentBy` set), which are left
|
|
1896
|
+
* exactly as they are;
|
|
1897
|
+
* 4. the request goes to `'unmined'` with `attempts: 0`, which is one of the
|
|
1898
|
+
* statuses `TaskCheckForProofs` polls, so the monitor proves it from here
|
|
1899
|
+
* exactly as it would any other broadcast transaction. A request that has
|
|
1900
|
+
* gone missing entirely is recreated from the transaction's own raw bytes.
|
|
1901
|
+
*
|
|
1902
|
+
* Returns `undefined` when there was nothing to repair (no transaction row, no
|
|
1903
|
+
* raw bytes to read the inputs from, or a transaction that is already live) —
|
|
1904
|
+
* the caller logs, and nothing is written.
|
|
1905
|
+
*/
|
|
1906
|
+
async repairSettledTokenTransaction(txid: string): Promise<TokenTransactionRepair | undefined> {
|
|
1907
|
+
const transactions = await this.findTransactions({ partial: { txid } })
|
|
1908
|
+
if (transactions.length === 0) return undefined
|
|
1909
|
+
const req = (await this.findProvenTxReqs({ partial: { txid } }))[0]
|
|
1910
|
+
|
|
1911
|
+
// Nothing to do unless the wallet actually believes this transaction died.
|
|
1912
|
+
const damaged = transactions.some(t => t.status === 'failed') || req?.status === 'invalid'
|
|
1913
|
+
if (!damaged) return undefined
|
|
1914
|
+
|
|
1915
|
+
const rawTx = req?.rawTx ?? transactions.find(t => t.rawTx && t.rawTx.length > 0)?.rawTx
|
|
1916
|
+
if (!rawTx || rawTx.length === 0) {
|
|
1917
|
+
devLog(`[StorageExpoSQLite] cannot repair ${txid}: no raw transaction to read its inputs from`)
|
|
1918
|
+
return undefined
|
|
1919
|
+
}
|
|
1920
|
+
let parsed: Transaction
|
|
1921
|
+
try {
|
|
1922
|
+
parsed = Transaction.fromBinary([...rawTx])
|
|
1923
|
+
} catch (e) {
|
|
1924
|
+
devLog(`[StorageExpoSQLite] cannot repair ${txid}: its raw transaction will not parse:`, e)
|
|
1925
|
+
return undefined
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
const repair: TokenTransactionRepair = {
|
|
1929
|
+
txid,
|
|
1930
|
+
transactionIds: [],
|
|
1931
|
+
wasTxStatuses: transactions.map(t => t.status),
|
|
1932
|
+
wasReqStatus: req?.status,
|
|
1933
|
+
inputsMarkedSpent: 0,
|
|
1934
|
+
outputsMadeSpendable: 0,
|
|
1935
|
+
reqCreated: false
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
await this.transaction(async trx => {
|
|
1939
|
+
for (const tx of transactions) {
|
|
1940
|
+
if (tx.status === 'completed') continue
|
|
1941
|
+
repair.transactionIds.push(tx.transactionId)
|
|
1942
|
+
await this.updateTransaction(tx.transactionId, { status: 'unproven' }, trx)
|
|
1943
|
+
|
|
1944
|
+
for (const input of parsed.inputs) {
|
|
1945
|
+
const sourceTXID = input.sourceTXID ?? input.sourceTransaction?.id('hex')
|
|
1946
|
+
if (!sourceTXID || typeof input.sourceOutputIndex !== 'number') continue
|
|
1947
|
+
const matches = await this.findOutputs({
|
|
1948
|
+
partial: { userId: tx.userId, txid: sourceTXID, vout: input.sourceOutputIndex },
|
|
1949
|
+
trx
|
|
1950
|
+
})
|
|
1951
|
+
for (const output of matches) {
|
|
1952
|
+
if (output.outputId == null) continue
|
|
1953
|
+
await this.updateOutput(output.outputId, { spendable: false, spentBy: tx.transactionId }, trx)
|
|
1954
|
+
repair.inputsMarkedSpent++
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
|
|
1958
|
+
const own = await this.findOutputs({ partial: { userId: tx.userId, transactionId: tx.transactionId }, trx })
|
|
1959
|
+
for (const output of own) {
|
|
1960
|
+
// Spent by something else since the failure: that spend is the newer
|
|
1961
|
+
// fact about this coin and must not be undone by a repair.
|
|
1962
|
+
if (output.outputId == null || output.spentBy != null || output.spendable) continue
|
|
1963
|
+
await this.updateOutput(output.outputId, { spendable: true }, trx)
|
|
1964
|
+
repair.outputsMadeSpendable++
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
if (req) {
|
|
1969
|
+
await this.updateProvenTxReq(req.provenTxReqId, { status: 'unmined', attempts: 0 }, trx)
|
|
1970
|
+
} else {
|
|
1971
|
+
const now = new Date()
|
|
1972
|
+
await this.insertProvenTxReq(
|
|
1973
|
+
{
|
|
1974
|
+
created_at: now,
|
|
1975
|
+
updated_at: now,
|
|
1976
|
+
provenTxReqId: 0,
|
|
1977
|
+
txid,
|
|
1978
|
+
status: 'unmined',
|
|
1979
|
+
attempts: 0,
|
|
1980
|
+
notified: false,
|
|
1981
|
+
history: '{}',
|
|
1982
|
+
notify: JSON.stringify({ transactionIds: repair.transactionIds }),
|
|
1983
|
+
rawTx: [...rawTx]
|
|
1984
|
+
} as TableProvenTxReq,
|
|
1985
|
+
trx
|
|
1986
|
+
)
|
|
1987
|
+
repair.reqCreated = true
|
|
1988
|
+
}
|
|
1989
|
+
})
|
|
1990
|
+
|
|
1991
|
+
return repair
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1853
1994
|
async purgeData(_params: PurgeParams, _trx?: TrxToken): Promise<PurgeResults> {
|
|
1854
1995
|
return { count: 0, log: '' }
|
|
1855
1996
|
}
|
|
@@ -1929,7 +2070,81 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1929
2070
|
}
|
|
1930
2071
|
|
|
1931
2072
|
/**
|
|
1932
|
-
*
|
|
2073
|
+
* Guard #2 for the monitor's own retry path.
|
|
2074
|
+
*
|
|
2075
|
+
* `TaskSendWaiting` posts 'unsent' requests through the module function, not
|
|
2076
|
+
* through `attemptToPostReqsToNetwork` on this instance, so the hold below
|
|
2077
|
+
* never saw them — and an internalized token payment lands exactly there:
|
|
2078
|
+
* `internalizeAction` with delayed broadcast leaves its request 'unsent'. On
|
|
2079
|
+
* 2026-09-15 a recipient wallet raw-broadcast four just-credited token
|
|
2080
|
+
* transactions (one of them a known double-spend) before any `/submit`.
|
|
2081
|
+
* `WalletContext` calls this from its `processUnsent` patch: every request
|
|
2082
|
+
* with a `token_settlements` row is held for the drain and the caller is
|
|
2083
|
+
* told which ones, so it posts only the rest. Never throws.
|
|
2084
|
+
*/
|
|
2085
|
+
async holdTokenReqsForDrain(reqApis: TableProvenTxReq[]): Promise<Set<string>> {
|
|
2086
|
+
try {
|
|
2087
|
+
const tokenTxids = await this.tokenSettlementTxids(reqApis.map(r => r.txid))
|
|
2088
|
+
if (tokenTxids.size === 0) return tokenTxids
|
|
2089
|
+
const reqs = reqApis.filter(r => tokenTxids.has(r.txid)).map(r => new EntityProvenTxReq(r))
|
|
2090
|
+
devLog(`[StorageExpoSQLite] holding ${reqs.length} token req(s) from the monitor's retry for the settlement drain`)
|
|
2091
|
+
await this.holdTokenReqs(reqs)
|
|
2092
|
+
return tokenTxids
|
|
2093
|
+
} catch (e) {
|
|
2094
|
+
devLog('[StorageExpoSQLite] could not hold token reqs from the monitor retry; withholding them anyway:', e)
|
|
2095
|
+
return new Set(reqApis.map(r => r.txid))
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
|
|
2099
|
+
/**
|
|
2100
|
+
* Which of these txids the Mandala settlement drain owns.
|
|
2101
|
+
*
|
|
2102
|
+
* A missing table (a device that has not yet run the additive migration) or
|
|
2103
|
+
* any other read failure yields the empty set, which is exactly the
|
|
2104
|
+
* pre-feature behaviour — logged, never thrown, because a broken read here
|
|
2105
|
+
* must not take down every broadcast in the wallet.
|
|
2106
|
+
*/
|
|
2107
|
+
private async tokenSettlementTxids(txids: string[]): Promise<Set<string>> {
|
|
2108
|
+
if (txids.length === 0 || !this.db) return new Set()
|
|
2109
|
+
try {
|
|
2110
|
+
const rows = (await this.db.getAllAsync(
|
|
2111
|
+
`SELECT txid FROM token_settlements WHERE txid IN (${txids.map(() => '?').join(',')})`,
|
|
2112
|
+
txids
|
|
2113
|
+
)) as { txid: string }[]
|
|
2114
|
+
return new Set(rows.map(r => r.txid))
|
|
2115
|
+
} catch (e) {
|
|
2116
|
+
devLog('[StorageExpoSQLite] could not read token_settlements, treating every req as plain BSV:', e)
|
|
2117
|
+
return new Set()
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
|
|
2121
|
+
/**
|
|
2122
|
+
* Hold token requests whatever `groupOfflineHolds` says.
|
|
2123
|
+
*
|
|
2124
|
+
* The all-or-nothing refusal `groupOfflineHolds` offers is right for the BSV
|
|
2125
|
+
* path — refusing there falls back to the ordinary broadcast. For a token req
|
|
2126
|
+
* that fallback is precisely the harm this guard exists to prevent, so an
|
|
2127
|
+
* ungroupable token req is simply not broadcast: it keeps its
|
|
2128
|
+
* `token_settlements` row, which the drain owns independently of any queue
|
|
2129
|
+
* bookkeeping (FIX I) and which `listStuckSettlements` surfaces if it never
|
|
2130
|
+
* moves. The failure is loud in the log and recoverable; a premature
|
|
2131
|
+
* broadcast is neither.
|
|
2132
|
+
*/
|
|
2133
|
+
private async holdTokenReqs(reqs: EntityProvenTxReq[]): Promise<void> {
|
|
2134
|
+
const holds = groupOfflineHolds(await this.resolveHoldPairs(reqs))
|
|
2135
|
+
if (!holds) {
|
|
2136
|
+
devLog(
|
|
2137
|
+
'[StorageExpoSQLite] token req(s) could not be attributed for a queue row; withholding anyway:',
|
|
2138
|
+
reqs.map(r => r.txid).join(', ')
|
|
2139
|
+
)
|
|
2140
|
+
return
|
|
2141
|
+
}
|
|
2142
|
+
for (const hold of holds.values()) await this.holdReqsOffline(hold.reqs, hold.userId, hold.role)
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
/**
|
|
2146
|
+
* Offline, hold the requests. Online, behave exactly as before — EXCEPT for a
|
|
2147
|
+
* token request, which is held either way.
|
|
1933
2148
|
*
|
|
1934
2149
|
* This override is reached only from `shareReqsWithWorld`
|
|
1935
2150
|
* (`storage/methods/processAction.js:146`, a method call on storage), which
|
|
@@ -1938,15 +2153,105 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1938
2153
|
* directly (`monitor/tasks/TaskSendWaiting.js:180`), so the monitor's
|
|
1939
2154
|
* ordinary broadcast retries are deliberately NOT intercepted.
|
|
1940
2155
|
*
|
|
1941
|
-
*
|
|
1942
|
-
*
|
|
1943
|
-
*
|
|
1944
|
-
*
|
|
1945
|
-
*
|
|
2156
|
+
* **Token guard (offline-settlement spec §4.3, guard #2).** A transaction
|
|
2157
|
+
* with a `token_settlements` row may only be broadcast by `postTokenStep`,
|
|
2158
|
+
* after the issuer's overlay has admitted it and every unadmitted token
|
|
2159
|
+
* ancestor it spends. Holding "only when offline" left the common shop case
|
|
2160
|
+
* wide open — payee has Wi-Fi, payer none — because the payee's own
|
|
2161
|
+
* `internalizeAction` then reached a real, unmediated broadcast. So token
|
|
2162
|
+
* reqs are split off and held unconditionally, and the online branch is taken
|
|
2163
|
+
* only for what is left. The result still covers every txid the caller handed
|
|
2164
|
+
* in: reporting on a subset would make `internalizeAction` roll back a
|
|
2165
|
+
* payment that was in fact accepted for delivery.
|
|
2166
|
+
*
|
|
2167
|
+
* Guard #3 follows from this one: because a token req is never handed to
|
|
2168
|
+
* `sendWith` outside `postTokenStep`, it never reaches `unsent`/`sending`,
|
|
2169
|
+
* which is all that keeps `TaskSendWaiting` — which bypasses this override
|
|
2170
|
+
* entirely — from broadcasting it out from under the drain.
|
|
2171
|
+
*
|
|
2172
|
+
* Narrower than "offline means hold" on the BSV side: only requests whose
|
|
2173
|
+
* transaction is already in a hold-safe status are parked, so in practice
|
|
2174
|
+
* this holds the internalize path the feature needs and leaves the
|
|
2175
|
+
* non-delayed `createAction` path with the `serviceError` and automatic
|
|
2176
|
+
* `TaskSendWaiting` retry it has today. `groupOfflineHolds` makes that call;
|
|
2177
|
+
* see `utils/offline/hold.ts`.
|
|
1946
2178
|
*
|
|
1947
2179
|
* The returned 'success' means "accepted for delivery", not "the network has
|
|
1948
2180
|
* it"; see `utils/offline/hold.ts` for why nothing persisted claims otherwise.
|
|
1949
2181
|
*/
|
|
2182
|
+
/**
|
|
2183
|
+
* Guard #2's RESULT half: a held token request must not read as a posted one.
|
|
2184
|
+
*
|
|
2185
|
+
* `attemptToPostReqsToNetwork` answers `status: 'success'` for a token
|
|
2186
|
+
* request it HELD, and it has to — `'success'` there means "accepted for
|
|
2187
|
+
* delivery", which is what stops `internalizeAction` rolling back a payment
|
|
2188
|
+
* it has already verified (see `offline/hold.ts`). But `aggregateActionResults`
|
|
2189
|
+
* turns that same `'success'` into `SendWithResult.status = 'unproven'`,
|
|
2190
|
+
* i.e. "the processing network has accepted this transaction" — and on
|
|
2191
|
+
* 2026-09-15 `@bsv/mandala`'s `broadcastAcceptedTx` believed it, cleared its
|
|
2192
|
+
* `'accepted'` journal entry for a transaction nothing had broadcast, and so
|
|
2193
|
+
* left the live noSend action looking abandoned to the next reconcile sweep.
|
|
2194
|
+
* One aborted action and one released-but-spent coin later, that is the
|
|
2195
|
+
* incident.
|
|
2196
|
+
*
|
|
2197
|
+
* So a `sendWith` release of a token transaction that is still HELD reports
|
|
2198
|
+
* nothing at all for that txid. Omission rather than a made-up status,
|
|
2199
|
+
* deliberately: `SendWithResult.status` is a three-value SDK union, and
|
|
2200
|
+
* `Wallet.createAction` throws `WERR_REVIEW_ACTIONS` unless EVERY entry reads
|
|
2201
|
+
* `'unproven'` — so inventing a fourth value would turn a correct hold into a
|
|
2202
|
+
* thrown error for every caller, while an absent entry is simply "this wallet
|
|
2203
|
+
* is not telling you it went out", which is the truth and which no caller can
|
|
2204
|
+
* mistake for delivery.
|
|
2205
|
+
*
|
|
2206
|
+
* Scoped as narrowly as it can be: only txids that have a `token_settlements`
|
|
2207
|
+
* row AND whose request is still parked at `'nosend'`. Once `postTokenStep`
|
|
2208
|
+
* has really broadcast the tip its request is past `'nosend'` and its results
|
|
2209
|
+
* pass through exactly as before, and a plain BSV action is never looked at.
|
|
2210
|
+
*
|
|
2211
|
+
* `internalizeAction` is unaffected — it calls `shareReqsWithWorld` directly
|
|
2212
|
+
* rather than through `processAction` — which is what keeps the receiver's
|
|
2213
|
+
* credit from rolling back.
|
|
2214
|
+
*/
|
|
2215
|
+
async processAction(auth: AuthId, args: StorageProcessActionArgs): Promise<StorageProcessActionResults> {
|
|
2216
|
+
const r = await super.processAction(auth, args)
|
|
2217
|
+
const swr = r.sendWithResults
|
|
2218
|
+
if (!swr || swr.length === 0) return r
|
|
2219
|
+
|
|
2220
|
+
let heldTokenTxids: Set<string>
|
|
2221
|
+
try {
|
|
2222
|
+
heldTokenTxids = await this.heldTokenTxidsIn(swr.map(s => s.txid))
|
|
2223
|
+
} catch (e) {
|
|
2224
|
+
// A read fault here must not change what the wallet reports; the guard in
|
|
2225
|
+
// front of the broadcast has already done the load-bearing work.
|
|
2226
|
+
devLog('[StorageExpoSQLite] could not check held token reqs for sendWithResults:', e)
|
|
2227
|
+
return r
|
|
2228
|
+
}
|
|
2229
|
+
if (heldTokenTxids.size === 0) return r
|
|
2230
|
+
|
|
2231
|
+
devLog(
|
|
2232
|
+
`[StorageExpoSQLite] omitting ${heldTokenTxids.size} held token req(s) from sendWithResults; ` +
|
|
2233
|
+
'the settlement drain owns their broadcast'
|
|
2234
|
+
)
|
|
2235
|
+
return { ...r, sendWithResults: swr.filter(s => !heldTokenTxids.has(s.txid)) }
|
|
2236
|
+
}
|
|
2237
|
+
|
|
2238
|
+
/**
|
|
2239
|
+
* Of these txids, the ones that both have a `token_settlements` row and are
|
|
2240
|
+
* still parked at request status `'nosend'` — i.e. held by guard #2 and not
|
|
2241
|
+
* yet broadcast by the drain. Read failures propagate; the one caller decides
|
|
2242
|
+
* what a failure means.
|
|
2243
|
+
*/
|
|
2244
|
+
private async heldTokenTxidsIn(txids: string[]): Promise<Set<string>> {
|
|
2245
|
+
const tokenTxids = await this.tokenSettlementTxids(txids)
|
|
2246
|
+
if (tokenTxids.size === 0) return new Set()
|
|
2247
|
+
const held = new Set<string>()
|
|
2248
|
+
for (const txid of tokenTxids) {
|
|
2249
|
+
const req = (await this.findProvenTxReqs({ partial: { txid } }))[0]
|
|
2250
|
+
if (req?.status === 'nosend') held.add(txid)
|
|
2251
|
+
}
|
|
2252
|
+
return held
|
|
2253
|
+
}
|
|
2254
|
+
|
|
1950
2255
|
async attemptToPostReqsToNetwork(
|
|
1951
2256
|
reqs: EntityProvenTxReq[],
|
|
1952
2257
|
trx?: TrxToken,
|
|
@@ -1954,6 +2259,21 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1954
2259
|
): Promise<PostReqsToNetworkResult> {
|
|
1955
2260
|
if (reqs.length === 0) return await super.attemptToPostReqsToNetwork(reqs, trx, logger)
|
|
1956
2261
|
|
|
2262
|
+
const tokenTxids = await this.tokenSettlementTxids(reqs.map(r => r.txid))
|
|
2263
|
+
const tokenReqs = tokenTxids.size > 0 ? reqs.filter(r => tokenTxids.has(r.txid)) : []
|
|
2264
|
+
const rest = tokenTxids.size > 0 ? reqs.filter(r => !tokenTxids.has(r.txid)) : reqs
|
|
2265
|
+
|
|
2266
|
+
if (tokenReqs.length > 0) {
|
|
2267
|
+
devLog(
|
|
2268
|
+
`[StorageExpoSQLite] holding ${tokenReqs.length} token req(s) for the settlement drain, regardless of connectivity`
|
|
2269
|
+
)
|
|
2270
|
+
await this.holdTokenReqs(tokenReqs)
|
|
2271
|
+
// Nothing else in the call: answer for the whole call without ever
|
|
2272
|
+
// asking whether we are online, because the answer could not change it.
|
|
2273
|
+
if (rest.length === 0) return { ...buildOfflineHoldResult(reqs), beef: new Beef(), log: '' }
|
|
2274
|
+
}
|
|
2275
|
+
const held = tokenReqs.length > 0 ? buildOfflineHoldResult(tokenReqs).details : []
|
|
2276
|
+
|
|
1957
2277
|
let online = true
|
|
1958
2278
|
try {
|
|
1959
2279
|
online = await getOnline()
|
|
@@ -1962,9 +2282,12 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1962
2282
|
// online so the real post runs exactly as it did before this override.
|
|
1963
2283
|
devLog('[StorageExpoSQLite] connectivity probe failed, assuming online:', e)
|
|
1964
2284
|
}
|
|
1965
|
-
if (online)
|
|
2285
|
+
if (online) {
|
|
2286
|
+
const posted = await super.attemptToPostReqsToNetwork(rest, trx, logger)
|
|
2287
|
+
return held.length > 0 ? { ...posted, details: [...posted.details, ...held] } : posted
|
|
2288
|
+
}
|
|
1966
2289
|
|
|
1967
|
-
const pairs = await this.resolveHoldPairs(
|
|
2290
|
+
const pairs = await this.resolveHoldPairs(rest)
|
|
1968
2291
|
const holds = groupOfflineHolds(pairs)
|
|
1969
2292
|
if (!holds) {
|
|
1970
2293
|
// Either a request could not be attributed to a user, so we could not
|
|
@@ -1977,10 +2300,13 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1977
2300
|
'[StorageExpoSQLite] offline: not holding, delegating to the real post:',
|
|
1978
2301
|
pairs.map(p => `${p.req.txid} ${p.tx ? `tx ${p.tx.status}` : 'unattributed'}`).join(', ')
|
|
1979
2302
|
)
|
|
1980
|
-
|
|
2303
|
+
// `rest` only: the token reqs are already held above and must never be
|
|
2304
|
+
// handed to a real post, whatever the rest of the batch turned out to be.
|
|
2305
|
+
const posted = await super.attemptToPostReqsToNetwork(rest, trx, logger)
|
|
2306
|
+
return held.length > 0 ? { ...posted, details: [...posted.details, ...held] } : posted
|
|
1981
2307
|
}
|
|
1982
2308
|
|
|
1983
|
-
devLog(`[StorageExpoSQLite] offline: holding ${
|
|
2309
|
+
devLog(`[StorageExpoSQLite] offline: holding ${rest.length} req(s) for later delivery`)
|
|
1984
2310
|
for (const hold of holds.values()) {
|
|
1985
2311
|
await this.holdReqsOffline(hold.reqs, hold.userId, hold.role)
|
|
1986
2312
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for raw SQLite database images (the bytes of a `.db` file).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/** "SQLite format 3\0" — the 16-byte magic at the start of every database file. */
|
|
6
|
+
const SQLITE_MAGIC = [0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00]
|
|
7
|
+
|
|
8
|
+
const HEADER_WRITE_VERSION = 18
|
|
9
|
+
const HEADER_READ_VERSION = 19
|
|
10
|
+
const FORMAT_LEGACY = 1
|
|
11
|
+
const FORMAT_WAL = 2
|
|
12
|
+
|
|
13
|
+
function hasSqliteMagic(bytes: Uint8Array): boolean {
|
|
14
|
+
if (bytes.length < 100) return false
|
|
15
|
+
for (let i = 0; i < SQLITE_MAGIC.length; i++) {
|
|
16
|
+
if (bytes[i] !== SQLITE_MAGIC[i]) return false
|
|
17
|
+
}
|
|
18
|
+
return true
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Make a database image safe to hand to `deserializeDatabaseAsync`.
|
|
23
|
+
*
|
|
24
|
+
* The wallet database runs in WAL mode, so every export of it (an iOS byte
|
|
25
|
+
* copy or an Android `serializeAsync` image) carries header bytes 18/19 = 2,
|
|
26
|
+
* which tells SQLite the file is in WAL mode. `sqlite3_deserialize` loads the
|
|
27
|
+
* image under the memdb VFS, which implements no shared-memory (`xShmMap`)
|
|
28
|
+
* methods, so the pager's attempt to open the WAL fails with SQLITE_CANTOPEN
|
|
29
|
+
* ("unable to open database file") on the first read — surfacing from
|
|
30
|
+
* `backupDatabaseAsync` during import.
|
|
31
|
+
*
|
|
32
|
+
* The image itself is complete (the export checkpoints before copying, and
|
|
33
|
+
* `serializeAsync` reads through the pager), so flipping the two version
|
|
34
|
+
* bytes to rollback-journal mode (1) loses nothing. The caller's buffer is
|
|
35
|
+
* not modified; a patched copy is returned only when a change is needed.
|
|
36
|
+
* Non-SQLite input is returned as-is so the real validation error still
|
|
37
|
+
* comes from SQLite.
|
|
38
|
+
*/
|
|
39
|
+
export function prepareSqliteImageForDeserialize(bytes: Uint8Array): Uint8Array {
|
|
40
|
+
if (!hasSqliteMagic(bytes)) return bytes
|
|
41
|
+
if (bytes[HEADER_WRITE_VERSION] !== FORMAT_WAL && bytes[HEADER_READ_VERSION] !== FORMAT_WAL) {
|
|
42
|
+
return bytes
|
|
43
|
+
}
|
|
44
|
+
const out = new Uint8Array(bytes)
|
|
45
|
+
if (out[HEADER_WRITE_VERSION] === FORMAT_WAL) out[HEADER_WRITE_VERSION] = FORMAT_LEGACY
|
|
46
|
+
if (out[HEADER_READ_VERSION] === FORMAT_WAL) out[HEADER_READ_VERSION] = FORMAT_LEGACY
|
|
47
|
+
return out
|
|
48
|
+
}
|