@bsv/expo-wallet-toolbox 0.26.0 → 0.28.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.
@@ -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
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The wallet label for a payment's paymail address. It lives in its own file so
3
+ * `rails/handle.ts` can use it without importing `rails/paymail.ts`, which
4
+ * imports `handle.ts`.
5
+ */
6
+ export const PAYMAIL_LABEL_PREFIX = 'paymail:'
7
+
8
+ const MAX_ADDRESS_LENGTH = 254
9
+ const ADDRESS = /^[a-z0-9._+-]{1,64}@[a-z0-9.-]{1,190}\.[a-z]{2,}$/
10
+ // eslint-disable-next-line no-control-regex
11
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/
12
+
13
+ /**
14
+ * `paymail:<lower-case address>` for a valid address, else `undefined`. The
15
+ * value comes from a sender's token, so it is untrusted: anything that is not a
16
+ * short plain address gives no label.
17
+ */
18
+ export function incomingPaymailLabel(value: unknown): string | undefined {
19
+ if (typeof value !== 'string' || value.length > MAX_ADDRESS_LENGTH) return undefined
20
+ if (CONTROL.test(value)) return undefined
21
+ const address = value.toLowerCase()
22
+ if (!ADDRESS.test(address)) return undefined
23
+ return `${PAYMAIL_LABEL_PREFIX}${address}`
24
+ }
@@ -18,10 +18,12 @@ 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'
26
+ import { incomingPaymailLabel } from '../paymailLabel'
25
27
  import { cleanPeerPayNote } from '../../parsePeerPayURI'
26
28
  import { isDuplicateMessageError, sendControlMessage, type ResendReason } from '../../peerpay/control'
27
29
  import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
@@ -199,7 +201,7 @@ export type CreditOutcome = 'credited' | 'duplicate'
199
201
  * The recorded description is the note the sender attached to the token or,
200
202
  * failing that, the sender's abbreviated identity key: the same default the
201
203
  * sending wallet wrote for the recipient, so both sides name one payment the
202
- * same way. The sender is not added to the labels; the activity list recovers
204
+ * same way. The sender's key is not added to the labels; the activity list recovers
203
205
  * the counterparty from the output's senderIdentityKey instead.
204
206
  *
205
207
  * `repairBeef` is the second chance. The token's AtomicBEEF was minted at send
