@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,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Nearby/offline rejected-receive NACK.
|
|
3
|
+
*
|
|
4
|
+
* Auto-send `{ type: 'resend_request', reason: 'bounced_offline' }` once per
|
|
5
|
+
* txid. Request-again uses `force` so the user can still re-send after that.
|
|
6
|
+
* `offline_nacks` is a KV map of txid → `{ nackSentAt }` so two mounted
|
|
7
|
+
* screens (home + /pay) cannot spam the sender.
|
|
8
|
+
*/
|
|
9
|
+
import { sendControlMessage } from './control'
|
|
10
|
+
|
|
11
|
+
export const OFFLINE_NACKS_KEY = 'offline_nacks'
|
|
12
|
+
|
|
13
|
+
export type OfflineNackMap = Record<string, { nackSentAt: number }>
|
|
14
|
+
|
|
15
|
+
interface StorageLike {
|
|
16
|
+
getKeyValue: (key: string) => Promise<string | undefined>
|
|
17
|
+
setKeyValue: (key: string, value: string) => Promise<void>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type SendClient = { sendMessage(args: { recipient: string; messageBox: string; body: string }): Promise<unknown> }
|
|
21
|
+
|
|
22
|
+
/** In-process lock so Home and Pay cannot both auto-send the same txid. */
|
|
23
|
+
const sending = new Set<string>()
|
|
24
|
+
|
|
25
|
+
export async function readOfflineNacks(storage: StorageLike): Promise<OfflineNackMap> {
|
|
26
|
+
try {
|
|
27
|
+
const raw = await storage.getKeyValue(OFFLINE_NACKS_KEY)
|
|
28
|
+
if (!raw) return {}
|
|
29
|
+
const parsed = JSON.parse(raw) as unknown
|
|
30
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
|
|
31
|
+
const out: OfflineNackMap = {}
|
|
32
|
+
for (const [txid, value] of Object.entries(parsed as Record<string, unknown>)) {
|
|
33
|
+
if (!txid) continue
|
|
34
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
35
|
+
out[txid] = { nackSentAt: value }
|
|
36
|
+
continue
|
|
37
|
+
}
|
|
38
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
39
|
+
const at = (value as { nackSentAt?: unknown }).nackSentAt
|
|
40
|
+
if (typeof at === 'number' && Number.isFinite(at)) out[txid] = { nackSentAt: at }
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return out
|
|
44
|
+
} catch {
|
|
45
|
+
return {}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function sendBouncedOfflineNack(args: {
|
|
50
|
+
client: SendClient
|
|
51
|
+
storage: StorageLike
|
|
52
|
+
txid: string
|
|
53
|
+
recipient: string
|
|
54
|
+
force?: boolean
|
|
55
|
+
}): Promise<boolean> {
|
|
56
|
+
const { client, storage, txid, recipient, force } = args
|
|
57
|
+
if (!txid || !recipient) return false
|
|
58
|
+
if (!force) {
|
|
59
|
+
if (sending.has(txid)) return false
|
|
60
|
+
const existing = await readOfflineNacks(storage)
|
|
61
|
+
if (existing[txid]) return false
|
|
62
|
+
}
|
|
63
|
+
sending.add(txid)
|
|
64
|
+
try {
|
|
65
|
+
await sendControlMessage(client, {
|
|
66
|
+
recipient,
|
|
67
|
+
message: { type: 'resend_request', txid, reason: 'bounced_offline' }
|
|
68
|
+
})
|
|
69
|
+
const map = await readOfflineNacks(storage)
|
|
70
|
+
map[txid] = { nackSentAt: Date.now() }
|
|
71
|
+
await storage.setKeyValue(OFFLINE_NACKS_KEY, JSON.stringify(map))
|
|
72
|
+
return true
|
|
73
|
+
} finally {
|
|
74
|
+
sending.delete(txid)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function nackRejectedReceived(args: {
|
|
79
|
+
client: SendClient
|
|
80
|
+
storage: StorageLike
|
|
81
|
+
rows: { txid: string; senderIdentityKey: string | null }[]
|
|
82
|
+
}): Promise<void> {
|
|
83
|
+
for (const row of args.rows) {
|
|
84
|
+
if (!row.senderIdentityKey) continue
|
|
85
|
+
try {
|
|
86
|
+
await sendBouncedOfflineNack({
|
|
87
|
+
client: args.client,
|
|
88
|
+
storage: args.storage,
|
|
89
|
+
txid: row.txid,
|
|
90
|
+
recipient: row.senderIdentityKey
|
|
91
|
+
})
|
|
92
|
+
} catch {
|
|
93
|
+
// Best-effort auto NACK. Request again is the user's retry.
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PeerPay Outbox — Persistent Outbound Payment Token Queue
|
|
3
|
+
*
|
|
4
|
+
* Outbound PeerPay payments are persisted to the wallet's key_value_store table
|
|
5
|
+
* BEFORE the payment token is delivered to the recipient's MessageBox. This ensures
|
|
6
|
+
* the derivation data (derivationPrefix, derivationSuffix, AtomicBEEF) is never
|
|
7
|
+
* lost if the app crashes or loses connectivity between transaction broadcast and
|
|
8
|
+
* message delivery.
|
|
9
|
+
*
|
|
10
|
+
* Storage format: a JSON array stored under the key "peerpay_outbox".
|
|
11
|
+
* Each entry includes the full PaymentToken plus metadata for tracking delivery state.
|
|
12
|
+
*
|
|
13
|
+
* Unsent entries persist until dismissed; sent entries are retained for
|
|
14
|
+
* SENT_RETENTION_MS then pruned. Retry is manual — the UI lists unsent only.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// ── Types ──────────────────────────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
export interface OutboxEntry {
|
|
20
|
+
/** Unique ID: `${timestamp}_${recipientKey.slice(0, 8)}` */
|
|
21
|
+
id: string
|
|
22
|
+
/** ISO 8601 creation timestamp */
|
|
23
|
+
createdAt: string
|
|
24
|
+
/** Recipient identity key (hex compressed pubkey) */
|
|
25
|
+
recipient: string
|
|
26
|
+
/** Full payment token — stored in its entirety so retry needs no wallet round-trip */
|
|
27
|
+
token: {
|
|
28
|
+
customInstructions: {
|
|
29
|
+
derivationPrefix: string
|
|
30
|
+
derivationSuffix: string
|
|
31
|
+
}
|
|
32
|
+
transaction: number[]
|
|
33
|
+
amount: number
|
|
34
|
+
/** User's note; delivered inside the token and shown by the recipient. */
|
|
35
|
+
note?: string
|
|
36
|
+
/**
|
|
37
|
+
* Which output pays the recipient. Omitted on a fresh send, where the rail
|
|
38
|
+
* pins the payment to output 0; carried on a rebuild, where the index is
|
|
39
|
+
* read back from the action rather than assumed.
|
|
40
|
+
*/
|
|
41
|
+
outputIndex?: number
|
|
42
|
+
}
|
|
43
|
+
/** The MessageBox host URL used at creation time */
|
|
44
|
+
messageBoxUrl: string
|
|
45
|
+
/**
|
|
46
|
+
* The RECIPIENT's message-box host, when a BRC-125 link named one via its
|
|
47
|
+
* `url` extension. Every re-send of this entry goes here, bypassing the
|
|
48
|
+
* overlay lookup. Absent for entries minted from a bare key.
|
|
49
|
+
*/
|
|
50
|
+
recipientHost?: string
|
|
51
|
+
status: 'unsent' | 'sent'
|
|
52
|
+
/** ISO 8601 timestamp of most recent delivery attempt */
|
|
53
|
+
lastAttemptAt?: string
|
|
54
|
+
/** Error message from the most recent failed delivery attempt */
|
|
55
|
+
lastError?: string
|
|
56
|
+
/**
|
|
57
|
+
* Txid of the noSend transaction backing this token. Present on entries
|
|
58
|
+
* minted since the deferred-broadcast flow; its absence marks a legacy entry
|
|
59
|
+
* whose transaction was already broadcast at creation.
|
|
60
|
+
*/
|
|
61
|
+
txid?: string
|
|
62
|
+
/**
|
|
63
|
+
* True once the token reached the recipient's message box. From that point
|
|
64
|
+
* the payment is considered handed over: retry only re-attempts the
|
|
65
|
+
* broadcast, and cancel no longer aborts the transaction.
|
|
66
|
+
*/
|
|
67
|
+
delivered?: boolean
|
|
68
|
+
/**
|
|
69
|
+
* Set immediately before sendMessage. A crash after the box accepted the
|
|
70
|
+
* token can leave delivering without delivered — cancel must not abort;
|
|
71
|
+
* retry re-sends (HMAC message id is idempotent).
|
|
72
|
+
*/
|
|
73
|
+
delivering?: boolean
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
interface StorageLike {
|
|
77
|
+
getKeyValue: (key: string) => Promise<string | undefined>
|
|
78
|
+
setKeyValue: (key: string, value: string) => Promise<void>
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ── Constants ─────────────────────────────────────────────────────────────────
|
|
82
|
+
|
|
83
|
+
const OUTBOX_KEY = 'peerpay_outbox'
|
|
84
|
+
|
|
85
|
+
/** How long sent entries are kept as a sender-side token copy before pruning. */
|
|
86
|
+
export const SENT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000
|
|
87
|
+
|
|
88
|
+
// ── Private helpers ───────────────────────────────────────────────────────────
|
|
89
|
+
|
|
90
|
+
async function readEntries(storage: StorageLike): Promise<OutboxEntry[]> {
|
|
91
|
+
try {
|
|
92
|
+
const raw = await storage.getKeyValue(OUTBOX_KEY)
|
|
93
|
+
if (!raw) return []
|
|
94
|
+
return JSON.parse(raw) as OutboxEntry[]
|
|
95
|
+
} catch {
|
|
96
|
+
return []
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function writeEntries(storage: StorageLike, entries: OutboxEntry[]): Promise<void> {
|
|
101
|
+
await storage.setKeyValue(OUTBOX_KEY, JSON.stringify(entries))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ── Public API ────────────────────────────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Returns all outbox entries (any status).
|
|
108
|
+
*/
|
|
109
|
+
export async function getOutboxEntries(storage: StorageLike): Promise<OutboxEntry[]> {
|
|
110
|
+
return readEntries(storage)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Persist a new outbound payment token to the outbox before delivery is attempted.
|
|
115
|
+
* Returns the generated entry ID.
|
|
116
|
+
*/
|
|
117
|
+
export async function saveOutboxEntry(
|
|
118
|
+
storage: StorageLike,
|
|
119
|
+
params: {
|
|
120
|
+
recipient: string
|
|
121
|
+
token: OutboxEntry['token']
|
|
122
|
+
messageBoxUrl: string
|
|
123
|
+
txid?: string
|
|
124
|
+
recipientHost?: string
|
|
125
|
+
}
|
|
126
|
+
): Promise<string> {
|
|
127
|
+
const { recipient, token, messageBoxUrl, txid, recipientHost } = params
|
|
128
|
+
const id = `${Date.now()}_${recipient.slice(0, 8)}`
|
|
129
|
+
const entry: OutboxEntry = {
|
|
130
|
+
id,
|
|
131
|
+
createdAt: new Date().toISOString(),
|
|
132
|
+
recipient,
|
|
133
|
+
token,
|
|
134
|
+
messageBoxUrl,
|
|
135
|
+
status: 'unsent',
|
|
136
|
+
...(txid ? { txid } : {}),
|
|
137
|
+
...(recipientHost ? { recipientHost } : {})
|
|
138
|
+
}
|
|
139
|
+
const all = await readEntries(storage)
|
|
140
|
+
all.push(entry)
|
|
141
|
+
await writeEntries(storage, all)
|
|
142
|
+
return id
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Mark an entry as successfully delivered.
|
|
147
|
+
* Called immediately after `sendMessage()` returns without error.
|
|
148
|
+
*/
|
|
149
|
+
export async function markOutboxSent(storage: StorageLike, id: string): Promise<void> {
|
|
150
|
+
const all = await readEntries(storage)
|
|
151
|
+
const entry = all.find(e => e.id === id)
|
|
152
|
+
if (entry) {
|
|
153
|
+
entry.status = 'sent'
|
|
154
|
+
await writeEntries(storage, all)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Merge a partial update into an entry.
|
|
160
|
+
* Used to record `lastAttemptAt` and `lastError` on failed retry attempts.
|
|
161
|
+
*/
|
|
162
|
+
export async function updateOutboxEntry(storage: StorageLike, id: string, patch: Partial<OutboxEntry>): Promise<void> {
|
|
163
|
+
const all = await readEntries(storage)
|
|
164
|
+
const idx = all.findIndex(e => e.id === id)
|
|
165
|
+
if (idx !== -1) {
|
|
166
|
+
all[idx] = { ...all[idx], ...patch }
|
|
167
|
+
await writeEntries(storage, all)
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Remove an entry from the outbox permanently.
|
|
173
|
+
* Called when the user explicitly dismisses an entry.
|
|
174
|
+
*/
|
|
175
|
+
export async function removeOutboxEntry(storage: StorageLike, id: string): Promise<void> {
|
|
176
|
+
const all = await readEntries(storage)
|
|
177
|
+
await writeEntries(
|
|
178
|
+
storage,
|
|
179
|
+
all.filter(e => e.id !== id)
|
|
180
|
+
)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* True when a sent entry is past SENT_RETENTION_MS.
|
|
185
|
+
* Missing createdAt on a sent entry expires immediately (legacy).
|
|
186
|
+
*/
|
|
187
|
+
export function isSentExpired(entry: OutboxEntry, now: number = Date.now()): boolean {
|
|
188
|
+
if (entry.status !== 'sent') return false
|
|
189
|
+
if (!entry.createdAt) return true
|
|
190
|
+
const created = Date.parse(entry.createdAt)
|
|
191
|
+
if (Number.isNaN(created)) return true
|
|
192
|
+
return now - created > SENT_RETENTION_MS
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Remove only expired sent rows. Returns how many were removed.
|
|
197
|
+
*/
|
|
198
|
+
export async function pruneExpiredSent(storage: StorageLike, now: number = Date.now()): Promise<number> {
|
|
199
|
+
const all = await readEntries(storage)
|
|
200
|
+
const kept = all.filter(e => !isSentExpired(e, now))
|
|
201
|
+
const removed = all.length - kept.length
|
|
202
|
+
if (removed > 0) await writeEntries(storage, kept)
|
|
203
|
+
return removed
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Entries that still need Retry/Cancel — everything not yet marked sent. */
|
|
207
|
+
export function unsentEntries(entries: OutboxEntry[]): OutboxEntry[] {
|
|
208
|
+
return entries.filter(e => e.status !== 'sent')
|
|
209
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { OutboxEntry } from './outbox'
|
|
2
|
+
|
|
3
|
+
export function instructionsFromOutput(customInstructions: unknown): {
|
|
4
|
+
derivationPrefix: string
|
|
5
|
+
derivationSuffix: string
|
|
6
|
+
} | undefined {
|
|
7
|
+
let parsed: unknown = customInstructions
|
|
8
|
+
if (typeof customInstructions === 'string') {
|
|
9
|
+
try {
|
|
10
|
+
parsed = JSON.parse(customInstructions)
|
|
11
|
+
} catch {
|
|
12
|
+
return undefined
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
if (!parsed || typeof parsed !== 'object') return undefined
|
|
16
|
+
const { derivationPrefix, derivationSuffix } = parsed as Record<string, unknown>
|
|
17
|
+
if (typeof derivationPrefix !== 'string' || typeof derivationSuffix !== 'string') return undefined
|
|
18
|
+
return { derivationPrefix, derivationSuffix }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type RebuildOutput = {
|
|
22
|
+
customInstructions?: string | object
|
|
23
|
+
satoshis?: number
|
|
24
|
+
outputIndex?: number
|
|
25
|
+
basket?: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The output that paid the recipient, not the one that paid us back.
|
|
30
|
+
*
|
|
31
|
+
* Change carries derivation data too, so "first output with customInstructions"
|
|
32
|
+
* could rebuild a token describing the sender's own change — wrong amount, and
|
|
33
|
+
* keys the recipient cannot derive. Change lands in one of this wallet's
|
|
34
|
+
* baskets; an output paying someone else belongs to no basket of ours, so that
|
|
35
|
+
* is the one to take. If nothing is marked either way, fall back to the first
|
|
36
|
+
* output that carries derivation data — the previous behaviour.
|
|
37
|
+
*/
|
|
38
|
+
function paymentOutput(outputs: RebuildOutput[]):
|
|
39
|
+
| { instructions: { derivationPrefix: string; derivationSuffix: string }; out: RebuildOutput }
|
|
40
|
+
| undefined {
|
|
41
|
+
const parsed = outputs
|
|
42
|
+
.map(out => ({ out, instructions: instructionsFromOutput(out.customInstructions) }))
|
|
43
|
+
.filter((x): x is { out: RebuildOutput; instructions: { derivationPrefix: string; derivationSuffix: string } } =>
|
|
44
|
+
x.instructions !== undefined
|
|
45
|
+
)
|
|
46
|
+
if (parsed.length === 0) return undefined
|
|
47
|
+
return parsed.find(x => !x.out.basket) ?? parsed[0]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function rebuildPeerPayToken(args: {
|
|
51
|
+
action: { txid?: string; outputs?: RebuildOutput[] }
|
|
52
|
+
recipient: string
|
|
53
|
+
refetch: (txid: string) => Promise<number[] | undefined>
|
|
54
|
+
}): Promise<{ token: OutboxEntry['token']; recipient: string } | undefined> {
|
|
55
|
+
const { action, recipient, refetch } = args
|
|
56
|
+
if (!action.txid) return undefined
|
|
57
|
+
|
|
58
|
+
const chosen = paymentOutput(action.outputs ?? [])
|
|
59
|
+
if (!chosen) return undefined
|
|
60
|
+
|
|
61
|
+
const beef = await refetch(action.txid)
|
|
62
|
+
if (!beef) return undefined
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
token: {
|
|
66
|
+
customInstructions: chosen.instructions,
|
|
67
|
+
transaction: beef,
|
|
68
|
+
amount: typeof chosen.out.satoshis === 'number' ? chosen.out.satoshis : 0,
|
|
69
|
+
// The recipient internalizes `outputIndex ?? 0`. Both rails pin the
|
|
70
|
+
// payment to output 0 today, but the index is known here and guessing it
|
|
71
|
+
// would credit the wrong output the moment that stops being true.
|
|
72
|
+
...(typeof chosen.out.outputIndex === 'number' ? { outputIndex: chosen.out.outputIndex } : {})
|
|
73
|
+
},
|
|
74
|
+
recipient
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The transaction bytes a resend ships.
|
|
3
|
+
*
|
|
4
|
+
* Three sources, in this order:
|
|
5
|
+
*
|
|
6
|
+
* NETWORK first, by txid. A mined transaction comes back with whatever proof
|
|
7
|
+
* is current, which is what repairs a merkle path staled by a reorg — the
|
|
8
|
+
* reason `refetchAtomicBeef` exists.
|
|
9
|
+
*
|
|
10
|
+
* STORAGE second, assembled with ancestry (`getBeefForTransaction`), then the
|
|
11
|
+
* plain known-txid lookup, then the transaction's OWN stored bytes. A nearby payment whose code was never scanned was
|
|
12
|
+
* never broadcast: it is `nosend`, no service has heard of it, and the only
|
|
13
|
+
* copy is this device's. That is exactly the payment a resend is for, so a
|
|
14
|
+
* local source is not a nicety — without it the feature misses its main case.
|
|
15
|
+
* The payee internalizes and broadcasts, which is the nearby rail's normal
|
|
16
|
+
* settlement path anyway.
|
|
17
|
+
*
|
|
18
|
+
* The third source exists because the first two can BOTH fail on a payment
|
|
19
|
+
* this device holds in full. Each walks the input chain by asking storage for
|
|
20
|
+
* every ancestor txid in turn (`getValidBeefForKnownTxid`, which throws on the
|
|
21
|
+
* first one it does not hold) — so one ancestor that only ever existed inside
|
|
22
|
+
* a stored `inputBEEF`, never as its own row, fails the whole assembly. But
|
|
23
|
+
* `transactions.inputBEEF` is precisely the ancestry `createAction` captured
|
|
24
|
+
* and validated when it built this payment: rawTx plus that column is a
|
|
25
|
+
* complete, self-contained answer, with no walk and no service call.
|
|
26
|
+
*
|
|
27
|
+
* What the bar is, and is not: the bytes must parse, name this txid, and carry
|
|
28
|
+
* their ancestry (`toAtomicBEEF` throws when an input has no source
|
|
29
|
+
* transaction) — enough that the payee's wallet is not handed something it will
|
|
30
|
+
* refuse. It deliberately does NOT require a verified merkle proof. A
|
|
31
|
+
* never-broadcast transaction has none by construction, so demanding one
|
|
32
|
+
* rejected precisely the payment this path exists to rescue, and reported it as
|
|
33
|
+
* "couldn't get this payment's data" to someone who was online the whole time.
|
|
34
|
+
* The receiving wallet validates independently, as it does for any payment.
|
|
35
|
+
*/
|
|
36
|
+
import { Beef } from '@bsv/sdk'
|
|
37
|
+
|
|
38
|
+
type BeefLike = { toBinary(): number[] }
|
|
39
|
+
|
|
40
|
+
export type LocalBeefStorage = {
|
|
41
|
+
getValidBeefForKnownTxid?(txid: string): Promise<BeefLike>
|
|
42
|
+
getBeefForTransaction?(txid: string, options: Record<string, unknown>): Promise<BeefLike>
|
|
43
|
+
findTransactions?(args: {
|
|
44
|
+
partial: { txid: string }
|
|
45
|
+
}): Promise<{ rawTx?: number[] | Uint8Array | null; inputBEEF?: number[] | Uint8Array | null }[]>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** AtomicBEEF for `txid` from a local Beef, or undefined if it cannot be made. */
|
|
49
|
+
export function atomicFromLocalBeef(beef: BeefLike, txid: string): number[] | undefined {
|
|
50
|
+
try {
|
|
51
|
+
const parsed = Beef.fromBinary(beef.toBinary())
|
|
52
|
+
const tx = parsed.findAtomicTransaction(txid)
|
|
53
|
+
if (!tx) return undefined
|
|
54
|
+
// Throws rather than emitting a partial beef when an input has no source
|
|
55
|
+
// transaction — the ancestry gap we must not hand onward.
|
|
56
|
+
const atomic = tx.toAtomicBEEF()
|
|
57
|
+
if (Beef.fromBinary(atomic).atomicTxid !== txid) return undefined
|
|
58
|
+
return atomic
|
|
59
|
+
} catch {
|
|
60
|
+
return undefined
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The transaction's own row: its rawTx merged onto the ancestry createAction
|
|
65
|
+
* stored with it. No ancestor walk, so nothing to fail to find. */
|
|
66
|
+
async function fromStoredTx(storage: LocalBeefStorage, txid: string): Promise<number[] | undefined> {
|
|
67
|
+
try {
|
|
68
|
+
const rows = (await storage.findTransactions?.({ partial: { txid } })) ?? []
|
|
69
|
+
const row = rows[0]
|
|
70
|
+
if (!row?.rawTx) return undefined
|
|
71
|
+
const beef = row.inputBEEF ? Beef.fromBinary(Array.from(row.inputBEEF)) : new Beef()
|
|
72
|
+
beef.mergeRawTx(Array.from(row.rawTx))
|
|
73
|
+
return atomicFromLocalBeef(beef, txid)
|
|
74
|
+
} catch {
|
|
75
|
+
return undefined
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function fromStorage(storage: LocalBeefStorage, txid: string): Promise<number[] | undefined> {
|
|
80
|
+
// Ancestry-assembling lookup first: it merges input beefs (and reaches for
|
|
81
|
+
// services when storage is short a link), which is what makes toAtomicBEEF
|
|
82
|
+
// able to emit a self-contained proof for an unbroadcast transaction.
|
|
83
|
+
for (const read of [
|
|
84
|
+
async () => await storage.getBeefForTransaction?.(txid, {}),
|
|
85
|
+
async () => await storage.getValidBeefForKnownTxid?.(txid)
|
|
86
|
+
]) {
|
|
87
|
+
try {
|
|
88
|
+
const beef = await read()
|
|
89
|
+
if (!beef) continue
|
|
90
|
+
const atomic = atomicFromLocalBeef(beef, txid)
|
|
91
|
+
if (atomic) return atomic
|
|
92
|
+
} catch (e) {
|
|
93
|
+
// Either lookup throws for a txid it does not hold. Try the next — but
|
|
94
|
+
// say which one gave up, because "couldn't get this payment's data" on a
|
|
95
|
+
// payment this device built is otherwise unattributable from a log.
|
|
96
|
+
console.warn('[resend] local beef lookup failed:', e instanceof Error ? e.message : e)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return await fromStoredTx(storage, txid)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function makeResendBeef(args: {
|
|
103
|
+
/** Network lookup by txid — `makeBeefRepair` in production. */
|
|
104
|
+
refetch: (txid: string) => Promise<number[] | undefined>
|
|
105
|
+
storage?: LocalBeefStorage | null
|
|
106
|
+
}): (txid: string) => Promise<number[] | undefined> {
|
|
107
|
+
return async (txid: string) => {
|
|
108
|
+
const fetched = await args.refetch(txid).catch(() => undefined)
|
|
109
|
+
if (fetched) return fetched
|
|
110
|
+
if (!args.storage) return undefined
|
|
111
|
+
const local = await fromStorage(args.storage, txid)
|
|
112
|
+
if (!local) console.warn(`[resend] no usable transaction bytes for ${txid}, from the network or this device`)
|
|
113
|
+
return local
|
|
114
|
+
}
|
|
115
|
+
}
|