@bsv/expo-wallet-toolbox 0.2.1 → 0.3.1

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/core/index.ts CHANGED
@@ -29,6 +29,8 @@ export {
29
29
  // Theme tokens and providers
30
30
  export { ThemeProvider, useTheme } from './theme/ThemeContext'
31
31
  export { spacing, radii, typography, lightColors, darkColors, hitTargets } from './theme/tokens'
32
+ export { sigilPalette } from './theme/sigilPalette'
33
+ export type { SigilPalette } from './theme/sigilPalette'
32
34
  export { easings, springs, durations } from './theme/motion'
33
35
  export { useThemeStyles } from './theme/useThemeStyles'
34
36
 
@@ -127,15 +129,17 @@ export * from './pay/beefRepair'
127
129
  export * from './pay/creditErrors'
128
130
  export * from './pay/creditInbox'
129
131
  export * from './pay/userError'
132
+ export * from './pay/patp'
133
+ export * from './pay/counterparty'
130
134
  export * from './pay/rails/address'
131
135
  export * from './pay/rails/handle'
132
136
  // nearby.ts is a pure re-export barrel over localpay/* (already exported above)
133
137
  // and @bsv/air-gap; only its genuinely new names are re-exported here by hand —
134
138
  // a blanket `export *` would collide (TS2308) with the localpay/offline exports
135
139
  // above, since most of nearby.ts's surface is itself a re-export of those.
136
- // CAP_BLE is listed although `export * from './localpay/session'` already
137
- // carries it: an explicit re-export takes precedence over a star export, so
138
- // this is legal, and it keeps the block a faithful mirror of nearby.ts.
140
+ // CAP_BLE is the one nearby.ts name deliberately missing from this list:
141
+ // `export * from './localpay/session'` above already carries the same binding,
142
+ // and naming it twice trips eslint's import/export rule.
139
143
  export {
140
144
  AIR_GAP_PREFIX,
141
145
  AirGapDecoder,
@@ -156,7 +160,6 @@ export {
156
160
  readBluetoothState,
157
161
  prepareBle,
158
162
  raceReceivers,
159
- CAP_BLE,
160
163
  isDeclineReason,
161
164
  type TransportKind,
162
165
  type FloorReason,
@@ -185,7 +188,15 @@ export {
185
188
  touchWatched,
186
189
  unwatchAddress
187
190
  } from './pay/watchlist'
188
- export * from './parsePeerPayURI'
191
+ // isCompressedPublicKey is omitted here because './pay/rails' above already
192
+ // re-exports the same binding; naming it twice trips eslint's import/export rule.
193
+ export {
194
+ type PeerPayParams,
195
+ type PeerPayValidationResult,
196
+ parsePeerPayURI,
197
+ validatePeerPayURI,
198
+ peerPayValidationMessage
199
+ } from './parsePeerPayURI'
189
200
 
190
201
  // Blockchain header sync / checkpointing
191
202
  export * from './headers/checkpoints'
@@ -4,6 +4,7 @@ import { isRequestableAmount, type Session } from './session'
4
4
  import { PEERPAY_LABEL, PEERPAY_PROTOCOL_ID } from './pending'
5
5
  import type { Ack } from './types'
6
6
  import { getOnline } from '../net/online'
7
+ import { abbreviateKey } from '../pay/counterparty'
7
8
 
8
9
  /** The toolbox's per-txid verdict on a `sendWith` release. */
9
10
  type SendWithStatus = 'unproven' | 'sending' | 'failed'
@@ -125,7 +126,9 @@ export async function buildPaymentFrame(
125
126
 
126
127
  let result = await wallet.createAction(
127
128
  {
128
- description: 'Payment to a nearby device',
129
+ // The activity list uses the description as the row title, so it names
130
+ // the payee rather than the rail: the rail is already in the label.
131
+ description: abbreviateKey(session.identityKey),
129
132
  // The payee's identity key rides as a label, and the derivation data as
130
133
  // the output's customInstructions — exactly what the handle rail writes.
131
134
  // Both rails derive to BRC-29 (`counterparty: identityKey`, keyID
@@ -1,5 +1,6 @@
1
1
  import { Beef } from '@bsv/sdk'
2
2
  import type { PaymentFrame } from './codec'
3
+ import { abbreviateKey } from '../pay/counterparty'
3
4
 
4
5
  export const PENDING_KEY = 'localpay_pending'
5
6
  /**
@@ -11,7 +12,6 @@ export const PENDING_KEY = 'localpay_pending'
11
12
  export const PENDING_SUMMARY_KEY = 'localpay_pending_summary'
12
13
  export const PEERPAY_PROTOCOL_ID: [number, string] = [2, '3241645161d8']
13
14
  export const PEERPAY_LABEL = 'localpay'
14
- export const PEERPAY_DESCRIPTION = 'Payment received from a nearby device'
15
15
 
16
16
  export type PendingStatus = 'pending' | 'processing' | 'completed' | 'failed'
17
17
 
@@ -310,7 +310,10 @@ export async function processPending(
310
310
  }
311
311
  }
312
312
  ],
313
- description: PEERPAY_DESCRIPTION,
313
+ // The activity list uses the description as the row title, so it
314
+ // names the payer. The counterparty itself is recovered from
315
+ // outputs.senderIdentityKey, which is why the label stays rail-only.
316
+ description: abbreviateKey(p.frame.senderIdentityKey),
314
317
  labels: [PEERPAY_LABEL]
315
318
  },
316
319
  originator
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Who was on the other side of a wallet action, recovered from what the rails
3
+ * actually persist. Each rail records its counterparty differently and only
4
+ * some of them record one at all, so the activity list needs one place that
5
+ * turns labels, senderIdentityKey and txid into a single answer it can name
6
+ * and draw a sigil for.
7
+ */
8
+ import { Hash, Utils } from '@bsv/sdk'
9
+ import { patp } from './patp'
10
+
11
+ /** A compressed secp256k1 public key in hex: what peer rails write as a label. */
12
+ export const PUBKEY_LABEL = /^(02|03)[0-9a-fA-F]{64}$/
13
+
14
+ /**
15
+ * The public key of private key 1. The address sweep has no real sender
16
+ * identity, so it fills senderIdentityKey with this well-known key; treating it
17
+ * as a counterparty would give every swept payment the same face.
18
+ */
19
+ export const SENTINEL_SENDER_KEY = '0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'
20
+
21
+ /** An outbound address send labels the action 'to:' + addressLabel payload. */
22
+ export const TO_ADDRESS_LABEL_PREFIX = 'to:'
23
+
24
+ /** An inbound address sweep labels the action 'from:' + addressLabel payload for the payer's zeroth-input P2PKH address. */
25
+ export const FROM_ADDRESS_LABEL_PREFIX = 'from:'
26
+
27
+ type AddressLabelPrefix = typeof TO_ADDRESS_LABEL_PREFIX | typeof FROM_ADDRESS_LABEL_PREFIX
28
+
29
+ /** Version byte plus hash160: the 21 bytes a P2PKH address encodes. */
30
+ const ADDRESS_LABEL_PAYLOAD = /^[0-9a-f]{42}$/i
31
+
32
+ export type Counterparty = { kind: 'identityKey' | 'address' | 'txid'; value: string }
33
+
34
+ export type CounterpartySource = { labels?: string[]; senderIdentityKey?: string | null; txid?: string }
35
+
36
+ /**
37
+ * The label the address rail writes for an address. The wallet folds every
38
+ * label to lower case before storing it (@bsv/sdk's validateLabel), and base58
39
+ * is case-sensitive, so the address's own spelling would come back unreadable.
40
+ * Hex is case-insensitive and the version byte keeps the network, so the label
41
+ * decodes back to exactly the address that was written.
42
+ */
43
+ export function addressLabel(prefix: AddressLabelPrefix, address: string): string {
44
+ const { prefix: version, data } = Utils.fromBase58Check(address)
45
+ return prefix + Utils.toHex([...(version as number[]), ...(data as number[])])
46
+ }
47
+
48
+ /**
49
+ * The address behind a to:/from: label. A payload this package did not write
50
+ * (anything but 21 hex bytes) is passed through verbatim rather than dropped:
51
+ * it still names something, and the seed falls back to hashing the string.
52
+ */
53
+ function addressFromLabel(label: string): string | undefined {
54
+ for (const prefix of [TO_ADDRESS_LABEL_PREFIX, FROM_ADDRESS_LABEL_PREFIX]) {
55
+ if (!label.startsWith(prefix)) continue
56
+ const payload = label.slice(prefix.length)
57
+ if (payload.length === 0) return undefined
58
+ if (!ADDRESS_LABEL_PAYLOAD.test(payload)) return payload
59
+ const bytes = Utils.toArray(payload, 'hex')
60
+ return Utils.toBase58Check(bytes.slice(1), bytes.slice(0, 1))
61
+ }
62
+ return undefined
63
+ }
64
+
65
+ /**
66
+ * Most specific identification first: a pubkey label (outbound peer payment),
67
+ * then the recorded sender (inbound peer payment), then an address label
68
+ * (either direction of the address rail), then the txid so that every action
69
+ * still gets a stable, if anonymous, face.
70
+ */
71
+ export function counterpartyOf(a: CounterpartySource): Counterparty | null {
72
+ const labels = a.labels ?? []
73
+ const keyLabel = labels.find(label => PUBKEY_LABEL.test(label))
74
+ if (keyLabel !== undefined) return { kind: 'identityKey', value: keyLabel }
75
+ const sender = a.senderIdentityKey
76
+ if (typeof sender === 'string' && sender.length > 0 && sender !== SENTINEL_SENDER_KEY) {
77
+ return { kind: 'identityKey', value: sender }
78
+ }
79
+ for (const label of labels) {
80
+ const address = addressFromLabel(label)
81
+ if (address !== undefined) return { kind: 'address', value: address }
82
+ }
83
+ if (typeof a.txid === 'string' && a.txid.length > 0) return { kind: 'txid', value: a.txid }
84
+ return null
85
+ }
86
+
87
+ /** '02abcdef…beef' style: enough of both ends to tell two keys apart at a glance. */
88
+ export function abbreviateKey(s: string): string {
89
+ return s.length <= 13 ? s : s.slice(0, 8) + '…' + s.slice(-4)
90
+ }
91
+
92
+ /** Whole bytes only: an odd digit count has no byte form and is not a key or txid. */
93
+ const HEX_BYTES = /^(?:[0-9a-fA-F]{2})+$/
94
+
95
+ /** @bsv/sdk types its base58 parts as `number[] | string`; only the array form is ever returned without `enc`. */
96
+ function asBytes(part: number[] | string): number[] {
97
+ return typeof part === 'string' ? Utils.toArray(part, 'hex') : part
98
+ }
99
+
100
+ /**
101
+ * The bytes a counterparty is made of, which every derived property (the
102
+ * shape seed, the hue) reads windows from. A key or txid is its own hex; an
103
+ * address is the version byte followed by the hash160 it encodes, so anything
104
+ * derived from its tail is a property of the key behind it rather than of its
105
+ * base58 spelling, and the mainnet and testnet forms of one key share a face.
106
+ * A value that will not parse still gets 32 deterministic bytes from a hash of
107
+ * the raw string: a stray label must never take down an activity row.
108
+ */
109
+ export function counterpartyBytes(cp: Counterparty): number[] {
110
+ try {
111
+ if (cp.kind === 'address') {
112
+ const { prefix, data } = Utils.fromBase58Check(cp.value)
113
+ return [...asBytes(prefix), ...asBytes(data)]
114
+ }
115
+ // Utils.toArray also rejects bad hex, but this is the contract this module
116
+ // relies on, so it is stated here rather than borrowed from SDK internals.
117
+ if (!HEX_BYTES.test(cp.value)) throw new Error('counterpartyBytes: not hex')
118
+ return Utils.toArray(cp.value, 'hex')
119
+ } catch {
120
+ return Hash.sha256(Utils.toArray(cp.value, 'utf8'))
121
+ }
122
+ }
123
+
124
+ /** Big-endian u32 of `bytes[start .. start+4)`. The caller guarantees the window exists. */
125
+ function u32At(bytes: number[], start: number): number {
126
+ const [b0, b1, b2, b3] = bytes.slice(start, start + 4)
127
+ return ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3) >>> 0
128
+ }
129
+
130
+ /**
131
+ * A 32-bit seed for the counterparty's sigil shape: the last four bytes. Keys,
132
+ * txids and hash160s are uniformly distributed already, so no further mixing
133
+ * is needed before `patp`. Fewer than four bytes (a short but valid hex
134
+ * string) are hashed first so there is always a tail to read.
135
+ */
136
+ export function counterpartySeed(cp: Counterparty): number {
137
+ const bytes = counterpartyBytes(cp)
138
+ const src = bytes.length >= 4 ? bytes : Hash.sha256(bytes)
139
+ return u32At(src, src.length - 4)
140
+ }
141
+
142
+ /**
143
+ * A hue in degrees, 0..359, for the counterparty's sigil tile: the four bytes
144
+ * immediately before the seed bytes, modulo 360. Reading a different window
145
+ * from the seed is the point: two counterparties that happen to share a
146
+ * shape still get different colours, and vice versa, so the tile carries
147
+ * more information than either alone. Fewer than eight bytes are hashed
148
+ * first so there is always a window to read.
149
+ */
150
+ export function counterpartyHue(cp: Counterparty): number {
151
+ const bytes = counterpartyBytes(cp)
152
+ const src = bytes.length >= 8 ? bytes : Hash.sha256(bytes)
153
+ return u32At(src, src.length - 8) % 360
154
+ }
155
+
156
+ /** The Urbit @p name sigil-js draws for this counterparty. */
157
+ export function sigilPointOf(cp: Counterparty): string {
158
+ return patp(counterpartySeed(cp))
159
+ }
@@ -21,9 +21,6 @@ import type { CreditFailureKind } from './creditErrors'
21
21
  import { sendControlMessage } from '../peerpay/control'
22
22
  import { loadInboxAttempts, saveInboxAttempts } from '../peerpay/inboxAttempts'
23
23
 
24
- /** Same default the receive screen used when the note was left blank. */
25
- export const INBOX_DESCRIPTION = 'Identity Payment'
26
-
27
24
  /** Placeholder token so unparseable inbox rows can share the IncomingPayment row UI. */
28
25
  export const DAMAGED_TOKEN_PLACEHOLDER: IncomingPayment['token'] = {
29
26
  customInstructions: { derivationPrefix: '', derivationSuffix: '' },
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Urbit `@p` names for 32-bit integers, e.g. 15663360 -> '~nidsut-tomdun'.
3
+ *
4
+ * Faithful port of urbit-ob 5.0.1 (src/internal/co.js, ob.js, muk.js),
5
+ * restricted to the 32-bit domain we need: one syllable for n < 256 (galaxy),
6
+ * two for n < 65536 (star), four for everything else (planet). Planets are
7
+ * Feistel-scrambled exactly as in Urbit so that neighbouring seeds do not get
8
+ * neighbouring names, and so the output matches what any other @p tooling
9
+ * (sigil-js, urbit-ob, Landscape) would show for the same number.
10
+ *
11
+ * urbit-ob is not a dependency: it pulls in bn.js and lodash for arithmetic
12
+ * that fits comfortably in a JS double once the domain is 2^32. Everything
13
+ * here is plain numbers; `Math.imul` and `>>> 0` supply the 32-bit wrap the
14
+ * hash needs.
15
+ */
16
+
17
+ // ++po in hoon.hoon: 256 prefix and 256 suffix syllables, 3 chars each.
18
+ const PREFIX_TABLE =
19
+ 'dozmarbinwansamlitsighidfidlissogdirwacsabwissib' +
20
+ 'rigsoldopmodfoglidhopdardorlorhodfolrintogsilmir' +
21
+ 'holpaslacrovlivdalsatlibtabhanticpidtorbolfosdot' +
22
+ 'losdilforpilramtirwintadbicdifrocwidbisdasmidlop' +
23
+ 'rilnardapmolsanlocnovsitnidtipsicropwitnatpanmin' +
24
+ 'ritpodmottamtolsavposnapnopsomfinfonbanmorworsip' +
25
+ 'ronnorbotwicsocwatdolmagpicdavbidbaltimtasmallig' +
26
+ 'sivtagpadsaldivdactansidfabtarmonranniswolmispal' +
27
+ 'lasdismaprabtobrollatlonnodnavfignomnibpagsopral' +
28
+ 'bilhaddocridmocpacravripfaltodtiltinhapmicfanpat' +
29
+ 'taclabmogsimsonpinlomrictapfirhasbosbatpochactid' +
30
+ 'havsaplindibhosdabbitbarracparloddosbortochilmac' +
31
+ 'tomdigfilfasmithobharmighinradmashalraglagfadtop' +
32
+ 'mophabnilnosmilfopfamdatnoldinhatnacrisfotribhoc' +
33
+ 'nimlarfitwalrapsarnalmoslandondanladdovrivbacpol' +
34
+ 'laptalpitnambonrostonfodponsovnocsorlavmatmipfip'
35
+
36
+ const SUFFIX_TABLE =
37
+ 'zodnecbudwessevpersutletfulpensytdurwepserwylsun' +
38
+ 'rypsyxdyrnuphebpeglupdepdysputlughecryttyvsydnex' +
39
+ 'lunmeplutseppesdelsulpedtemledtulmetwenbynhexfeb' +
40
+ 'pyldulhetmevruttylwydtepbesdexsefwycburderneppur' +
41
+ 'rysrebdennutsubpetrulsynregtydsupsemwynrecmegnet' +
42
+ 'secmulnymtevwebsummutnyxrextebfushepbenmuswyxsym' +
43
+ 'selrucdecwexsyrwetdylmynmesdetbetbeltuxtugmyrpel' +
44
+ 'syptermebsetdutdegtexsurfeltudnuxruxrenwytnubmed' +
45
+ 'lytdusnebrumtynseglyxpunresredfunrevrefmectedrus' +
46
+ 'bexlebduxrynnumpyxrygryxfeptyrtustyclegnemfermer' +
47
+ 'tenlusnussyltecmexpubrymtucfyllepdebbermughuttun' +
48
+ 'bylsudpemdevlurdefbusbeprunmelpexdytbyttyplevmyl' +
49
+ 'wedducfurfexnulluclennerlexrupnedlecrydlydfenwel' +
50
+ 'nydhusrelrudneshesfetdesretdunlernyrsebhulryllud' +
51
+ 'remlysfynwerrycsugnysnyllyndyndemluxfedsedbecmun' +
52
+ 'lyrtesmudnytbyrsenwegfyrmurtelreptegpecnelnevfes'
53
+
54
+ const PREFIXES = PREFIX_TABLE.match(/.{3}/g) as string[]
55
+ const SUFFIXES = SUFFIX_TABLE.match(/.{3}/g) as string[]
56
+
57
+ /** Per-round hash seeds ("raku") from ++ob in hoon.hoon. */
58
+ const RAKU = [0xb76d5eed, 0xee281300, 0x85bcae01, 0x4b387af7]
59
+
60
+ // Feistel parameters: 4 rounds over the domain 65535 x 65536, which is exactly
61
+ // the 0xffff0000 planet numbers between 0x10000 and 0xffffffff.
62
+ const ROUNDS = 4
63
+ const A = 65535
64
+ const B = 65536
65
+ const K = 0xffffffff
66
+
67
+ /**
68
+ * MurmurHash3 (32-bit, Austin Appleby's x86 variant) over a short byte array.
69
+ * urbit-ob's `muk` feeds it a 2-byte string; the general loop is kept so the
70
+ * function reads as the well-known algorithm rather than a special case.
71
+ */
72
+ function murmur3(bytes: number[], seed: number): number {
73
+ const c1 = 0xcc9e2d51
74
+ const c2 = 0x1b873593
75
+ let h1 = seed | 0
76
+ const blockEnd = bytes.length & ~3
77
+ let i = 0
78
+ for (; i < blockEnd; i += 4) {
79
+ let k1 = bytes[i] | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24)
80
+ k1 = Math.imul(k1, c1)
81
+ k1 = (k1 << 15) | (k1 >>> 17)
82
+ k1 = Math.imul(k1, c2)
83
+ h1 ^= k1
84
+ h1 = (h1 << 13) | (h1 >>> 19)
85
+ h1 = (Math.imul(h1, 5) + 0xe6546b64) | 0
86
+ }
87
+ const rem = bytes.length & 3
88
+ if (rem > 0) {
89
+ let k1 = 0
90
+ if (rem === 3) k1 ^= bytes[i + 2] << 16
91
+ if (rem >= 2) k1 ^= bytes[i + 1] << 8
92
+ k1 ^= bytes[i]
93
+ k1 = Math.imul(k1, c1)
94
+ k1 = (k1 << 15) | (k1 >>> 17)
95
+ k1 = Math.imul(k1, c2)
96
+ h1 ^= k1
97
+ }
98
+ h1 ^= bytes.length
99
+ h1 ^= h1 >>> 16
100
+ h1 = Math.imul(h1, 0x85ebca6b)
101
+ h1 ^= h1 >>> 13
102
+ h1 = Math.imul(h1, 0xc2b2ae35)
103
+ h1 ^= h1 >>> 16
104
+ return h1 >>> 0
105
+ }
106
+
107
+ /** ++muk: murmur3 of the key's low two bytes, little-endian, with the given seed. */
108
+ function muk(seed: number, key: number): number {
109
+ return murmur3([key & 0xff, (key >>> 8) & 0xff], seed)
110
+ }
111
+
112
+ /** The round function: a PRF indexed by round number. */
113
+ function F(round: number, arg: number): number {
114
+ return muk(RAKU[round], arg)
115
+ }
116
+
117
+ /**
118
+ * One pass of the generalised Feistel cipher (Black and Rogaway 2002, as
119
+ * adjusted in hoon.hoon). The final recombination is asymmetric when the
120
+ * round count is even: that quirk is what makes urbit-ob's `feis` agree with
121
+ * the ship names Urbit has already handed out, so it is kept verbatim.
122
+ */
123
+ function fe(m: number): number {
124
+ let ell = m % A
125
+ let arr = Math.floor(m / A)
126
+ for (let j = 1; j <= ROUNDS; j++) {
127
+ const eff = F(j - 1, arr)
128
+ const tmp = j % 2 !== 0 ? (ell + eff) % A : (ell + eff) % B
129
+ ell = arr
130
+ arr = tmp
131
+ }
132
+ if (ROUNDS % 2 !== 0) return A * arr + ell
133
+ return arr === A ? A * arr + ell : A * ell + arr
134
+ }
135
+
136
+ /** `Fe`: cycle-walk once more if the first pass lands outside the domain. */
137
+ function feis(m: number): number {
138
+ const c = fe(m)
139
+ return c < K ? c : fe(c)
140
+ }
141
+
142
+ /** ++fein: scramble planets only; galaxies and stars keep their raw number. */
143
+ function fein(n: number): number {
144
+ return n >= 0x10000 && n <= 0xffffffff ? 0x10000 + feis(n - 0x10000) : n
145
+ }
146
+
147
+ /**
148
+ * Canonical Urbit @p for an unsigned 32-bit integer, '~'-prefixed.
149
+ * Throws a RangeError for anything outside that domain: moons and comets
150
+ * need 64 and 128 bits and are deliberately out of scope here.
151
+ */
152
+ export function patp(n: number): string {
153
+ if (!Number.isInteger(n) || n < 0 || n > 0xffffffff) {
154
+ throw new RangeError(`patp: expected an integer in [0, 2^32), got ${String(n)}`)
155
+ }
156
+ const sxz = fein(n)
157
+ if (sxz < 256) return '~' + SUFFIXES[sxz]
158
+ // Each 16-bit chunk becomes prefix+suffix; the high chunk is spoken first.
159
+ const words: string[] = []
160
+ let rest = sxz
161
+ while (rest > 0) {
162
+ const chunk = rest % 65536
163
+ words.unshift(PREFIXES[chunk >>> 8] + SUFFIXES[chunk & 0xff])
164
+ rest = Math.floor(rest / 65536)
165
+ }
166
+ return '~' + words.join('-')
167
+ }
168
+
169
+ /**
170
+ * The last eight hex digits of a hex string as an unsigned 32-bit integer.
171
+ * Meant for txids and compressed public keys, whose tails are already
172
+ * uniformly distributed, so no further mixing is needed before `patp`.
173
+ * Throws when the input is not hex or is shorter than eight digits, so a
174
+ * caller that hands over the wrong field finds out immediately.
175
+ */
176
+ export function u32FromHexTail(hex: string): number {
177
+ if (!/^[0-9a-fA-F]{8,}$/.test(hex)) {
178
+ throw new Error(`u32FromHexTail: expected at least 8 hex digits, got ${hex.length} chars`)
179
+ }
180
+ return Number.parseInt(hex.slice(-8), 16)
181
+ }
@@ -22,6 +22,7 @@ import {
22
22
  type WalletProtocol
23
23
  } from '@bsv/sdk'
24
24
  import type { AppChain } from '../../config'
25
+ import { abbreviateKey, addressLabel, FROM_ADDRESS_LABEL_PREFIX, TO_ADDRESS_LABEL_PREFIX } from '../counterparty'
25
26
  import { isValidBsvAddress } from './index'
26
27
 
27
28
  export const BRC29_PROTOCOL_ID: WalletProtocol = [2, '3241645161d8']
@@ -215,14 +216,41 @@ export function parseWocBeefBody(resp: { ok: boolean; text: string }): number[]
215
216
  }
216
217
  }
217
218
 
219
+ /**
220
+ * The address a conventional wallet paid from, read off the zeroth input's
221
+ * P2PKH unlocking script: a signature push followed by a 33-byte compressed
222
+ * key. That is the only place the sweep can learn anything about the payer,
223
+ * since the remittance carries a sentinel sender rather than a real one.
224
+ * Anything else (coinbase, unsigned, multisig, a key that will not parse)
225
+ * yields undefined so the caller falls back to a generic description instead
226
+ * of guessing at a face; a throw here would count a good payment as failed.
227
+ */
228
+ export function payerAddressOf(tx: Transaction, network: 'mainnet' | 'testnet' = 'mainnet'): string | undefined {
229
+ const chunks = tx.inputs[0]?.unlockingScript?.chunks
230
+ if (chunks === undefined || chunks.length !== 2) return undefined
231
+ const key = chunks[1].data
232
+ if (key === undefined || key.length !== 33 || (key[0] !== 0x02 && key[0] !== 0x03)) return undefined
233
+ try {
234
+ return PublicKey.fromString(Utils.toHex(key)).toAddress(network)
235
+ } catch {
236
+ return undefined
237
+ }
238
+ }
239
+
218
240
  /**
219
241
  * The sweep. Ported from legacy-payments.tsx's handleImportFunds with one
220
- * change and one only: the trigger. Nothing about what it writes moves.
242
+ * change to its trigger. What it writes has since grown a payer-facing
243
+ * description and a `from:` label so the activity list can name and draw the
244
+ * payer; both are additive and derived, and the dedup contract below is
245
+ * untouched. The label carries the address as hex (see addressLabel): the
246
+ * wallet lower-cases labels on the way in, which base58 does not survive.
221
247
  *
222
248
  * The sentinel sender key (PrivateKey(1)'s public key) and the label list are
223
249
  * both load-bearing: the labels are how getInternalizedUtxos recognises what
224
- * has already been imported, and the address label in particular is what makes
225
- * a second sweep a no-op instead of a double credit.
250
+ * has already been imported, and the bare address label in particular is what
251
+ * makes a second sweep a no-op instead of a double credit. The `from:` label
252
+ * is a different string from the bare address, so the `labelQueryMode: 'all'`
253
+ * lookups and the `ts:` parse in getProcessedTransactions never see it.
226
254
  *
227
255
  * Each UTXO is fetched and internalized in its own try/catch so one bad BEEF
228
256
  * cannot skip the rest of the address.
@@ -275,11 +303,21 @@ export async function sweepAddress(args: {
275
303
  derivationSuffix: LEGACY_DERIVATION_SUFFIX
276
304
  }
277
305
  }))
306
+ // Same network the rail derives its own receive addresses on, so payer
307
+ // and payee addresses read consistently in one history.
308
+ const payerAddress = payerAddressOf(tx, woc.network)
278
309
  const internalizeArgs: InternalizeActionArgs = {
279
310
  tx: tx.toAtomicBEEF(),
280
- description: 'Payment to your address',
311
+ description: payerAddress !== undefined ? abbreviateKey(payerAddress) : 'Payment to your address',
281
312
  outputs,
282
- labels: ['legacy', 'inbound', 'bsvbrowser', address, `ts:${nowSeconds}`]
313
+ labels: [
314
+ 'legacy',
315
+ 'inbound',
316
+ 'bsvbrowser',
317
+ address,
318
+ `ts:${nowSeconds}`,
319
+ ...(payerAddress !== undefined ? [addressLabel(FROM_ADDRESS_LABEL_PREFIX, payerAddress)] : [])
320
+ ]
283
321
  }
284
322
  const response = await wallet.internalizeAction(internalizeArgs, adminOriginator)
285
323
  if (response?.accepted) importedSatoshis += relevant.reduce((sum, o) => sum + o.satoshis, 0)
@@ -313,9 +351,11 @@ export async function sendToAddress(args: {
313
351
  const isSendMax = sats === 2099999999999999
314
352
  const result = (await wallet.createAction(
315
353
  {
316
- description: 'Send BSV to address',
354
+ // The recipient's address is the description so the activity list has a
355
+ // name for the row without a lookup; the to: label is what lets it draw a face.
356
+ description: abbreviateKey(address),
317
357
  outputs: [{ lockingScript, satoshis: sats, outputDescription: 'BSV for recipient address' }],
318
- labels: ['legacy', 'outbound'],
358
+ labels: ['legacy', 'outbound', addressLabel(TO_ADDRESS_LABEL_PREFIX, address)],
319
359
  ...(isSendMax ? { options: { randomizeOutputs: false } } : {})
320
360
  },
321
361
  adminOriginator
@@ -20,6 +20,7 @@ import {
20
20
  type OutboxEntry
21
21
  } from '../../peerpay/outbox'
22
22
  import type { CreditFailureKind } from '../creditErrors'
23
+ import { abbreviateKey } from '../counterparty'
23
24
  import { isDuplicateMessageError, sendControlMessage, type ResendReason } from '../../peerpay/control'
24
25
  import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
25
26
 
@@ -85,6 +86,12 @@ export function peerPayLinkFor(identityKey: string, sats?: number, messageBoxUrl
85
86
  /**
86
87
  * Credit an incoming payment, then acknowledge it. Never acknowledge first.
87
88
  *
89
+ * The recorded description is the note the sender attached to the token or,
90
+ * failing that, the sender's abbreviated identity key: the same default the
91
+ * sending wallet wrote for the recipient, so both sides name one payment the
92
+ * same way. The sender is not added to the labels; the activity list recovers
93
+ * the counterparty from the output's senderIdentityKey instead.
94
+ *
88
95
  * `repairBeef` is the second chance. The token's AtomicBEEF was minted at send
89
96
  * time, and a reorg between then and now invalidates its merkle path without
90
97
  * touching the transaction itself — the toolbox reports that as
@@ -97,13 +104,16 @@ export async function internalizeIncoming(
97
104
  client: Pick<PeerPayClient, 'acknowledgeMessage'>,
98
105
  adminOriginator: string,
99
106
  payment: IncomingPayment,
100
- description: string,
101
107
  repairBeef?: (txid: string) => Promise<number[] | undefined>
102
108
  ): Promise<void> {
103
109
  // A note the sender attached to the token becomes the description the
104
- // recipient's wallet records — same field the sender's action carries.
110
+ // recipient's wallet records, the same field the sender's action carries.
105
111
  const note = (payment.token as { note?: unknown }).note
106
112
  const noted = typeof note === 'string' && note.trim().length > 0 ? note.trim().slice(0, 500) : undefined
113
+ // Same rule as the sender's side: the note verbatim, space-padded to the
114
+ // 5-byte validation floor when it is shorter. The abbreviated key is 13
115
+ // characters, so it never needs padding.
116
+ const description = noted ? noted.padEnd(5) : abbreviateKey(payment.sender)
107
117
 
108
118
  const argsFor = (tx: number[] | typeof payment.token.transaction) => ({
109
119
  tx,
@@ -119,9 +129,7 @@ export async function internalizeIncoming(
119
129
  }
120
130
  ],
121
131
  labels: ['peerpay'],
122
- // Same rule as the sender's side: the note verbatim, space-padded to the
123
- // 5-byte validation floor when it is shorter.
124
- description: noted ? noted.padEnd(5) : description
132
+ description
125
133
  })
126
134
 
127
135
  try {
@@ -185,15 +193,14 @@ export async function acceptWithRetry(
185
193
  client: Pick<PeerPayClient, 'listIncomingPayments'>,
186
194
  messageBoxUrl: string,
187
195
  payment: IncomingPayment,
188
- description: string,
189
- internalize: (p: IncomingPayment, d: string) => Promise<void>
196
+ internalize: (p: IncomingPayment) => Promise<void>
190
197
  ): Promise<void> {
191
198
  void client
192
199
  void messageBoxUrl
193
200
  try {
194
- await internalize(payment, description)
201
+ await internalize(payment)
195
202
  } catch {
196
- await internalize(payment, description)
203
+ await internalize(payment)
197
204
  }
198
205
  }
199
206
 
@@ -403,12 +410,15 @@ export async function sendViaHandle(args: {
403
410
  // advertised host when there is one and otherwise falls back to the host this
404
411
  // wallet is configured for, which is where both parties' apps look by default.
405
412
 
406
- // The note IS the description when one was given — verbatim; otherwise
407
- // "Pay <who>". BRC-100 requires 5–2000 bytes and the validator does not
408
- // trim, so a very short note is padded with trailing spaces rather than
409
- // decorated, and everything is clamped at the top end.
413
+ // The note IS the description when one was given, verbatim; otherwise the
414
+ // recipient's name, or their abbreviated key. No "Pay" prefix: the activity
415
+ // row already shows the direction, and the receive side records the sender
416
+ // the same way, so both wallets name one payment alike. BRC-100 requires
417
+ // 5-2000 bytes and the validator does not trim, so a very short note is
418
+ // padded with trailing spaces rather than decorated, and everything is
419
+ // clamped at the top end.
410
420
  const note = args.note?.trim() || undefined
411
- const description = (note ?? `Pay ${recipientName?.trim() || recipient.slice(0, 8)}`).slice(0, 500).padEnd(5)
421
+ const description = (note ?? (recipientName?.trim() || abbreviateKey(recipient))).slice(0, 500).padEnd(5)
412
422
 
413
423
  // Standard BRC-29: fresh prefix/suffix, key derived toward the recipient.
414
424
  const derivationPrefix = Utils.toBase64(Random(8))
@@ -1,4 +1,5 @@
1
1
  import { Beef } from '@bsv/sdk'
2
+ import { PUBKEY_LABEL } from '../pay/counterparty'
2
3
  import {
3
4
  ackControlMessages,
4
5
  isDuplicateMessageError,
@@ -14,8 +15,6 @@ const PAYMENT_INBOX = 'payment_inbox'
14
15
  /** Stored unanswered `resend_request`s so Home can show a banner without re-listing. */
15
16
  export const UNANSWERED_RESENDS_KEY = 'peerpay_unanswered_resends'
16
17
 
17
- const PUBKEY_LABEL = /^(02|03)[0-9a-fA-F]{64}$/
18
-
19
18
  /**
20
19
  * Rail labels an outbound payment can carry. Both are resendable: each writes
21
20
  * the payee's identity key as a label and BRC-29 derivation data as the
@@ -35,10 +35,11 @@ export type MigrationResult =
35
35
  /** Reads a legacy plaintext item. Prompt-free — these were always written
36
36
  * unauthenticated. Kept exported so the provider can still serve a session
37
37
  * whose migration failed, instead of showing the user an empty wallet. */
38
- export async function readLegacySecret(name: SecretName): Promise<string | null> {
38
+ export async function readLegacySecret(name: SecretName, options?: { strict?: boolean }): Promise<string | null> {
39
39
  try {
40
40
  return await SecureStore.getItemAsync(LEGACY_KEYS[name])
41
- } catch {
41
+ } catch (err) {
42
+ if (options?.strict) throw err
42
43
  return null
43
44
  }
44
45
  }