@bsv/expo-wallet-toolbox 0.26.0 → 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.
- package/CHANGELOG.md +27 -0
- package/core/context/WalletContext.tsx +20 -1
- package/core/i18n/translations.tsx +24 -0
- package/core/identity/handleRegistry/classify.ts +74 -0
- package/core/identity/handleRegistry/resolver.ts +77 -34
- package/core/identity/handleRegistry/rules.ts +4 -0
- package/core/index.ts +7 -0
- package/core/monitor/TaskDrainOutbox.ts +13 -3
- package/core/pay/paymail/address.ts +19 -0
- package/core/pay/paymail/client.ts +177 -0
- package/core/pay/paymail/networkCheck.ts +56 -0
- package/core/pay/rails/handle.ts +46 -9
- package/core/pay/rails/paymail.ts +542 -0
- package/core/peerpay/handleResendRequests.ts +6 -6
- package/core/peerpay/outbox.ts +185 -17
- package/core/peerpay/rebuildToken.ts +2 -2
- package/package.json +1 -1
- package/ui/components/pay/ImportedOutboxApproval.tsx +23 -2
- package/ui/components/pay/UniversalSend.tsx +75 -4
- package/ui/screens/WalletHomeScreen.tsx +104 -4
- package/ui/txStatus.ts +1 -1
|
@@ -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
|
+
}
|
package/core/pay/rails/handle.ts
CHANGED
|
@@ -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
|
|
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 {
|
|
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:
|
|
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<
|
|
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:
|
|
960
|
+
entry: PeerPayOutboxEntry
|
|
924
961
|
}): Promise<void> {
|
|
925
962
|
const { wallet, adminOriginator, client, storage, entry } = args
|
|
926
963
|
if (entry.status !== 'unsent') return
|