@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,128 @@
|
|
|
1
|
+
import { Platform } from 'react-native'
|
|
2
|
+
import { getLocalPayBleTransport, getLocalPayTransport } from 'react-native-localpay-transport'
|
|
3
|
+
import { CAP_AWDL, CAP_BLE, CAP_BLE_SCAN, CAP_NEARBY, HINT_BT, RUNG_MASK, type Session } from '../session'
|
|
4
|
+
import type { BluetoothState } from '../deviceCaps'
|
|
5
|
+
|
|
6
|
+
export type TransportKind = 'awdl' | 'nearby' | 'ble' | 'qr'
|
|
7
|
+
|
|
8
|
+
/** True when this device can act as an AWDL peer. */
|
|
9
|
+
export function localSupportsAwdl(): boolean {
|
|
10
|
+
if (Platform.OS !== 'ios') return false
|
|
11
|
+
try {
|
|
12
|
+
return getLocalPayTransport()?.isSupported() ?? false
|
|
13
|
+
} catch {
|
|
14
|
+
return false
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* True when this device can act as a Nearby Connections peer. The same native
|
|
20
|
+
* surface as AWDL, from the Kotlin backend: isSupported() there means Google
|
|
21
|
+
* Play services is present. Runtime permissions are requested at flow entry,
|
|
22
|
+
* not here — a denial degrades the mint/ladder to QR at that point.
|
|
23
|
+
*/
|
|
24
|
+
export function localSupportsNearby(): boolean {
|
|
25
|
+
if (Platform.OS !== 'android') return false
|
|
26
|
+
try {
|
|
27
|
+
return getLocalPayTransport()?.isSupported() ?? false
|
|
28
|
+
} catch {
|
|
29
|
+
return false
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* True when this device can act as a BLE peer. No Platform.OS gate: BLE is the
|
|
35
|
+
* one radio that exists on both platforms, which is the whole reason it is on
|
|
36
|
+
* the ladder (spec §5). Prompt-free — the native isSupported() reads hardware
|
|
37
|
+
* presence plus CBManager.authorization / BluetoothAdapter without creating a
|
|
38
|
+
* manager, and `notDetermined` counts as supported so the ladder can pick BLE
|
|
39
|
+
* and let the iOS prompt appear inside sendFrame()/prepare() (spec §7).
|
|
40
|
+
* denied/restricted report unsupported and floor the pair to QR, and so does a
|
|
41
|
+
* radio the native side already knows is powered off (Android always, via
|
|
42
|
+
* BluetoothAdapter.isEnabled; iOS once a manager has existed in this process)
|
|
43
|
+
* — that is what makes describeFloor's local_bt_off row reachable.
|
|
44
|
+
*/
|
|
45
|
+
export function localSupportsBle(): boolean {
|
|
46
|
+
try {
|
|
47
|
+
return getLocalPayBleTransport()?.isSupported() ?? false
|
|
48
|
+
} catch {
|
|
49
|
+
return false
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The rung both sides can climb to. Caps say what the PEER advertised at mint
|
|
55
|
+
* time; the local check says what THIS device can do. Same-OS pairs keep the
|
|
56
|
+
* higher-throughput radio they have today; cross-OS pairs land on BLE because
|
|
57
|
+
* the peer's AWDL/Nearby bits can never match local ability. `session.os` is
|
|
58
|
+
* metadata and is deliberately not read here (see Session.os). QR is the
|
|
59
|
+
* floor every pair can reach — and the automatic fallback when a chosen radio
|
|
60
|
+
* fails at send time (see NearbyFlow's executeSend).
|
|
61
|
+
*/
|
|
62
|
+
export function selectTransport(session: Session): TransportKind {
|
|
63
|
+
if ((session.caps & CAP_AWDL) !== 0 && localSupportsAwdl()) return 'awdl'
|
|
64
|
+
if ((session.caps & CAP_NEARBY) !== 0 && localSupportsNearby()) return 'nearby'
|
|
65
|
+
if ((session.caps & CAP_BLE) !== 0 && localSupportsBle()) return 'ble'
|
|
66
|
+
return 'qr'
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The GATT role THIS device takes as payer once the ladder chose 'ble'. */
|
|
70
|
+
export type BleRole = 'central' | 'peripheral'
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Peripheral only when the payee advertised that it is scanning (CAP_BLE_SCAN)
|
|
74
|
+
* AND this device is Android. Android as central against an iOS peripheral
|
|
75
|
+
* fails below the app — its controller's link-layer instants are applied by
|
|
76
|
+
* the iPhone seconds to minutes late (spec 2026-09-03) — so it advertises and
|
|
77
|
+
* lets the iOS payee connect. The platform check is a local-ability check in
|
|
78
|
+
* the spirit of localSupportsNearby(), not a read of the peer's OS:
|
|
79
|
+
* `session.os` stays metadata.
|
|
80
|
+
*/
|
|
81
|
+
export function bleRole(session: Session): BleRole {
|
|
82
|
+
return (session.caps & CAP_BLE_SCAN) !== 0 && Platform.OS === 'android' ? 'peripheral' : 'central'
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Why a payer is on the QR fountain. 'none' when a radio was selected, or
|
|
87
|
+
* when nothing in the table applies.
|
|
88
|
+
*/
|
|
89
|
+
export type FloorReason =
|
|
90
|
+
| 'none'
|
|
91
|
+
/** The peer is not listening on any radio rung at all. */
|
|
92
|
+
| 'peer_no_radio'
|
|
93
|
+
/** The peer has no BLE rung and its Bluetooth is off (or unknown). */
|
|
94
|
+
| 'peer_bt_off'
|
|
95
|
+
/** The peer advertises BLE but this app's Bluetooth permission is denied. */
|
|
96
|
+
| 'local_ble_denied'
|
|
97
|
+
/** The peer advertises BLE but this device's Bluetooth radio is off. */
|
|
98
|
+
| 'local_bt_off'
|
|
99
|
+
/** Other OS, peer Bluetooth on, but the peer's app could not advertise BLE. */
|
|
100
|
+
| 'cross_os_no_ble'
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The one line of copy the payer's confirm screen shows when the pair is on
|
|
104
|
+
* the fountain floor (spec §5). Pure: reads the caps the peer minted into the
|
|
105
|
+
* QR (rung bits + hint bits) and what the caller already knows about this
|
|
106
|
+
* device. Evaluated only when selectTransport() returned 'qr'; every other
|
|
107
|
+
* outcome is 'none' so the copy never contradicts a live radio.
|
|
108
|
+
*
|
|
109
|
+
* Order matters: the local_* rows fire before the peer rows because a peer
|
|
110
|
+
* that advertised BLE has done its part — the fix is on this side. session.os
|
|
111
|
+
* is read here (it is copy, exactly what Session.os is for) but never for
|
|
112
|
+
* dispatch.
|
|
113
|
+
*/
|
|
114
|
+
export function describeFloor(
|
|
115
|
+
session: Session,
|
|
116
|
+
local: { os: 'ios' | 'android'; bluetooth: BluetoothState }
|
|
117
|
+
): FloorReason {
|
|
118
|
+
if (selectTransport(session) !== 'qr') return 'none'
|
|
119
|
+
const caps = session.caps
|
|
120
|
+
if ((caps & RUNG_MASK) === 0) return 'peer_no_radio'
|
|
121
|
+
const peerBle = (caps & CAP_BLE) !== 0
|
|
122
|
+
const peerBtOn = (caps & HINT_BT) !== 0
|
|
123
|
+
if (peerBle && local.bluetooth === 'unauthorized') return 'local_ble_denied'
|
|
124
|
+
if (peerBle && local.bluetooth === 'poweredOff') return 'local_bt_off'
|
|
125
|
+
if (!peerBle && session.os !== undefined && session.os !== local.os && peerBtOn) return 'cross_os_no_ble'
|
|
126
|
+
if (!peerBle && !peerBtOn) return 'peer_bt_off'
|
|
127
|
+
return 'none'
|
|
128
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import type { LocalPayTransport } from 'react-native-localpay-transport'
|
|
2
|
+
import { sealFrame, unsealFrame, type PaymentFrame } from '../codec'
|
|
3
|
+
import { instanceName, type Session } from '../session'
|
|
4
|
+
import {
|
|
5
|
+
AckError,
|
|
6
|
+
type Ack,
|
|
7
|
+
type ConfirmDelivery,
|
|
8
|
+
type DeclineReason,
|
|
9
|
+
type LocalPaymentTransport,
|
|
10
|
+
type ReceivedFrame
|
|
11
|
+
} from '../types'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Whole-exchange budget: connect + transfer + the payee's save + ack. Shared
|
|
15
|
+
* by every socketed rung — only the connect-phase budget is radio-specific,
|
|
16
|
+
* and that one is the caller's `connectTimeoutMs`. Must clear the widest
|
|
17
|
+
* connectTimeoutMs (BLE's 15 s, see ble.ts) with margin left for the actual
|
|
18
|
+
* transfer.
|
|
19
|
+
*/
|
|
20
|
+
export const SEND_TIMEOUT_MS = 30_000
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The four methods this wrapper drives. `LocalPayTransport` (AWDL on iOS,
|
|
24
|
+
* Nearby Connections on Android) and `LocalPayBleTransport` (GATT on both)
|
|
25
|
+
* are separate Nitro HybridObjects with no common base in the specs; they
|
|
26
|
+
* share these four signatures exactly, and that structural overlap is what
|
|
27
|
+
* lets one wrapper serve both. A Pick, so the BLE object's extra prompt-free
|
|
28
|
+
* probes (bluetoothState, nfcAvailable, prepare) never leak into the wrapper.
|
|
29
|
+
*/
|
|
30
|
+
export type LocalPayNative = Pick<LocalPayTransport, 'startListening' | 'stopListening' | 'confirmFrame' | 'sendFrame'>
|
|
31
|
+
|
|
32
|
+
export function toBase64(b: Uint8Array): string {
|
|
33
|
+
let s = ''
|
|
34
|
+
for (const byte of b) s += String.fromCharCode(byte)
|
|
35
|
+
return globalThis.btoa(s)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function fromBase64(s: string): Uint8Array {
|
|
39
|
+
return Uint8Array.from(globalThis.atob(s), c => c.charCodeAt(0))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Decode and validate an ack payload. Throws AckError for anything that
|
|
44
|
+
* isn't a well-formed { ok: boolean, error?: string } object — a genuine
|
|
45
|
+
* peer decline (ok: false) is not an error and must be returned normally.
|
|
46
|
+
*/
|
|
47
|
+
export function parseAck(ackBase64: string): Ack {
|
|
48
|
+
let parsed: unknown
|
|
49
|
+
try {
|
|
50
|
+
parsed = JSON.parse(new TextDecoder().decode(fromBase64(ackBase64)))
|
|
51
|
+
} catch {
|
|
52
|
+
throw new AckError('malformed ack: invalid base64 or JSON')
|
|
53
|
+
}
|
|
54
|
+
if (typeof parsed !== 'object' || parsed === null) {
|
|
55
|
+
throw new AckError('malformed ack: expected an object')
|
|
56
|
+
}
|
|
57
|
+
const { ok, error } = parsed as Record<string, unknown>
|
|
58
|
+
if (typeof ok !== 'boolean') {
|
|
59
|
+
throw new AckError('malformed ack: missing boolean "ok"')
|
|
60
|
+
}
|
|
61
|
+
if (error !== undefined && typeof error !== 'string') {
|
|
62
|
+
throw new AckError('malformed ack: "error" must be a string')
|
|
63
|
+
}
|
|
64
|
+
return error === undefined ? { ok } : { ok, error }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Wraps the native `confirmFrame` in the contract ConfirmDelivery promises:
|
|
69
|
+
* at most one ack per delivery, and never a rejection.
|
|
70
|
+
*
|
|
71
|
+
* The latch is defence in depth against a second ack contradicting the first:
|
|
72
|
+
* `settleReceived` has many exits and each one confirms, so a missed `return`
|
|
73
|
+
* would otherwise let a decline follow an acceptance for the same payment. The
|
|
74
|
+
* swallow matters because the payee's copy is already durable by the time a
|
|
75
|
+
* positive ack is sent — a socket error here is a payer-side retry problem,
|
|
76
|
+
* not a reason to tell the payee its payment failed.
|
|
77
|
+
*/
|
|
78
|
+
export function makeConfirm(native: LocalPayNative): ConfirmDelivery {
|
|
79
|
+
let acked = false
|
|
80
|
+
return (accepted, reason) => {
|
|
81
|
+
if (acked) return Promise.resolve()
|
|
82
|
+
acked = true
|
|
83
|
+
try {
|
|
84
|
+
return native.confirmFrame(accepted, reason ?? '').catch(warnAckFailure)
|
|
85
|
+
} catch (e) {
|
|
86
|
+
warnAckFailure(e)
|
|
87
|
+
return Promise.resolve()
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function warnAckFailure(e: unknown): void {
|
|
93
|
+
console.warn('[localpay] confirmFrame failed:', e instanceof Error ? e.message : String(e))
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Decline without a handle, from inside a native callback. Cannot throw: a
|
|
98
|
+
* throw here would unwind into Swift's `onFrame` invocation rather than into
|
|
99
|
+
* any JS caller.
|
|
100
|
+
*/
|
|
101
|
+
export function declineQuietly(native: LocalPayNative, reason: DeclineReason): void {
|
|
102
|
+
try {
|
|
103
|
+
void native.confirmFrame(false, reason).catch(warnAckFailure)
|
|
104
|
+
} catch (e) {
|
|
105
|
+
warnAckFailure(e)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The socketed transport wrapper, shared by every radio backend. The native
|
|
111
|
+
* surface is identical across them (two Nitro specs, same four transport
|
|
112
|
+
* methods): iOS implements LocalPayTransport over AWDL/Network.framework,
|
|
113
|
+
* Android over Google Nearby Connections, and both implement
|
|
114
|
+
* LocalPayBleTransport over GATT. `native` is the cached accessor for the
|
|
115
|
+
* HybridObject this rung drives (getLocalPayTransport or
|
|
116
|
+
* getLocalPayBleTransport); which backend it returns is decided by the
|
|
117
|
+
* platform at build time, so `kind` here is attribution, not dispatch.
|
|
118
|
+
*
|
|
119
|
+
* `connectTimeoutMs` is the connect-phase budget before the payer gives up and
|
|
120
|
+
* falls back to the QR. Radio-specific, so each rung owns its constant: AWDL's
|
|
121
|
+
* Bonjour discovery over an already-established Wi-Fi link resolves (or
|
|
122
|
+
* doesn't) inside ~4s, but Nearby has to do BLE discovery and then a
|
|
123
|
+
* Wi-Fi/hotspot upgrade before a connection even exists — 4s there would
|
|
124
|
+
* false-positive "no route to peer" on a link that just needed more time to
|
|
125
|
+
* come up. BLE sits between the two: scan + connect + MTU + discovery in ~6s.
|
|
126
|
+
*/
|
|
127
|
+
export function makeSocketTransport(
|
|
128
|
+
kind: 'awdl' | 'nearby' | 'ble',
|
|
129
|
+
native: () => LocalPayNative | null,
|
|
130
|
+
connectTimeoutMs: number
|
|
131
|
+
): LocalPaymentTransport {
|
|
132
|
+
return {
|
|
133
|
+
kind,
|
|
134
|
+
|
|
135
|
+
receive(session: Session, signal: AbortSignal): Promise<ReceivedFrame> {
|
|
136
|
+
const backend = native()
|
|
137
|
+
if (!backend) return Promise.reject(new Error(`${kind} transport unavailable`))
|
|
138
|
+
if (signal.aborted) return Promise.reject(new Error('cancelled'))
|
|
139
|
+
const name = instanceName(session.sessionId)
|
|
140
|
+
|
|
141
|
+
return new Promise<ReceivedFrame>((resolve, reject) => {
|
|
142
|
+
let settled = false
|
|
143
|
+
/**
|
|
144
|
+
* `teardown` says whether settling should also tear the native listener
|
|
145
|
+
* down. It must be FALSE on the success path: the native side already
|
|
146
|
+
* cancelled the listener itself the instant it accepted (first-success-
|
|
147
|
+
* wins), and it is now holding the payer's connection open waiting for
|
|
148
|
+
* confirmFrame(). stopListening() cancels held connections, so calling
|
|
149
|
+
* it here would destroy the very socket the ack has to travel back over
|
|
150
|
+
* — the payer would time out on a payment the payee successfully saved.
|
|
151
|
+
*/
|
|
152
|
+
const finish = (teardown: boolean, fn: () => void) => {
|
|
153
|
+
if (settled) return
|
|
154
|
+
settled = true
|
|
155
|
+
signal.removeEventListener('abort', onAbort)
|
|
156
|
+
if (teardown) void backend.stopListening().catch(() => {})
|
|
157
|
+
fn()
|
|
158
|
+
}
|
|
159
|
+
const onAbort = () => finish(true, () => reject(new Error('cancelled')))
|
|
160
|
+
signal.addEventListener('abort', onAbort)
|
|
161
|
+
|
|
162
|
+
backend
|
|
163
|
+
.startListening(
|
|
164
|
+
name,
|
|
165
|
+
toBase64(session.psk),
|
|
166
|
+
frameBase64 => {
|
|
167
|
+
// Decode BEFORE finish(). `finish` latches `settled` and tears the
|
|
168
|
+
// listener down before it invokes its callback, so a throw from
|
|
169
|
+
// inside that callback can never be recovered by a second finish() —
|
|
170
|
+
// the guard returns early and the promise never settles at all,
|
|
171
|
+
// leaving the payee spinning against a listener that is already gone.
|
|
172
|
+
// Any version skew, truncation or trailing bytes reaches this path.
|
|
173
|
+
let frame: PaymentFrame
|
|
174
|
+
try {
|
|
175
|
+
frame = unsealFrame(fromBase64(frameBase64), session.psk)
|
|
176
|
+
} catch (e) {
|
|
177
|
+
// The only decline the caller can never issue itself: receive()
|
|
178
|
+
// rejects here, so no ReceivedFrame — and therefore no confirm
|
|
179
|
+
// handle — ever reaches the screen. Declining from inside the
|
|
180
|
+
// transport is what stops the payer sitting on a green "Sent"
|
|
181
|
+
// until its own timeout. Nothing was persisted, so this is a
|
|
182
|
+
// provable "queued nothing" and the payer may release its inputs.
|
|
183
|
+
//
|
|
184
|
+
// teardown is false here for the same reason as on success:
|
|
185
|
+
// stopListening() would cancel the connection the decline has
|
|
186
|
+
// to go out on. confirmFrame does the full teardown itself, and
|
|
187
|
+
// the native listener was already cancelled at accept time.
|
|
188
|
+
declineQuietly(backend, 'decode_failed')
|
|
189
|
+
return finish(false, () => reject(e))
|
|
190
|
+
}
|
|
191
|
+
finish(false, () => resolve({ frame, confirm: makeConfirm(backend) }))
|
|
192
|
+
},
|
|
193
|
+
message => finish(true, () => reject(new Error(message)))
|
|
194
|
+
)
|
|
195
|
+
.catch(e => finish(true, () => reject(e)))
|
|
196
|
+
})
|
|
197
|
+
},
|
|
198
|
+
|
|
199
|
+
send(session: Session, frame: PaymentFrame, signal: AbortSignal): Promise<Ack> {
|
|
200
|
+
const backend = native()
|
|
201
|
+
if (!backend) return Promise.reject(new Error(`${kind} transport unavailable`))
|
|
202
|
+
if (signal.aborted) return Promise.reject(new Error('cancelled'))
|
|
203
|
+
|
|
204
|
+
return new Promise<Ack>((resolve, reject) => {
|
|
205
|
+
let settled = false
|
|
206
|
+
const cleanup = () => signal.removeEventListener('abort', onAbort)
|
|
207
|
+
const onAbort = () => {
|
|
208
|
+
if (settled) return
|
|
209
|
+
settled = true
|
|
210
|
+
cleanup()
|
|
211
|
+
reject(new Error('cancelled'))
|
|
212
|
+
}
|
|
213
|
+
signal.addEventListener('abort', onAbort)
|
|
214
|
+
|
|
215
|
+
backend
|
|
216
|
+
.sendFrame(
|
|
217
|
+
instanceName(session.sessionId),
|
|
218
|
+
toBase64(session.psk),
|
|
219
|
+
toBase64(sealFrame(frame, session.psk)),
|
|
220
|
+
SEND_TIMEOUT_MS,
|
|
221
|
+
connectTimeoutMs
|
|
222
|
+
)
|
|
223
|
+
.then(
|
|
224
|
+
ackBase64 => {
|
|
225
|
+
if (settled) return
|
|
226
|
+
settled = true
|
|
227
|
+
cleanup()
|
|
228
|
+
try {
|
|
229
|
+
resolve(parseAck(ackBase64))
|
|
230
|
+
} catch (e) {
|
|
231
|
+
reject(e)
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
e => {
|
|
235
|
+
if (settled) return
|
|
236
|
+
settled = true
|
|
237
|
+
cleanup()
|
|
238
|
+
reject(e)
|
|
239
|
+
}
|
|
240
|
+
)
|
|
241
|
+
})
|
|
242
|
+
},
|
|
243
|
+
}
|
|
244
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { PaymentFrame } from './codec'
|
|
2
|
+
import type { Session } from './session'
|
|
3
|
+
|
|
4
|
+
export interface Ack {
|
|
5
|
+
ok: boolean
|
|
6
|
+
error?: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Why a payee refused a delivered frame.
|
|
11
|
+
*
|
|
12
|
+
* A stable machine code, deliberately not display text: it crosses the wire in
|
|
13
|
+
* `Ack.error` and is rendered on the PAYER's device, in the PAYER's locale.
|
|
14
|
+
* Sending the payee's already-localized sentence would show a Japanese payer a
|
|
15
|
+
* Polish error. The payer maps these to its own strings and falls back to
|
|
16
|
+
* echoing anything it does not recognise.
|
|
17
|
+
*
|
|
18
|
+
* Every one of these means the payee queued NOTHING, so the payer may safely
|
|
19
|
+
* release the inputs its `noSend` action is holding. Nothing that could leave
|
|
20
|
+
* the payment half-committed may ever be reported as a decline.
|
|
21
|
+
*/
|
|
22
|
+
export type DeclineReason =
|
|
23
|
+
/** The frame's derivation nonces or amount do not match the live request. */
|
|
24
|
+
| 'session_mismatch'
|
|
25
|
+
/** This one-shot session was already settled by an earlier delivery. */
|
|
26
|
+
| 'already_paid'
|
|
27
|
+
/** Storage was unavailable, busy, or the write failed. Retryable. */
|
|
28
|
+
| 'save_failed'
|
|
29
|
+
/** The frame did not decode — version skew, truncation, trailing bytes. */
|
|
30
|
+
| 'decode_failed'
|
|
31
|
+
|
|
32
|
+
const DECLINE_REASONS: readonly string[] = [
|
|
33
|
+
'session_mismatch',
|
|
34
|
+
'already_paid',
|
|
35
|
+
'save_failed',
|
|
36
|
+
'decode_failed'
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
export function isDeclineReason(value: string): value is DeclineReason {
|
|
40
|
+
return DECLINE_REASONS.includes(value)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Acknowledges a delivered frame back to the payer.
|
|
45
|
+
*
|
|
46
|
+
* Call with `true` ONLY once the payment is durably persisted: a positive ack
|
|
47
|
+
* is what releases the payer's transaction for broadcast, and it must never be
|
|
48
|
+
* a claim that mere receipt has occurred. Call with `false` on every path that
|
|
49
|
+
* queued nothing, so the payer learns immediately instead of resting on a
|
|
50
|
+
* green "Sent".
|
|
51
|
+
*
|
|
52
|
+
* Idempotent, and never rejects — a failed ack is not a failed payment on the
|
|
53
|
+
* payee's side, and must not be allowed to flip a settled screen.
|
|
54
|
+
*/
|
|
55
|
+
export type ConfirmDelivery = (accepted: boolean, reason?: DeclineReason) => Promise<void>
|
|
56
|
+
|
|
57
|
+
/** A frame that arrived, plus the handle that tells the payer what became of it. */
|
|
58
|
+
export interface ReceivedFrame {
|
|
59
|
+
frame: PaymentFrame
|
|
60
|
+
confirm: ConfirmDelivery
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface LocalPaymentTransport {
|
|
64
|
+
readonly kind: 'awdl' | 'nearby' | 'ble' | 'qr'
|
|
65
|
+
receive(session: Session, signal: AbortSignal): Promise<ReceivedFrame>
|
|
66
|
+
send(session: Session, frame: PaymentFrame, signal: AbortSignal): Promise<Ack>
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export class QrHandoffRequired extends Error {
|
|
70
|
+
constructor() {
|
|
71
|
+
super('QR transport is driven by the UI, not by this interface')
|
|
72
|
+
this.name = 'QrHandoffRequired'
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Thrown when an ack cannot be decoded or does not have the shape of a valid Ack. */
|
|
77
|
+
export class AckError extends Error {
|
|
78
|
+
constructor(message: string) {
|
|
79
|
+
super(message)
|
|
80
|
+
this.name = 'AckError'
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { BigNumber, Curve, Hash, P2PKH, PublicKey, Transaction, Utils } from '@bsv/sdk'
|
|
2
|
+
import { MandalaToken } from '@bsv/templates'
|
|
3
|
+
import type { PaymentFrame } from './codec'
|
|
4
|
+
import { PEERPAY_PROTOCOL_ID } from './pending'
|
|
5
|
+
import { isRequestableAmount } from './session'
|
|
6
|
+
|
|
7
|
+
// mandala's FT derivation protocol — the payer locks token outputs under it
|
|
8
|
+
// with OUR payee-minted nonces as keyID, preserving the frame-to-session binding
|
|
9
|
+
export const FT_PROTOCOL_ID: [2, string] = [2, 'mandala token']
|
|
10
|
+
|
|
11
|
+
export type VerifiedPayment =
|
|
12
|
+
| { kind: 'bsv'; satoshis: number }
|
|
13
|
+
| { kind: 'token'; assetId: string; amount: number }
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Why a frame could not be shown to pay this device.
|
|
17
|
+
*
|
|
18
|
+
* Two kinds, because the payee's decline reason differs: bytes that are not a
|
|
19
|
+
* transaction are a decode problem the payer can retry from, whereas a
|
|
20
|
+
* transaction that pays someone else is a frame that was never for us.
|
|
21
|
+
*/
|
|
22
|
+
export type FrameVerifyKind = 'unparseable' | 'not_mine'
|
|
23
|
+
|
|
24
|
+
export class FrameVerifyError extends Error {
|
|
25
|
+
readonly kind: FrameVerifyKind
|
|
26
|
+
constructor(kind: FrameVerifyKind, message: string) {
|
|
27
|
+
super(message)
|
|
28
|
+
this.name = 'FrameVerifyError'
|
|
29
|
+
this.kind = kind
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The one wallet capability this module needs: BRC-42 derivation. */
|
|
34
|
+
export interface DerivingWallet {
|
|
35
|
+
getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The satoshis a delivered frame actually pays this device.
|
|
40
|
+
*
|
|
41
|
+
* `internalizeAction` credits the output, not any field beside it, so the
|
|
42
|
+
* figure a payee renders as a receipt has to come from the transaction — and
|
|
43
|
+
* is only worth reading once the output is shown to be ours. The derivation
|
|
44
|
+
* below is the payee-side mirror of the payer's in `build.ts`: same protocol,
|
|
45
|
+
* same keyID, same counterparty, `forSelf` flipped. If the script matches, the
|
|
46
|
+
* output is spendable by this device and its satoshi count is the payment.
|
|
47
|
+
*
|
|
48
|
+
* Throws on every failure and returns on none, so a caller cannot mistake a
|
|
49
|
+
* refusal for a zero-value payment. MUST be called before the settle path
|
|
50
|
+
* latches or writes anything: every throw here has to remain a provable
|
|
51
|
+
* "queued nothing" decline.
|
|
52
|
+
*/
|
|
53
|
+
export async function verifyFramePayment(
|
|
54
|
+
wallet: DerivingWallet,
|
|
55
|
+
frame: PaymentFrame,
|
|
56
|
+
originator: string
|
|
57
|
+
): Promise<VerifiedPayment> {
|
|
58
|
+
let tx: Transaction
|
|
59
|
+
try {
|
|
60
|
+
tx = Transaction.fromAtomicBEEF(frame.transaction)
|
|
61
|
+
} catch (e) {
|
|
62
|
+
throw new FrameVerifyError('unparseable', `frame transaction is not readable AtomicBEEF: ${messageOf(e)}`)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const output = tx.outputs[frame.outputIndex]
|
|
66
|
+
if (!output) {
|
|
67
|
+
throw new FrameVerifyError(
|
|
68
|
+
'unparseable',
|
|
69
|
+
`frame names outputIndex ${frame.outputIndex}, but the transaction has ${tx.outputs.length} outputs`
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (frame.kind === 'bsv') {
|
|
74
|
+
const { publicKey } = await wallet.getPublicKey(
|
|
75
|
+
{
|
|
76
|
+
protocolID: PEERPAY_PROTOCOL_ID,
|
|
77
|
+
keyID: `${frame.derivationPrefix} ${frame.derivationSuffix}`,
|
|
78
|
+
counterparty: frame.senderIdentityKey,
|
|
79
|
+
forSelf: true
|
|
80
|
+
},
|
|
81
|
+
originator
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
let expected: string
|
|
85
|
+
try {
|
|
86
|
+
expected = new P2PKH().lock(PublicKey.fromString(publicKey).toAddress()).toHex()
|
|
87
|
+
} catch (e) {
|
|
88
|
+
// The derived key is ours and should always parse; a failure here means we
|
|
89
|
+
// cannot say the output is ours, which is the same refusal either way.
|
|
90
|
+
throw new FrameVerifyError('not_mine', `could not derive this device’s expected script: ${messageOf(e)}`)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (output.lockingScript.toHex() !== expected) {
|
|
94
|
+
throw new FrameVerifyError('not_mine', 'the named output does not pay this device')
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Optional on the SDK type, and a zero or fractional value would render as a
|
|
98
|
+
// receipt for money that never moved.
|
|
99
|
+
if (!isRequestableAmount(output.satoshis)) {
|
|
100
|
+
throw new FrameVerifyError('not_mine', `the named output carries no usable satoshi value: ${output.satoshis}`)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return { kind: 'bsv', satoshis: output.satoshis }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (!frame.token) throw new FrameVerifyError('unparseable', 'token frame without token block')
|
|
107
|
+
|
|
108
|
+
let decoded: { assetId: string; amount: number; pubKeyHash: number[] }
|
|
109
|
+
try {
|
|
110
|
+
decoded = MandalaToken.decode(output.lockingScript)
|
|
111
|
+
} catch (e) {
|
|
112
|
+
throw new FrameVerifyError('not_mine', `the named output is not a token script: ${messageOf(e)}`)
|
|
113
|
+
}
|
|
114
|
+
if (decoded.assetId !== frame.token.assetId) {
|
|
115
|
+
throw new FrameVerifyError('not_mine', 'the output moves a different asset than the frame declares')
|
|
116
|
+
}
|
|
117
|
+
const { publicKey } = await wallet.getPublicKey(
|
|
118
|
+
{
|
|
119
|
+
protocolID: FT_PROTOCOL_ID,
|
|
120
|
+
keyID: `${frame.derivationPrefix} ${frame.derivationSuffix}`,
|
|
121
|
+
counterparty: frame.senderIdentityKey,
|
|
122
|
+
forSelf: true
|
|
123
|
+
},
|
|
124
|
+
originator
|
|
125
|
+
)
|
|
126
|
+
const expectedPkh = Hash.hash160(Utils.toArray(publicKey, 'hex'))
|
|
127
|
+
const mine = decoded.pubKeyHash.length === expectedPkh.length &&
|
|
128
|
+
decoded.pubKeyHash.every((b, i) => b === expectedPkh[i])
|
|
129
|
+
if (!mine) throw new FrameVerifyError('not_mine', 'the named token output does not pay this device')
|
|
130
|
+
if (!Number.isSafeInteger(decoded.amount) || decoded.amount < 1) {
|
|
131
|
+
throw new FrameVerifyError('not_mine', `the named output carries no usable token amount: ${decoded.amount}`)
|
|
132
|
+
}
|
|
133
|
+
return { kind: 'token', assetId: decoded.assetId, amount: decoded.amount }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The one wallet capability `verifyRecipientLinkage` needs: BRC-72 decryption. */
|
|
137
|
+
export interface LinkageDecryptingWallet {
|
|
138
|
+
decrypt(args: unknown, originator?: string): Promise<{ plaintext: number[] }>
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Prove the payer minted honest linkage for OUR output: decrypt the
|
|
143
|
+
* BRC-72 blob (we are its verifier), recover derivedKey = counterparty +
|
|
144
|
+
* L·G, and require its hash160 to equal the output's pubKeyHash. This
|
|
145
|
+
* shows the payer CAN produce valid linkage — the overlay's own verdict
|
|
146
|
+
* at submission remains the real admission gate.
|
|
147
|
+
*/
|
|
148
|
+
export async function verifyRecipientLinkage(
|
|
149
|
+
wallet: LinkageDecryptingWallet,
|
|
150
|
+
recipientLinkage: Uint8Array,
|
|
151
|
+
expectedPubKeyHash: number[],
|
|
152
|
+
originator: string
|
|
153
|
+
): Promise<void> {
|
|
154
|
+
let linkage: {
|
|
155
|
+
prover: string; counterparty: string
|
|
156
|
+
protocolID: [number, string]; keyID: string; encryptedLinkage: number[]
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
const parsed = JSON.parse(new TextDecoder().decode(recipientLinkage)) as Record<string, unknown>
|
|
160
|
+
if (
|
|
161
|
+
typeof parsed.prover !== 'string' || parsed.prover.length !== 66 ||
|
|
162
|
+
typeof parsed.counterparty !== 'string' || parsed.counterparty.length !== 66 ||
|
|
163
|
+
!Array.isArray(parsed.protocolID) || typeof parsed.keyID !== 'string' ||
|
|
164
|
+
!Array.isArray(parsed.encryptedLinkage)
|
|
165
|
+
) throw new Error('missing linkage fields')
|
|
166
|
+
linkage = parsed as typeof linkage
|
|
167
|
+
} catch (e) {
|
|
168
|
+
throw new FrameVerifyError('unparseable', `recipientLinkage is not a readable SpecificLinkage: ${messageOf(e)}`)
|
|
169
|
+
}
|
|
170
|
+
let plaintext: number[]
|
|
171
|
+
try {
|
|
172
|
+
;({ plaintext } = await wallet.decrypt(
|
|
173
|
+
{
|
|
174
|
+
ciphertext: linkage.encryptedLinkage,
|
|
175
|
+
protocolID: [2, `specific linkage revelation ${linkage.protocolID[0]} ${linkage.protocolID[1]}`],
|
|
176
|
+
keyID: linkage.keyID,
|
|
177
|
+
counterparty: linkage.prover
|
|
178
|
+
},
|
|
179
|
+
originator
|
|
180
|
+
))
|
|
181
|
+
} catch (e) {
|
|
182
|
+
throw new FrameVerifyError('not_mine', `recipientLinkage did not decrypt for this device: ${messageOf(e)}`)
|
|
183
|
+
}
|
|
184
|
+
let derivedPkh: number[]
|
|
185
|
+
try {
|
|
186
|
+
const curve = new Curve()
|
|
187
|
+
const sum = PublicKey.fromString(linkage.counterparty).add(curve.g.mul(new BigNumber(plaintext)))
|
|
188
|
+
derivedPkh = Hash.hash160(Utils.toArray(new PublicKey(sum.x, sum.y).toString(), 'hex'))
|
|
189
|
+
} catch (e) {
|
|
190
|
+
// `linkage.counterparty` is 66 hex chars by the shape check above, but
|
|
191
|
+
// hex-shaped is not curve-valid: hostile JSON can still name a point this
|
|
192
|
+
// library refuses to parse or add. That is a platform Error, not a
|
|
193
|
+
// FrameVerifyError, so it must be caught here to keep this module's
|
|
194
|
+
// every-failure-is-FrameVerifyError contract.
|
|
195
|
+
throw new FrameVerifyError('not_mine', `recipientLinkage counterparty key is unusable: ${messageOf(e)}`)
|
|
196
|
+
}
|
|
197
|
+
const matches = derivedPkh.length === expectedPubKeyHash.length &&
|
|
198
|
+
derivedPkh.every((b, i) => b === expectedPubKeyHash[i])
|
|
199
|
+
if (!matches) throw new FrameVerifyError('not_mine', 'recipientLinkage does not control the paid output')
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function messageOf(e: unknown): string {
|
|
203
|
+
return e instanceof Error ? e.message : String(e)
|
|
204
|
+
}
|