@bsv/expo-wallet-toolbox 0.25.1 → 0.27.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.
Files changed (59) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/core/context/WalletContext.tsx +23 -2
  3. package/core/i18n/translations.tsx +245 -36
  4. package/core/identity/handleRegistry/classify.ts +74 -0
  5. package/core/identity/handleRegistry/client.ts +110 -16
  6. package/core/identity/handleRegistry/registration.ts +115 -17
  7. package/core/identity/handleRegistry/resolver.ts +77 -34
  8. package/core/identity/handleRegistry/rules.ts +4 -0
  9. package/core/index.ts +7 -0
  10. package/core/monitor/TaskDrainOutbox.ts +13 -3
  11. package/core/pay/paymail/address.ts +19 -0
  12. package/core/pay/paymail/client.ts +177 -0
  13. package/core/pay/paymail/networkCheck.ts +56 -0
  14. package/core/pay/rails/handle.ts +46 -9
  15. package/core/pay/rails/paymail.ts +542 -0
  16. package/core/peerpay/handleResendRequests.ts +6 -6
  17. package/core/peerpay/outbox.ts +185 -17
  18. package/core/peerpay/rebuildToken.ts +2 -2
  19. package/core/profiles/profileStore.ts +4 -1
  20. package/core/services/groupSpendingLimit.ts +26 -0
  21. package/core/services/signingPermissionPolicy.ts +14 -8
  22. package/core/services/vault/ceremony.ts +13 -0
  23. package/core/services/vault/ceremonyHost.ts +58 -0
  24. package/core/services/vault/failedVaultSpend.ts +40 -0
  25. package/core/services/vault/outputAuthority.ts +13 -6
  26. package/core/services/vault/transfers.ts +56 -12
  27. package/core/storage/encryptedDbImage.ts +11 -2
  28. package/core/theme/tokens.ts +26 -12
  29. package/package.json +2 -1
  30. package/ui/components/QRScanner.tsx +24 -22
  31. package/ui/components/pay/ImportedOutboxApproval.tsx +23 -2
  32. package/ui/components/pay/MessageBoxConfig.tsx +10 -16
  33. package/ui/components/pay/NearbyAdvisoryModal.tsx +6 -13
  34. package/ui/components/pay/NearbyFlow.tsx +72 -35
  35. package/ui/components/pay/PayForm.tsx +27 -19
  36. package/ui/components/pay/PaymentSuccessOverlay.tsx +8 -6
  37. package/ui/components/pay/UniversalSend.tsx +79 -5
  38. package/ui/components/ui/AlertCard.tsx +3 -2
  39. package/ui/components/ui/BalancedText.tsx +117 -0
  40. package/ui/components/ui/ErrorBoundary.tsx +31 -14
  41. package/ui/components/ui/GroupedList.tsx +28 -22
  42. package/ui/components/ui/ListRow.tsx +126 -35
  43. package/ui/components/ui/PermissionSheet.tsx +31 -24
  44. package/ui/components/ui/PresenceRow.tsx +15 -23
  45. package/ui/components/ui/Sheet.tsx +11 -17
  46. package/ui/components/ui/Toast.tsx +13 -17
  47. package/ui/components/vault/EnrollWizard.tsx +446 -196
  48. package/ui/components/vault/KeyChooser.tsx +7 -20
  49. package/ui/components/vault/VaultCeremonySheet.tsx +44 -36
  50. package/ui/components/wallet/AmountInput.tsx +11 -17
  51. package/ui/components/wallet/BiometricAdvisoryModal.tsx +13 -17
  52. package/ui/index.ts +1 -1
  53. package/ui/screens/TrustScreen.tsx +49 -61
  54. package/ui/screens/VaultScreen.tsx +99 -60
  55. package/ui/screens/VaultTransferScreen.tsx +34 -27
  56. package/ui/screens/WalletCheckScreen.tsx +25 -24
  57. package/ui/screens/WalletConfigScreen.tsx +66 -72
  58. package/ui/screens/WalletHomeScreen.tsx +104 -4
  59. package/ui/txStatus.ts +1 -1
@@ -31,10 +31,19 @@ export interface RegistryEndpoints {
31
31
  readonly pinned: boolean
32
32
  }
33
33
 
34
+ /** What discovery found for a domain, before anyone decides what it means. */
35
+ export type CapabilityDiscovery =
36
+ | { kind: 'ok'; domain: string; origin: string; capabilities: Readonly<Record<string, unknown>> }
37
+ | { kind: 'unsecured' } // SRV not authenticated, or SRV target not a public https origin
38
+ | { kind: 'none' } // answered, but not a usable capability document (HTTP 4xx, not an object)
39
+ | { kind: 'failed' } // DNS or HTTP gave no answer (throw, timeout, 5xx)
40
+
34
41
  export interface RegistryResolver {
35
42
  resolve(domain: string): Promise<RegistryEndpoints | null>
43
+ /** The raw capability map from the same cached, DNSSEC-checked discovery. */
44
+ discoverCapabilities(domain: string): Promise<CapabilityDiscovery>
36
45
  /** Test seam, and the way a "try again" control forgets a failed lookup. */
37
- clearCache(): void
46
+ clearCache(domain?: string): void
38
47
  }
