@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,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The payer's side of the offline queue: record that this payment still needs
|
|
3
|
+
* broadcasting, then promote the withheld transaction so its change is
|
|
4
|
+
* spendable.
|
|
5
|
+
*
|
|
6
|
+
* `buildPaymentFrame` creates the payment with `noSend: true`, which
|
|
7
|
+
* `determineReqTxStatus` (`storage/methods/processAction.js:150-159`) leaves
|
|
8
|
+
* BOTH the request and the transaction at `nosend`. The request staying
|
|
9
|
+
* `nosend` is exactly what the release drain wants — `processOfflineActions`'s
|
|
10
|
+
* `postOwned` posts a request it finds at `nosend` as-is, and deliberately does
|
|
11
|
+
* not promote it first (see that function's comment on why promoting the
|
|
12
|
+
* request would buy nothing and could hand the monitor a chance to broadcast
|
|
13
|
+
* out of order). The TRANSACTION is the one row that must move: a `nosend`
|
|
14
|
+
* transaction's change is invisible to `allocateChangeInput`
|
|
15
|
+
* (`storage/StorageExpoSQLite.ts:1284`, whose status list is
|
|
16
|
+
* `['completed','unproven']` plus optionally `'sending'`), so until this
|
|
17
|
+
* promotion runs, a payer stuck underground could never fund a second offline
|
|
18
|
+
* payment out of the first one's change. `nosend -> unproven` is a pure status
|
|
19
|
+
* write with no output side-effects — only `failed` has any
|
|
20
|
+
* (`StorageProvider.js:397-436`).
|
|
21
|
+
*
|
|
22
|
+
* ORDER MATTERS. The queue-row insert runs FIRST, deliberately, because it is
|
|
23
|
+
* durable and the status promotion is not: nothing in this app re-drives a
|
|
24
|
+
* hold that failed partway (see `finalizeDelivery`'s catch — a thrown hold is
|
|
25
|
+
* reported as `broadcast: 'pending'`, not retried). If the insert lands and
|
|
26
|
+
* the promotion then throws, `processOfflineActions`'s drain still finds this
|
|
27
|
+
* txid's row and will post it — `postOwned` reads whatever transaction status
|
|
28
|
+
* a request's outputs are ALREADY at before posting and only restores that
|
|
29
|
+
* same status on a service error (`processOfflineActions.ts` — "holdSafeTxStatuses
|
|
30
|
+
* admits 'nosend' as well as 'unproven'"), and `attemptToPostReqsToNetwork`
|
|
31
|
+
* promotes the transaction forward on any successful post regardless of what
|
|
32
|
+
* it started at (`attemptToPostReqsToNetwork.js:189-197,268`). So a failed
|
|
33
|
+
* promotion only costs this device the ability to spend this change while
|
|
34
|
+
* still offline; it resolves itself the moment the drain successfully posts
|
|
35
|
+
* the transaction, with no data lost. The reverse order would risk the
|
|
36
|
+
* opposite failure: a promoted-but-unqueued transaction that nothing will
|
|
37
|
+
* ever broadcast, because `processOfflineActions` only ever looks at
|
|
38
|
+
* `offline_actions` rows, and no monitor task sweeps a plain `nosend`
|
|
39
|
+
* transaction to send it — `TaskSendWaiting` selects only
|
|
40
|
+
* `['unsent','sending']`, and `TaskCheckNoSends` (the only task that reads
|
|
41
|
+
* `nosend` rows at all) only requests merkle proofs for transactions that may
|
|
42
|
+
* have been broadcast BY SOME OTHER MEANS; it never calls `sendWith` and never
|
|
43
|
+
* advances status.
|
|
44
|
+
*
|
|
45
|
+
* Deliberately NOT built on `holdReqsOffline` (Task 8): that method's contract
|
|
46
|
+
* is the opposite of this one's job. It takes the transaction status as a
|
|
47
|
+
* PRECONDITION and leaves it untouched — its whole point, on the receiving
|
|
48
|
+
* side, is that `internalizeAction` already left the transaction `unproven`
|
|
49
|
+
* before it runs. Coupling this payer-side promotion into it would mean either
|
|
50
|
+
* bending that documented invariant (risking the receiving path it protects)
|
|
51
|
+
* or calling it and then promoting the transaction separately anyway, which
|
|
52
|
+
* shares nothing. What genuinely is shared — the `offline_actions` insert — is
|
|
53
|
+
* reused directly via `insertOfflineAction`.
|
|
54
|
+
*/
|
|
55
|
+
import { insertOfflineAction, updateOfflineAction } from '../storage/methods/offlineActions'
|
|
56
|
+
import { TaskSendOffline } from '../monitor/TaskSendOffline'
|
|
57
|
+
import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
|
|
58
|
+
|
|
59
|
+
export async function holdSentPaymentOffline(args: {
|
|
60
|
+
storage: StorageExpoSQLite
|
|
61
|
+
txid: string
|
|
62
|
+
/** The full bsvpayf1: QR string, persisted so the code can be re-shown later. */
|
|
63
|
+
framePayload?: string
|
|
64
|
+
}): Promise<void> {
|
|
65
|
+
const { storage, txid, framePayload } = args
|
|
66
|
+
const db = storage.sqliteDb
|
|
67
|
+
if (!db) throw new Error('the database is not open, cannot queue this payment for release')
|
|
68
|
+
|
|
69
|
+
// The transaction row is the one authority this needs for both facts: its
|
|
70
|
+
// own transactionId, to promote, and its userId, to attribute the queue row.
|
|
71
|
+
// Resolving userId any other way risks a value unconnected to this payment —
|
|
72
|
+
// and `offline_actions.userId` is a foreign key with enforcement OFF in this
|
|
73
|
+
// app (no `PRAGMA foreign_keys` anywhere), so a wrong id would not fail loudly,
|
|
74
|
+
// it would silently park the payment under a user nothing ever queries. If the
|
|
75
|
+
// transaction cannot be found at all, there is no safe id to fall back to, so
|
|
76
|
+
// this throws rather than guessing — the caller (`finalizeDelivery`) already
|
|
77
|
+
// treats a failed hold as a non-fatal `broadcast: 'pending'`, because the
|
|
78
|
+
// payee holds its own durable copy regardless of whether this device's queue
|
|
79
|
+
// bookkeeping succeeds.
|
|
80
|
+
const tx = (await storage.findTransactions({ partial: { txid }, noRawTx: true }))[0]
|
|
81
|
+
if (!tx) throw new Error(`no transaction record for ${txid}, cannot queue it for release`)
|
|
82
|
+
|
|
83
|
+
// Insert before promote — see the ORDER MATTERS note above.
|
|
84
|
+
await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload })
|
|
85
|
+
TaskSendOffline.noteEnqueued()
|
|
86
|
+
await storage.updateTransactionStatus('unproven', tx.transactionId)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Keep a handed-over payment WITHOUT releasing it for broadcast.
|
|
92
|
+
*
|
|
93
|
+
* The payer left the code screen instead of confirming the hand-over, so
|
|
94
|
+
* nothing is known about whether the payee scanned. Holding it would post it —
|
|
95
|
+
* `holdSentPaymentOffline` promotes the transaction and wakes the drain, which
|
|
96
|
+
* is how backing out came to send the payment outright. Parking keeps both
|
|
97
|
+
* possibilities open instead: the frame is stored so the code can be shown
|
|
98
|
+
* again, and the transaction stays `nosend`, so its inputs are still reserved
|
|
99
|
+
* and it can still be aborted.
|
|
100
|
+
*
|
|
101
|
+
* If the payee did scan and broadcasts their copy, the payment settles from
|
|
102
|
+
* their side and this device sees it confirm. If they did not, the payer can
|
|
103
|
+
* cancel and nothing was ever spent.
|
|
104
|
+
*/
|
|
105
|
+
export async function parkSentPaymentOffline(args: {
|
|
106
|
+
storage: StorageExpoSQLite
|
|
107
|
+
txid: string
|
|
108
|
+
framePayload?: string
|
|
109
|
+
}): Promise<void> {
|
|
110
|
+
const { storage, txid, framePayload } = args
|
|
111
|
+
const db = storage.sqliteDb
|
|
112
|
+
if (!db) throw new Error('the database is not open, cannot park this payment')
|
|
113
|
+
|
|
114
|
+
const tx = (await storage.findTransactions({ partial: { txid }, noRawTx: true }))[0]
|
|
115
|
+
if (!tx) throw new Error(`no transaction record for ${txid}, cannot park it`)
|
|
116
|
+
|
|
117
|
+
// No promote, and no TaskSendOffline.noteEnqueued(): both are what turn a
|
|
118
|
+
// stored frame into a broadcast.
|
|
119
|
+
await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload }, 'parked')
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Release a parked payment: the payer showed the code again and this time
|
|
125
|
+
* confirmed the hand-over.
|
|
126
|
+
*
|
|
127
|
+
* The same two writes `holdSentPaymentOffline` makes, minus the insert — the
|
|
128
|
+
* row already exists from parking, so it is flipped to 'queued' instead. Same
|
|
129
|
+
* order for the same reason: the durable row moves first, the promotion after.
|
|
130
|
+
*/
|
|
131
|
+
export async function releaseParkedPayment(args: { storage: StorageExpoSQLite; txid: string }): Promise<void> {
|
|
132
|
+
const { storage, txid } = args
|
|
133
|
+
const db = storage.sqliteDb
|
|
134
|
+
if (!db) throw new Error('the database is not open, cannot release this payment')
|
|
135
|
+
|
|
136
|
+
const tx = (await storage.findTransactions({ partial: { txid }, noRawTx: true }))[0]
|
|
137
|
+
if (!tx) throw new Error(`no transaction record for ${txid}, cannot release it`)
|
|
138
|
+
|
|
139
|
+
await updateOfflineAction(db, txid, { status: 'queued' })
|
|
140
|
+
TaskSendOffline.noteEnqueued()
|
|
141
|
+
// Already promoted if the payee broadcast and this device saw it; the write
|
|
142
|
+
// is only correct while the transaction is still being withheld.
|
|
143
|
+
if (tx.status === 'nosend') await storage.updateTransactionStatus('unproven', tx.transactionId)
|
|
144
|
+
}
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What to release, in what order, and what a broadcast result means.
|
|
3
|
+
*
|
|
4
|
+
* Split from the driver so the two decisions that can lose money — ordering and
|
|
5
|
+
* cascading — are unit-testable without a database or a network. Reading a
|
|
6
|
+
* broadcast result is here for the same reason: "did this actually reach the
|
|
7
|
+
* network" is a decision, not plumbing, and getting it wrong marks a queue row
|
|
8
|
+
* 'sent' for a transaction nobody has.
|
|
9
|
+
*/
|
|
10
|
+
import { dependencyOrder, descendantsOf, releaseOrder, type OrderableTx } from './order'
|
|
11
|
+
import type { OfflineActionRow } from '../storage/methods/offlineActions'
|
|
12
|
+
import type { ProvenTxReqStatus } from '@bsv/wallet-toolbox-mobile/out/src/sdk/types'
|
|
13
|
+
|
|
14
|
+
export type PostOutcome = 'success' | 'serviceError' | 'invalidTx' | 'doubleSpend'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Dependency-ordered release list.
|
|
18
|
+
*
|
|
19
|
+
* `owned` marks a transaction the QUEUE still has a row for — it is computed from
|
|
20
|
+
* `rows`, not from whether a request exists. Those are posted through
|
|
21
|
+
* `attemptToPostReqsToNetwork` so the toolbox does its own status bookkeeping;
|
|
22
|
+
* everything else in the graph is treated as a foreign ancestor that arrived
|
|
23
|
+
* inside somebody's BEEF and is posted directly through `postBeef`. Whether an
|
|
24
|
+
* owned txid actually has a request is the driver's business, and it stops the run
|
|
25
|
+
* rather than posting if one is missing (`processOfflineActions`'s
|
|
26
|
+
* `step.owned && !action` branch).
|
|
27
|
+
*
|
|
28
|
+
* The `status !== 'sent'` filter is belt-and-braces: the driver only ever reads
|
|
29
|
+
* 'queued' and 'posting' rows, so a 'sent' one does not reach here today, and a
|
|
30
|
+
* caller that passed one would be saying the transaction is already out.
|
|
31
|
+
*
|
|
32
|
+
* Getting the distinction wrong is how a child becomes an orphan: EF carries
|
|
33
|
+
* input scripts but not parent transactions, so an unbroadcast ancestor has to go
|
|
34
|
+
* out on its own first.
|
|
35
|
+
*/
|
|
36
|
+
export function planRelease(args: {
|
|
37
|
+
rows: OfflineActionRow[]
|
|
38
|
+
txs: OrderableTx[]
|
|
39
|
+
}): { txid: string; owned: boolean }[] {
|
|
40
|
+
const owned = new Set(args.rows.filter(r => r.status !== 'sent').map(r => r.txid))
|
|
41
|
+
return releaseOrder(args.txs).map(txid => ({ txid, owned: owned.has(txid) }))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Turn one broadcast result into state changes.
|
|
46
|
+
*
|
|
47
|
+
* · success — this transaction is out; continue down the list.
|
|
48
|
+
* · serviceError — no evidence of invalidity, only of no network. Block the
|
|
49
|
+
* failed transaction and everything that spends it, leaving
|
|
50
|
+
* them queued, but let every other, independent root in the
|
|
51
|
+
* plan keep going. Never reject on this.
|
|
52
|
+
* · invalidTx /
|
|
53
|
+
* doubleSpend — the network refuses it, so no descendant of it can ever be
|
|
54
|
+
* valid. Reject it and every descendant; nothing is left to
|
|
55
|
+
* skip, because a rejection is final rather than deferred.
|
|
56
|
+
*
|
|
57
|
+
* `rows` is accepted so a caller hands the same pair of arguments to this and to
|
|
58
|
+
* `planRelease`, but the cascade deliberately never consults it. Descendants are
|
|
59
|
+
* read from the BEEF alone: a transaction the wallet built while offline by
|
|
60
|
+
* spending the poisoned money has a request and a transaction row but no queue
|
|
61
|
+
* row of its own, and it is exactly the thing that must stop being spendable.
|
|
62
|
+
*
|
|
63
|
+
* `rejected` comes back in the order it must be applied: a full reverse dependency
|
|
64
|
+
* order, every child before every transaction it spends, the refused one last.
|
|
65
|
+
* Failing a transaction releases its inputs back to spendable
|
|
66
|
+
* (`StorageProvider.releaseInputsAllocatedToFailedTransaction`,
|
|
67
|
+
* `StorageProvider.js:365-373`) before marking its own outputs unspendable, and
|
|
68
|
+
* `EntityTransaction.getInputs` re-finds those inputs by txid and vout whether or
|
|
69
|
+
* not `spentBy` was cleared — so a child failed after its parent does not merely
|
|
70
|
+
* race it, it reliably undoes it. Applied child-first, each parent's own failure
|
|
71
|
+
* has the last word.
|
|
72
|
+
*/
|
|
73
|
+
export function applyOutcome(args: {
|
|
74
|
+
txid: string
|
|
75
|
+
outcome: PostOutcome
|
|
76
|
+
txs: OrderableTx[]
|
|
77
|
+
rows: OfflineActionRow[]
|
|
78
|
+
}): {
|
|
79
|
+
sent: string[]
|
|
80
|
+
rejected: { txid: string; reason: string; poisonedByTxid: string }[]
|
|
81
|
+
/**
|
|
82
|
+
* Txids that must be skipped for the rest of this run and left queued: the
|
|
83
|
+
* failed transaction plus everything that spends it. A serviceError carries
|
|
84
|
+
* no verdict, so nothing is rejected — but no descendant may post before its
|
|
85
|
+
* parent, and every OTHER root in the plan is unaffected and keeps going.
|
|
86
|
+
* The old run-global `stop` made one unreachable service poison a whole
|
|
87
|
+
* queue of independent payments per pass.
|
|
88
|
+
*/
|
|
89
|
+
blocked: string[]
|
|
90
|
+
} {
|
|
91
|
+
const { txid, outcome, txs } = args
|
|
92
|
+
if (outcome === 'success') return { sent: [txid], rejected: [], blocked: [] }
|
|
93
|
+
if (outcome === 'serviceError') {
|
|
94
|
+
return { sent: [], rejected: [], blocked: [txid, ...descendantsOf(txid, txs)] }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const reason =
|
|
98
|
+
outcome === 'doubleSpend'
|
|
99
|
+
? 'the network reported a double spend of an input'
|
|
100
|
+
: 'the transaction was rejected as invalid'
|
|
101
|
+
// Reverse dependency order over the whole cascade, which is why it uses
|
|
102
|
+
// `dependencyOrder` and not `releaseOrder`: the latter drops mined and txid-only
|
|
103
|
+
// transactions because they need no broadcast, but a cascade still has to place
|
|
104
|
+
// them, since one can be both somebody's child and somebody's parent and neither
|
|
105
|
+
// end of the list is right for it. `descendantsOf` cannot supply the order
|
|
106
|
+
// either — it reports by discovery, and a transaction can spend both the refused
|
|
107
|
+
// one and one of its own siblings.
|
|
108
|
+
const known = new Map(txs.map(t => [t.txid, t]))
|
|
109
|
+
const members = [txid, ...descendantsOf(txid, txs)].map(
|
|
110
|
+
t => known.get(t) ?? { txid: t, hasProof: false, isTxidOnly: false, inputTxids: [] }
|
|
111
|
+
)
|
|
112
|
+
const ordered = dependencyOrder(members).reverse()
|
|
113
|
+
const rejected = ordered.map(t => ({
|
|
114
|
+
txid: t,
|
|
115
|
+
reason: t === txid ? reason : `an ancestor was rejected: ${reason}`,
|
|
116
|
+
poisonedByTxid: txid
|
|
117
|
+
}))
|
|
118
|
+
return { sent: [], rejected, blocked: [] }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Every `ProvenTxReqStatus` (`sdk/types.d.ts:51`), classified by the verdict it
|
|
123
|
+
* records.
|
|
124
|
+
*
|
|
125
|
+
* · 'success' — `alreadySentStatuses` (`storageProviderHelpers.js:12`): the
|
|
126
|
+
* wallet's own record that the transaction reached the network,
|
|
127
|
+
* and the only witness this module trusts for delivery.
|
|
128
|
+
* · 'doubleSpend' /
|
|
129
|
+
* 'invalidTx' — a refusal already recorded against it.
|
|
130
|
+
* · 'undecided' — no verdict yet, so the transaction behind it could still turn
|
|
131
|
+
* out to be spending poisoned money and a cascade has to be
|
|
132
|
+
* able to see it.
|
|
133
|
+
*
|
|
134
|
+
* One `Record` keyed by the union rather than several hand-kept lists, because a
|
|
135
|
+
* status this file does not know about is a poisoned descendant that keeps its
|
|
136
|
+
* outputs spendable. Keyed that way, a status added or removed upstream is a
|
|
137
|
+
* compile error here; the partition below is pinned by tests as well, so a
|
|
138
|
+
* reclassification is caught too. Note `unfail`: `ProvenTxReqTerminalStatus` is
|
|
139
|
+
* only `['completed','invalid','doubleSpend']` (`sdk/types.js:7`), so a request
|
|
140
|
+
* being resurrected is undecided and must not be overlooked.
|
|
141
|
+
*/
|
|
142
|
+
const reqStatusVerdicts: Record<ProvenTxReqStatus, 'success' | 'doubleSpend' | 'invalidTx' | 'undecided'> = {
|
|
143
|
+
unmined: 'success',
|
|
144
|
+
callback: 'success',
|
|
145
|
+
unconfirmed: 'success',
|
|
146
|
+
completed: 'success',
|
|
147
|
+
doubleSpend: 'doubleSpend',
|
|
148
|
+
invalid: 'invalidTx',
|
|
149
|
+
sending: 'undecided',
|
|
150
|
+
unsent: 'undecided',
|
|
151
|
+
nosend: 'undecided',
|
|
152
|
+
unknown: 'undecided',
|
|
153
|
+
nonfinal: 'undecided',
|
|
154
|
+
unprocessed: 'undecided',
|
|
155
|
+
unfail: 'undecided'
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function statusesVerdicted(...verdicts: (typeof reqStatusVerdicts)[ProvenTxReqStatus][]): ProvenTxReqStatus[] {
|
|
159
|
+
const keys = Object.keys(reqStatusVerdicts) as ProvenTxReqStatus[]
|
|
160
|
+
return keys.filter(s => verdicts.includes(reqStatusVerdicts[s]))
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Every request status there is, so a test can prove the partition is complete. */
|
|
164
|
+
export const allReqStatuses: readonly ProvenTxReqStatus[] = Object.keys(reqStatusVerdicts) as ProvenTxReqStatus[]
|
|
165
|
+
|
|
166
|
+
/** Statuses that mean the transaction has already been handed to the network. */
|
|
167
|
+
export const alreadySentStatuses: readonly ProvenTxReqStatus[] = statusesVerdicted('success')
|
|
168
|
+
|
|
169
|
+
/** Receipt overlay: true only when storage already records a network hand-off. */
|
|
170
|
+
export function receiptBroadcastFromReqStatus(status: string | undefined): boolean {
|
|
171
|
+
return status !== undefined && (alreadySentStatuses as readonly string[]).includes(status)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Statuses that already carry a recorded refusal. */
|
|
175
|
+
export const refusedReqStatuses: readonly ProvenTxReqStatus[] = statusesVerdicted('doubleSpend', 'invalidTx')
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Statuses carrying no verdict yet.
|
|
179
|
+
*
|
|
180
|
+
* This is the set a cascade must widen its graph over: the wallet re-spent money
|
|
181
|
+
* it received underground, and Task 8 leaves such an outgoing request to
|
|
182
|
+
* `TaskSendWaiting` rather than parking it, so nothing put that transaction in the
|
|
183
|
+
* queue or in any held beef. A status wrongly missing from here is a poisoned
|
|
184
|
+
* descendant that keeps its outputs spendable.
|
|
185
|
+
*/
|
|
186
|
+
export const undecidedReqStatuses: ProvenTxReqStatus[] = statusesVerdicted('undecided')
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The verdict already recorded against a request in storage, or undefined if the
|
|
190
|
+
* request still needs posting.
|
|
191
|
+
*
|
|
192
|
+
* Used twice: before a post, to skip a request a previous interrupted run had
|
|
193
|
+
* already got out (or already had refused); and after one, as the authority on
|
|
194
|
+
* whether the post landed. An unrecognised status reads as undecided, which
|
|
195
|
+
* neither claims delivery nor rejects anything.
|
|
196
|
+
*/
|
|
197
|
+
export function outcomeFromReqStatus(status: string | undefined): PostOutcome | undefined {
|
|
198
|
+
if (status === undefined) return undefined
|
|
199
|
+
const verdict = reqStatusVerdicts[status as ProvenTxReqStatus]
|
|
200
|
+
return verdict === undefined || verdict === 'undecided' ? undefined : verdict
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Read the result of posting a transaction this wallet owns.
|
|
205
|
+
*
|
|
206
|
+
* Storage decides delivery, not the returned status. A `'success'` from
|
|
207
|
+
* `attemptToPostReqsToNetwork` can also come from an offline hold, which means
|
|
208
|
+
* "accepted for delivery" rather than "the network has it"; if connectivity drops
|
|
209
|
+
* between this engine's own online check and its post, that is precisely what
|
|
210
|
+
* comes back. A real broadcast always leaves the request at 'unmined'
|
|
211
|
+
* (`attemptToPostReqsToNetwork.js:236-239`), so requiring that persisted status
|
|
212
|
+
* cannot mistake a hold for a delivery — and the safe direction of the remaining
|
|
213
|
+
* doubt is 'serviceError', which retries and never rejects.
|
|
214
|
+
*
|
|
215
|
+
* A failure is believed from either witness: `reqStatus` catches the case where
|
|
216
|
+
* the post reported no verdict because storage had already recorded one.
|
|
217
|
+
*/
|
|
218
|
+
export function outcomeOfOwnedPost(args: { detailStatus?: string; reqStatus?: string }): PostOutcome {
|
|
219
|
+
const recorded = outcomeFromReqStatus(args.reqStatus)
|
|
220
|
+
if (recorded !== undefined) return recorded
|
|
221
|
+
if (args.detailStatus === 'doubleSpend') return 'doubleSpend'
|
|
222
|
+
if (args.detailStatus === 'invalid' || args.detailStatus === 'invalidTx') return 'invalidTx'
|
|
223
|
+
return 'serviceError'
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** One service's per-txid outcome. Structurally satisfied by `PostTxResultForTxid`. */
|
|
227
|
+
export interface PostedTxidResult {
|
|
228
|
+
txid: string
|
|
229
|
+
status: string
|
|
230
|
+
/** The service already had this transaction, which its own docs say to read as success. */
|
|
231
|
+
alreadyKnown?: boolean
|
|
232
|
+
doubleSpend?: boolean
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** One service's reply. Structurally satisfied by `PostBeefResult`. */
|
|
236
|
+
export interface PostedResult {
|
|
237
|
+
txidResults: PostedTxidResult[]
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Read the result of posting a foreign ancestor, which has no request here to
|
|
242
|
+
* record a verdict on, so the reply is the only witness there is.
|
|
243
|
+
*
|
|
244
|
+
* A double spend outranks a success, matching the toolbox's own aggregate
|
|
245
|
+
* (`attemptToPostReqsToNetwork.js:174-181`) so the codebase has one rule for it.
|
|
246
|
+
*
|
|
247
|
+
* A plain error is never read as invalidity. This ancestor arrived inside a BEEF
|
|
248
|
+
* that `internalizeAction` had already verified — scripts and SPV both — so a
|
|
249
|
+
* bare rejection is far more likely to mean our merged BEEF is missing bytes
|
|
250
|
+
* this service needed than that the transaction is bad, and rejecting it would
|
|
251
|
+
* cascade into money the user legitimately holds. Left retryable, the drain
|
|
252
|
+
* simply stalls, which loses nothing.
|
|
253
|
+
*/
|
|
254
|
+
export function outcomeOfForeignPost(args: { txid: string; results: PostedResult[] }): PostOutcome {
|
|
255
|
+
let success = false
|
|
256
|
+
for (const result of args.results) {
|
|
257
|
+
for (const r of result.txidResults) {
|
|
258
|
+
if (r.txid !== args.txid) continue
|
|
259
|
+
if (r.doubleSpend === true) return 'doubleSpend'
|
|
260
|
+
if (r.status === 'success' || r.alreadyKnown === true) success = true
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return success ? 'success' : 'serviceError'
|
|
264
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which queued payments are worth telling the user about.
|
|
3
|
+
*
|
|
4
|
+
* "Waiting to be broadcast — nothing is settled until they do" is true of a
|
|
5
|
+
* payment queued underground for an hour. It is not what a user needs to read
|
|
6
|
+
* for the half second between a payment joining the queue and the drain posting
|
|
7
|
+
* it, which is what they see when they release one while online: the banner
|
|
8
|
+
* flashes up and vanishes, having claimed a problem that never existed.
|
|
9
|
+
*
|
|
10
|
+
* So while online, a queued row stays quiet for a grace period. Offline there
|
|
11
|
+
* is no grace: nothing will post it until the network comes back, and that is
|
|
12
|
+
* the whole point of saying so. A row still queued after the grace has earned
|
|
13
|
+
* the banner — by then it really is stuck on something.
|
|
14
|
+
*
|
|
15
|
+
* The caller is told when to look again (`nextCheckMs`), because a row that is
|
|
16
|
+
* merely young becomes newsworthy by the passage of time alone, and nothing
|
|
17
|
+
* else would wake the screen to notice.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Long enough to cover a normal post, short enough that a stall still surfaces fast. */
|
|
21
|
+
export const QUEUE_GRACE_MS = 6000
|
|
22
|
+
|
|
23
|
+
export type GraceRow = { status: string; created_at?: string; updated_at?: string }
|
|
24
|
+
|
|
25
|
+
function ageMs(row: GraceRow, nowMs: number): number {
|
|
26
|
+
const stamp = row.updated_at ?? row.created_at
|
|
27
|
+
if (!stamp) return Number.POSITIVE_INFINITY
|
|
28
|
+
const t = new Date(stamp).getTime()
|
|
29
|
+
if (Number.isNaN(t)) return Number.POSITIVE_INFINITY
|
|
30
|
+
// A clock skewed the wrong way must not hide the banner forever.
|
|
31
|
+
return Math.max(0, nowMs - t)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function partitionQueueByGrace<T extends GraceRow>(
|
|
35
|
+
rows: T[],
|
|
36
|
+
args: { online: boolean; nowMs: number; graceMs?: number }
|
|
37
|
+
): { shown: T[]; nextCheckMs?: number } {
|
|
38
|
+
const graceMs = args.graceMs ?? QUEUE_GRACE_MS
|
|
39
|
+
if (!args.online) return { shown: rows }
|
|
40
|
+
|
|
41
|
+
const shown: T[] = []
|
|
42
|
+
let soonest: number | undefined
|
|
43
|
+
for (const row of rows) {
|
|
44
|
+
const remaining = graceMs - ageMs(row, args.nowMs)
|
|
45
|
+
if (remaining <= 0) {
|
|
46
|
+
shown.push(row)
|
|
47
|
+
continue
|
|
48
|
+
}
|
|
49
|
+
soonest = soonest === undefined ? remaining : Math.min(soonest, remaining)
|
|
50
|
+
}
|
|
51
|
+
return soonest === undefined ? { shown } : { shown, nextCheckMs: soonest }
|
|
52
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { PublicKey } from '@bsv/sdk'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* BRC-125 PeerPay URI (https://bsv.brc.dev/payments/0125).
|
|
5
|
+
*
|
|
6
|
+
* peerpay-URI = "peerpay:" identity-key [ "?" query ]
|
|
7
|
+
* sats-param = "sats=" 1*DIGIT
|
|
8
|
+
*
|
|
9
|
+
* Plus one extension parameter this app emits and reads: `url`, the payee's
|
|
10
|
+
* message-box host, so a payer can skip the overlay lookup. Per BRC-125 an extension that does not parse
|
|
11
|
+
* is ignored, not fatal — a typo in the hint must not block a payment
|
|
12
|
+
* whose key is fine. Only https is accepted because the payer will
|
|
13
|
+
* authenticate against whatever host this names.
|
|
14
|
+
*/
|
|
15
|
+
export interface PeerPayParams {
|
|
16
|
+
identityKey: string
|
|
17
|
+
sats?: number
|
|
18
|
+
messageBoxUrl?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface PeerPayValidationResult {
|
|
22
|
+
isPeerPay: boolean
|
|
23
|
+
identityKey?: string
|
|
24
|
+
sats?: number
|
|
25
|
+
/** Present only when the link carried a usable https `url` extension. */
|
|
26
|
+
messageBoxUrl?: string
|
|
27
|
+
errors: {
|
|
28
|
+
identityKey?: string
|
|
29
|
+
sats?: string
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const PEERPAY_SCHEME = 'peerpay:'
|
|
34
|
+
const COMPRESSED_PUBLIC_KEY_REGEX = /^0[23][0-9a-fA-F]{64}$/
|
|
35
|
+
/**
|
|
36
|
+
* https, a host, then an optional path/query/fragment with no whitespace. The
|
|
37
|
+
* authority chunk excludes `@` and `\` so a `mb.trusted.example@evil.example`
|
|
38
|
+
* userinfo cannot present a readable prefix that is not the real host.
|
|
39
|
+
*/
|
|
40
|
+
const MESSAGE_BOX_URL_REGEX = /^https:\/\/[^\s/?#@\\]+(?:[/?#]\S*)?$/i
|
|
41
|
+
|
|
42
|
+
export function parsePeerPayURI(uri: string): PeerPayParams | null {
|
|
43
|
+
const result = validatePeerPayURI(uri)
|
|
44
|
+
if (!result.isPeerPay || !result.identityKey || result.errors.identityKey || result.errors.sats) return null
|
|
45
|
+
return {
|
|
46
|
+
identityKey: result.identityKey,
|
|
47
|
+
sats: result.sats,
|
|
48
|
+
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function validatePeerPayURI(uri: string): PeerPayValidationResult {
|
|
53
|
+
const trimmed = uri.trim()
|
|
54
|
+
if (!trimmed.toLowerCase().startsWith(PEERPAY_SCHEME)) {
|
|
55
|
+
return { isPeerPay: false, errors: { identityKey: 'Not a peerpay link' } }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let withoutScheme = trimmed.slice(PEERPAY_SCHEME.length)
|
|
59
|
+
if (withoutScheme.startsWith('//')) withoutScheme = withoutScheme.slice(2)
|
|
60
|
+
const queryIndex = withoutScheme.indexOf('?')
|
|
61
|
+
const keyPart = queryIndex === -1 ? withoutScheme : withoutScheme.slice(0, queryIndex)
|
|
62
|
+
const queryPart = queryIndex === -1 ? '' : withoutScheme.slice(queryIndex + 1)
|
|
63
|
+
const errors: PeerPayValidationResult['errors'] = {}
|
|
64
|
+
|
|
65
|
+
let identityKey: string | undefined
|
|
66
|
+
if (isValidIdentityKey(keyPart)) {
|
|
67
|
+
identityKey = keyPart.toLowerCase()
|
|
68
|
+
} else {
|
|
69
|
+
errors.identityKey = 'PeerPay link contains an invalid identity key'
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let sats: number | undefined
|
|
73
|
+
let messageBoxUrl: string | undefined
|
|
74
|
+
if (queryPart) {
|
|
75
|
+
const params = new URLSearchParams(queryPart)
|
|
76
|
+
if (params.has('sats')) {
|
|
77
|
+
const satsStr = params.get('sats') ?? ''
|
|
78
|
+
if (/^(0|[1-9][0-9]*)$/.test(satsStr)) {
|
|
79
|
+
const parsed = Number(satsStr)
|
|
80
|
+
if (Number.isSafeInteger(parsed)) {
|
|
81
|
+
if (parsed > 0) sats = parsed
|
|
82
|
+
} else {
|
|
83
|
+
errors.sats = 'PeerPay link contains an invalid sats amount'
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
errors.sats = 'PeerPay link contains an invalid sats amount'
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const url = (params.get('url') ?? '').trim().replace(/\/+$/, '')
|
|
90
|
+
if (url && MESSAGE_BOX_URL_REGEX.test(url)) messageBoxUrl = url
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return { isPeerPay: true, identityKey, sats, ...(messageBoxUrl ? { messageBoxUrl } : {}), errors }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The human-readable problem with a peerpay link, or null when there is none. */
|
|
97
|
+
export function peerPayValidationMessage(result: PeerPayValidationResult | null): string | null {
|
|
98
|
+
if (!result || !result.isPeerPay) return null
|
|
99
|
+
const messages = [result.errors.identityKey, result.errors.sats].filter(Boolean)
|
|
100
|
+
return messages.length ? messages.join('. ') : null
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A 33-byte compressed secp256k1 key in hex, either case, on the curve. Round-trips through
|
|
105
|
+
* PublicKey because the SDK reduces an out-of-range x mod p instead of throwing — parse success
|
|
106
|
+
* alone would accept a key nobody holds.
|
|
107
|
+
*/
|
|
108
|
+
export function isCompressedPublicKey(text: string): boolean {
|
|
109
|
+
if (!COMPRESSED_PUBLIC_KEY_REGEX.test(text)) return false
|
|
110
|
+
try {
|
|
111
|
+
return PublicKey.fromString(text).toString().toLowerCase() === text.toLowerCase()
|
|
112
|
+
} catch {
|
|
113
|
+
return false
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function isValidIdentityKey(identityKey: string) {
|
|
118
|
+
return COMPRESSED_PUBLIC_KEY_REGEX.test(identityKey) && isCompressedPublicKey(identityKey)
|
|
119
|
+
}
|