@bsv/expo-wallet-toolbox 0.1.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/LICENSE.txt +28 -0
- package/README.md +512 -0
- package/assets/sounds/payment-receive.wav +0 -0
- package/assets/sounds/payment-send.wav +0 -0
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/amountFormatHelpers.ts +330 -0
- package/core/backup/RemoteSyncReader.ts +94 -0
- package/core/backup/client.ts +111 -0
- package/core/backup/codec.ts +218 -0
- package/core/backup/constants.ts +88 -0
- package/core/backup/cursor.ts +138 -0
- package/core/backup/derive.ts +46 -0
- package/core/backup/deviceId.ts +33 -0
- package/core/backup/erase.ts +67 -0
- package/core/backup/preference.ts +33 -0
- package/core/backup/push.ts +295 -0
- package/core/backup/restore.ts +152 -0
- package/core/backup/restoreOnImport.ts +119 -0
- package/core/backup/status.ts +46 -0
- package/core/config.tsx +47 -0
- package/core/constants.ts +35 -0
- package/core/context/ExchangeRateContext.tsx +69 -0
- package/core/context/LocalStorageProvider.tsx +225 -0
- package/core/context/UserContext.tsx +129 -0
- package/core/context/VaultContext.tsx +79 -0
- package/core/context/WalletConnectionContext.tsx +454 -0
- package/core/context/WalletContext.tsx +2938 -0
- package/core/context/buildGeneration.ts +37 -0
- package/core/deviceTier.ts +89 -0
- package/core/diskSpace.ts +62 -0
- package/core/displayCurrencies.ts +56 -0
- package/core/headers/OfflineFirstChaintracks.ts +176 -0
- package/core/headers/checkpoints.ts +39 -0
- package/core/headers/fs.ts +119 -0
- package/core/headers/headerStore.ts +333 -0
- package/core/headers/prewarm.ts +36 -0
- package/core/headers/syncHeaders.ts +73 -0
- package/core/hooks/useConfirmationSound.ts +135 -0
- package/core/hooks/useHaptics.ts +51 -0
- package/core/hooks/usePermissionQueue.ts +69 -0
- package/core/i18n/translations.tsx +6692 -0
- package/core/index.ts +295 -0
- package/core/localpay/blePermissions.ts +32 -0
- package/core/localpay/build.ts +392 -0
- package/core/localpay/codec.ts +338 -0
- package/core/localpay/deviceCaps.ts +175 -0
- package/core/localpay/nearbyAdvisory.ts +32 -0
- package/core/localpay/nearbyPermissions.ts +34 -0
- package/core/localpay/pending.ts +385 -0
- package/core/localpay/pendingAborts.ts +67 -0
- package/core/localpay/qr.ts +16 -0
- package/core/localpay/session.ts +277 -0
- package/core/localpay/sessionPolicy.ts +5 -0
- package/core/localpay/transport/awdl.ts +11 -0
- package/core/localpay/transport/ble.ts +159 -0
- package/core/localpay/transport/nearby.ts +12 -0
- package/core/localpay/transport/race.ts +110 -0
- package/core/localpay/transport/select.ts +128 -0
- package/core/localpay/transport/socket.ts +244 -0
- package/core/localpay/types.ts +82 -0
- package/core/localpay/verify.ts +204 -0
- package/core/logging.config.ts +10 -0
- package/core/logging.ts +77 -0
- package/core/mnemonicWallet.ts +180 -0
- package/core/monitor/TaskBackupPush.ts +168 -0
- package/core/monitor/TaskCreditInbox.ts +116 -0
- package/core/monitor/TaskDrainOutbox.ts +122 -0
- package/core/monitor/TaskSendOffline.ts +123 -0
- package/core/monitor/unfailRetry.ts +116 -0
- package/core/net/chainMatch.ts +34 -0
- package/core/net/online.ts +34 -0
- package/core/offline/cancelParked.ts +56 -0
- package/core/offline/hold.ts +127 -0
- package/core/offline/order.ts +109 -0
- package/core/offline/payerHold.ts +144 -0
- package/core/offline/plan.ts +264 -0
- package/core/offline/queueGrace.ts +52 -0
- package/core/parsePeerPayURI.ts +119 -0
- package/core/pay/beefRepair.ts +106 -0
- package/core/pay/creditErrors.ts +46 -0
- package/core/pay/creditInbox.ts +202 -0
- package/core/pay/damagedInbox.ts +64 -0
- package/core/pay/proofNudge.ts +23 -0
- package/core/pay/provenTxFromBump.ts +31 -0
- package/core/pay/rails/address.ts +329 -0
- package/core/pay/rails/handle.ts +617 -0
- package/core/pay/rails/index.ts +197 -0
- package/core/pay/rails/nearby.ts +79 -0
- package/core/pay/receiveFocus.ts +13 -0
- package/core/pay/recordProof.ts +91 -0
- package/core/pay/refreshProofGuard.ts +34 -0
- package/core/pay/sweeper.ts +75 -0
- package/core/pay/tokenAmount.ts +18 -0
- package/core/pay/userError.ts +18 -0
- package/core/pay/watchlist.ts +126 -0
- package/core/peerpay/control.ts +122 -0
- package/core/peerpay/handleResendRequests.ts +475 -0
- package/core/peerpay/inboxAttempts.ts +33 -0
- package/core/peerpay/metadataDecryptor.ts +42 -0
- package/core/peerpay/offlineNacks.ts +96 -0
- package/core/peerpay/outbox.ts +209 -0
- package/core/peerpay/rebuildToken.ts +76 -0
- package/core/peerpay/resendBeef.ts +115 -0
- package/core/services/arcadeBroadcastProvider.ts +214 -0
- package/core/services/capWalletArgs.ts +99 -0
- package/core/services/exchangeRate.ts +63 -0
- package/core/services/secrets/envelope.ts +102 -0
- package/core/services/secrets/hkdf.ts +37 -0
- package/core/services/secrets/index.ts +63 -0
- package/core/services/secrets/kek.ts +274 -0
- package/core/services/secrets/migration.ts +188 -0
- package/core/services/secrets/policy.ts +120 -0
- package/core/services/secrets/storage.ts +54 -0
- package/core/services/secrets/store.ts +125 -0
- package/core/services/secrets/types.ts +85 -0
- package/core/services/usdFxRates.ts +101 -0
- package/core/services/vault/VaultKeyService.ts +312 -0
- package/core/services/vault/backupAttestation.ts +136 -0
- package/core/services/vault/ceremony.ts +972 -0
- package/core/services/vault/ceremonyHost.ts +46 -0
- package/core/services/vault/devMock.ts +22 -0
- package/core/services/vault/driver.ts +197 -0
- package/core/services/vault/guard.ts +90 -0
- package/core/services/vault/k1.ts +75 -0
- package/core/services/vault/mockYubiKey.ts +217 -0
- package/core/services/vault/random.ts +20 -0
- package/core/services/vault/sealing.ts +84 -0
- package/core/services/vault/session.ts +59 -0
- package/core/services/vault/transfers.ts +1151 -0
- package/core/services/vault/types.ts +109 -0
- package/core/services/vault/vaultDerivation.ts +152 -0
- package/core/services/vault/vaultPassphrase.ts +287 -0
- package/core/services/vault/vaultStore.ts +104 -0
- package/core/services/walletArgLimits.ts +234 -0
- package/core/services/walletServiceConfig.ts +170 -0
- package/core/storage/LocalStorageAdapter.ts +58 -0
- package/core/storage/README.md +391 -0
- package/core/storage/StorageExpoSQLite.ts +2008 -0
- package/core/storage/errors.ts +73 -0
- package/core/storage/index.ts +3 -0
- package/core/storage/methods/findSql.ts +286 -0
- package/core/storage/methods/historyNotes.ts +61 -0
- package/core/storage/methods/listActionsSql.ts +212 -0
- package/core/storage/methods/listOutputsSql.ts +211 -0
- package/core/storage/methods/offlineActions.ts +156 -0
- package/core/storage/methods/processOfflineActions.ts +503 -0
- package/core/storage/methods/reclaim.ts +135 -0
- package/core/storage/methods/reviewStatusSql.ts +167 -0
- package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
- package/core/storage/methods/walletBalanceSql.ts +55 -0
- package/core/storage/schema/createTables.ts +385 -0
- package/core/storage/skipQueuedAncestors.ts +29 -0
- package/core/storage/sqlUpdateValue.ts +12 -0
- package/core/stores/ConnectionStore.ts +71 -0
- package/core/theme/ThemeContext.tsx +182 -0
- package/core/theme/assertThemeContrast.ts +109 -0
- package/core/theme/motion.ts +50 -0
- package/core/theme/tokens.ts +232 -0
- package/core/theme/useThemeStyles.tsx +156 -0
- package/core/walletDbRegistry.ts +110 -0
- package/core/walletMonitor.ts +149 -0
- package/core/walletRepair/runWalletCheck.ts +195 -0
- package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
- package/package.json +86 -0
- package/ui/backupShares.ts +367 -0
- package/ui/components/QRScanner.tsx +353 -0
- package/ui/components/pay/AddressReceive.tsx +507 -0
- package/ui/components/pay/AvailableBalance.tsx +61 -0
- package/ui/components/pay/HandleReceive.tsx +896 -0
- package/ui/components/pay/MessageBoxConfig.tsx +256 -0
- package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
- package/ui/components/pay/NearbyFlow.tsx +2542 -0
- package/ui/components/pay/OfflineNotice.tsx +337 -0
- package/ui/components/pay/PayCellRow.tsx +101 -0
- package/ui/components/pay/PayForm.tsx +223 -0
- package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
- package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
- package/ui/components/pay/RecipientField.tsx +308 -0
- package/ui/components/pay/RequestHub.tsx +75 -0
- package/ui/components/pay/ResultBanner.tsx +69 -0
- package/ui/components/pay/UniversalSend.tsx +687 -0
- package/ui/components/pay/useRecipientInput.ts +270 -0
- package/ui/components/security/WalletLockNotice.tsx +138 -0
- package/ui/components/ui/AlertCard.tsx +223 -0
- package/ui/components/ui/AppLogo.tsx +166 -0
- package/ui/components/ui/BlurChrome.tsx +72 -0
- package/ui/components/ui/Celebration.tsx +84 -0
- package/ui/components/ui/ChoiceSheet.ts +69 -0
- package/ui/components/ui/CustomSafeArea.tsx +74 -0
- package/ui/components/ui/ErrorBoundary.tsx +154 -0
- package/ui/components/ui/GroupedList.tsx +125 -0
- package/ui/components/ui/IconButton.tsx +105 -0
- package/ui/components/ui/ListRow.tsx +197 -0
- package/ui/components/ui/PermissionSheet.tsx +920 -0
- package/ui/components/ui/PresenceRow.tsx +215 -0
- package/ui/components/ui/PressableScale.tsx +105 -0
- package/ui/components/ui/ScreenGradient.tsx +47 -0
- package/ui/components/ui/ScrollFade.tsx +76 -0
- package/ui/components/ui/Sheet.tsx +342 -0
- package/ui/components/ui/Toast.tsx +142 -0
- package/ui/components/ui/index.ts +8 -0
- package/ui/components/vault/EnrollWizard.tsx +627 -0
- package/ui/components/vault/PassphraseField.tsx +306 -0
- package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
- package/ui/components/vault/VaultBackdrop.tsx +354 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
- package/ui/components/wallet/ActivityRow.tsx +408 -0
- package/ui/components/wallet/AmountDisplay.tsx +48 -0
- package/ui/components/wallet/AmountInput.tsx +256 -0
- package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
- package/ui/components/wallet/Balance.tsx +144 -0
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
- package/ui/exportDatabases.ts +122 -0
- package/ui/exportTransactions.ts +129 -0
- package/ui/hooks/useOfflineNoticeActions.ts +136 -0
- package/ui/hooks/useOnline.ts +70 -0
- package/ui/hooks/useSpendableBalance.ts +58 -0
- package/ui/hooks/useVaultBalance.ts +50 -0
- package/ui/importDatabases.ts +170 -0
- package/ui/index.ts +136 -0
- package/ui/isImageUrl.ts +10 -0
- package/ui/printRecoveryShares.ts +93 -0
- package/ui/resolveIdentity.ts +125 -0
- package/ui/screens/ConnectionsScreen.tsx +438 -0
- package/ui/screens/LogsScreen.tsx +432 -0
- package/ui/screens/PairScreen.tsx +288 -0
- package/ui/screens/PayScreen.tsx +479 -0
- package/ui/screens/SettingsScreen.tsx +180 -0
- package/ui/screens/TrustScreen.tsx +831 -0
- package/ui/screens/VaultRecoverScreen.tsx +226 -0
- package/ui/screens/VaultScreen.tsx +423 -0
- package/ui/screens/VaultTransferScreen.tsx +293 -0
- package/ui/screens/WalletCheckScreen.tsx +539 -0
- package/ui/screens/WalletConfigScreen.tsx +1095 -0
- package/ui/screens/WalletHomeScreen.tsx +1597 -0
- package/ui/screens/homeBadges.ts +18 -0
- package/ui/txStatus.ts +79 -0
- package/ui/validateTrust.ts +44 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The three reviewStatus rules, as SQL against a SQLite handle.
|
|
3
|
+
*
|
|
4
|
+
* Mirrors reviewStatusIdb: fail txs whose proven_tx_req is invalid; restore
|
|
5
|
+
* inputs allocated to a terminal-failed spender; mark outputs generated by a
|
|
6
|
+
* terminal-failed tx unspendable.
|
|
7
|
+
*
|
|
8
|
+
* skipTxids (live queued/posting offline_actions) are left untouched so a
|
|
9
|
+
* still-in-flight offline send is not failed out from under the queue.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { devLog } from '../../logging'
|
|
13
|
+
|
|
14
|
+
const SAFE_REQ_STATUSES = new Set(['invalid', 'doubleSpend'])
|
|
15
|
+
|
|
16
|
+
export type ReviewStatusDb = {
|
|
17
|
+
prepare(sql: string): {
|
|
18
|
+
all: (...params: unknown[]) => unknown[]
|
|
19
|
+
run: (...params: unknown[]) => unknown
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const LIVE_OFFLINE_SKIP_TXIDS_SQL = `
|
|
24
|
+
SELECT txid FROM offline_actions
|
|
25
|
+
WHERE status IN ('queued','posting') AND txid IS NOT NULL AND txid <> ''
|
|
26
|
+
`.trim()
|
|
27
|
+
|
|
28
|
+
export const REVIEW_INVALID_REQ_TXS_SQL = `
|
|
29
|
+
SELECT t.transactionId, t.txid, t.status
|
|
30
|
+
FROM transactions t
|
|
31
|
+
JOIN proven_tx_reqs r ON r.txid = t.txid
|
|
32
|
+
WHERE r.status = 'invalid' AND t.status <> 'failed' AND t.provenTxId IS NULL AND t.status <> 'completed'
|
|
33
|
+
`.trim()
|
|
34
|
+
|
|
35
|
+
export const REVIEW_FAILED_TXS_SQL = `SELECT transactionId, txid FROM transactions WHERE status = 'failed'`
|
|
36
|
+
|
|
37
|
+
export const REVIEW_REQ_STATUSES_SQL = `SELECT status FROM proven_tx_reqs WHERE txid = ?`
|
|
38
|
+
|
|
39
|
+
export const REVIEW_OUTPUTS_SQL = `SELECT outputId, transactionId, spendable, spentBy FROM outputs WHERE NOT (spendable = 0 AND spentBy IS NULL)`
|
|
40
|
+
|
|
41
|
+
const FAIL_TX_SQL = `UPDATE transactions SET status = 'failed' WHERE transactionId = ?`
|
|
42
|
+
const RESTORE_INPUT_SQL = `UPDATE outputs SET spendable = 1, spentBy = NULL WHERE outputId = ?`
|
|
43
|
+
const UNSPEND_OUTPUT_SQL = `UPDATE outputs SET spendable = 0, spentBy = NULL WHERE outputId = ?`
|
|
44
|
+
|
|
45
|
+
export type ReviewFailedTx = { transactionId: number; txid?: string | null }
|
|
46
|
+
export type ReviewOutput = {
|
|
47
|
+
outputId: number
|
|
48
|
+
transactionId: number
|
|
49
|
+
spendable: number | boolean
|
|
50
|
+
spentBy?: number | null
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function failInvalidReqTxs(args: {
|
|
54
|
+
rows: { transactionId: number; txid: string | null }[]
|
|
55
|
+
skipTxids: Set<string>
|
|
56
|
+
fail: (transactionId: number) => Promise<void>
|
|
57
|
+
}): Promise<{ failed: number; skipped: number }> {
|
|
58
|
+
let failed = 0
|
|
59
|
+
let skipped = 0
|
|
60
|
+
const seen = new Set<number>()
|
|
61
|
+
for (const row of args.rows) {
|
|
62
|
+
if (seen.has(row.transactionId)) continue
|
|
63
|
+
seen.add(row.transactionId)
|
|
64
|
+
if (row.txid && args.skipTxids.has(row.txid)) {
|
|
65
|
+
skipped++
|
|
66
|
+
continue
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
await args.fail(row.transactionId)
|
|
70
|
+
failed++
|
|
71
|
+
} catch (e) {
|
|
72
|
+
skipped++
|
|
73
|
+
devLog(
|
|
74
|
+
`[reviewStatus] could not fail transaction ${row.transactionId}:`,
|
|
75
|
+
e instanceof Error ? e.message : e
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { failed, skipped }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Failed txs whose reqs are all invalid/doubleSpend (or missing) are safe to restore against. */
|
|
83
|
+
export function collectFailedTransactionIds(
|
|
84
|
+
failedTxs: ReviewFailedTx[],
|
|
85
|
+
reqStatusesByTxid: Map<string, string[]>,
|
|
86
|
+
skipTxids: Set<string>
|
|
87
|
+
): { failedTransactionIds: Set<number>; safeFailedTransactionIds: Set<number> } {
|
|
88
|
+
const failedTransactionIds = new Set<number>()
|
|
89
|
+
const safeFailedTransactionIds = new Set<number>()
|
|
90
|
+
for (const tx of failedTxs) {
|
|
91
|
+
if (tx.txid && skipTxids.has(tx.txid)) continue
|
|
92
|
+
failedTransactionIds.add(tx.transactionId)
|
|
93
|
+
let hasBlockingReq = false
|
|
94
|
+
if (tx.txid != null && tx.txid !== '') {
|
|
95
|
+
const reqs = reqStatusesByTxid.get(tx.txid) ?? []
|
|
96
|
+
hasBlockingReq = reqs.some(status => !SAFE_REQ_STATUSES.has(status))
|
|
97
|
+
}
|
|
98
|
+
if (!hasBlockingReq) safeFailedTransactionIds.add(tx.transactionId)
|
|
99
|
+
}
|
|
100
|
+
return { failedTransactionIds, safeFailedTransactionIds }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function outputReviewAction(
|
|
104
|
+
output: ReviewOutput,
|
|
105
|
+
failedTransactionIds: Set<number>,
|
|
106
|
+
safeFailedTransactionIds: Set<number>
|
|
107
|
+
): 'restore' | 'unspend' | undefined {
|
|
108
|
+
const generatedByFailedTx = failedTransactionIds.has(output.transactionId)
|
|
109
|
+
const generatedBySafeFailedTx = safeFailedTransactionIds.has(output.transactionId)
|
|
110
|
+
const spentBySafeFailedTx = output.spentBy != null && safeFailedTransactionIds.has(output.spentBy)
|
|
111
|
+
if (spentBySafeFailedTx && !generatedByFailedTx) return 'restore'
|
|
112
|
+
if (generatedBySafeFailedTx && (Boolean(output.spendable) || output.spentBy != null)) return 'unspend'
|
|
113
|
+
return undefined
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function reviewStatusOnDb(db: ReviewStatusDb, opts: { skipTxids: Set<string> }): { log: string } {
|
|
117
|
+
const { skipTxids } = opts
|
|
118
|
+
let log = ''
|
|
119
|
+
|
|
120
|
+
const seenFail = new Set<number>()
|
|
121
|
+
const invalid = db.prepare(REVIEW_INVALID_REQ_TXS_SQL).all() as {
|
|
122
|
+
transactionId: number
|
|
123
|
+
txid: string | null
|
|
124
|
+
status: string
|
|
125
|
+
}[]
|
|
126
|
+
const failStmt = db.prepare(FAIL_TX_SQL)
|
|
127
|
+
for (const tx of invalid) {
|
|
128
|
+
if (seenFail.has(tx.transactionId)) continue
|
|
129
|
+
seenFail.add(tx.transactionId)
|
|
130
|
+
if (tx.txid && skipTxids.has(tx.txid)) continue
|
|
131
|
+
log += `transaction ${tx.transactionId} updated to status of 'failed' was ${tx.status}\n`
|
|
132
|
+
failStmt.run(tx.transactionId)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const failedTxs = db.prepare(REVIEW_FAILED_TXS_SQL).all() as ReviewFailedTx[]
|
|
136
|
+
const reqStatusesByTxid = new Map<string, string[]>()
|
|
137
|
+
const reqStmt = db.prepare(REVIEW_REQ_STATUSES_SQL)
|
|
138
|
+
for (const tx of failedTxs) {
|
|
139
|
+
if (tx.txid == null || tx.txid === '' || reqStatusesByTxid.has(tx.txid)) continue
|
|
140
|
+
const reqs = reqStmt.all(tx.txid) as { status: string }[]
|
|
141
|
+
reqStatusesByTxid.set(
|
|
142
|
+
tx.txid,
|
|
143
|
+
reqs.map(row => row.status)
|
|
144
|
+
)
|
|
145
|
+
}
|
|
146
|
+
const { failedTransactionIds, safeFailedTransactionIds } = collectFailedTransactionIds(
|
|
147
|
+
failedTxs,
|
|
148
|
+
reqStatusesByTxid,
|
|
149
|
+
skipTxids
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
const restoreStmt = db.prepare(RESTORE_INPUT_SQL)
|
|
153
|
+
const unspendStmt = db.prepare(UNSPEND_OUTPUT_SQL)
|
|
154
|
+
const outputs = db.prepare(REVIEW_OUTPUTS_SQL).all() as ReviewOutput[]
|
|
155
|
+
for (const output of outputs) {
|
|
156
|
+
const action = outputReviewAction(output, failedTransactionIds, safeFailedTransactionIds)
|
|
157
|
+
if (action === 'restore') {
|
|
158
|
+
restoreStmt.run(output.outputId)
|
|
159
|
+
log += `output ${output.outputId} updated to spendable because spentBy is failed\n`
|
|
160
|
+
} else if (action === 'unspend') {
|
|
161
|
+
unspendStmt.run(output.outputId)
|
|
162
|
+
log += `output ${output.outputId} updated to not spendable because transaction is failed\n`
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return { log }
|
|
167
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transactions nothing will ever prove on its own: `unproven`, with no
|
|
3
|
+
* proven_tx_req for TaskCheckForProofs to work from and no proven_tx already
|
|
4
|
+
* recorded. Left behind when an `internalizeAction` fails after inserting the
|
|
5
|
+
* transaction row and its retry takes the toolbox's merge path, which creates
|
|
6
|
+
* no req. The wallet repairs these itself with `recordProof` (see pay/).
|
|
7
|
+
*/
|
|
8
|
+
import type { OfflineDb } from './offlineActions'
|
|
9
|
+
|
|
10
|
+
export const UNPROVEN_TXIDS_WITHOUT_REQ_SQL = `
|
|
11
|
+
SELECT DISTINCT t.txid AS txid
|
|
12
|
+
FROM transactions t
|
|
13
|
+
WHERE t.status = 'unproven'
|
|
14
|
+
AND t.txid IS NOT NULL
|
|
15
|
+
AND NOT EXISTS (SELECT 1 FROM proven_tx_reqs r WHERE r.txid = t.txid)
|
|
16
|
+
AND NOT EXISTS (SELECT 1 FROM proven_txs p WHERE p.txid = t.txid)
|
|
17
|
+
ORDER BY t.txid
|
|
18
|
+
`
|
|
19
|
+
|
|
20
|
+
/** Same shape (and same reasoning about `params`) as `OfflineDb` in ./offlineActions. */
|
|
21
|
+
export type UnprovenQueryDb = Pick<OfflineDb, 'getAllAsync'>
|
|
22
|
+
|
|
23
|
+
export async function findUnprovenTxidsWithoutReq(db: UnprovenQueryDb): Promise<string[]> {
|
|
24
|
+
const rows = (await db.getAllAsync(UNPROVEN_TXIDS_WITHOUT_REQ_SQL, [])) as { txid: string }[]
|
|
25
|
+
return rows.map(r => r.txid)
|
|
26
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The wallet balance, as one SQL aggregate — and ONE definition of what the
|
|
3
|
+
* balance is, used from both ends:
|
|
4
|
+
*
|
|
5
|
+
* - `listOutputsSql`, when the toolbox asks for the `specOpWalletBalance` basket
|
|
6
|
+
* - the wallet screen, which calls this directly
|
|
7
|
+
*
|
|
8
|
+
* Calling it directly matters. Every read through `WalletStorageManager` queues
|
|
9
|
+
* on a single FIFO reader lock, and the monitor's tasks hold that lock — along
|
|
10
|
+
* with the writer and sync locks — across NETWORK calls: `attemptToPostReqsToNetwork`
|
|
11
|
+
* broadcasts from inside `runAsStorageProvider`. A balance read issued while a
|
|
12
|
+
* transaction is being broadcast therefore waits for the broadcast, not for the
|
|
13
|
+
* database. That is where the multi-second balance reads on device came from,
|
|
14
|
+
* not from the ~145 rows the query actually touches.
|
|
15
|
+
*
|
|
16
|
+
* This is a side-effect-free read of our own SQLite file, so it does not need
|
|
17
|
+
* the lock the writes need.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** The basket the toolbox counts as the wallet balance, and the transaction
|
|
21
|
+
* states in which an output's satoshis are really yours. Mirrors what
|
|
22
|
+
* `listOutputsSql` builds for every other outputs query. */
|
|
23
|
+
export const BALANCE_BASKET = 'default'
|
|
24
|
+
export const BALANCE_TX_STATUS = ['completed', 'unproven', 'nosend']
|
|
25
|
+
|
|
26
|
+
/** The slice of StorageExpoSQLite this needs. Structural, so a caller can pass
|
|
27
|
+
* the real provider and a test can pass one backed by any SQLite handle. */
|
|
28
|
+
export interface BalanceStorage {
|
|
29
|
+
findOutputBaskets(args: { partial: { userId: number; name: string } }): Promise<{ basketId: number }[]>
|
|
30
|
+
sumOutputSatoshis(
|
|
31
|
+
args: { partial: Record<string, unknown>; txStatus?: string[]; noScript?: boolean },
|
|
32
|
+
tagIds?: number[],
|
|
33
|
+
isQueryModeAll?: boolean
|
|
34
|
+
): Promise<{ count: number; total: number }>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Sum the spendable satoshis in the default basket for one user.
|
|
39
|
+
*
|
|
40
|
+
* Returns `null` when the basket does not exist yet — a wallet that has never
|
|
41
|
+
* held anything. Callers should treat that as "no figure available" rather than
|
|
42
|
+
* as a balance of zero, so a wallet still building does not flash 0 over a
|
|
43
|
+
* cached figure.
|
|
44
|
+
*/
|
|
45
|
+
export async function readWalletBalance(storage: BalanceStorage, userId: number): Promise<number | null> {
|
|
46
|
+
const baskets = await storage.findOutputBaskets({ partial: { userId, name: BALANCE_BASKET } })
|
|
47
|
+
if (baskets.length !== 1) return null
|
|
48
|
+
|
|
49
|
+
const { total } = await storage.sumOutputSatoshis({
|
|
50
|
+
partial: { userId, basketId: baskets[0].basketId, spendable: true },
|
|
51
|
+
txStatus: BALANCE_TX_STATUS,
|
|
52
|
+
noScript: true
|
|
53
|
+
})
|
|
54
|
+
return total
|
|
55
|
+
}
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import type { SQLiteDatabase } from 'expo-sqlite'
|
|
2
|
+
import type { BindValue } from '../methods/offlineActions'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* SQL statements to create all wallet storage tables
|
|
6
|
+
* Schema aligned with @bsv/wallet-toolbox-mobile Table type definitions
|
|
7
|
+
*/
|
|
8
|
+
export async function createTables(db: SQLiteDatabase): Promise<void> {
|
|
9
|
+
// Users table
|
|
10
|
+
await db.execAsync(`
|
|
11
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
12
|
+
userId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
13
|
+
created_at TEXT NOT NULL,
|
|
14
|
+
updated_at TEXT NOT NULL,
|
|
15
|
+
identityKey TEXT NOT NULL UNIQUE,
|
|
16
|
+
activeStorage TEXT
|
|
17
|
+
);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS idx_users_identityKey ON users(identityKey);
|
|
19
|
+
`)
|
|
20
|
+
|
|
21
|
+
// Proven transactions table
|
|
22
|
+
await db.execAsync(`
|
|
23
|
+
CREATE TABLE IF NOT EXISTS proven_txs (
|
|
24
|
+
provenTxId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
25
|
+
created_at TEXT NOT NULL,
|
|
26
|
+
updated_at TEXT NOT NULL,
|
|
27
|
+
txid TEXT NOT NULL UNIQUE,
|
|
28
|
+
height INTEGER NOT NULL,
|
|
29
|
+
"index" INTEGER NOT NULL,
|
|
30
|
+
merklePath BLOB NOT NULL,
|
|
31
|
+
rawTx BLOB NOT NULL,
|
|
32
|
+
blockHash TEXT NOT NULL,
|
|
33
|
+
merkleRoot TEXT NOT NULL
|
|
34
|
+
);
|
|
35
|
+
CREATE INDEX IF NOT EXISTS idx_proven_txs_txid ON proven_txs(txid);
|
|
36
|
+
`)
|
|
37
|
+
|
|
38
|
+
// Proven transaction requests table
|
|
39
|
+
await db.execAsync(`
|
|
40
|
+
CREATE TABLE IF NOT EXISTS proven_tx_reqs (
|
|
41
|
+
provenTxReqId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
42
|
+
created_at TEXT NOT NULL,
|
|
43
|
+
updated_at TEXT NOT NULL,
|
|
44
|
+
txid TEXT NOT NULL UNIQUE,
|
|
45
|
+
status TEXT NOT NULL,
|
|
46
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
47
|
+
notified INTEGER NOT NULL DEFAULT 0,
|
|
48
|
+
history TEXT,
|
|
49
|
+
notify TEXT,
|
|
50
|
+
rawTx BLOB,
|
|
51
|
+
inputBEEF BLOB,
|
|
52
|
+
batch TEXT,
|
|
53
|
+
provenTxId INTEGER,
|
|
54
|
+
wasBroadcast INTEGER NOT NULL DEFAULT 0,
|
|
55
|
+
rebroadcastAttempts INTEGER NOT NULL DEFAULT 0,
|
|
56
|
+
FOREIGN KEY (provenTxId) REFERENCES proven_txs(provenTxId)
|
|
57
|
+
);
|
|
58
|
+
CREATE INDEX IF NOT EXISTS idx_proven_tx_reqs_txid ON proven_tx_reqs(txid);
|
|
59
|
+
CREATE INDEX IF NOT EXISTS idx_proven_tx_reqs_status ON proven_tx_reqs(status);
|
|
60
|
+
CREATE INDEX IF NOT EXISTS idx_proven_tx_reqs_batch ON proven_tx_reqs(batch);
|
|
61
|
+
CREATE INDEX IF NOT EXISTS idx_proven_tx_reqs_provenTxId ON proven_tx_reqs(provenTxId);
|
|
62
|
+
`)
|
|
63
|
+
|
|
64
|
+
// Migration 2026-04-30-001: add wasBroadcast/rebroadcastAttempts to existing DBs.
|
|
65
|
+
// SQLite has no IF NOT EXISTS for ADD COLUMN; rely on PRAGMA table_info.
|
|
66
|
+
const cols = (await db.getAllAsync(`PRAGMA table_info(proven_tx_reqs)`)) as Array<{ name: string }>
|
|
67
|
+
const names = new Set(cols.map(c => c.name))
|
|
68
|
+
if (!names.has('wasBroadcast')) {
|
|
69
|
+
await db.execAsync(`ALTER TABLE proven_tx_reqs ADD COLUMN wasBroadcast INTEGER NOT NULL DEFAULT 0`)
|
|
70
|
+
}
|
|
71
|
+
if (!names.has('rebroadcastAttempts')) {
|
|
72
|
+
await db.execAsync(`ALTER TABLE proven_tx_reqs ADD COLUMN rebroadcastAttempts INTEGER NOT NULL DEFAULT 0`)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Certificates table
|
|
76
|
+
await db.execAsync(`
|
|
77
|
+
CREATE TABLE IF NOT EXISTS certificates (
|
|
78
|
+
certificateId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
79
|
+
created_at TEXT NOT NULL,
|
|
80
|
+
updated_at TEXT NOT NULL,
|
|
81
|
+
userId INTEGER NOT NULL,
|
|
82
|
+
type TEXT NOT NULL,
|
|
83
|
+
subject TEXT NOT NULL,
|
|
84
|
+
serialNumber TEXT NOT NULL,
|
|
85
|
+
certifier TEXT NOT NULL,
|
|
86
|
+
verifier TEXT,
|
|
87
|
+
revocationOutpoint TEXT NOT NULL,
|
|
88
|
+
signature TEXT NOT NULL,
|
|
89
|
+
isDeleted INTEGER NOT NULL DEFAULT 0,
|
|
90
|
+
FOREIGN KEY (userId) REFERENCES users(userId)
|
|
91
|
+
);
|
|
92
|
+
CREATE INDEX IF NOT EXISTS idx_certificates_userId ON certificates(userId);
|
|
93
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_certificates_unique ON certificates(userId, type, certifier, serialNumber);
|
|
94
|
+
`)
|
|
95
|
+
|
|
96
|
+
// Certificate fields table
|
|
97
|
+
await db.execAsync(`
|
|
98
|
+
CREATE TABLE IF NOT EXISTS certificate_fields (
|
|
99
|
+
certificateId INTEGER NOT NULL,
|
|
100
|
+
userId INTEGER NOT NULL,
|
|
101
|
+
created_at TEXT NOT NULL,
|
|
102
|
+
updated_at TEXT NOT NULL,
|
|
103
|
+
fieldName TEXT NOT NULL,
|
|
104
|
+
fieldValue TEXT NOT NULL,
|
|
105
|
+
masterKey TEXT NOT NULL,
|
|
106
|
+
PRIMARY KEY (certificateId, fieldName),
|
|
107
|
+
FOREIGN KEY (certificateId) REFERENCES certificates(certificateId),
|
|
108
|
+
FOREIGN KEY (userId) REFERENCES users(userId)
|
|
109
|
+
);
|
|
110
|
+
CREATE INDEX IF NOT EXISTS idx_certificate_fields_userId ON certificate_fields(userId);
|
|
111
|
+
CREATE INDEX IF NOT EXISTS idx_certificate_fields_certificateId ON certificate_fields(certificateId);
|
|
112
|
+
`)
|
|
113
|
+
|
|
114
|
+
// Output baskets table
|
|
115
|
+
await db.execAsync(`
|
|
116
|
+
CREATE TABLE IF NOT EXISTS output_baskets (
|
|
117
|
+
basketId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
118
|
+
created_at TEXT NOT NULL,
|
|
119
|
+
updated_at TEXT NOT NULL,
|
|
120
|
+
userId INTEGER NOT NULL,
|
|
121
|
+
name TEXT NOT NULL,
|
|
122
|
+
numberOfDesiredUTXOs INTEGER NOT NULL DEFAULT 144,
|
|
123
|
+
minimumDesiredUTXOValue INTEGER NOT NULL DEFAULT 32,
|
|
124
|
+
isDeleted INTEGER NOT NULL DEFAULT 0,
|
|
125
|
+
FOREIGN KEY (userId) REFERENCES users(userId)
|
|
126
|
+
);
|
|
127
|
+
CREATE INDEX IF NOT EXISTS idx_output_baskets_userId ON output_baskets(userId);
|
|
128
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_output_baskets_name_userId ON output_baskets(name, userId);
|
|
129
|
+
`)
|
|
130
|
+
|
|
131
|
+
// Transactions table
|
|
132
|
+
await db.execAsync(`
|
|
133
|
+
CREATE TABLE IF NOT EXISTS transactions (
|
|
134
|
+
transactionId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
135
|
+
created_at TEXT NOT NULL,
|
|
136
|
+
updated_at TEXT NOT NULL,
|
|
137
|
+
userId INTEGER NOT NULL,
|
|
138
|
+
status TEXT NOT NULL,
|
|
139
|
+
reference TEXT NOT NULL UNIQUE,
|
|
140
|
+
isOutgoing INTEGER NOT NULL DEFAULT 0,
|
|
141
|
+
satoshis INTEGER NOT NULL DEFAULT 0,
|
|
142
|
+
description TEXT,
|
|
143
|
+
version INTEGER,
|
|
144
|
+
lockTime INTEGER,
|
|
145
|
+
txid TEXT,
|
|
146
|
+
inputBEEF BLOB,
|
|
147
|
+
rawTx BLOB,
|
|
148
|
+
provenTxId INTEGER,
|
|
149
|
+
FOREIGN KEY (userId) REFERENCES users(userId),
|
|
150
|
+
FOREIGN KEY (provenTxId) REFERENCES proven_txs(provenTxId)
|
|
151
|
+
);
|
|
152
|
+
CREATE INDEX IF NOT EXISTS idx_transactions_userId ON transactions(userId);
|
|
153
|
+
CREATE INDEX IF NOT EXISTS idx_transactions_status ON transactions(status);
|
|
154
|
+
CREATE INDEX IF NOT EXISTS idx_transactions_reference ON transactions(reference);
|
|
155
|
+
CREATE INDEX IF NOT EXISTS idx_transactions_provenTxId ON transactions(provenTxId);
|
|
156
|
+
CREATE INDEX IF NOT EXISTS idx_transactions_txid ON transactions(txid);
|
|
157
|
+
`)
|
|
158
|
+
|
|
159
|
+
// Commissions table
|
|
160
|
+
await db.execAsync(`
|
|
161
|
+
CREATE TABLE IF NOT EXISTS commissions (
|
|
162
|
+
commissionId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
163
|
+
created_at TEXT NOT NULL,
|
|
164
|
+
updated_at TEXT NOT NULL,
|
|
165
|
+
userId INTEGER NOT NULL,
|
|
166
|
+
transactionId INTEGER NOT NULL UNIQUE,
|
|
167
|
+
satoshis INTEGER NOT NULL,
|
|
168
|
+
keyOffset TEXT,
|
|
169
|
+
isRedeemed INTEGER NOT NULL DEFAULT 0,
|
|
170
|
+
lockingScript BLOB,
|
|
171
|
+
FOREIGN KEY (userId) REFERENCES users(userId),
|
|
172
|
+
FOREIGN KEY (transactionId) REFERENCES transactions(transactionId)
|
|
173
|
+
);
|
|
174
|
+
CREATE INDEX IF NOT EXISTS idx_commissions_userId ON commissions(userId);
|
|
175
|
+
CREATE INDEX IF NOT EXISTS idx_commissions_transactionId ON commissions(transactionId);
|
|
176
|
+
`)
|
|
177
|
+
|
|
178
|
+
// Outputs table
|
|
179
|
+
await db.execAsync(`
|
|
180
|
+
CREATE TABLE IF NOT EXISTS outputs (
|
|
181
|
+
outputId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
182
|
+
created_at TEXT NOT NULL,
|
|
183
|
+
updated_at TEXT NOT NULL,
|
|
184
|
+
userId INTEGER NOT NULL,
|
|
185
|
+
transactionId INTEGER NOT NULL,
|
|
186
|
+
basketId INTEGER,
|
|
187
|
+
spendable INTEGER NOT NULL DEFAULT 1,
|
|
188
|
+
change INTEGER NOT NULL DEFAULT 0,
|
|
189
|
+
outputDescription TEXT,
|
|
190
|
+
vout INTEGER NOT NULL,
|
|
191
|
+
satoshis INTEGER NOT NULL,
|
|
192
|
+
providedBy TEXT NOT NULL,
|
|
193
|
+
purpose TEXT,
|
|
194
|
+
type TEXT,
|
|
195
|
+
txid TEXT,
|
|
196
|
+
senderIdentityKey TEXT,
|
|
197
|
+
derivationPrefix TEXT,
|
|
198
|
+
derivationSuffix TEXT,
|
|
199
|
+
customInstructions TEXT,
|
|
200
|
+
spentBy INTEGER,
|
|
201
|
+
sequenceNumber INTEGER,
|
|
202
|
+
spendingDescription TEXT,
|
|
203
|
+
scriptLength INTEGER,
|
|
204
|
+
scriptOffset INTEGER,
|
|
205
|
+
lockingScript BLOB,
|
|
206
|
+
FOREIGN KEY (userId) REFERENCES users(userId),
|
|
207
|
+
FOREIGN KEY (transactionId) REFERENCES transactions(transactionId),
|
|
208
|
+
FOREIGN KEY (basketId) REFERENCES output_baskets(basketId)
|
|
209
|
+
);
|
|
210
|
+
CREATE INDEX IF NOT EXISTS idx_outputs_userId ON outputs(userId);
|
|
211
|
+
CREATE INDEX IF NOT EXISTS idx_outputs_transactionId ON outputs(transactionId);
|
|
212
|
+
CREATE INDEX IF NOT EXISTS idx_outputs_basketId ON outputs(basketId);
|
|
213
|
+
CREATE INDEX IF NOT EXISTS idx_outputs_spentBy ON outputs(spentBy);
|
|
214
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_outputs_unique ON outputs(transactionId, vout, userId);
|
|
215
|
+
`)
|
|
216
|
+
|
|
217
|
+
// Output tags table
|
|
218
|
+
await db.execAsync(`
|
|
219
|
+
CREATE TABLE IF NOT EXISTS output_tags (
|
|
220
|
+
outputTagId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
221
|
+
created_at TEXT NOT NULL,
|
|
222
|
+
updated_at TEXT NOT NULL,
|
|
223
|
+
userId INTEGER NOT NULL,
|
|
224
|
+
tag TEXT NOT NULL,
|
|
225
|
+
isDeleted INTEGER NOT NULL DEFAULT 0,
|
|
226
|
+
FOREIGN KEY (userId) REFERENCES users(userId)
|
|
227
|
+
);
|
|
228
|
+
CREATE INDEX IF NOT EXISTS idx_output_tags_userId ON output_tags(userId);
|
|
229
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_output_tags_tag_userId ON output_tags(tag, userId);
|
|
230
|
+
`)
|
|
231
|
+
|
|
232
|
+
// Output tags map table
|
|
233
|
+
await db.execAsync(`
|
|
234
|
+
CREATE TABLE IF NOT EXISTS output_tags_map (
|
|
235
|
+
outputTagId INTEGER NOT NULL,
|
|
236
|
+
outputId INTEGER NOT NULL,
|
|
237
|
+
created_at TEXT NOT NULL,
|
|
238
|
+
updated_at TEXT NOT NULL,
|
|
239
|
+
isDeleted INTEGER NOT NULL DEFAULT 0,
|
|
240
|
+
PRIMARY KEY (outputTagId, outputId),
|
|
241
|
+
FOREIGN KEY (outputTagId) REFERENCES output_tags(outputTagId),
|
|
242
|
+
FOREIGN KEY (outputId) REFERENCES outputs(outputId)
|
|
243
|
+
);
|
|
244
|
+
CREATE INDEX IF NOT EXISTS idx_output_tags_map_outputTagId ON output_tags_map(outputTagId);
|
|
245
|
+
CREATE INDEX IF NOT EXISTS idx_output_tags_map_outputId ON output_tags_map(outputId);
|
|
246
|
+
`)
|
|
247
|
+
|
|
248
|
+
// Transaction labels table
|
|
249
|
+
await db.execAsync(`
|
|
250
|
+
CREATE TABLE IF NOT EXISTS tx_labels (
|
|
251
|
+
txLabelId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
252
|
+
created_at TEXT NOT NULL,
|
|
253
|
+
updated_at TEXT NOT NULL,
|
|
254
|
+
userId INTEGER NOT NULL,
|
|
255
|
+
label TEXT NOT NULL,
|
|
256
|
+
isDeleted INTEGER NOT NULL DEFAULT 0,
|
|
257
|
+
FOREIGN KEY (userId) REFERENCES users(userId)
|
|
258
|
+
);
|
|
259
|
+
CREATE INDEX IF NOT EXISTS idx_tx_labels_userId ON tx_labels(userId);
|
|
260
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_tx_labels_label_userId ON tx_labels(label, userId);
|
|
261
|
+
`)
|
|
262
|
+
|
|
263
|
+
// Transaction labels map table
|
|
264
|
+
await db.execAsync(`
|
|
265
|
+
CREATE TABLE IF NOT EXISTS tx_labels_map (
|
|
266
|
+
txLabelId INTEGER NOT NULL,
|
|
267
|
+
transactionId INTEGER NOT NULL,
|
|
268
|
+
created_at TEXT NOT NULL,
|
|
269
|
+
updated_at TEXT NOT NULL,
|
|
270
|
+
isDeleted INTEGER NOT NULL DEFAULT 0,
|
|
271
|
+
PRIMARY KEY (txLabelId, transactionId),
|
|
272
|
+
FOREIGN KEY (txLabelId) REFERENCES tx_labels(txLabelId),
|
|
273
|
+
FOREIGN KEY (transactionId) REFERENCES transactions(transactionId)
|
|
274
|
+
);
|
|
275
|
+
CREATE INDEX IF NOT EXISTS idx_tx_labels_map_txLabelId ON tx_labels_map(txLabelId);
|
|
276
|
+
CREATE INDEX IF NOT EXISTS idx_tx_labels_map_transactionId ON tx_labels_map(transactionId);
|
|
277
|
+
`)
|
|
278
|
+
|
|
279
|
+
// Monitor events table
|
|
280
|
+
await db.execAsync(`
|
|
281
|
+
CREATE TABLE IF NOT EXISTS monitor_events (
|
|
282
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
283
|
+
created_at TEXT NOT NULL,
|
|
284
|
+
updated_at TEXT NOT NULL,
|
|
285
|
+
event TEXT NOT NULL,
|
|
286
|
+
details TEXT
|
|
287
|
+
);
|
|
288
|
+
`)
|
|
289
|
+
|
|
290
|
+
// Sync states table
|
|
291
|
+
await db.execAsync(`
|
|
292
|
+
CREATE TABLE IF NOT EXISTS sync_states (
|
|
293
|
+
syncStateId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
294
|
+
created_at TEXT NOT NULL,
|
|
295
|
+
updated_at TEXT NOT NULL,
|
|
296
|
+
userId INTEGER NOT NULL,
|
|
297
|
+
storageIdentityKey TEXT NOT NULL,
|
|
298
|
+
storageName TEXT NOT NULL,
|
|
299
|
+
status TEXT NOT NULL,
|
|
300
|
+
init INTEGER NOT NULL DEFAULT 0,
|
|
301
|
+
refNum TEXT NOT NULL UNIQUE,
|
|
302
|
+
syncMap TEXT,
|
|
303
|
+
"when" TEXT,
|
|
304
|
+
satoshis INTEGER,
|
|
305
|
+
errorLocal TEXT,
|
|
306
|
+
errorOther TEXT,
|
|
307
|
+
FOREIGN KEY (userId) REFERENCES users(userId)
|
|
308
|
+
);
|
|
309
|
+
CREATE INDEX IF NOT EXISTS idx_sync_states_userId ON sync_states(userId);
|
|
310
|
+
CREATE INDEX IF NOT EXISTS idx_sync_states_status ON sync_states(status);
|
|
311
|
+
CREATE INDEX IF NOT EXISTS idx_sync_states_refNum ON sync_states(refNum);
|
|
312
|
+
`)
|
|
313
|
+
|
|
314
|
+
// Settings table (singleton)
|
|
315
|
+
await db.execAsync(`
|
|
316
|
+
CREATE TABLE IF NOT EXISTS settings (
|
|
317
|
+
storageIdentityKey TEXT PRIMARY KEY,
|
|
318
|
+
created_at TEXT NOT NULL,
|
|
319
|
+
updated_at TEXT NOT NULL,
|
|
320
|
+
storageName TEXT NOT NULL,
|
|
321
|
+
chain TEXT NOT NULL,
|
|
322
|
+
dbtype TEXT NOT NULL,
|
|
323
|
+
maxOutputScript INTEGER NOT NULL
|
|
324
|
+
);
|
|
325
|
+
`)
|
|
326
|
+
|
|
327
|
+
// Key-value store for app-level state (e.g. SSE lastEventId)
|
|
328
|
+
await db.execAsync(`
|
|
329
|
+
CREATE TABLE IF NOT EXISTS key_value_store (
|
|
330
|
+
key TEXT PRIMARY KEY,
|
|
331
|
+
value TEXT NOT NULL,
|
|
332
|
+
updated_at TEXT NOT NULL
|
|
333
|
+
);
|
|
334
|
+
`)
|
|
335
|
+
|
|
336
|
+
// Offline actions — the broadcast queue and provenance record for
|
|
337
|
+
// transactions accepted with no network. The money itself lives in the normal
|
|
338
|
+
// transactions/outputs tables the whole time (that is what keeps it
|
|
339
|
+
// spendable); this table records what still needs sending, in what order it
|
|
340
|
+
// arrived, and who handed it to us.
|
|
341
|
+
await db.execAsync(`
|
|
342
|
+
CREATE TABLE IF NOT EXISTS offline_actions (
|
|
343
|
+
offlineActionId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
344
|
+
created_at TEXT NOT NULL,
|
|
345
|
+
updated_at TEXT NOT NULL,
|
|
346
|
+
userId INTEGER NOT NULL,
|
|
347
|
+
txid TEXT NOT NULL UNIQUE,
|
|
348
|
+
seq INTEGER NOT NULL,
|
|
349
|
+
role TEXT NOT NULL,
|
|
350
|
+
senderIdentityKey TEXT,
|
|
351
|
+
receivedVia TEXT,
|
|
352
|
+
status TEXT NOT NULL,
|
|
353
|
+
rejectedReason TEXT,
|
|
354
|
+
poisonedByTxid TEXT,
|
|
355
|
+
framePayload TEXT,
|
|
356
|
+
FOREIGN KEY (userId) REFERENCES users(userId)
|
|
357
|
+
);
|
|
358
|
+
CREATE INDEX IF NOT EXISTS idx_offline_actions_status ON offline_actions(status);
|
|
359
|
+
CREATE INDEX IF NOT EXISTS idx_offline_actions_userId ON offline_actions(userId);
|
|
360
|
+
CREATE INDEX IF NOT EXISTS idx_offline_actions_seq ON offline_actions(seq);
|
|
361
|
+
CREATE INDEX IF NOT EXISTS idx_offline_actions_txid ON offline_actions(txid);
|
|
362
|
+
`)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Post-ship column additions to offline_actions. CREATE TABLE IF NOT EXISTS
|
|
367
|
+
* cannot alter an existing table, so upgrades go through a PRAGMA check + a
|
|
368
|
+
* guarded ALTER. Add future columns to the COLUMNS list; never remove or
|
|
369
|
+
* retype one here — SQLite ALTER cannot do either, and this table is live
|
|
370
|
+
* money bookkeeping on shipped devices.
|
|
371
|
+
*/
|
|
372
|
+
const OFFLINE_ACTIONS_COLUMNS: { name: string; ddl: string }[] = [
|
|
373
|
+
{ name: 'framePayload', ddl: 'ALTER TABLE offline_actions ADD COLUMN framePayload TEXT' }
|
|
374
|
+
]
|
|
375
|
+
|
|
376
|
+
export async function ensureOfflineActionsColumns(db: {
|
|
377
|
+
getAllAsync(sql: string, params: BindValue[]): Promise<unknown[]>
|
|
378
|
+
execAsync(sql: string): Promise<unknown>
|
|
379
|
+
}): Promise<void> {
|
|
380
|
+
const info = (await db.getAllAsync('PRAGMA table_info(offline_actions)', [])) as { name: string }[]
|
|
381
|
+
const have = new Set(info.map(c => c.name))
|
|
382
|
+
for (const col of OFFLINE_ACTIONS_COLUMNS) {
|
|
383
|
+
if (!have.has(col.name)) await db.execAsync(col.ddl)
|
|
384
|
+
}
|
|
385
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether TaskSendWaiting must skip a request this pass because one of its
|
|
3
|
+
* inputs is still sitting in the offline queue.
|
|
4
|
+
*
|
|
5
|
+
* A child posted ahead of a queued parent is refused as an orphan. The drain
|
|
6
|
+
* (`TaskSendOffline`) owns parent-first release; this predicate only parks the
|
|
7
|
+
* child and asks the drain to run.
|
|
8
|
+
*/
|
|
9
|
+
import { Transaction } from '@bsv/sdk'
|
|
10
|
+
|
|
11
|
+
export function shouldDeferSendWaiting(inputTxids: string[], queuedTxids: Set<string>): boolean {
|
|
12
|
+
return inputTxids.some(id => queuedTxids.has(id))
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Input txids of a stored raw transaction, or [] if the bytes will not parse. */
|
|
16
|
+
export function inputTxidsFromRawTx(rawTx: number[] | Uint8Array | undefined): string[] {
|
|
17
|
+
if (rawTx == null) return []
|
|
18
|
+
try {
|
|
19
|
+
const tx = Transaction.fromBinary(Array.from(rawTx))
|
|
20
|
+
const ids: string[] = []
|
|
21
|
+
for (const input of tx.inputs) {
|
|
22
|
+
const id = input.sourceTXID
|
|
23
|
+
if (typeof id === 'string' && id.length > 0) ids.push(id)
|
|
24
|
+
}
|
|
25
|
+
return ids
|
|
26
|
+
} catch {
|
|
27
|
+
return []
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type SqlBindResult = { omit: true } | { omit: false; value: unknown }
|
|
2
|
+
|
|
3
|
+
/** Map an update field to a SQL bind, or omit it from the SET clause. */
|
|
4
|
+
export function sqlBindValue(table: string, column: string, value: unknown): SqlBindResult {
|
|
5
|
+
if (value === undefined) {
|
|
6
|
+
if (table === 'outputs' && column === 'spentBy') {
|
|
7
|
+
return { omit: false, value: null }
|
|
8
|
+
}
|
|
9
|
+
return { omit: true }
|
|
10
|
+
}
|
|
11
|
+
return { omit: false, value }
|
|
12
|
+
}
|