39
48
 
40
49
  export const REGISTRY_TIMEOUT_MS = 8000
@@ -106,7 +115,12 @@ async function readBoundedJson(res: Response, fallback: () => Promise<unknown>,
106
115
  * single stalled body would wedge every later write for the life of the
107
116
  * process, with no toast and no timeout.
108
117
  */
109
- export async function fetchWithTimeout(fetchImpl: typeof fetch, url: string, init?: RequestInit): Promise<Response> {
118
+ export async function fetchWithTimeout(
119
+ fetchImpl: typeof fetch,
120
+ url: string,
121
+ init?: RequestInit,
122
+ timeoutMs: number = REGISTRY_TIMEOUT_MS
123
+ ): Promise<Response> {
110
124
  const controller = new AbortController()
111
125
  const caller = init?.signal ?? null
112
126
  const onAbort = () => controller.abort(caller?.reason)
@@ -114,7 +128,7 @@ export async function fetchWithTimeout(fetchImpl: typeof fetch, url: string, ini
114
128
  caller?.addEventListener('abort', onAbort)
115
129
  const release = () => caller?.removeEventListener('abort', onAbort)
116
130
  const startedAt = Date.now()
117
- const timer = setTimeout(() => controller.abort(), REGISTRY_TIMEOUT_MS)
131
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
118
132
  let response: Response
119
133
  try {
120
134
  response = await fetchImpl(url, { ...init, signal: controller.signal })
@@ -141,9 +155,9 @@ export async function fetchWithTimeout(fetchImpl: typeof fetch, url: string, ini
141
155
  bodyTimer = setTimeout(
142
156
  () => {
143
157
  controller.abort()
144
- reject(new Error(`handleRegistry: no body from ${url} after ${REGISTRY_TIMEOUT_MS}ms`))
158
+ reject(new Error(`handleRegistry: no body from ${url} after ${timeoutMs}ms`))
145
159
  },
146
- Math.max(0, REGISTRY_TIMEOUT_MS - (Date.now() - startedAt))
160
+ Math.max(0, timeoutMs - (Date.now() - startedAt))
147
161
  )
148
162
  void readBoundedJson(response, fallback, url).then(resolve, reject)
149
163
  })
@@ -202,6 +216,10 @@ function templateOf(value: unknown, placeholder: string): string | null {
202
216
  return isPublicHttpsUrl(value) ? value : null
203
217
  }
204
218
 
219
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
220
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
221
+ }
222
+
205
223
  export function createRegistryResolver(args: {
206
224
  pinned?: RegistryPin
207
225
  /** Trusted test transport; production must retain the native byte ceiling. */
@@ -214,7 +232,7 @@ export function createRegistryResolver(args: {
214
232
  const dohEndpoints = args.dohEndpoints ?? DOH_ENDPOINTS
215
233
  const pinnedDomain = args.pinned?.domain.trim().toLowerCase() ?? ''
216
234
  const pinnedOrigin = trimTrailingSlashes(args.pinned?.url.trim() ?? '')
217
- const cache = new Map<string, { at: number; value: RegistryEndpoints | null }>()
235
+ const cache = new Map<string, { at: number; value: CapabilityDiscovery }>()
218
236
 
219
237
  const pinnedEndpoints: RegistryEndpoints | null =
220
238
  pinnedDomain !== '' && pinnedOrigin !== ''
@@ -235,7 +253,7 @@ export function createRegistryResolver(args: {
235
253
  * DNSSEC failure into `https://<domain>`. It is a failure of that resolver
236
254
  * instead, and the next one gets the question.
237
255
  */
238
- async function lookupSrv(domain: string): Promise<{ target: string; port: number } | null> {
256
+ async function lookupSrv(domain: string): Promise<{ target: string; port: number } | 'unsecured' | null> {
239
257
  const fallback = { target: domain, port: 443 }
240
258
  for (const endpoint of dohEndpoints) {
241
259
  let body: DohResponse
@@ -255,58 +273,83 @@ export function createRegistryResolver(args: {
255
273
  if (body.Status === NXDOMAIN || records.length === 0) return fallback
256
274
  records.sort((a, b) => a.priority - b.priority || b.weight - a.weight)
257
275
  const best = records[0]
258
- if (body.AD !== true && best.target !== domain) return null
276
+ if (body.AD !== true && best.target !== domain) return 'unsecured'
259
277
  return { target: best.target, port: best.port }
260
278
  }
261
279
  return null
262
280
  }
263
281
 
264
- async function discover(domain: string): Promise<RegistryEndpoints | null> {
282
+ async function discover(domain: string): Promise<CapabilityDiscovery> {
265
283
  const host = await lookupSrv(domain)
266
- if (!host) return null
284
+ if (host === null) return { kind: 'failed' }
285
+ if (host === 'unsecured') return { kind: 'unsecured' }
267
286
  const origin = `https://${host.target}${host.port === 443 ? '' : `:${host.port}`}`
268
287
  // An SRV target is ordinarily just a hostname, but nothing stops one from
269
288
  // being an IP literal, `localhost`, or a `.local` name — and DNSSEC only
270
289
  // authenticates that the domain's own zone said so, not that it is a
271
290
  // sensible destination (XR-073 / SEC2-057, SEC2-076).
272
- if (!isPublicHttpsUrl(`${origin}/`)) return null
273
- let capabilities: Record<string, unknown>
291
+ if (!isPublicHttpsUrl(`${origin}/`)) return { kind: 'unsecured' }
292
+ let body: unknown
274
293
  try {
275
294
  const res = await fetchWithTimeout(fetchImpl, `${origin}/.well-known/bsvalias`, {
276
295
  headers: { accept: 'application/json' }
277
296
  })
278
- if (!res.ok) return null
279
- const body = (await res.json()) as { capabilities?: Record<string, unknown> }
280
- capabilities = body?.capabilities ?? {}
297
+ if (!res.ok) return res.status >= 500 ? { kind: 'failed' } : { kind: 'none' }
298
+ body = await res.json()
281
299
  } catch {
282
- return null
300
+ return { kind: 'failed' }
283
301
  }
284
- const searchTemplate = templateOf(capabilities[BRFC_LOOKUP], '{query}')
285
- const reverseTemplate = templateOf(capabilities[BRFC_REVERSE_LOOKUP], '{pubkey}')
286
- if (!searchTemplate || !reverseTemplate) return null
287
- return {
288
- domain,
289
- search: query => searchTemplate.replace('{query}', encodeURIComponent(query)),
290
- reverse: pubkey => reverseTemplate.replace('{pubkey}', encodeURIComponent(pubkey)),
291
- pinned: false
302
+ if (!isPlainObject(body)) return { kind: 'none' }
303
+ const capabilities = body.capabilities ?? {}
304
+ if (!isPlainObject(capabilities)) return { kind: 'none' }
305
+ return { kind: 'ok', domain, origin, capabilities }
306
+ }
307
+
308
+ async function discoverCapabilities(rawDomain: string): Promise<CapabilityDiscovery> {
309
+ const domain = rawDomain.trim().toLowerCase()
310
+ if (pinnedEndpoints && domain === pinnedDomain) {
311
+ return {
312
+ kind: 'ok',
313
+ domain,
314
+ origin: pinnedOrigin,
315
+ capabilities: {
316
+ [BRFC_LOOKUP]: `${pinnedOrigin}/api/handle/{query}`,
317
+ [BRFC_REVERSE_LOOKUP]: `${pinnedOrigin}/api/identityKey/{pubkey}`
318
+ }
319
+ }
292
320
  }
321
+ // Ahead of the cache, not inside discovery: a half-typed domain is not an
322
+ // answer, and the cache has no eviction — search resolves as the user types.
323
+ if (!looksLikeDomain(domain)) return { kind: 'none' }
324
+ const hit = cache.get(domain)
325
+ if (hit && now() - hit.at < (hit.value.kind === 'ok' ? RESOLVER_SUCCESS_TTL_MS : RESOLVER_FAILURE_TTL_MS)) {
326
+ return hit.value
327
+ }
328
+ const value = await discover(domain)
329
+ cache.set(domain, { at: now(), value })
330
+ return value
293
331
  }
294
332
 
295
333
  return {
296
334
  async resolve(rawDomain) {
297
335
  const domain = rawDomain.trim().toLowerCase()
298
336
  if (pinnedEndpoints && domain === pinnedDomain) return pinnedEndpoints
299
- // Ahead of the cache, not inside discovery: a half-typed domain is not an
300
- // answer, and the cache has no eviction — search resolves as the user types.
301
- if (!looksLikeDomain(domain)) return null
302
- const hit = cache.get(domain)
303
- if (hit && now() - hit.at < (hit.value ? RESOLVER_SUCCESS_TTL_MS : RESOLVER_FAILURE_TTL_MS)) return hit.value
304
- const value = await discover(domain)
305
- cache.set(domain, { at: now(), value })
306
- return value
337
+ const found = await discoverCapabilities(domain)
338
+ if (found.kind !== 'ok') return null
339
+ const searchTemplate = templateOf(found.capabilities[BRFC_LOOKUP], '{query}')
340
+ const reverseTemplate = templateOf(found.capabilities[BRFC_REVERSE_LOOKUP], '{pubkey}')
341
+ if (!searchTemplate || !reverseTemplate) return null
342
+ return {
343
+ domain,
344
+ search: query => searchTemplate.replace('{query}', encodeURIComponent(query)),
345
+ reverse: pubkey => reverseTemplate.replace('{pubkey}', encodeURIComponent(pubkey)),
346
+ pinned: false
347
+ }
307
348
  },
308
- clearCache() {
309
- cache.clear()
349
+ discoverCapabilities,
350
+ clearCache(domain) {
351
+ if (domain === undefined) cache.clear()
352
+ else cache.delete(domain.trim().toLowerCase())
310
353
  }
311
354
  }
312
355
  }
@@ -20,6 +20,10 @@ export const PROFILE_CERT_TYPE = 'SbatVXXssDW3AO0J9bxIljkHGbPBGCVAXg94gXFf0cE='
20
20
  export const BRFC_LOOKUP = '0ace65da5987'
21
21
  /** BRFC id of the `public profile reverse lookup` capability — key → profile. */
22
22
  export const BRFC_REVERSE_LOOKUP = '43dcf83ddc5f'
23
+ /** BRFC id of the paymail P2P payment destination capability. */
24
+ export const BRFC_P2P_DESTINATION = '2a40af698840'
25
+ /** BRFC id of the paymail P2P receive-BEEF capability. */
26
+ export const BRFC_P2P_RECEIVE_BEEF = '5c55a7fdb7bb'
23
27
  /** There is no on-chain revocation: a profile is replaced or tombstoned. */
24
28
  export const ZERO_OUTPOINT = `${'0'.repeat(64)}.0`
25
29
 
package/core/index.ts CHANGED
@@ -317,6 +317,13 @@ export * from './pay/rails/address'
317
317
  export * from './pay/rails/sweep'
318
318
  export * from './pay/rails/handle'
319
319
  export * from './pay/rails/direct'
320
+ export * from './pay/rails/paymail'
321
+ export * from './pay/paymail/client'
322
+ export * from './pay/paymail/networkCheck'
323
+ export { classifyPaymailDomain, classifyPaymailDomainDetailed } from './identity/handleRegistry/classify'
324
+ export type { PaymailClass, PaymailClassification, UnsupportedReason } from './identity/handleRegistry/classify'
325
+ export { createRegistryResolver } from './identity/handleRegistry/resolver'
326
+ export type { RegistryResolver, CapabilityDiscovery } from './identity/handleRegistry/resolver'
320
327
  // nearby.ts is a pure re-export barrel over localpay/* (already exported above)
321
328
  // and @bsv/air-gap; only its genuinely new names are re-exported here by hand —
322
329
  // a blanket `export *` would collide (TS2308) with the localpay/offline exports
@@ -21,15 +21,25 @@ export interface DrainOutboxResult {
21
21
  stopped?: boolean
22
22
  }
23
23
 
24
- /** Retry unsent entries in order; the first throw aborts the rest. */
24
+ /**
25
+ * Retry unsent entries in order; the first throw aborts the rest. A throw from
26
+ * an entry that `isolate` accepts (a paymail row: its receiver is a third
27
+ * party that can fail for good) is skipped instead, so it cannot starve the
28
+ * rows behind it. Such a row stays counted as remaining, so the pass backs off.
29
+ */
25
30
  export async function drainUnsentEntries(args: {
26
31
  entries: OutboxEntry[]
27
32
  retry: (entry: OutboxEntry) => Promise<void>
33
+ isolate?: (entry: OutboxEntry) => boolean
28
34
  }): Promise<DrainOutboxResult> {
29
35
  let retried = 0
30
36
  for (const entry of args.entries) {
31
- await args.retry(entry)
32
- retried++
37
+ try {
38
+ await args.retry(entry)
39
+ retried++
40
+ } catch (e) {
41
+ if (!args.isolate?.(entry)) throw e
42
+ }
33
43
  }
34
44
  return { retried, remaining: args.entries.length - retried, stopped: false }
35
45
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Paymail address rules shared by the send path and the outbox import check.
3
+ *
4
+ * The alias follows the bsvalias grammar (letters, digits, `-`, `_`, `.`), so
5
+ * it may start with `_`, `.` or `-`. `+` is accepted after the first character
6
+ * for sub-addressing. `/`, `?`, `#`, whitespace and `@` are never allowed; the
7
+ * alias is also URL-encoded when a capability template is filled.
8
+ */
9
+ import { looksLikeDomain } from '../../identity/handleRegistry/rules'
10
+
11
+ export const ALIAS_FORMAT = /^[a-z0-9._-][a-z0-9._+-]{0,63}$/
12
+
13
+ /** The lowercased alias and domain, or null when this is not a paymail. */
14
+ export function parsePaymail(paymail: string): { alias: string; domain: string } | null {
15
+ if (typeof paymail !== 'string') return null
16
+ const parts = paymail.trim().toLowerCase().split('@')
17
+ if (parts.length !== 2 || !ALIAS_FORMAT.test(parts[0]) || !looksLikeDomain(parts[1])) return null
18
+ return { alias: parts[0], domain: parts[1] }
19
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * A small client for legacy paymail (HandCash and similar): ask a receiver for
3
+ * a P2P payment destination, then post it the transaction as plain BEEF.
4
+ *
5
+ * Own code on the toolbox's bounded fetch, not `@bsv/paymail`: that package's
6
+ * main bundle drags in an Express router and `joi`, and its own discovery
7
+ * would skip our AD-flag and public-URL checks. Every URL here comes from the
8
+ * resolver's checked discovery and is checked again once it is filled in.
9
+ */
10
+ import { isLegacyCapabilityUrl } from '../../identity/handleRegistry/classify'
11
+ import {
12
+ REGISTRY_MAX_BODY_BYTES,
13
+ fetchWithTimeout,
14
+ type RegistryResolver
15
+ } from '../../identity/handleRegistry/resolver'
16
+ import { BRFC_P2P_DESTINATION, BRFC_P2P_RECEIVE_BEEF } from '../../identity/handleRegistry/rules'
17
+ import { parsePaymail } from './address'
18
+ import { isPublicHttpsUrl } from '../../net/publicDestination'
19
+ import { createBoundedNativeFetch } from '../../network/boundedFetch'
20
+
21
+ export const PAYMAIL_TIMEOUT_MS = 15_000
22
+ export const MAX_DESTINATION_OUTPUTS = 10
23
+
24
+ const MAX_SCRIPT_HEX_CHARS = 10_000
25
+ const MAX_REFERENCE_CHARS = 4_096
26
+ const PLACEHOLDERS = ['{alias}', '{domain.tld}'] as const
27
+ const MAX_ERROR_MESSAGE_CHARS = 200
28
+ const HEX_FORMAT = /^(?:[0-9a-f]{2})+$/i
29
+ const TXID_FORMAT = /^[0-9a-f]{64}$/i
30
+
31
+ export interface P2pOutput {
32
+ script: string
33
+ satoshis: number
34
+ }
35
+ export interface P2pDestination {
36
+ outputs: P2pOutput[]
37
+ reference: string
38
+ beefEndpoint: string
39
+ }
40
+ export type DestinationResult =
41
+ | { kind: 'ok'; destination: P2pDestination }
42
+ | {
43
+ kind: 'failed'
44
+ reason: 'invalid_paymail' | 'unsupported' | 'unreachable' | 'refused' | 'invalid_destination'
45
+ message: string
46
+ }
47
+ export type PostBeefResult =
48
+ | { kind: 'accepted'; txid: string; note: string }
49
+ | { kind: 'http'; status: number; message: string }
50
+ | { kind: 'network'; message: string }
51
+
52
+ export interface LegacyPaymailClient {
53
+ getP2pDestination(paymail: string, satoshis: number): Promise<DestinationResult>
54
+ postBeef(args: { endpoint: string; beefHex: string; reference: string }): Promise<PostBeefResult>
55
+ }
56
+
57
+ type Failed = Extract<DestinationResult, { kind: 'failed' }>
58
+ const fail = (reason: Failed['reason'], message: string): Failed => ({ kind: 'failed', reason, message })
59
+
60
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
61
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
62
+ }
63
+
64
+ /** The body as JSON, or the sentinel when it is not JSON. Never throws. */
65
+ async function readJson(res: Response): Promise<{ ok: true; body: unknown } | { ok: false }> {
66
+ try {
67
+ return { ok: true, body: await res.json() }
68
+ } catch {
69
+ return { ok: false }
70
+ }
71
+ }
72
+
73
+ function errorMessage(parsed: { ok: true; body: unknown } | { ok: false }, status: number): string {
74
+ if (parsed.ok && isPlainObject(parsed.body) && typeof parsed.body.message === 'string') {
75
+ // The host's text is untrusted: no control characters, a short length.
76
+ // eslint-disable-next-line no-control-regex
77
+ const clean = parsed.body.message.slice(0, 2_000).replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ').trim()
78
+ if (clean) return clean.slice(0, MAX_ERROR_MESSAGE_CHARS)
79
+ }
80
+ return `HTTP ${status}`
81
+ }
82
+
83
+ function fill(template: string, alias: string, domain: string): string {
84
+ return template
85
+ .split('{alias}')
86
+ .join(encodeURIComponent(alias))
87
+ .split('{domain.tld}')
88
+ .join(encodeURIComponent(domain))
89
+ }
90
+
91
+ function parseDestinationBody(body: unknown, satoshis: number): { outputs: P2pOutput[]; reference: string } | null {
92
+ if (!isPlainObject(body)) return null
93
+ const { outputs, reference } = body
94
+ if (!Array.isArray(outputs) || outputs.length < 1 || outputs.length > MAX_DESTINATION_OUTPUTS) return null
95
+ if (typeof reference !== 'string' || reference === '' || reference.length > MAX_REFERENCE_CHARS) return null
96
+ const parsed: P2pOutput[] = []
97
+ let sum = 0
98
+ for (const o of outputs) {
99
+ if (!isPlainObject(o)) return null
100
+ const { script, satoshis: amount } = o
101
+ if (typeof script !== 'string' || script.length > MAX_SCRIPT_HEX_CHARS || !HEX_FORMAT.test(script)) return null
102
+ if (typeof amount !== 'number' || !Number.isSafeInteger(amount) || amount <= 0) return null
103
+ sum += amount
104
+ parsed.push({ script, satoshis: amount })
105
+ }
106
+ if (sum !== satoshis) return null
107
+ return { outputs: parsed, reference }
108
+ }
109
+
110
+ export function createLegacyPaymailClient(args: {
111
+ resolver: Pick<RegistryResolver, 'discoverCapabilities'>
112
+ fetchImpl?: typeof fetch
113
+ }): LegacyPaymailClient {
114
+ const fetchImpl = args.fetchImpl ?? createBoundedNativeFetch(REGISTRY_MAX_BODY_BYTES)
115
+ const post = (url: string, body: unknown) =>
116
+ fetchWithTimeout(
117
+ fetchImpl,
118
+ url,
119
+ {
120
+ method: 'POST',
121
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
122
+ body: JSON.stringify(body)
123
+ },
124
+ PAYMAIL_TIMEOUT_MS
125
+ )
126
+
127
+ return {
128
+ async getP2pDestination(paymail, satoshis) {
129
+ const parsedAddress = parsePaymail(paymail)
130
+ if (!parsedAddress) return fail('invalid_paymail', 'Not a valid paymail.')
131
+ const { alias, domain } = parsedAddress
132
+ const found = await args.resolver.discoverCapabilities(domain)
133
+ if (found.kind === 'failed') return fail('unreachable', 'Could not reach that paymail host.')
134
+ if (found.kind !== 'ok') return fail('unsupported', 'That paymail host does not take this kind of payment.')
135
+ const destTemplate = found.capabilities[BRFC_P2P_DESTINATION]
136
+ const beefTemplate = found.capabilities[BRFC_P2P_RECEIVE_BEEF]
137
+ if (!isLegacyCapabilityUrl(destTemplate, PLACEHOLDERS) || !isLegacyCapabilityUrl(beefTemplate, PLACEHOLDERS)) {
138
+ return fail('unsupported', 'That paymail host does not take this kind of payment.')
139
+ }
140
+ const destUrl = fill(destTemplate, alias, domain)
141
+ const beefEndpoint = fill(beefTemplate, alias, domain)
142
+ if (!isPublicHttpsUrl(destUrl) || !isPublicHttpsUrl(beefEndpoint)) {
143
+ return fail('unsupported', 'That paymail host does not take this kind of payment.')
144
+ }
145
+ let res: Response
146
+ try {
147
+ res = await post(destUrl, { satoshis })
148
+ } catch {
149
+ return fail('unreachable', 'Could not reach that paymail host.')
150
+ }
151
+ const parsed = await readJson(res)
152
+ if (!res.ok) return fail('refused', errorMessage(parsed, res.status))
153
+ if (!parsed.ok) return fail('invalid_destination', 'The paymail host sent an unreadable destination.')
154
+ const dest = parseDestinationBody(parsed.body, satoshis)
155
+ if (!dest) return fail('invalid_destination', 'The paymail host sent a destination that does not check out.')
156
+ return { kind: 'ok', destination: { ...dest, beefEndpoint } }
157
+ },
158
+
159
+ async postBeef({ endpoint, beefHex, reference }) {
160
+ if (!isPublicHttpsUrl(endpoint)) return { kind: 'network', message: 'endpoint_not_public' }
161
+ let res: Response
162
+ try {
163
+ res = await post(endpoint, { beef: beefHex, reference })
164
+ } catch (e) {
165
+ return { kind: 'network', message: e instanceof Error ? e.message : String(e) }
166
+ }
167
+ const parsed = await readJson(res)
168
+ if (!res.ok) return { kind: 'http', status: res.status, message: errorMessage(parsed, res.status) }
169
+ // The receiver answered 2xx, so it may well hold the payment: anything we
170
+ // cannot read is an unknown result, never a refusal.
171
+ if (!parsed.ok || !isPlainObject(parsed.body)) return { kind: 'network', message: 'unreadable_receipt' }
172
+ const { txid, note } = parsed.body
173
+ if (typeof txid !== 'string' || !TXID_FORMAT.test(txid)) return { kind: 'network', message: 'unreadable_receipt' }
174
+ return { kind: 'accepted', txid, note: typeof note === 'string' ? note : '' }
175
+ }
176
+ }
177
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Ask the network (never Arcade) whether it knows a txid. Used by the paymail
3
+ * rail to decide if a receiver that answered with an error still got the
4
+ * payment. Every call has a deadline so a hung status service cannot stall the
5
+ * send, the retry or the outbox drain.
6
+ */
7
+
8
+ export type StatusFn = (
9
+ txids: string[]
10
+ ) => Promise<{ status?: string; results?: { txid: string; status: string }[] }>
11
+
12
+ export type NetworkVerdict = 'known' | 'unknown' | 'error'
13
+
14
+ export const NETWORK_CALL_DEADLINE_MS = 10_000
15
+
16
+ /** Reject with `Error('deadline')` if `work` has not settled after `ms`. */
17
+ export function withDeadline<T>(work: Promise<T>, ms: number = NETWORK_CALL_DEADLINE_MS): Promise<T> {
18
+ return new Promise<T>((resolve, reject) => {
19
+ const timer = setTimeout(() => reject(new Error('deadline')), ms)
20
+ work.then(
21
+ v => {
22
+ clearTimeout(timer)
23
+ resolve(v)
24
+ },
25
+ e => {
26
+ clearTimeout(timer)
27
+ reject(e)
28
+ }
29
+ )
30
+ })
31
+ }
32
+
33
+ /** Status function backed by the storage's services (same source as `verifyDeclinedAborts`). */
34
+ export function statusFnFromStorage(storage: { getServices(): unknown }): StatusFn {
35
+ return async txids => {
36
+ const services = storage.getServices() as { getStatusForTxids?: StatusFn }
37
+ if (typeof services?.getStatusForTxids !== 'function') throw new Error('status_unavailable')
38
+ return services.getStatusForTxids(txids)
39
+ }
40
+ }
41
+
42
+ export async function networkKnowsTxid(
43
+ getStatusForTxids: StatusFn,
44
+ txid: string,
45
+ deadlineMs: number = NETWORK_CALL_DEADLINE_MS
46
+ ): Promise<NetworkVerdict> {
47
+ try {
48
+ const res = await withDeadline(Promise.resolve().then(() => getStatusForTxids([txid])), deadlineMs)
49
+ if (res == null || res.status === 'error' || !Array.isArray(res.results)) return 'error'
50
+ const want = txid.toLowerCase()
51
+ const row = res.results.find(r => typeof r?.txid === 'string' && r.txid.toLowerCase() === want)
52
+ return row != null && (row.status === 'mined' || row.status === 'known') ? 'known' : 'unknown'
53
+ } catch {
54
+ return 'error'
55
+ }
56
+ }
@@ -18,7 +18,8 @@ import {
18
18
  removeOutboxEntry,
19
19
  saveOutboxEntry,
20
20
  updateOutboxEntry,
21
- type OutboxEntry
21
+ type OutboxEntry,
22
+ type PeerPayOutboxEntry
22
23
  } from '../../peerpay/outbox'
23
24
  import type { CreditFailureKind } from '../creditErrors'
24
25
  import { abbreviateKey } from '../counterparty'
@@ -532,6 +533,34 @@ export async function broadcastNoSend(
532
533
  if (!released) throw new Error('broadcast_not_confirmed')
533
534
  }
534
535
 
536
+ const ACTION_PAGE_SIZE = 1000
537
+ const ACTION_MAX_PAGES = 10
538
+
539
+ /**
540
+ * Find the action for `txid` among the actions with `label`, paging with
541
+ * `offset` until a short page. `complete` is false when the search ended
542
+ * without proof of absence (it hit the page maximum): the caller must then
543
+ * treat a missing match as unknown, never as "gone".
544
+ */
545
+ export async function findActionByTxid(
546
+ wallet: Pick<HandleRailWallet, 'listActions'>,
547
+ adminOriginator: string,
548
+ txid: string,
549
+ label: string
550
+ ): Promise<{ match?: { txid?: string; reference?: string; status?: string }; complete: boolean }> {
551
+ for (let page = 0; page < ACTION_MAX_PAGES; page++) {
552
+ const args =
553
+ page === 0
554
+ ? { labels: [label], limit: ACTION_PAGE_SIZE }
555
+ : { labels: [label], limit: ACTION_PAGE_SIZE, offset: page * ACTION_PAGE_SIZE }
556
+ const { actions } = await wallet.listActions(args, adminOriginator)
557
+ const match = actions.find(a => a.txid === txid)
558
+ if (match) return { match: match as never, complete: true }
559
+ if (actions.length < ACTION_PAGE_SIZE) return { complete: true }
560
+ }
561
+ return { complete: false }
562
+ }
563
+
535
564
  /**
536
565
  * Abort a PeerPay noSend by recovering its reference from listActions.
537
566
  *
@@ -545,15 +574,15 @@ export async function broadcastNoSend(
545
574
  * the result keeps that row (and the reservation) in place until an abort
546
575
  * actually lands.
547
576
  */
548
- export async function abortPeerPayNosend(
577
+ export async function abortNosendByTxid(
549
578
  wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>,
550
579
  adminOriginator: string,
551
- txid: string
580
+ txid: string,
581
+ label: string
552
582
  ): Promise<boolean> {
553
583
  // createAction returns no reference for a completed noSend action, so the
554
584
  // abort handle is recovered from listActions by txid.
555
- const { actions } = await wallet.listActions({ labels: ['peerpay'], limit: 1000 }, adminOriginator)
556
- const match = actions.find(a => a.txid === txid)
585
+ const { match } = await findActionByTxid(wallet, adminOriginator, txid, label)
557
586
  if (!match?.reference) return false
558
587
  const result = (await wallet.abortAction({ reference: match.reference }, adminOriginator)) as
559
588
  | { aborted?: boolean }
@@ -561,6 +590,14 @@ export async function abortPeerPayNosend(
561
590
  return result?.aborted !== false
562
591
  }
563
592
 
593
+ export async function abortPeerPayNosend(
594
+ wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>,
595
+ adminOriginator: string,
596
+ txid: string
597
+ ): Promise<boolean> {
598
+ return abortNosendByTxid(wallet, adminOriginator, txid, 'peerpay')
599
+ }
600
+
564
601
  /**
565
602
  * Pay a handle. Five steps, in this order:
566
603
  * 1 mint the token with noSend (nothing hits the network yet)
@@ -643,7 +680,7 @@ export async function sendViaHandle(args: {
643
680
  /** A payment minted with noSend: signed, saved by the caller, not yet broadcast. */
644
681
  export interface MintedPeerPayToken {
645
682
  txid: string
646
- token: OutboxEntry['token']
683
+ token: PeerPayOutboxEntry['token']
647
684
  /** What output 0 pays the recipient, read off the transaction (covers send-max). */
648
685
  satoshis: number
649
686
  }
@@ -757,7 +794,7 @@ export async function cancelOutboxPayment(args: {
757
794
  wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>
758
795
  adminOriginator: string
759
796
  storage: StorageLike
760
- entry: Pick<OutboxEntry, 'id' | 'txid' | 'delivered' | 'delivering' | 'recipient' | 'recipientHost'>
797
+ entry: Pick<PeerPayOutboxEntry, 'id' | 'txid' | 'delivered' | 'delivering' | 'recipient' | 'recipientHost'>
761
798
  client?: Pick<PeerPayClient, 'sendMessage'>
762
799
  mode?: 'undelivered' | 'abandon'
763
800
  }): Promise<{ aborted: boolean; needsAbandon?: boolean }> {
@@ -822,7 +859,7 @@ export function isAbortSafe(
822
859
  action: { labels?: string[]; txid?: string },
823
860
  outboxEntries: Array<Pick<OutboxEntry, 'txid' | 'delivered' | 'delivering'>>
824
861
  ): { aborted: boolean; needsAbandon?: boolean } {
825
- if (!action.labels?.includes('peerpay')) return { aborted: true }
862
+ if (!action.labels?.includes('peerpay') && !action.labels?.includes('paymail')) return { aborted: true }
826
863
  const stored = action.txid != null ? outboxEntries.find(e => e.txid === action.txid) : undefined
827
864
  if (stored == null || stored.delivered === true || stored.delivering === true) {
828
865
  return { aborted: false, needsAbandon: true }
@@ -920,7 +957,7 @@ export async function retryDelivery(args: {
920
957
  adminOriginator: string
921
958
  client: Pick<PeerPayClient, 'sendMessage'>
922
959
  storage: StorageLike
923
- entry: OutboxEntry
960
+ entry: PeerPayOutboxEntry
924
961
  }): Promise<void> {
925
962
  const { wallet, adminOriginator, client, storage, entry } = args
926
963
  if (entry.status !== 'unsent') return