@bsv/expo-wallet-toolbox 0.15.2 → 0.17.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/CHANGELOG.md +199 -0
- package/core/backup/appData.ts +5 -1
- package/core/backup/codec.ts +9 -3
- package/core/backup/contactsBackup.ts +145 -0
- package/core/backup/push.ts +14 -0
- package/core/backup/restore.ts +26 -4
- package/core/backup/restoreOnImport.ts +28 -4
- package/core/contacts/contactsStore.ts +47 -3
- package/core/context/LocalStorageProvider.tsx +3 -1
- package/core/context/WalletContext.tsx +256 -76
- package/core/context/startupPrewarm.ts +54 -0
- package/core/directpay/dialFailure.ts +56 -0
- package/core/directpay/index.ts +7 -0
- package/core/directpay/payFlow.ts +117 -0
- package/core/directpay/paymentKey.ts +16 -0
- package/core/directpay/settings.ts +253 -0
- package/core/directpay/status.ts +52 -0
- package/core/directpay/types.ts +128 -0
- package/core/hooks/useConfirmationSound.ts +7 -0
- package/core/i18n/translations.tsx +354 -12
- package/core/identity/handleRegistry/client.ts +2 -1
- package/core/identity/handleRegistry/profileKeys.ts +16 -0
- package/core/identity/handleRegistry/resolver.ts +2 -1
- package/core/identity/handleRegistry/rules.ts +7 -3
- package/core/index.ts +14 -2
- package/core/localpay/build.ts +4 -3
- package/core/localpay/session.ts +6 -0
- package/core/localpay/transport/select.ts +64 -3
- package/core/localpay/verify.ts +2 -1
- package/core/net/trimTrailingSlashes.ts +13 -0
- package/core/parsePeerPayURI.ts +25 -2
- package/core/pay/creditInbox.ts +31 -1
- package/core/pay/rails/address.ts +3 -2
- package/core/pay/rails/handle.ts +8 -2
- package/core/pay/rails/index.ts +6 -4
- package/core/pos/protocol.ts +172 -0
- package/core/profiles/discovery.ts +17 -8
- package/core/profiles/profileStore.ts +34 -7
- package/core/profiles/removalProblems.ts +41 -0
- package/core/push/registration.ts +2 -1
- package/core/services/callbackToken.ts +7 -0
- package/core/services/revokeConnection.ts +98 -0
- package/core/storage/schema/createTables.ts +24 -0
- package/core/toolboxConfig.ts +85 -5
- package/package.json +1 -1
- package/ui/components/pay/MessageBoxConfig.tsx +2 -1
- package/ui/components/pay/NearbyFlow.tsx +410 -7
- package/ui/exportTransactions.ts +26 -13
- package/ui/index.ts +2 -2
- package/ui/screens/ConnectionsScreen.tsx +8 -63
- package/ui/screens/ProfileScreen.tsx +2 -40
- package/ui/screens/WalletConfigScreen.tsx +57 -51
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import { Platform } from 'react-native'
|
|
2
2
|
import { getLocalPayBleTransport, getLocalPayTransport } from '@bsv/react-native-localpay-transport'
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
CAP_AWDL,
|
|
5
|
+
CAP_BLE,
|
|
6
|
+
CAP_BLE_SCAN,
|
|
7
|
+
CAP_NEARBY,
|
|
8
|
+
HINT_BT,
|
|
9
|
+
HINT_NET,
|
|
10
|
+
HINT_ONLINE_KNOWN,
|
|
11
|
+
HINT_WIFI,
|
|
12
|
+
RUNG_MASK,
|
|
13
|
+
type Session
|
|
14
|
+
} from '../session'
|
|
4
15
|
import type { BluetoothState } from '../deviceCaps'
|
|
5
16
|
|
|
6
17
|
export type TransportKind = 'awdl' | 'nearby' | 'ble' | 'qr'
|
|
@@ -57,15 +68,65 @@ export function localSupportsBle(): boolean {
|
|
|
57
68
|
* the peer's AWDL/Nearby bits can never match local ability. `session.os` is
|
|
58
69
|
* metadata and is deliberately not read here (see Session.os). QR is the
|
|
59
70
|
* floor every pair can reach — and the automatic fallback when a chosen radio
|
|
60
|
-
* fails at send time (see NearbyFlow's executeSend)
|
|
71
|
+
* fails at send time (see NearbyFlow's executeSend), after fallbackRadio()
|
|
72
|
+
* below when the first radio never connected.
|
|
61
73
|
*/
|
|
62
74
|
export function selectTransport(session: Session): TransportKind {
|
|
63
|
-
if ((session.caps & CAP_AWDL) !== 0 && localSupportsAwdl()) return 'awdl'
|
|
75
|
+
if ((session.caps & CAP_AWDL) !== 0 && !peerKnownOffWifi(session) && localSupportsAwdl()) return 'awdl'
|
|
64
76
|
if ((session.caps & CAP_NEARBY) !== 0 && localSupportsNearby()) return 'nearby'
|
|
65
77
|
if ((session.caps & CAP_BLE) !== 0 && localSupportsBle()) return 'ble'
|
|
66
78
|
return 'qr'
|
|
67
79
|
}
|
|
68
80
|
|
|
81
|
+
/**
|
|
82
|
+
* The text every native connect-phase failure carries: the code-14 connect
|
|
83
|
+
* timeout, and (AWDL) any `.failed`/`.cancelled` that landed before the link
|
|
84
|
+
* reached `.ready` — see HybridLocalPayTransport.swift `neverConnected`.
|
|
85
|
+
*/
|
|
86
|
+
export const NEVER_CONNECTED_MARKER = 'no route to peer'
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* True when a radio send failed before its link came up, so not one byte of
|
|
90
|
+
* the frame left this device. Only then may the payer try a second radio: a
|
|
91
|
+
* failure after the link was up (a lost ack, a timeout waiting for the payee's
|
|
92
|
+
* save) may already have delivered the frame, and delivering it again on
|
|
93
|
+
* another radio would land in a payee race that is already settled — which
|
|
94
|
+
* answers with a decline the payer would act on by releasing inputs the payee
|
|
95
|
+
* now holds a signed transaction for. Those failures go to the QR fountain.
|
|
96
|
+
*/
|
|
97
|
+
export function failedBeforeConnect(error: unknown): boolean {
|
|
98
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
99
|
+
return message.includes(NEVER_CONNECTED_MARKER)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The radio to try after `failed` never connected, or null for "go to QR".
|
|
104
|
+
* Graceful degradation on iOS is AWDL (fastest, ~300 ms) → BLE → QR: AWDL can
|
|
105
|
+
* fail for reasons this device cannot see in advance (the peer's Wi-Fi radio,
|
|
106
|
+
* Local Network permission, the two phones on different Wi-Fi channels), and
|
|
107
|
+
* BLE is only offered when the payee minted CAP_BLE with its radio powered on.
|
|
108
|
+
* Only AWDL has a fallback rung — its native side is the one that proves a
|
|
109
|
+
* failure happened before `.ready` (see failedBeforeConnect).
|
|
110
|
+
*/
|
|
111
|
+
export function fallbackRadio(session: Session, failed: TransportKind): TransportKind | null {
|
|
112
|
+
if (failed === 'awdl' && (session.caps & CAP_BLE) !== 0 && localSupportsBle()) return 'ble'
|
|
113
|
+
return null
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The payee's QR says, from a network probe that answered, that it was not on
|
|
118
|
+
* a Wi-Fi network when it made the code. Its AWDL bit can still be set then —
|
|
119
|
+
* Control Center's Wi-Fi toggle only disconnects, so the radio (and awdl0)
|
|
120
|
+
* stays up — but AWDL between phones off a network fails in practice and
|
|
121
|
+
* costs the payer the whole connect timeout before the next rung. So the
|
|
122
|
+
* payer does not try it. Unknown (no probe answer, or an older code with no
|
|
123
|
+
* hint bits) is not "off": the AWDL rung stays as it was.
|
|
124
|
+
*/
|
|
125
|
+
export function peerKnownOffWifi(session: Session): boolean {
|
|
126
|
+
const known = (session.caps & (HINT_ONLINE_KNOWN | HINT_NET)) !== 0
|
|
127
|
+
return known && (session.caps & HINT_WIFI) === 0
|
|
128
|
+
}
|
|
129
|
+
|
|
69
130
|
/** The GATT role THIS device takes as payer once the ladder chose 'ble'. */
|
|
70
131
|
export type BleRole = 'central' | 'peripheral'
|
|
71
132
|
|
package/core/localpay/verify.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { coverFromFrame, type CoverVerifier } from '../mandala/bundle'
|
|
|
6
6
|
import { PEERPAY_PROTOCOL_ID } from './pending'
|
|
7
7
|
import { isRequestableAmount } from './session'
|
|
8
8
|
import type { DeclineReason } from './types'
|
|
9
|
+
import { trimTrailingSlashes } from '../net/trimTrailingSlashes'
|
|
9
10
|
|
|
10
11
|
// mandala's FT derivation protocol — the payer locks token outputs under it
|
|
11
12
|
// with OUR payee-minted nonces as keyID, preserving the frame-to-session binding
|
|
@@ -323,7 +324,7 @@ function sameOverlay(
|
|
|
323
324
|
token: { overlayUrl: string; overlayIdentityKey: string },
|
|
324
325
|
asset: { overlayUrl: string; overlayIdentityKey: string }
|
|
325
326
|
): boolean {
|
|
326
|
-
const url = (u: string) => u.trim()
|
|
327
|
+
const url = (u: string) => trimTrailingSlashes(u.trim())
|
|
327
328
|
return (
|
|
328
329
|
token.overlayIdentityKey.toLowerCase() === asset.overlayIdentityKey.toLowerCase() &&
|
|
329
330
|
url(token.overlayUrl) === url(asset.overlayUrl)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `s` without its trailing slashes ("https://host//" → "https://host").
|
|
3
|
+
*
|
|
4
|
+
* In place of `s.replace(/\/+$/, '')`: on a string with many slashes that
|
|
5
|
+
* aren't at its end, that regex backtracks from every one of them, quadratic
|
|
6
|
+
* in the input (CodeQL js/polynomial-redos). URLs reach these call sites
|
|
7
|
+
* from links, QR codes and other apps.
|
|
8
|
+
*/
|
|
9
|
+
export function trimTrailingSlashes(s: string): string {
|
|
10
|
+
let end = s.length
|
|
11
|
+
while (end > 0 && s.charCodeAt(end - 1) === 47 /* '/' */) end--
|
|
12
|
+
return end === s.length ? s : s.slice(0, end)
|
|
13
|
+
}
|
package/core/parsePeerPayURI.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PublicKey } from '@bsv/sdk'
|
|
2
|
+
import { trimTrailingSlashes } from './net/trimTrailingSlashes'
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* BRC-125 PeerPay URI (https://bsv.brc.dev/payments/0125).
|
|
@@ -20,7 +21,21 @@ import { PublicKey } from '@bsv/sdk'
|
|
|
20
21
|
* is ignored, not fatal — a typo in the hint must not block a payment
|
|
21
22
|
* whose key is fine. Only https is accepted because the payer will
|
|
22
23
|
* authenticate against whatever host this names.
|
|
24
|
+
*
|
|
25
|
+
* And `note`: what the payment is for, as the payee wrote it, for the payer's
|
|
26
|
+
* wallet to start the payment's own note with. Shown as text only; trimmed,
|
|
27
|
+
* stripped of control characters and capped at PEERPAY_NOTE_MAX. A wallet
|
|
28
|
+
* that doesn't know it ignores it (BRC-125's extension rule).
|
|
23
29
|
*/
|
|
30
|
+
export const PEERPAY_NOTE_MAX = 120
|
|
31
|
+
|
|
32
|
+
/** A note as a link may carry it: plain, single-line text, or nothing. */
|
|
33
|
+
export function cleanPeerPayNote(raw: string | null | undefined): string | undefined {
|
|
34
|
+
// eslint-disable-next-line no-control-regex
|
|
35
|
+
const text = (raw ?? '').replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, ' ').replace(/\s+/g, ' ').trim()
|
|
36
|
+
return text ? Array.from(text).slice(0, PEERPAY_NOTE_MAX).join('') : undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
24
39
|
export interface PeerPayParams {
|
|
25
40
|
identityKey: string
|
|
26
41
|
sats?: number
|
|
@@ -29,6 +44,8 @@ export interface PeerPayParams {
|
|
|
29
44
|
/** Base units of `asset`. Never present without it. */
|
|
30
45
|
amount?: number
|
|
31
46
|
messageBoxUrl?: string
|
|
47
|
+
/** What it's for, as the payee wrote it (the `note` extension). */
|
|
48
|
+
note?: string
|
|
32
49
|
}
|
|
33
50
|
|
|
34
51
|
export interface PeerPayValidationResult {
|
|
@@ -39,6 +56,8 @@ export interface PeerPayValidationResult {
|
|
|
39
56
|
amount?: number
|
|
40
57
|
/** Present only when the link carried a usable https `url` extension. */
|
|
41
58
|
messageBoxUrl?: string
|
|
59
|
+
/** Present only when the link carried a non-empty `note` extension. */
|
|
60
|
+
note?: string
|
|
42
61
|
errors: {
|
|
43
62
|
identityKey?: string
|
|
44
63
|
sats?: string
|
|
@@ -73,7 +92,8 @@ export function parsePeerPayURI(uri: string): PeerPayParams | null {
|
|
|
73
92
|
...(result.sats !== undefined ? { sats: result.sats } : {}),
|
|
74
93
|
...(result.asset !== undefined ? { asset: result.asset } : {}),
|
|
75
94
|
...(result.amount !== undefined ? { amount: result.amount } : {}),
|
|
76
|
-
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
95
|
+
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {}),
|
|
96
|
+
...(result.note ? { note: result.note } : {})
|
|
77
97
|
}
|
|
78
98
|
}
|
|
79
99
|
|
|
@@ -101,6 +121,7 @@ export function validatePeerPayURI(uri: string): PeerPayValidationResult {
|
|
|
101
121
|
let asset: string | undefined
|
|
102
122
|
let amount: number | undefined
|
|
103
123
|
let messageBoxUrl: string | undefined
|
|
124
|
+
let note: string | undefined
|
|
104
125
|
if (queryPart) {
|
|
105
126
|
const params = new URLSearchParams(queryPart)
|
|
106
127
|
if (params.has('sats')) {
|
|
@@ -123,8 +144,9 @@ export function validatePeerPayURI(uri: string): PeerPayValidationResult {
|
|
|
123
144
|
if (params.has('sats') && (params.has('asset') || params.has('amount'))) {
|
|
124
145
|
errors.sats = 'PeerPay link mixes sats with a token request'
|
|
125
146
|
}
|
|
126
|
-
const url = (params.get('url') ?? '').trim()
|
|
147
|
+
const url = trimTrailingSlashes((params.get('url') ?? '').trim())
|
|
127
148
|
if (url && MESSAGE_BOX_URL_REGEX.test(url)) messageBoxUrl = url
|
|
149
|
+
note = cleanPeerPayNote(params.get('note'))
|
|
128
150
|
}
|
|
129
151
|
|
|
130
152
|
return {
|
|
@@ -134,6 +156,7 @@ export function validatePeerPayURI(uri: string): PeerPayValidationResult {
|
|
|
134
156
|
...(asset !== undefined ? { asset } : {}),
|
|
135
157
|
...(amount !== undefined ? { amount } : {}),
|
|
136
158
|
...(messageBoxUrl ? { messageBoxUrl } : {}),
|
|
159
|
+
...(note ? { note } : {}),
|
|
137
160
|
errors
|
|
138
161
|
}
|
|
139
162
|
}
|
package/core/pay/creditInbox.ts
CHANGED
|
@@ -93,6 +93,36 @@ async function listRawInbox(
|
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
+
/**
|
|
97
|
+
* The sender's note, put back on each parsed payment. The MessageBox client
|
|
98
|
+
* rebuilds a token from the PaymentToken fields alone, so the `note` this
|
|
99
|
+
* app's sending side adds (see sendViaHandle) is dropped on the way in; the
|
|
100
|
+
* raw message still has it.
|
|
101
|
+
*/
|
|
102
|
+
export function withSenderNotes(
|
|
103
|
+
list: IncomingPayment[],
|
|
104
|
+
raw: { messageId: string; body: unknown }[]
|
|
105
|
+
): IncomingPayment[] {
|
|
106
|
+
const notes = new Map<string, string>()
|
|
107
|
+
for (const m of raw) {
|
|
108
|
+
let body = m.body
|
|
109
|
+
if (typeof body === 'string') {
|
|
110
|
+
try {
|
|
111
|
+
body = JSON.parse(body)
|
|
112
|
+
} catch {
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const note = body && typeof body === 'object' ? (body as { note?: unknown }).note : undefined
|
|
117
|
+
if (typeof note === 'string' && note.trim()) notes.set(String(m.messageId), note)
|
|
118
|
+
}
|
|
119
|
+
if (!notes.size) return list
|
|
120
|
+
return list.map(p => {
|
|
121
|
+
const note = notes.get(String(p.messageId))
|
|
122
|
+
return note && p.token && typeof p.token === 'object' ? { ...p, token: { ...p.token, note } as typeof p.token } : p
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
|
|
96
126
|
function attentionCountFor(
|
|
97
127
|
displayPayments: IncomingPayment[],
|
|
98
128
|
damaged: DamagedInboxMessage[],
|
|
@@ -117,8 +147,8 @@ async function runCreditInbox(args: {
|
|
|
117
147
|
accept: (payment: IncomingPayment) => Promise<void>
|
|
118
148
|
}): Promise<CreditInboxResult> {
|
|
119
149
|
const { client, messageBoxUrl, storage, force, classify, accept } = args
|
|
120
|
-
const list = await client.listIncomingPayments(messageBoxUrl)
|
|
121
150
|
const raw = await listRawInbox(client, messageBoxUrl)
|
|
151
|
+
const list = withSenderNotes(await client.listIncomingPayments(messageBoxUrl), raw)
|
|
122
152
|
const fromDiff = listDamagedInboxMessages({ raw, parsed: list })
|
|
123
153
|
const byId = new Map(fromDiff.map(d => [d.messageId, d]))
|
|
124
154
|
for (const p of list) {
|
|
@@ -535,8 +535,9 @@ export async function sendToAddress(args: {
|
|
|
535
535
|
{
|
|
536
536
|
// The recipient's address is the description so the activity list has a
|
|
537
537
|
// name for the row without a lookup; the to: label is what lets it draw
|
|
538
|
-
// a face. A sender's own note overrides it, same as the other rails
|
|
539
|
-
description
|
|
538
|
+
// a face. A sender's own note overrides it, same as the other rails,
|
|
539
|
+
// space-padded to the 5-byte minimum a description must have.
|
|
540
|
+
description: (note?.trim() || abbreviateKey(address)).padEnd(5),
|
|
540
541
|
outputs: [{ lockingScript, satoshis: sats, outputDescription: 'BSV for recipient address' }],
|
|
541
542
|
labels: ['legacy', 'outbound', addressLabel(TO_ADDRESS_LABEL_PREFIX, address)],
|
|
542
543
|
...(isSendMax ? { options: { randomizeOutputs: false } } : {})
|
package/core/pay/rails/handle.ts
CHANGED
|
@@ -21,9 +21,11 @@ import {
|
|
|
21
21
|
} from '../../peerpay/outbox'
|
|
22
22
|
import type { CreditFailureKind } from '../creditErrors'
|
|
23
23
|
import { abbreviateKey } from '../counterparty'
|
|
24
|
+
import { cleanPeerPayNote } from '../../parsePeerPayURI'
|
|
24
25
|
import { isDuplicateMessageError, sendControlMessage, type ResendReason } from '../../peerpay/control'
|
|
25
26
|
import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
|
|
26
27
|
import type { MandalaRuntime, TokenSendResult } from '../../mandala/runtime'
|
|
28
|
+
import { trimTrailingSlashes } from '../../net/trimTrailingSlashes'
|
|
27
29
|
|
|
28
30
|
export const MESSAGE_BOX_URL_KEY = 'message_box_url'
|
|
29
31
|
export const DEFAULT_MESSAGE_BOX_URL = 'https://messagebox.bsvblockchain.tech'
|
|
@@ -81,7 +83,9 @@ export function peerPayLinkFor(
|
|
|
81
83
|
identityKey: string,
|
|
82
84
|
sats?: number,
|
|
83
85
|
messageBoxUrl?: string,
|
|
84
|
-
token?: { assetId: string; baseUnits?: number }
|
|
86
|
+
token?: { assetId: string; baseUnits?: number },
|
|
87
|
+
/** what it's for: the link's `note` extension (see parsePeerPayURI.ts) */
|
|
88
|
+
note?: string
|
|
85
89
|
): string {
|
|
86
90
|
const params: string[] = []
|
|
87
91
|
if (token) {
|
|
@@ -92,8 +96,10 @@ export function peerPayLinkFor(
|
|
|
92
96
|
const amount = sats !== undefined ? Math.round(Number(sats)) : NaN
|
|
93
97
|
if (Number.isFinite(amount) && amount > 0) params.push(`sats=${amount}`)
|
|
94
98
|
}
|
|
95
|
-
const host = (messageBoxUrl ?? '').trim()
|
|
99
|
+
const host = trimTrailingSlashes((messageBoxUrl ?? '').trim())
|
|
96
100
|
if (host && host !== NO_MESSAGE_BOX) params.push(`url=${encodeURIComponent(host)}`)
|
|
101
|
+
const forWhat = cleanPeerPayNote(note)
|
|
102
|
+
if (forWhat) params.push(`note=${encodeURIComponent(forWhat)}`)
|
|
97
103
|
const base = `peerpay:${identityKey.toLowerCase()}`
|
|
98
104
|
return params.length ? `${base}?${params.join('&')}` : base
|
|
99
105
|
}
|
package/core/pay/rails/index.ts
CHANGED
|
@@ -30,7 +30,7 @@ export type RailId = 'nearby' | 'handle' | 'address'
|
|
|
30
30
|
*/
|
|
31
31
|
export type PayTarget =
|
|
32
32
|
| { kind: 'nearby'; session: Session }
|
|
33
|
-
| { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string }
|
|
33
|
+
| { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string; note?: string }
|
|
34
34
|
| { kind: 'address'; address: string; sats?: number; network?: 'main' | 'test' }
|
|
35
35
|
|
|
36
36
|
/** Six cell names. Since the universal input, `pay-*` are deep-link aliases that all open the send form; `get-*` open one receive method directly. */
|
|
@@ -131,7 +131,7 @@ export type RecipientInput =
|
|
|
131
131
|
| { kind: 'empty' }
|
|
132
132
|
| { kind: 'address'; address: string; network?: 'main' | 'test' }
|
|
133
133
|
| { kind: 'invalid_address' }
|
|
134
|
-
| { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string }
|
|
134
|
+
| { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string; note?: string }
|
|
135
135
|
| { kind: 'invalid_link'; message: string }
|
|
136
136
|
| { kind: 'search'; query: string }
|
|
137
137
|
|
|
@@ -153,7 +153,8 @@ function handleFromPeerPay(result: PeerPayValidationResult): RecipientInput {
|
|
|
153
153
|
...(result.sats !== undefined ? { sats: result.sats } : {}),
|
|
154
154
|
...(result.asset !== undefined ? { asset: result.asset } : {}),
|
|
155
155
|
...(result.amount !== undefined ? { amount: result.amount } : {}),
|
|
156
|
-
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
156
|
+
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {}),
|
|
157
|
+
...(result.note ? { note: result.note } : {})
|
|
157
158
|
}
|
|
158
159
|
}
|
|
159
160
|
|
|
@@ -203,7 +204,8 @@ export function classifyScan(raw: string): PayTarget | null {
|
|
|
203
204
|
...(result.sats !== undefined ? { sats: result.sats } : {}),
|
|
204
205
|
...(result.asset !== undefined ? { asset: result.asset } : {}),
|
|
205
206
|
...(result.amount !== undefined ? { amount: result.amount } : {}),
|
|
206
|
-
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
207
|
+
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {}),
|
|
208
|
+
...(result.note ? { note: result.note } : {})
|
|
207
209
|
}
|
|
208
210
|
}
|
|
209
211
|
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { ProtoWallet, PublicKey, Random, type WalletInterface } from '@bsv/sdk'
|
|
2
|
+
import { decodeSession, type Session } from '../localpay/session'
|
|
3
|
+
|
|
4
|
+
export const POS_PROTOCOL: [2, string] = [2, 'bsv pos authorization']
|
|
5
|
+
export const POS_PREFIX = 'bsvpos1:'
|
|
6
|
+
export type Signer = Pick<WalletInterface, 'getPublicKey' | 'createSignature'>
|
|
7
|
+
export interface Signed<T> {
|
|
8
|
+
payload: T
|
|
9
|
+
identityKey: string
|
|
10
|
+
signature: number[]
|
|
11
|
+
}
|
|
12
|
+
export interface Invite {
|
|
13
|
+
kind: 'invite'
|
|
14
|
+
merchant: string
|
|
15
|
+
name: string
|
|
16
|
+
service: string
|
|
17
|
+
chain: string
|
|
18
|
+
id: string
|
|
19
|
+
expires: number
|
|
20
|
+
}
|
|
21
|
+
export interface MerchantRequest {
|
|
22
|
+
kind: 'payment'
|
|
23
|
+
merchant: string
|
|
24
|
+
name: string
|
|
25
|
+
cashier: string
|
|
26
|
+
invoice: string
|
|
27
|
+
chain: string
|
|
28
|
+
expires: number
|
|
29
|
+
session: string
|
|
30
|
+
subtotal?: number
|
|
31
|
+
tip?: number
|
|
32
|
+
}
|
|
33
|
+
export interface Rpc {
|
|
34
|
+
version: 1
|
|
35
|
+
method: string
|
|
36
|
+
nonce: string
|
|
37
|
+
time: number
|
|
38
|
+
body: Record<string, unknown>
|
|
39
|
+
}
|
|
40
|
+
export interface Receipt {
|
|
41
|
+
invoice: string
|
|
42
|
+
txid: string
|
|
43
|
+
amount: number
|
|
44
|
+
status: 'accepted'
|
|
45
|
+
}
|
|
46
|
+
export function randomId(): string {
|
|
47
|
+
return Array.from(Random(16), b => b.toString(16).padStart(2, '0')).join('')
|
|
48
|
+
}
|
|
49
|
+
export function key(value: unknown): string {
|
|
50
|
+
if (typeof value !== 'string' || !/^(02|03)[0-9a-f]{64}$/i.test(value)) throw new Error('Invalid identity')
|
|
51
|
+
PublicKey.fromString(value)
|
|
52
|
+
return value.toLowerCase()
|
|
53
|
+
}
|
|
54
|
+
export function serviceUrl(value: unknown): string {
|
|
55
|
+
if (typeof value !== 'string') throw new Error('Invalid service address')
|
|
56
|
+
const url = new URL(value)
|
|
57
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)
|
|
58
|
+
throw new Error('Use an HTTPS merchant service address')
|
|
59
|
+
return url.toString().replace(/\/$/, '')
|
|
60
|
+
}
|
|
61
|
+
/** Sorted JSON fields and consistent Unicode separators across Go and JS. */
|
|
62
|
+
export function bytes(payload: unknown): number[] {
|
|
63
|
+
const ordered = (v: unknown): unknown =>
|
|
64
|
+
Array.isArray(v)
|
|
65
|
+
? v.map(ordered)
|
|
66
|
+
: v !== null && typeof v === 'object'
|
|
67
|
+
? Object.fromEntries(
|
|
68
|
+
Object.keys(v)
|
|
69
|
+
.sort()
|
|
70
|
+
.map(k => [k, ordered((v as Record<string, unknown>)[k])])
|
|
71
|
+
)
|
|
72
|
+
: v
|
|
73
|
+
const text = JSON.stringify(ordered(payload))
|
|
74
|
+
.replace(/\u2028/g, '\\u2028')
|
|
75
|
+
.replace(/\u2029/g, '\\u2029')
|
|
76
|
+
return Array.from(new TextEncoder().encode(text))
|
|
77
|
+
}
|
|
78
|
+
export async function sign<T>(wallet: Signer, payload: T, originator?: string): Promise<Signed<T>> {
|
|
79
|
+
const { publicKey } = await wallet.getPublicKey({ identityKey: true }, originator)
|
|
80
|
+
const { signature } = await wallet.createSignature(
|
|
81
|
+
{ protocolID: POS_PROTOCOL, keyID: 'v1', counterparty: 'anyone', data: bytes(payload) },
|
|
82
|
+
originator
|
|
83
|
+
)
|
|
84
|
+
return { payload, identityKey: key(publicKey), signature }
|
|
85
|
+
}
|
|
86
|
+
export async function verify<T>(value: Signed<T>, expected?: string): Promise<T> {
|
|
87
|
+
if (
|
|
88
|
+
!value ||
|
|
89
|
+
typeof value !== 'object' ||
|
|
90
|
+
!Array.isArray(value.signature) ||
|
|
91
|
+
value.signature.length > 80 ||
|
|
92
|
+
!value.signature.every(b => Number.isInteger(b) && b >= 0 && b <= 255)
|
|
93
|
+
)
|
|
94
|
+
throw new Error('Invalid merchant authorization')
|
|
95
|
+
const identity = key(value.identityKey)
|
|
96
|
+
if (expected && identity !== key(expected)) throw new Error('Merchant identity does not match')
|
|
97
|
+
const result = await new ProtoWallet('anyone').verifySignature({
|
|
98
|
+
protocolID: POS_PROTOCOL,
|
|
99
|
+
keyID: 'v1',
|
|
100
|
+
counterparty: identity,
|
|
101
|
+
data: bytes(value.payload),
|
|
102
|
+
signature: value.signature
|
|
103
|
+
})
|
|
104
|
+
if (!result.valid) throw new Error('Invalid merchant signature')
|
|
105
|
+
return value.payload
|
|
106
|
+
}
|
|
107
|
+
export function encodePos(value: Signed<Invite | MerchantRequest>): string {
|
|
108
|
+
return (
|
|
109
|
+
POS_PREFIX +
|
|
110
|
+
globalThis
|
|
111
|
+
.btoa(unescape(encodeURIComponent(JSON.stringify(value))))
|
|
112
|
+
.replace(/\+/g, '-')
|
|
113
|
+
.replace(/\//g, '_')
|
|
114
|
+
.replace(/=+$/, '')
|
|
115
|
+
)
|
|
116
|
+
}
|
|
117
|
+
export async function decodePos(text: string): Promise<Signed<Invite | MerchantRequest>> {
|
|
118
|
+
if (!text.startsWith(POS_PREFIX) || text.length > 12000) throw new Error('Invalid point-of-sale code')
|
|
119
|
+
const raw = text.slice(POS_PREFIX.length).replace(/-/g, '+').replace(/_/g, '/')
|
|
120
|
+
const value = JSON.parse(
|
|
121
|
+
decodeURIComponent(escape(globalThis.atob(raw + '='.repeat((4 - (raw.length % 4)) % 4))))
|
|
122
|
+
) as Signed<Invite | MerchantRequest>
|
|
123
|
+
const p = await verify(value)
|
|
124
|
+
if (
|
|
125
|
+
!p ||
|
|
126
|
+
!['invite', 'payment'].includes(p.kind) ||
|
|
127
|
+
key(p.merchant) !== key(value.identityKey) ||
|
|
128
|
+
typeof p.name !== 'string' ||
|
|
129
|
+
!p.name.trim() ||
|
|
130
|
+
p.name.length > 80 ||
|
|
131
|
+
!Number.isSafeInteger(p.expires) ||
|
|
132
|
+
p.expires <= Date.now() ||
|
|
133
|
+
!['main', 'test', 'teratest'].includes(p.chain)
|
|
134
|
+
)
|
|
135
|
+
throw new Error('Expired or invalid merchant code')
|
|
136
|
+
if (p.kind === 'invite') {
|
|
137
|
+
serviceUrl(p.service)
|
|
138
|
+
if (typeof p.id !== 'string' || !/^[a-f0-9]{32}$/.test(p.id)) throw new Error('Invalid enrollment code')
|
|
139
|
+
} else {
|
|
140
|
+
key(p.cashier)
|
|
141
|
+
if (typeof p.invoice !== 'string' || !/^[a-f0-9]{32}$/.test(p.invoice)) throw new Error('Invalid invoice')
|
|
142
|
+
const session = decodeSession(p.session)
|
|
143
|
+
if (key(session.identityKey) !== key(p.merchant) || !session.amount || session.asset)
|
|
144
|
+
throw new Error('Merchant request has an invalid destination')
|
|
145
|
+
if (p.subtotal !== undefined || p.tip !== undefined) {
|
|
146
|
+
const tip = p.tip ?? 0
|
|
147
|
+
if (
|
|
148
|
+
!Number.isSafeInteger(p.subtotal) ||
|
|
149
|
+
p.subtotal! < 1 ||
|
|
150
|
+
!Number.isSafeInteger(tip) ||
|
|
151
|
+
tip < 0 ||
|
|
152
|
+
tip > session.amount ||
|
|
153
|
+
p.subtotal !== session.amount - tip
|
|
154
|
+
)
|
|
155
|
+
throw new Error('Merchant request has an invalid tip breakdown')
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return value
|
|
159
|
+
}
|
|
160
|
+
export async function decodePaymentRequest(text: string): Promise<Session> {
|
|
161
|
+
if (!text.startsWith(POS_PREFIX)) return decodeSession(text)
|
|
162
|
+
const { payload } = await decodePos(text)
|
|
163
|
+
if (payload.kind !== 'payment') throw new Error('This code enrolls a cashier; it is not a payment request')
|
|
164
|
+
return {
|
|
165
|
+
...decodeSession(payload.session),
|
|
166
|
+
merchantName: payload.name,
|
|
167
|
+
merchantChain: payload.chain,
|
|
168
|
+
merchantExpires: payload.expires,
|
|
169
|
+
merchantSubtotal: payload.subtotal,
|
|
170
|
+
merchantTip: payload.tip
|
|
171
|
+
}
|
|
172
|
+
}
|
|
@@ -5,8 +5,9 @@
|
|
|
5
5
|
* pushed its history to its own remote-backup account (the pseudonym derives from
|
|
6
6
|
* that profile's primary key). So probe profile 1, 2, … in turn: a profile with a
|
|
7
7
|
* backup on any network exists; the first index with none on every network ends
|
|
8
|
-
* the search. Found profiles are only registered here
|
|
9
|
-
*
|
|
8
|
+
* the search. Found profiles are only registered here, with the networks their
|
|
9
|
+
* backups are on — each network replays the first time the profile is built
|
|
10
|
+
* there, so an import never stalls on them.
|
|
10
11
|
*
|
|
11
12
|
* A profile removed on this device keeps its slot as a tombstone. Discovery
|
|
12
13
|
* leaves it exactly as it is: no probe, no registration, and it does not end the
|
|
@@ -28,8 +29,11 @@ export type ProfileProbe = (primaryKey: number[], chain: BackupChain) => Promise
|
|
|
28
29
|
export interface DiscoverProfilesDeps {
|
|
29
30
|
mnemonic: string
|
|
30
31
|
probe: ProfileProbe
|
|
31
|
-
/**
|
|
32
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Record profile `index` as existing on `network`, with backups on `chains` (which
|
|
34
|
+
* include `network`). Called in index order.
|
|
35
|
+
*/
|
|
36
|
+
register: (index: number, network: AppChain, chains: BackupChain[]) => Promise<void>
|
|
33
37
|
/** Indices to pass over (profiles removed on this device): not probed, not registered, not a stop. */
|
|
34
38
|
skip?: (index: number) => boolean
|
|
35
39
|
/** First index to probe. Default 1 — profile 0 is the wallet being imported. */
|
|
@@ -60,21 +64,26 @@ export async function discoverProfiles(deps: DiscoverProfilesDeps): Promise<numb
|
|
|
60
64
|
break
|
|
61
65
|
}
|
|
62
66
|
if (found.length === 0) break
|
|
63
|
-
await deps.register(n, found.includes('main') ? 'main' : found[0])
|
|
67
|
+
await deps.register(n, found.includes('main') ? 'main' : found[0], found)
|
|
64
68
|
registered++
|
|
65
69
|
}
|
|
66
70
|
return registered
|
|
67
71
|
}
|
|
68
72
|
|
|
69
73
|
/**
|
|
70
|
-
* Add a discovered profile to the store,
|
|
74
|
+
* Add a discovered profile to the store, with a restore pending on each network in
|
|
75
|
+
* `chains`. Idempotent:
|
|
71
76
|
* only the next free slot is appended, so an index the store already holds (live
|
|
72
77
|
* or removed) is left untouched and a second import of the same seed adds
|
|
73
78
|
* nothing. Slots are counted with tombstones, never without them.
|
|
74
79
|
*/
|
|
75
|
-
export async function registerDiscoveredProfile(
|
|
80
|
+
export async function registerDiscoveredProfile(
|
|
81
|
+
index: number,
|
|
82
|
+
network: AppChain,
|
|
83
|
+
chains: readonly AppChain[] = [network]
|
|
84
|
+
): Promise<void> {
|
|
76
85
|
if (index === getProfilesState().profiles.length) {
|
|
77
|
-
await appendProfile(network, {
|
|
86
|
+
await appendProfile(network, { restorePending: chains })
|
|
78
87
|
}
|
|
79
88
|
}
|
|
80
89
|
|
|
@@ -41,8 +41,18 @@ export interface ProfileRecord {
|
|
|
41
41
|
network: AppChain
|
|
42
42
|
/** Recorded after this profile's first successful build on this device. Public. */
|
|
43
43
|
identityKey?: string
|
|
44
|
-
/**
|
|
45
|
-
|
|
44
|
+
/**
|
|
45
|
+
* The networks whose remote backup this profile still has to replay. Set when the
|
|
46
|
+
* profile is imported, discovered or added; a network leaves the list once its
|
|
47
|
+
* restore has run (or found nothing). Each one restores the first time this
|
|
48
|
+
* device builds the profile there. A profile created on this device has none.
|
|
49
|
+
*/
|
|
50
|
+
restorePending?: AppChain[]
|
|
51
|
+
/**
|
|
52
|
+
* The network of this profile's last successful build on this device: where a
|
|
53
|
+
* cold start falls back to when its own network cannot finish its restore.
|
|
54
|
+
*/
|
|
55
|
+
lastBuiltNetwork?: AppChain
|
|
46
56
|
/**
|
|
47
57
|
* Private label, device-only (not backed up, never published). Trimmed, at most
|
|
48
58
|
* MAX_PROFILE_NAME_LENGTH characters; absent = the default `profile<n+1>`.
|
|
@@ -59,6 +69,13 @@ export interface ProfilesState {
|
|
|
59
69
|
|
|
60
70
|
const CHAINS: readonly AppChain[] = ['main', 'test', 'teratest']
|
|
61
71
|
|
|
72
|
+
/** Known networks only, once each, in CHAINS order; undefined when none is left. */
|
|
73
|
+
export function normalizeRestorePending(raw: unknown): AppChain[] | undefined {
|
|
74
|
+
if (!Array.isArray(raw)) return undefined
|
|
75
|
+
const chains = CHAINS.filter(c => raw.includes(c))
|
|
76
|
+
return chains.length > 0 ? chains : undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
62
79
|
export function defaultProfilesState(): ProfilesState {
|
|
63
80
|
return { active: 0, profiles: [{ index: 0, network: DEFAULT_CHAIN }] }
|
|
64
81
|
}
|
|
@@ -103,11 +120,17 @@ export function parseProfilesState(raw: string | null): ProfilesState {
|
|
|
103
120
|
if (!r || !Number.isInteger(r.index) || (r.index as number) < 0 || (r.index as number) >= MAX_PROFILES) continue
|
|
104
121
|
if (byIndex.has(r.index as number)) continue
|
|
105
122
|
const name = normalizeProfileName(r.name)
|
|
123
|
+
// A record written before restores were per network carries `needsRestore: true`
|
|
124
|
+
// for a profile that has not been built since it was found: every network waits.
|
|
125
|
+
const restorePending = normalizeRestorePending(
|
|
126
|
+
(r as { needsRestore?: unknown }).needsRestore === true ? CHAINS : r.restorePending
|
|
127
|
+
)
|
|
106
128
|
byIndex.set(r.index as number, {
|
|
107
129
|
index: r.index as number,
|
|
108
130
|
network: CHAINS.includes(r.network as AppChain) ? (r.network as AppChain) : DEFAULT_CHAIN,
|
|
109
131
|
...(typeof r.identityKey === 'string' ? { identityKey: r.identityKey } : {}),
|
|
110
|
-
...(
|
|
132
|
+
...(restorePending ? { restorePending } : {}),
|
|
133
|
+
...(CHAINS.includes(r.lastBuiltNetwork as AppChain) ? { lastBuiltNetwork: r.lastBuiltNetwork as AppChain } : {}),
|
|
111
134
|
...(name ? { name } : {}),
|
|
112
135
|
// Profile 0 anchors the seed (vault, discovery, the bare keys): it is never a tombstone.
|
|
113
136
|
...(r.deleted === true && r.index !== 0 ? { deleted: true as const } : {})
|
|
@@ -185,11 +208,12 @@ export async function setActiveProfile(n: number): Promise<void> {
|
|
|
185
208
|
/** Append the next profile (index = current count). Does not activate it. */
|
|
186
209
|
export async function appendProfile(
|
|
187
210
|
network: AppChain = DEFAULT_CHAIN,
|
|
188
|
-
opts: {
|
|
211
|
+
opts: { restorePending?: readonly AppChain[] } = {}
|
|
189
212
|
): Promise<ProfileRecord> {
|
|
190
213
|
const index = state.profiles.length
|
|
191
214
|
if (index >= MAX_PROFILES) throw new Error('Too many profiles')
|
|
192
|
-
const
|
|
215
|
+
const restorePending = normalizeRestorePending(opts.restorePending)
|
|
216
|
+
const record: ProfileRecord = { index, network, ...(restorePending ? { restorePending } : {}) }
|
|
193
217
|
publish({ ...state, profiles: [...state.profiles, record] })
|
|
194
218
|
await persist()
|
|
195
219
|
return record
|
|
@@ -205,17 +229,20 @@ export async function updateProfile(n: number, patch: Partial<Omit<ProfileRecord
|
|
|
205
229
|
if (n === state.active) throw new Error('The active profile cannot be removed')
|
|
206
230
|
}
|
|
207
231
|
const next: ProfileRecord = { ...current, ...patch, index: n }
|
|
208
|
-
|
|
232
|
+
const restorePending = normalizeRestorePending(next.restorePending)
|
|
233
|
+
if (restorePending) next.restorePending = restorePending
|
|
234
|
+
else delete next.restorePending
|
|
209
235
|
if (!next.deleted) delete next.deleted
|
|
210
236
|
const name = normalizeProfileName(next.name)
|
|
211
237
|
if (name) next.name = name
|
|
212
238
|
else delete next.name
|
|
213
239
|
if (
|
|
214
240
|
next.network === current.network &&
|
|
241
|
+
next.lastBuiltNetwork === current.lastBuiltNetwork &&
|
|
215
242
|
next.identityKey === current.identityKey &&
|
|
216
243
|
next.name === current.name &&
|
|
217
244
|
!!next.deleted === !!current.deleted &&
|
|
218
|
-
|
|
245
|
+
String(next.restorePending ?? '') === String(current.restorePending ?? '')
|
|
219
246
|
) {
|
|
220
247
|
return
|
|
221
248
|
}
|