@bsv/expo-wallet-toolbox 0.2.1 → 0.3.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/README.md CHANGED
@@ -34,7 +34,7 @@ four dozen packages beyond the four listed — Expo native modules
34
34
  (camera, clipboard, secure-store, haptics, ...), state/i18n libraries
35
35
  (mobx, i18next), and BSV SDK packages. The **[Peer dependencies](#peer-dependencies)**
36
36
  table below is the full, audited list — `package.json`'s `peerDependencies`
37
- now declares all 49 entries (46 directly imported + 3 required only for
37
+ now declares all 50 entries (47 directly imported + 3 required only for
38
38
  native linking — see the Nitro row below), so a plain `npm install
39
39
  @bsv/expo-wallet-toolbox` surfaces the rest as peer-dependency warnings
40
40
  instead of silently missing them.
@@ -104,6 +104,26 @@ Expo SDK line.
104
104
  | `react-native-svg` | 15.15.3 |
105
105
  | `react-native-sse` | ^1.2.1 |
106
106
 
107
+ ### Pure JS rendering (required)
108
+
109
+ | Package | Version |
110
+ | --- | --- |
111
+ | `@urbit/sigil-js` | ^2.2.0 |
112
+
113
+ Draws the counterparty avatar on activity rows. This package imports only
114
+ its `./core` entry: the package root pulls in a DOM renderer that touches
115
+ `document` at import time. `./core` ships CJS, so Jest needs neither a
116
+ `transformIgnorePatterns` entry nor a mock for it (see
117
+ [Jest configuration](#jest-configuration)).
118
+
119
+ `./core` exists only as an entry in the package's `exports` map (there is no
120
+ `core.js` at the package root), so Metro's package-exports resolution must stay
121
+ enabled (`resolver.unstable_enablePackageExports`, on by default since Expo
122
+ SDK 53). A host that has switched it off to work around another dual-package
123
+ problem gets `Unable to resolve module @urbit/sigil-js/core` at bundle time;
124
+ the fix is a `resolveRequest` that maps `@urbit/sigil-js/core` to
125
+ `@urbit/sigil-js/dist/core.js`.
126
+
107
127
  ### State & i18n (required)
108
128
 
109
129
  | Package | Version |
@@ -429,6 +449,11 @@ are required — both hard-won during this package's extraction:
429
449
  directly), and `@bsv/backup-cache-client` (see below) must be in
430
450
  whatever pattern you end up with.
431
451
 
452
+ `@urbit/sigil-js`, the peer added with the activity-row sigil avatars,
453
+ needs no entry here: the `./core` entry this package imports ships CJS,
454
+ so Jest loads it untransformed. Install it alongside the other peers and
455
+ nothing else in this section changes.
456
+
432
457
  2. **Native-module and ESM-only-package mocks** — anything the package
433
458
  touches that has no pure-JS Jest-safe implementation, or that ships
434
459
  as ESM-only with no `require` export condition, needs a
@@ -58,7 +58,8 @@ const formatCurrency = (
58
58
  locale: string,
59
59
  currency: string,
60
60
  minDigits: number,
61
- maxDigits?: number
61
+ maxDigits?: number,
62
+ showPlus = false
62
63
  ): string => {
63
64
  const abs = Math.abs(value)
64
65
  let formatted: string
@@ -78,9 +79,14 @@ const formatCurrency = (
78
79
  } catch {
79
80
  formatted = `${currency} ${abs.toFixed(minDigits)}`
80
81
  }
81
- return value < 0 ? `(${formatted})` : formatted
82
+ // Same sign convention as the satoshi formatter, so a column of mixed
83
+ // currencies reads one way: minus for money out, plus for money in when the
84
+ // caller asks for it. Accounting parentheses were dropped because the row's
85
+ // direction cue lives in the sign, and "(...)" is not one.
86
+ return `${fiatSign(value, showPlus)}${formatted}`
82
87
  }
83
88
 
89
+ const fiatSign = (value: number, showPlus: boolean): string => (value < 0 ? '-' : showPlus && value > 0 ? '+' : '')
84
90
  /**
85
91
  * Format a satoshi amount as a locale-aware integer string with grouping separators.
86
92
  * E.g. 1234567 -> "1,234,567" (en-US) or "1.234.567" (de-DE)
@@ -113,38 +119,18 @@ const formatBsvLocale = (bsvValue: number): string => {
113
119
  }
114
120
  }
115
121
 
116
- /**
117
- * Format a sub-cent USD value as cents (¢).
118
- * Dynamically adjusts decimal precision based on magnitude.
119
- */
120
- const formatCents = (cents: number): string => {
121
- const absCents = Math.abs(cents)
122
- let maxDigits = 2
123
- if (absCents < 0.01) maxDigits = 4
124
- else if (absCents < 0.1) maxDigits = 3
125
-
126
- try {
127
- const formatted = new Intl.NumberFormat(localeDefault, {
128
- minimumFractionDigits: 0,
129
- maximumFractionDigits: maxDigits,
130
- useGrouping: true
131
- }).format(cents)
132
- return `${formatted}¢`
133
- } catch {
134
- return `${parseFloat(cents.toFixed(maxDigits))}¢`
135
- }
136
- }
137
-
138
122
  /**
139
123
  * Format a satoshi amount as fiat using satoshis-per-unit of that currency.
140
- * Values below one minor unit (1 cent, 1 yen, …) display as "< {smallest}".
141
- * Otherwise rounds up to the currency's minor unit.
124
+ * Values below one minor unit (1 cent, 1 yen, …) display as "< {smallest}",
125
+ * with the sign on the figure ("< -$0.01"). Otherwise rounds up to the
126
+ * currency's minor unit.
142
127
  */
143
128
  export const formatSatoshisAsFiat = (
144
129
  satoshis: number,
145
130
  satoshisPerUnit: number,
146
131
  showFiatAsInteger = false,
147
- currency = 'USD'
132
+ currency = 'USD',
133
+ showPlus = false
148
134
  ): string => {
149
135
  if (!Number.isInteger(Number(satoshis)) || !satoshisPerUnit || satoshisPerUnit <= 0) {
150
136
  return '...'
@@ -160,7 +146,7 @@ export const formatSatoshisAsFiat = (
160
146
 
161
147
  if (v > 0 && v < threshold && !showFiatAsInteger) {
162
148
  const smallest = formatCurrency(threshold, localeDefault, currency, digits, digits)
163
- return raw < 0 ? `< (${smallest})` : `< ${smallest}`
149
+ return `< ${fiatSign(raw, showPlus)}${smallest}`
164
150
  }
165
151
 
166
152
  const sign = raw < 0 ? -1 : 1
@@ -169,7 +155,7 @@ export const formatSatoshisAsFiat = (
169
155
  const minDigits = showFiatAsInteger ? 0 : digits
170
156
  const maxDigits = showFiatAsInteger ? 0 : digits
171
157
 
172
- return formatCurrency(rounded, localeDefault, currency, minDigits, maxDigits)
158
+ return formatCurrency(rounded, localeDefault, currency, minDigits, maxDigits, showPlus)
173
159
  }
174
160
 
175
161
  /**
@@ -212,7 +198,7 @@ export const formatAmount = (
212
198
 
213
199
  if (isFiatCurrency(currency)) {
214
200
  const per = satoshisPerFiatUnit(currency, satoshisPerUSD, usdToFiat)
215
- return formatSatoshisAsFiat(satoshis, per, showFiatAsInteger, currency)
201
+ return formatSatoshisAsFiat(satoshis, per, showFiatAsInteger, currency, showPlus)
216
202
  }
217
203
 
218
204
  return formatSatoshisAsBsv(satoshis, showPlus, abbreviate)
@@ -118,6 +118,18 @@ const DEFAULT_SETTINGS: WalletSettings = {
118
118
  iconUrl: 'https://whoiam.bsvblockchain.tech/whoiam.png',
119
119
  identityKey: '02e7eeb3986273db6843b790a1595ed0ff1b2ae8f43ae2e7f1a0c9db4dd3fb9441',
120
120
  trust: 5
121
+ },
122
+ // Values as published in https://auth.sigmaidentity.com/manifest.json
123
+ // (babbage.trust). Lowest trust of the shipped set: it is the newest
124
+ // certifier here and the list is ordered by trust on the Trust screen.
125
+ // The icon is an SVG; the Trust screen draws those with react-native-svg
126
+ // rather than the platform decoder, which mispositions its <text> glyph.
127
+ {
128
+ name: 'Sigma Identity',
129
+ description: 'Certifies verified identity claims',
130
+ iconUrl: 'https://auth.sigmaidentity.com/sigma-mark.svg',
131
+ identityKey: '02250905f0383085b53409876aefbf01fc8e7fd841922dc4ce55ae035b31341e6d',
132
+ trust: 2
121
133
  }
122
134
  ]
123
135
  }
@@ -168,7 +180,7 @@ import { inputTxidsFromRawTx, shouldDeferSendWaiting } from '../storage/skipQueu
168
180
  import { provenTxFromBump } from '../pay/provenTxFromBump'
169
181
  import { recordProof } from '../pay/recordProof'
170
182
  import { makeCreditClassifier } from '../pay/creditErrors'
171
- import { creditInboxOnce, INBOX_DESCRIPTION } from '../pay/creditInbox'
183
+ import { creditInboxOnce } from '../pay/creditInbox'
172
184
  import { isReceiveInboxFocused } from '../pay/receiveFocus'
173
185
  import { sounds } from '../hooks/useConfirmationSound'
174
186
  import i18n from '../i18n/translations'
@@ -1394,8 +1406,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1394
1406
  storage: phoneStorage!,
1395
1407
  classify,
1396
1408
  accept: payment =>
1397
- acceptWithRetry(client, messageBoxUrl, payment, INBOX_DESCRIPTION, (p, d) =>
1398
- internalizeIncoming(permissionsManager as never, client, adminOriginator, p, d, repairBeef)
1409
+ acceptWithRetry(client, messageBoxUrl, payment, p =>
1410
+ internalizeIncoming(permissionsManager as never, client, adminOriginator, p, repairBeef)
1399
1411
  )
1400
1412
  })
1401
1413
  return { accepted: r.accepted, attention: r.attentionCount, pending: r.pending }
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
+ }