@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,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PeerPay payment-control channel.
|
|
3
|
+
*
|
|
4
|
+
* A dedicated MessageBox (`payment_control`), not the payment inbox. Receivers
|
|
5
|
+
* post `resend_request` before acknowledging an uncreditable token so the
|
|
6
|
+
* sender still has the derivation data. Inbound handling of these messages is
|
|
7
|
+
* the sender's job (P1).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const PAYMENT_CONTROL_BOX = 'payment_control'
|
|
11
|
+
|
|
12
|
+
export type ResendReason = 'corrupt' | 'uncreditible' | 'double_spent' | 'bounced_offline'
|
|
13
|
+
|
|
14
|
+
export type PaymentControlMessage =
|
|
15
|
+
| { type: 'resend_request'; txid: string; reason: ResendReason; messageId?: string }
|
|
16
|
+
| { type: 'payment_cancelled'; txid: string }
|
|
17
|
+
|
|
18
|
+
const RESEND_REASONS: ReadonlySet<string> = new Set([
|
|
19
|
+
'corrupt',
|
|
20
|
+
'uncreditible',
|
|
21
|
+
'double_spent',
|
|
22
|
+
'bounced_offline'
|
|
23
|
+
])
|
|
24
|
+
|
|
25
|
+
function asObject(body: unknown): Record<string, unknown> | undefined {
|
|
26
|
+
let value: unknown = body
|
|
27
|
+
if (typeof value === 'string') {
|
|
28
|
+
try {
|
|
29
|
+
value = JSON.parse(value)
|
|
30
|
+
} catch {
|
|
31
|
+
return undefined
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
|
|
35
|
+
return value as Record<string, unknown>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Unknown types, missing txid, or invalid reason → undefined (forward-compatible). */
|
|
39
|
+
export function parseControlMessage(body: unknown): PaymentControlMessage | undefined {
|
|
40
|
+
const obj = asObject(body)
|
|
41
|
+
if (!obj) return undefined
|
|
42
|
+
const { type, txid } = obj
|
|
43
|
+
if (typeof type !== 'string' || typeof txid !== 'string' || txid.length === 0) return undefined
|
|
44
|
+
if (type === 'payment_cancelled') return { type, txid }
|
|
45
|
+
if (type !== 'resend_request') return undefined
|
|
46
|
+
if (typeof obj.reason !== 'string' || !RESEND_REASONS.has(obj.reason)) return undefined
|
|
47
|
+
return {
|
|
48
|
+
type: 'resend_request',
|
|
49
|
+
txid,
|
|
50
|
+
reason: obj.reason as ResendReason,
|
|
51
|
+
...(typeof obj.messageId === 'string' && obj.messageId.length > 0 ? { messageId: obj.messageId } : {})
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* `overrideHost` skips the overlay lookup and posts to a named box — for a control
|
|
57
|
+
* message about a payment that was itself delivered to a link-named host.
|
|
58
|
+
*/
|
|
59
|
+
export async function sendControlMessage(
|
|
60
|
+
client: {
|
|
61
|
+
sendMessage(args: { recipient: string; messageBox: string; body: string }, overrideHost?: string): Promise<unknown>
|
|
62
|
+
},
|
|
63
|
+
args: { recipient: string; message: PaymentControlMessage },
|
|
64
|
+
overrideHost?: string
|
|
65
|
+
): Promise<void> {
|
|
66
|
+
await client.sendMessage(
|
|
67
|
+
{
|
|
68
|
+
recipient: args.recipient,
|
|
69
|
+
messageBox: PAYMENT_CONTROL_BOX,
|
|
70
|
+
body: JSON.stringify(args.message)
|
|
71
|
+
},
|
|
72
|
+
overrideHost
|
|
73
|
+
)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type ControlBoxMessage = { messageId: string; sender: string; body: unknown }
|
|
77
|
+
|
|
78
|
+
/** Raw `payment_control` messages. `acceptPayments: false` avoids fee auto-internalize. */
|
|
79
|
+
export async function listControlMessages(
|
|
80
|
+
client: {
|
|
81
|
+
listMessages(args: {
|
|
82
|
+
messageBox: string
|
|
83
|
+
host?: string
|
|
84
|
+
acceptPayments?: boolean
|
|
85
|
+
}): Promise<ControlBoxMessage[]>
|
|
86
|
+
}
|
|
87
|
+
): Promise<ControlBoxMessage[]> {
|
|
88
|
+
const listed = await client.listMessages({
|
|
89
|
+
messageBox: PAYMENT_CONTROL_BOX,
|
|
90
|
+
acceptPayments: false
|
|
91
|
+
})
|
|
92
|
+
return Array.isArray(listed) ? listed : []
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function ackControlMessages(
|
|
96
|
+
client: { acknowledgeMessage(args: { messageIds: string[] }): Promise<unknown> },
|
|
97
|
+
messageIds: string[]
|
|
98
|
+
): Promise<void> {
|
|
99
|
+
if (messageIds.length === 0) return
|
|
100
|
+
await client.acknowledgeMessage({ messageIds })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Whether a failed delivery means the message box already holds this message.
|
|
105
|
+
*
|
|
106
|
+
* The box keys a message by an HMAC of its body against the recipient, so
|
|
107
|
+
* re-delivering an unchanged payment token collides with the copy already
|
|
108
|
+
* sitting in the recipient's box and the server refuses the write with a 400.
|
|
109
|
+
*
|
|
110
|
+
* That refusal is the outcome the caller wanted: the recipient HAS the message.
|
|
111
|
+
* Reporting it as a failure sent the user back to a Resend button that could
|
|
112
|
+
* never succeed — and the alternative, perturbing the body so it earns a fresh
|
|
113
|
+
* id, would plant a second copy of a payment the recipient already holds.
|
|
114
|
+
*
|
|
115
|
+
* Matched on the server's own words rather than the bare status, so a 400 for
|
|
116
|
+
* any other reason still surfaces as the failure it is.
|
|
117
|
+
*/
|
|
118
|
+
export function isDuplicateMessageError(e: unknown): boolean {
|
|
119
|
+
const text = e instanceof Error ? e.message : typeof e === 'string' ? e : ''
|
|
120
|
+
if (!/\b400\b/.test(text)) return false
|
|
121
|
+
return /duplicate|already[ _-]?(exists|sent|delivered|present|received)|ERR_DUPLICATE/i.test(text)
|
|
122
|
+
}
|
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
import { Beef } from '@bsv/sdk'
|
|
2
|
+
import {
|
|
3
|
+
ackControlMessages,
|
|
4
|
+
isDuplicateMessageError,
|
|
5
|
+
listControlMessages,
|
|
6
|
+
parseControlMessage
|
|
7
|
+
} from './control'
|
|
8
|
+
import { getOutboxEntries, type OutboxEntry } from './outbox'
|
|
9
|
+
import { instructionsFromOutput, rebuildPeerPayToken } from './rebuildToken'
|
|
10
|
+
|
|
11
|
+
/** The message box outbound payments are delivered into. Same name as handle.ts. */
|
|
12
|
+
const PAYMENT_INBOX = 'payment_inbox'
|
|
13
|
+
|
|
14
|
+
/** Stored unanswered `resend_request`s so Home can show a banner without re-listing. */
|
|
15
|
+
export const UNANSWERED_RESENDS_KEY = 'peerpay_unanswered_resends'
|
|
16
|
+
|
|
17
|
+
const PUBKEY_LABEL = /^(02|03)[0-9a-fA-F]{64}$/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Rail labels an outbound payment can carry. Both are resendable: each writes
|
|
21
|
+
* the payee's identity key as a label and BRC-29 derivation data as the
|
|
22
|
+
* output's customInstructions. Not exported — `localpay/pending` already
|
|
23
|
+
* exports a (differently-valued) PEERPAY_LABEL through the same barrel.
|
|
24
|
+
*/
|
|
25
|
+
const RESENDABLE_LABELS = ['peerpay', 'localpay']
|
|
26
|
+
|
|
27
|
+
interface StorageLike {
|
|
28
|
+
getKeyValue: (key: string) => Promise<string | undefined>
|
|
29
|
+
setKeyValue: (key: string, value: string) => Promise<void>
|
|
30
|
+
/** Optional, and only used to recover derivation data listActions did not
|
|
31
|
+
* hand back — see `outputsFromStorage`. */
|
|
32
|
+
findTransactions?: (args: {
|
|
33
|
+
partial: { txid: string }
|
|
34
|
+
noRawTx?: boolean
|
|
35
|
+
}) => Promise<{ transactionId?: number }[]>
|
|
36
|
+
findOutputs?: (args: {
|
|
37
|
+
partial: { transactionId: number }
|
|
38
|
+
noScript?: boolean
|
|
39
|
+
}) => Promise<{ vout?: number; satoshis?: number | null; customInstructions?: string | null; basketId?: number | null }[]>
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The action's outputs read straight from this device's own tables.
|
|
44
|
+
*
|
|
45
|
+
* `listActions` is the normal source, but it is a long way from the data: the
|
|
46
|
+
* permissions manager sits in front of it, the query is a capped window over
|
|
47
|
+
* two labels, and `includeOutputs` is the caller's to remember. When it comes
|
|
48
|
+
* back without derivation data the payment looks unrebuildable even though
|
|
49
|
+
* every byte needed is in `outputs.customInstructions` locally. This is the
|
|
50
|
+
* short way to the same facts.
|
|
51
|
+
*
|
|
52
|
+
* `basketId` stands in for the basket name: what `paymentOutput` needs to know
|
|
53
|
+
* is only whether an output landed in a basket of ours (change) or in none
|
|
54
|
+
* (the payee's).
|
|
55
|
+
*/
|
|
56
|
+
async function outputsFromStorage(storage: StorageLike, txid: string): Promise<PeerPayActionLike['outputs']> {
|
|
57
|
+
try {
|
|
58
|
+
const tx = (await storage.findTransactions?.({ partial: { txid }, noRawTx: true }))?.[0]
|
|
59
|
+
if (typeof tx?.transactionId !== 'number') return undefined
|
|
60
|
+
const rows = await storage.findOutputs?.({ partial: { transactionId: tx.transactionId }, noScript: true })
|
|
61
|
+
if (!rows?.length) return undefined
|
|
62
|
+
return rows.map(o => ({
|
|
63
|
+
customInstructions: o.customInstructions ?? undefined,
|
|
64
|
+
satoshis: typeof o.satoshis === 'number' ? o.satoshis : 0,
|
|
65
|
+
outputIndex: o.vout,
|
|
66
|
+
basket: o.basketId ? 'own' : undefined
|
|
67
|
+
}))
|
|
68
|
+
} catch {
|
|
69
|
+
return undefined
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function hasDerivationData(outputs: PeerPayActionLike['outputs']): boolean {
|
|
74
|
+
return !!outputs?.some(o => instructionsFromOutput(o.customInstructions))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* `customInstructions` as stored is not necessarily what was written.
|
|
79
|
+
*
|
|
80
|
+
* WalletPermissionsManager encrypts wallet metadata on the way into storage
|
|
81
|
+
* (`maybeEncryptMetadata`) and decrypts it again on the way out of listActions.
|
|
82
|
+
* Read the column directly and what comes back is base64 ciphertext, which
|
|
83
|
+
* parses as no JSON at all — so a rebuild that reached past listActions to the
|
|
84
|
+
* table would conclude the payment carries no derivation data.
|
|
85
|
+
*
|
|
86
|
+
* Anything that already parses is left untouched: metadata written before
|
|
87
|
+
* encryption was turned on is plaintext, and so is every value on a wallet
|
|
88
|
+
* that never had it on.
|
|
89
|
+
*/
|
|
90
|
+
async function decodeInstructions(
|
|
91
|
+
value: string | object | undefined,
|
|
92
|
+
decrypt?: (value: string) => Promise<string>
|
|
93
|
+
): Promise<string | object | undefined> {
|
|
94
|
+
if (instructionsFromOutput(value)) return value
|
|
95
|
+
if (typeof value !== 'string' || !decrypt) return value
|
|
96
|
+
try {
|
|
97
|
+
const plain = await decrypt(value)
|
|
98
|
+
return instructionsFromOutput(plain) ? plain : value
|
|
99
|
+
} catch {
|
|
100
|
+
return value
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function decodeOutputs(
|
|
105
|
+
outputs: PeerPayActionLike['outputs'],
|
|
106
|
+
decrypt?: (value: string) => Promise<string>
|
|
107
|
+
): Promise<PeerPayActionLike['outputs']> {
|
|
108
|
+
if (!outputs || !decrypt) return outputs
|
|
109
|
+
return await Promise.all(
|
|
110
|
+
outputs.map(async o => ({ ...o, customInstructions: await decodeInstructions(o.customInstructions, decrypt) }))
|
|
111
|
+
)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export type PeerPayActionLike = {
|
|
115
|
+
txid?: string
|
|
116
|
+
labels?: string[]
|
|
117
|
+
// `outputIndex` and `basket` are what let the rebuild tell the payment apart
|
|
118
|
+
// from this wallet's own change, which carries derivation data of its own.
|
|
119
|
+
outputs?: {
|
|
120
|
+
customInstructions?: string | object
|
|
121
|
+
satoshis?: number
|
|
122
|
+
outputIndex?: number
|
|
123
|
+
basket?: string
|
|
124
|
+
}[]
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export type PendingResend = { txid: string; sender: string }
|
|
128
|
+
|
|
129
|
+
type ListAckClient = {
|
|
130
|
+
listMessages(args: { messageBox: string; host?: string; acceptPayments?: boolean }): Promise<
|
|
131
|
+
{ messageId: string; sender: string; body: unknown }[]
|
|
132
|
+
>
|
|
133
|
+
acknowledgeMessage(args: { messageIds: string[] }): Promise<unknown>
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
type ResendClient = ListAckClient & {
|
|
137
|
+
sendMessage(args: { recipient: string; messageBox: string; body: string }): Promise<unknown>
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function txidFromInboxBody(body: unknown): string | undefined {
|
|
141
|
+
let value: unknown = body
|
|
142
|
+
if (typeof value === 'string') {
|
|
143
|
+
try {
|
|
144
|
+
value = JSON.parse(value)
|
|
145
|
+
} catch {
|
|
146
|
+
return undefined
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (!value || typeof value !== 'object') return undefined
|
|
150
|
+
const obj = value as { transaction?: unknown; token?: { transaction?: unknown } }
|
|
151
|
+
const tx = Array.isArray(obj.transaction)
|
|
152
|
+
? obj.transaction
|
|
153
|
+
: Array.isArray(obj.token?.transaction)
|
|
154
|
+
? obj.token.transaction
|
|
155
|
+
: undefined
|
|
156
|
+
if (!tx) return undefined
|
|
157
|
+
try {
|
|
158
|
+
const txid = Beef.fromBinary(Array.from(tx as number[])).atomicTxid
|
|
159
|
+
return typeof txid === 'string' && txid.length > 0 ? txid : undefined
|
|
160
|
+
} catch {
|
|
161
|
+
return undefined
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Drop a still-uncredited token for `txid` from `sender`. Already-internalized
|
|
167
|
+
* txs are left alone — a cancel after broadcast cannot un-mine.
|
|
168
|
+
* Empty `sender` matches nothing (fail closed).
|
|
169
|
+
*/
|
|
170
|
+
async function dropInboxTokenForTxid(
|
|
171
|
+
client: ListAckClient,
|
|
172
|
+
txid: string,
|
|
173
|
+
sender: string
|
|
174
|
+
): Promise<'dropped' | 'gone' | 'refused'> {
|
|
175
|
+
const listed = await client.listMessages({
|
|
176
|
+
messageBox: PAYMENT_INBOX,
|
|
177
|
+
acceptPayments: false
|
|
178
|
+
})
|
|
179
|
+
const rows = Array.isArray(listed) ? listed : []
|
|
180
|
+
const ids = rows
|
|
181
|
+
.filter(m => m.sender === sender && sender !== '' && txidFromInboxBody(m.body) === txid)
|
|
182
|
+
.map(m => String(m.messageId))
|
|
183
|
+
if (ids.length > 0) {
|
|
184
|
+
await client.acknowledgeMessage({ messageIds: ids })
|
|
185
|
+
return 'dropped'
|
|
186
|
+
}
|
|
187
|
+
if (rows.some(m => txidFromInboxBody(m.body) === txid)) return 'refused'
|
|
188
|
+
return 'gone'
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Drop authenticated inbox tokens, then ack the control message. */
|
|
192
|
+
async function consumePaymentCancelled(
|
|
193
|
+
client: ListAckClient,
|
|
194
|
+
msg: { messageId: string; sender?: unknown },
|
|
195
|
+
txid: string
|
|
196
|
+
): Promise<void> {
|
|
197
|
+
const sender = typeof msg.sender === 'string' ? msg.sender : ''
|
|
198
|
+
try {
|
|
199
|
+
const result = await dropInboxTokenForTxid(client, txid, sender)
|
|
200
|
+
if (result === 'refused') return
|
|
201
|
+
} catch {
|
|
202
|
+
// Leave the control message so a later poll retries the inbox drop.
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
await ackControlMessages(client, [msg.messageId])
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function recipientFromLabels(labels: string[] | undefined): string | undefined {
|
|
209
|
+
return labels?.find(l => PUBKEY_LABEL.test(l))
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function outboxTxid(entry: OutboxEntry): string | undefined {
|
|
213
|
+
if (typeof entry.txid === 'string' && entry.txid.length > 0) return entry.txid
|
|
214
|
+
try {
|
|
215
|
+
const txid = Beef.fromBinary(Array.from(entry.token.transaction)).atomicTxid
|
|
216
|
+
return typeof txid === 'string' && txid.length > 0 ? txid : undefined
|
|
217
|
+
} catch {
|
|
218
|
+
return undefined
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function actionFromOutbox(entry: OutboxEntry, txid: string): PeerPayActionLike {
|
|
223
|
+
return {
|
|
224
|
+
txid,
|
|
225
|
+
labels: ['peerpay'],
|
|
226
|
+
// The entry already names the payment output, so there is no change to tell
|
|
227
|
+
// it apart from — an unbasketed single output is exactly that statement.
|
|
228
|
+
outputs: [
|
|
229
|
+
{
|
|
230
|
+
customInstructions: entry.token.customInstructions,
|
|
231
|
+
satoshis: entry.token.amount,
|
|
232
|
+
...(typeof entry.token.outputIndex === 'number' ? { outputIndex: entry.token.outputIndex } : {})
|
|
233
|
+
}
|
|
234
|
+
]
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function makeListPeerPayAction(
|
|
239
|
+
wallet:
|
|
240
|
+
| {
|
|
241
|
+
listActions(
|
|
242
|
+
args: unknown,
|
|
243
|
+
originator?: string
|
|
244
|
+
): Promise<{ actions: PeerPayActionLike[] }>
|
|
245
|
+
}
|
|
246
|
+
| null
|
|
247
|
+
| undefined,
|
|
248
|
+
adminOriginator: string
|
|
249
|
+
): (txid: string) => Promise<PeerPayActionLike | undefined> {
|
|
250
|
+
let cache: Promise<PeerPayActionLike[] | undefined> | undefined
|
|
251
|
+
return async txid => {
|
|
252
|
+
if (!wallet) return undefined
|
|
253
|
+
if (!cache) {
|
|
254
|
+
cache = wallet
|
|
255
|
+
.listActions(
|
|
256
|
+
// Both rails, because both are resendable: a nearby payment carries
|
|
257
|
+
// the same BRC-29 derivation data and the payee's identity key.
|
|
258
|
+
// labelQueryMode defaults to 'any', so this is peerpay OR localpay.
|
|
259
|
+
{
|
|
260
|
+
labels: RESENDABLE_LABELS,
|
|
261
|
+
includeOutputs: true,
|
|
262
|
+
includeLabels: true,
|
|
263
|
+
limit: 1000
|
|
264
|
+
},
|
|
265
|
+
adminOriginator
|
|
266
|
+
)
|
|
267
|
+
.then(r => r.actions ?? [])
|
|
268
|
+
.catch(() => undefined)
|
|
269
|
+
}
|
|
270
|
+
const actions = await cache
|
|
271
|
+
return actions?.find(a => a.txid === txid)
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export async function loadUnansweredResends(storage: StorageLike): Promise<PendingResend[]> {
|
|
276
|
+
try {
|
|
277
|
+
const raw = await storage.getKeyValue(UNANSWERED_RESENDS_KEY)
|
|
278
|
+
if (!raw) return []
|
|
279
|
+
const parsed = JSON.parse(raw) as unknown
|
|
280
|
+
if (!Array.isArray(parsed)) return []
|
|
281
|
+
return parsed.filter(
|
|
282
|
+
(row): row is PendingResend =>
|
|
283
|
+
!!row &&
|
|
284
|
+
typeof row === 'object' &&
|
|
285
|
+
typeof (row as PendingResend).txid === 'string' &&
|
|
286
|
+
(row as PendingResend).txid.length > 0 &&
|
|
287
|
+
typeof (row as PendingResend).sender === 'string'
|
|
288
|
+
)
|
|
289
|
+
} catch {
|
|
290
|
+
return []
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function storeUnansweredResends(storage: StorageLike, pending: PendingResend[]): Promise<void> {
|
|
295
|
+
await storage.setKeyValue(UNANSWERED_RESENDS_KEY, JSON.stringify(pending))
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* List `resend_request`s and persist them. Does not rebuild or send —
|
|
300
|
+
* only the Resend tap (`handleResendRequests`) and the activity chip do that.
|
|
301
|
+
*/
|
|
302
|
+
export async function listPendingResendRequests(args: {
|
|
303
|
+
client: ListAckClient
|
|
304
|
+
storage: StorageLike
|
|
305
|
+
}): Promise<{ pending: PendingResend[] }> {
|
|
306
|
+
const messages = await listControlMessages(args.client)
|
|
307
|
+
const pending: PendingResend[] = []
|
|
308
|
+
for (const msg of messages) {
|
|
309
|
+
const parsed = parseControlMessage(msg.body)
|
|
310
|
+
if (parsed?.type === 'payment_cancelled') {
|
|
311
|
+
try {
|
|
312
|
+
await consumePaymentCancelled(args.client, msg, parsed.txid)
|
|
313
|
+
} catch {
|
|
314
|
+
// Inbox drop already retried inside consume; a failed control ack is
|
|
315
|
+
// retried on the next poll. Do not skip remaining resend rows.
|
|
316
|
+
}
|
|
317
|
+
continue
|
|
318
|
+
}
|
|
319
|
+
if (!parsed || parsed.type !== 'resend_request') continue
|
|
320
|
+
pending.push({
|
|
321
|
+
txid: parsed.txid,
|
|
322
|
+
sender: typeof msg.sender === 'string' ? msg.sender : ''
|
|
323
|
+
})
|
|
324
|
+
}
|
|
325
|
+
await storeUnansweredResends(args.storage, pending)
|
|
326
|
+
return { pending }
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Rebuild a token for `txid` and drop it in the recipient's payment inbox.
|
|
331
|
+
* Used by the Resend tap and the activity-row "Send details again" chip.
|
|
332
|
+
*/
|
|
333
|
+
/**
|
|
334
|
+
* Why a resend could not happen.
|
|
335
|
+
*
|
|
336
|
+
* A single boolean was indistinguishable from a crash at the call site, so
|
|
337
|
+
* every failure reached the user as "Unknown error" — the dead end this
|
|
338
|
+
* feature exists to remove, reproduced inside it. `no_record` and
|
|
339
|
+
* `no_recipient` are the honest answers for a payment made before its rail
|
|
340
|
+
* recorded the payee's key and derivation data: nothing on this device can
|
|
341
|
+
* rebuild it, and retrying will never change that.
|
|
342
|
+
*/
|
|
343
|
+
export type ResendFailure = 'no_record' | 'no_recipient' | 'no_transaction'
|
|
344
|
+
export type ResendOutcome = { ok: true } | { ok: false; reason: ResendFailure }
|
|
345
|
+
|
|
346
|
+
export async function resendPaymentDetails(args: {
|
|
347
|
+
client: { sendMessage(args: { recipient: string; messageBox: string; body: string }): Promise<unknown> }
|
|
348
|
+
storage: StorageLike
|
|
349
|
+
txid: string
|
|
350
|
+
listPeerPayAction: (txid: string) => Promise<PeerPayActionLike | undefined>
|
|
351
|
+
refetch: (txid: string) => Promise<number[] | undefined>
|
|
352
|
+
/** Unwraps metadata the permissions manager encrypted on its way to storage. */
|
|
353
|
+
decryptMetadata?: (value: string) => Promise<string>
|
|
354
|
+
}): Promise<ResendOutcome> {
|
|
355
|
+
return await rebuildAndDeliver(args)
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
async function rebuildAndDeliver(args: {
|
|
359
|
+
client: { sendMessage(args: { recipient: string; messageBox: string; body: string }): Promise<unknown> }
|
|
360
|
+
storage: StorageLike
|
|
361
|
+
txid: string
|
|
362
|
+
listPeerPayAction: (txid: string) => Promise<PeerPayActionLike | undefined>
|
|
363
|
+
refetch: (txid: string) => Promise<number[] | undefined>
|
|
364
|
+
/** Unwraps metadata the permissions manager encrypted on its way to storage. */
|
|
365
|
+
decryptMetadata?: (value: string) => Promise<string>
|
|
366
|
+
}): Promise<ResendOutcome> {
|
|
367
|
+
const entries = await getOutboxEntries(args.storage)
|
|
368
|
+
const entry = entries.find(e => outboxTxid(e) === args.txid)
|
|
369
|
+
const listed = entry ? undefined : await args.listPeerPayAction(args.txid)
|
|
370
|
+
const action = entry ? actionFromOutbox(entry, args.txid) : listed
|
|
371
|
+
// No outbox row and no labelled action: this payment predates the rail
|
|
372
|
+
// recording who it was for, so it cannot be rebuilt from this device.
|
|
373
|
+
if (!action) return { ok: false, reason: 'no_record' }
|
|
374
|
+
const recipient = entry?.recipient || recipientFromLabels(listed?.labels)
|
|
375
|
+
if (!recipient) return { ok: false, reason: 'no_recipient' }
|
|
376
|
+
|
|
377
|
+
// Without derivation data there is no token to build, and the rebuild would
|
|
378
|
+
// bail before it ever reached for the transaction — reporting "couldn't get
|
|
379
|
+
// this payment's data" about data it never went looking for.
|
|
380
|
+
let withOutputs = action
|
|
381
|
+
if (!hasDerivationData(action.outputs)) {
|
|
382
|
+
withOutputs = { ...action, outputs: await decodeOutputs(action.outputs, args.decryptMetadata) }
|
|
383
|
+
let outputs: PeerPayActionLike['outputs']
|
|
384
|
+
if (!hasDerivationData(withOutputs.outputs)) {
|
|
385
|
+
outputs = await decodeOutputs(await outputsFromStorage(args.storage, args.txid), args.decryptMetadata)
|
|
386
|
+
if (outputs) withOutputs = { ...action, outputs }
|
|
387
|
+
}
|
|
388
|
+
if (!hasDerivationData(withOutputs.outputs)) {
|
|
389
|
+
// Say what was actually seen. "No derivation data" is true of an action
|
|
390
|
+
// with no outputs, of outputs whose customInstructions never made it to
|
|
391
|
+
// storage, and of ones holding something that is not the expected JSON —
|
|
392
|
+
// three different faults that need three different fixes.
|
|
393
|
+
console.warn(
|
|
394
|
+
`[resend] no output with BRC-29 derivation data for ${args.txid};` +
|
|
395
|
+
` listActions gave ${action.outputs?.length ?? 0} output(s), storage gave ${outputs?.length ?? 0};` +
|
|
396
|
+
` customInstructions seen: ${JSON.stringify(
|
|
397
|
+
[...(action.outputs ?? []), ...(outputs ?? [])].map(o =>
|
|
398
|
+
typeof o.customInstructions === 'string' ? o.customInstructions.slice(0, 120) : o.customInstructions
|
|
399
|
+
)
|
|
400
|
+
)}`
|
|
401
|
+
)
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const rebuilt = await rebuildPeerPayToken({
|
|
406
|
+
action: withOutputs,
|
|
407
|
+
recipient,
|
|
408
|
+
refetch: args.refetch
|
|
409
|
+
})
|
|
410
|
+
// The recipient and derivation data resolved, so what is missing is the
|
|
411
|
+
// transaction itself — no proof from the network and no local copy.
|
|
412
|
+
if (!rebuilt) return { ok: false, reason: 'no_transaction' }
|
|
413
|
+
if (entry?.token.note) rebuilt.token.note = entry.token.note
|
|
414
|
+
|
|
415
|
+
try {
|
|
416
|
+
await args.client.sendMessage({
|
|
417
|
+
recipient: rebuilt.recipient,
|
|
418
|
+
messageBox: PAYMENT_INBOX,
|
|
419
|
+
body: JSON.stringify(rebuilt.token)
|
|
420
|
+
})
|
|
421
|
+
} catch (e) {
|
|
422
|
+
// The box already holds this exact token: the recipient has what the
|
|
423
|
+
// resend was trying to give them, so this is the wanted end state.
|
|
424
|
+
if (!isDuplicateMessageError(e)) throw e
|
|
425
|
+
}
|
|
426
|
+
return { ok: true }
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export async function handleResendRequests(args: {
|
|
430
|
+
client: ResendClient
|
|
431
|
+
storage: StorageLike
|
|
432
|
+
listPeerPayAction: (txid: string) => Promise<PeerPayActionLike | undefined>
|
|
433
|
+
refetch: (txid: string) => Promise<number[] | undefined>
|
|
434
|
+
decryptMetadata?: (value: string) => Promise<string>
|
|
435
|
+
}): Promise<{ resent: number; pending: PendingResend[] }> {
|
|
436
|
+
const { client, storage, listPeerPayAction, refetch, decryptMetadata } = args
|
|
437
|
+
const messages = await listControlMessages(client)
|
|
438
|
+
let resent = 0
|
|
439
|
+
const pending: PendingResend[] = []
|
|
440
|
+
|
|
441
|
+
for (const msg of messages) {
|
|
442
|
+
const parsed = parseControlMessage(msg.body)
|
|
443
|
+
if (parsed?.type === 'payment_cancelled') {
|
|
444
|
+
try {
|
|
445
|
+
await consumePaymentCancelled(client, msg, parsed.txid)
|
|
446
|
+
} catch {
|
|
447
|
+
// Same as listPendingResendRequests: one cancel must not skip resends.
|
|
448
|
+
}
|
|
449
|
+
continue
|
|
450
|
+
}
|
|
451
|
+
if (!parsed || parsed.type !== 'resend_request') continue
|
|
452
|
+
const sender = typeof msg.sender === 'string' ? msg.sender : ''
|
|
453
|
+
try {
|
|
454
|
+
const deliveredTo = await rebuildAndDeliver({
|
|
455
|
+
client,
|
|
456
|
+
storage,
|
|
457
|
+
txid: parsed.txid,
|
|
458
|
+
listPeerPayAction,
|
|
459
|
+
refetch,
|
|
460
|
+
decryptMetadata
|
|
461
|
+
})
|
|
462
|
+
if (!deliveredTo.ok) {
|
|
463
|
+
pending.push({ txid: parsed.txid, sender })
|
|
464
|
+
continue
|
|
465
|
+
}
|
|
466
|
+
await ackControlMessages(client, [msg.messageId])
|
|
467
|
+
resent++
|
|
468
|
+
} catch {
|
|
469
|
+
pending.push({ txid: parsed.txid, sender })
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
await storeUnansweredResends(storage, pending)
|
|
474
|
+
return { resent, pending }
|
|
475
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persisted auto-accept attempt state, keyed by inbox message id.
|
|
3
|
+
*
|
|
4
|
+
* Same KV pattern as the outbox: one JSON blob under a fixed key so HandleReceive
|
|
5
|
+
* and TaskCreditInbox share a ceiling instead of each burning MAX_AUTO_ATTEMPTS.
|
|
6
|
+
*/
|
|
7
|
+
import type { InboxAttempt } from '../pay/rails/handle'
|
|
8
|
+
|
|
9
|
+
interface StorageLike {
|
|
10
|
+
getKeyValue: (key: string) => Promise<string | undefined>
|
|
11
|
+
setKeyValue: (key: string, value: string) => Promise<void>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const INBOX_ATTEMPTS_KEY = 'peerpay_inbox_attempts'
|
|
15
|
+
|
|
16
|
+
export async function loadInboxAttempts(storage: StorageLike): Promise<Record<string, InboxAttempt>> {
|
|
17
|
+
try {
|
|
18
|
+
const raw = await storage.getKeyValue(INBOX_ATTEMPTS_KEY)
|
|
19
|
+
if (!raw) return {}
|
|
20
|
+
const parsed = JSON.parse(raw) as unknown
|
|
21
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
|
|
22
|
+
return parsed as Record<string, InboxAttempt>
|
|
23
|
+
} catch {
|
|
24
|
+
return {}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function saveInboxAttempts(
|
|
29
|
+
storage: StorageLike,
|
|
30
|
+
map: Record<string, InboxAttempt>
|
|
31
|
+
): Promise<void> {
|
|
32
|
+
await storage.setKeyValue(INBOX_ATTEMPTS_KEY, JSON.stringify(map))
|
|
33
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read back metadata the permissions manager encrypted on its way into storage.
|
|
3
|
+
*
|
|
4
|
+
* `WalletPermissionsManager` transparently encrypts descriptions and
|
|
5
|
+
* customInstructions with its own admin protocol (`maybeEncryptMetadata`) and
|
|
6
|
+
* decrypts them again as results leave `listActions` / `listOutputs`. Anything
|
|
7
|
+
* that reads the tables directly — a resend rebuilding a payment from the
|
|
8
|
+
* transaction's own output rows — sees base64 ciphertext instead.
|
|
9
|
+
*
|
|
10
|
+
* Prefers the manager's own method when it is there, so this cannot drift from
|
|
11
|
+
* how the value was written; falls back to the same decrypt call the manager
|
|
12
|
+
* makes, which is fixed by the token format and safe to restate.
|
|
13
|
+
*/
|
|
14
|
+
import { Utils } from '@bsv/sdk'
|
|
15
|
+
|
|
16
|
+
/** WalletPermissionsManager.METADATA_ENCRYPTION_PROTOCOL. */
|
|
17
|
+
const METADATA_PROTOCOL: [number, string] = [2, 'admin metadata encryption']
|
|
18
|
+
|
|
19
|
+
type ManagerLike = {
|
|
20
|
+
maybeDecryptMetadata?: (value: string) => Promise<string>
|
|
21
|
+
decrypt?: (
|
|
22
|
+
args: { ciphertext: number[]; protocolID: [number, string]; keyID: string },
|
|
23
|
+
originator?: string
|
|
24
|
+
) => Promise<{ plaintext: number[] }>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function makeMetadataDecryptor(
|
|
28
|
+
manager: unknown,
|
|
29
|
+
adminOriginator?: string
|
|
30
|
+
): ((value: string) => Promise<string>) | undefined {
|
|
31
|
+
const pm = manager as ManagerLike | null | undefined
|
|
32
|
+
if (!pm) return undefined
|
|
33
|
+
return async (value: string) => {
|
|
34
|
+
if (typeof pm.maybeDecryptMetadata === 'function') return await pm.maybeDecryptMetadata(value)
|
|
35
|
+
if (typeof pm.decrypt !== 'function') return value
|
|
36
|
+
const { plaintext } = await pm.decrypt(
|
|
37
|
+
{ ciphertext: Utils.toArray(value, 'base64'), protocolID: METADATA_PROTOCOL, keyID: '1' },
|
|
38
|
+
adminOriginator
|
|
39
|
+
)
|
|
40
|
+
return Utils.toUTF8(plaintext)
|
|
41
|
+
}
|
|
42
|
+
}
|