@@ -230,6 +232,10 @@ export async function internalizeIncoming(
230
232
 
231
233
  const description = creditDescription((payment.token as { note?: unknown }).note, payment.sender)
232
234
 
235
+ // A legacy sender's address, when the token carries a valid one. Never the
236
+ // bare `paymail` label: that one marks an outbox-protected outgoing action.
237
+ const paymailLabel = incomingPaymailLabel((payment.token as { paymail?: unknown }).paymail)
238
+
233
239
  const argsFor = (tx: number[] | typeof payment.token.transaction) => ({
234
240
  tx,
235
241
  outputs: [
@@ -243,7 +249,7 @@ export async function internalizeIncoming(
243
249
  protocol: 'wallet payment'
244
250
  }
245
251
  ],
246
- labels: ['peerpay'],
252
+ labels: ['peerpay', ...(paymailLabel ? [paymailLabel] : [])],
247
253
  description
248
254
  })
249
255
 
@@ -532,6 +538,34 @@ export async function broadcastNoSend(
532
538
  if (!released) throw new Error('broadcast_not_confirmed')
533
539
  }
534
540
 
541
+ const ACTION_PAGE_SIZE = 1000
542
+ const ACTION_MAX_PAGES = 10
543
+
544
+ /**
545
+ * Find the action for `txid` among the actions with `label`, paging with
546
+ * `offset` until a short page. `complete` is false when the search ended
547
+ * without proof of absence (it hit the page maximum): the caller must then
548
+ * treat a missing match as unknown, never as "gone".
549
+ */
550
+ export async function findActionByTxid(
551
+ wallet: Pick<HandleRailWallet, 'listActions'>,
552
+ adminOriginator: string,
553
+ txid: string,
554
+ label: string
555
+ ): Promise<{ match?: { txid?: string; reference?: string; status?: string }; complete: boolean }> {
556
+ for (let page = 0; page < ACTION_MAX_PAGES; page++) {
557
+ const args =
558
+ page === 0
559
+ ? { labels: [label], limit: ACTION_PAGE_SIZE }
560
+ : { labels: [label], limit: ACTION_PAGE_SIZE, offset: page * ACTION_PAGE_SIZE }
561
+ const { actions } = await wallet.listActions(args, adminOriginator)
562
+ const match = actions.find(a => a.txid === txid)
563
+ if (match) return { match: match as never, complete: true }
564
+ if (actions.length < ACTION_PAGE_SIZE) return { complete: true }
565
+ }
566
+ return { complete: false }
567
+ }
568
+
535
569
  /**
536
570
  * Abort a PeerPay noSend by recovering its reference from listActions.
537
571
  *
@@ -545,15 +579,15 @@ export async function broadcastNoSend(
545
579
  * the result keeps that row (and the reservation) in place until an abort
546
580
  * actually lands.
547
581
  */
548
- export async function abortPeerPayNosend(
582
+ export async function abortNosendByTxid(
549
583
  wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>,
550
584
  adminOriginator: string,
551
- txid: string
585
+ txid: string,
586
+ label: string
552
587
  ): Promise<boolean> {
553
588
  // createAction returns no reference for a completed noSend action, so the
554
589
  // 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)
590
+ const { match } = await findActionByTxid(wallet, adminOriginator, txid, label)
557
591
  if (!match?.reference) return false
558
592
  const result = (await wallet.abortAction({ reference: match.reference }, adminOriginator)) as
559
593
  | { aborted?: boolean }
@@ -561,6 +595,14 @@ export async function abortPeerPayNosend(
561
595
  return result?.aborted !== false
562
596
  }
563
597
 
598
+ export async function abortPeerPayNosend(
599
+ wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>,
600
+ adminOriginator: string,
601
+ txid: string
602
+ ): Promise<boolean> {
603
+ return abortNosendByTxid(wallet, adminOriginator, txid, 'peerpay')
604
+ }
605
+
564
606
  /**
565
607
  * Pay a handle. Five steps, in this order:
566
608
  * 1 mint the token with noSend (nothing hits the network yet)
@@ -643,7 +685,7 @@ export async function sendViaHandle(args: {
643
685
  /** A payment minted with noSend: signed, saved by the caller, not yet broadcast. */
644
686
  export interface MintedPeerPayToken {
645
687
  txid: string
646
- token: OutboxEntry['token']
688
+ token: PeerPayOutboxEntry['token']
647
689
  /** What output 0 pays the recipient, read off the transaction (covers send-max). */
648
690
  satoshis: number
649
691
  }
@@ -757,7 +799,7 @@ export async function cancelOutboxPayment(args: {
757
799
  wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>
758
800
  adminOriginator: string
759
801
  storage: StorageLike
760
- entry: Pick<OutboxEntry, 'id' | 'txid' | 'delivered' | 'delivering' | 'recipient' | 'recipientHost'>
802
+ entry: Pick<PeerPayOutboxEntry, 'id' | 'txid' | 'delivered' | 'delivering' | 'recipient' | 'recipientHost'>
761
803
  client?: Pick<PeerPayClient, 'sendMessage'>
762
804
  mode?: 'undelivered' | 'abandon'
763
805
  }): Promise<{ aborted: boolean; needsAbandon?: boolean }> {
@@ -822,7 +864,7 @@ export function isAbortSafe(
822
864
  action: { labels?: string[]; txid?: string },
823
865
  outboxEntries: Array<Pick<OutboxEntry, 'txid' | 'delivered' | 'delivering'>>
824
866
  ): { aborted: boolean; needsAbandon?: boolean } {
825
- if (!action.labels?.includes('peerpay')) return { aborted: true }
867
+ if (!action.labels?.includes('peerpay') && !action.labels?.includes('paymail')) return { aborted: true }
826
868
  const stored = action.txid != null ? outboxEntries.find(e => e.txid === action.txid) : undefined
827
869
  if (stored == null || stored.delivered === true || stored.delivering === true) {
828
870
  return { aborted: false, needsAbandon: true }
@@ -920,7 +962,7 @@ export async function retryDelivery(args: {
920
962
  adminOriginator: string
921
963
  client: Pick<PeerPayClient, 'sendMessage'>
922
964
  storage: StorageLike
923
- entry: OutboxEntry
965
+ entry: PeerPayOutboxEntry
924
966
  }): Promise<void> {
925
967
  const { wallet, adminOriginator, client, storage, entry } = args
926
968
  if (entry.status !== 'unsent') return