@bsv/expo-wallet-toolbox 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +0 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +9 -1
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +409 -20
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +97 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/storage/StorageExpoSQLite.ts +382 -56
  54. package/core/storage/dbImage.ts +48 -0
  55. package/core/storage/methods/findSql.ts +0 -54
  56. package/core/storage/methods/listOutputsSql.ts +7 -3
  57. package/core/storage/methods/offlineActions.ts +15 -0
  58. package/core/storage/methods/processOfflineActions.ts +263 -6
  59. package/core/storage/methods/walletBalanceSql.ts +16 -4
  60. package/core/storage/schema/createTables.ts +123 -0
  61. package/core/storage/sqlUpdateValue.ts +24 -0
  62. package/core/toolboxConfig.ts +112 -1
  63. package/core/walletRepair/runWalletCheck.ts +19 -2
  64. package/package.json +25 -24
  65. package/ui/components/QRScanner.tsx +1 -1
  66. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  67. package/ui/components/pay/AssetPicker.tsx +184 -0
  68. package/ui/components/pay/AvailableBalance.tsx +33 -2
  69. package/ui/components/pay/HandleReceive.tsx +213 -50
  70. package/ui/components/pay/NearbyFlow.tsx +616 -69
  71. package/ui/components/pay/PayForm.tsx +73 -8
  72. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  73. package/ui/components/pay/RecipientField.tsx +49 -4
  74. package/ui/components/pay/RequestHub.tsx +68 -8
  75. package/ui/components/pay/ResultBanner.tsx +41 -4
  76. package/ui/components/pay/UniversalSend.tsx +534 -30
  77. package/ui/components/pay/tokenSendCopy.ts +116 -0
  78. package/ui/components/pay/useRecipientInput.ts +36 -7
  79. package/ui/components/ui/PermissionSheet.tsx +65 -4
  80. package/ui/components/ui/Sheet.tsx +9 -2
  81. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  82. package/ui/components/vault/KeyChooser.tsx +96 -0
  83. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  84. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  85. package/ui/components/wallet/ActivityRow.tsx +101 -17
  86. package/ui/components/wallet/AmountInput.tsx +77 -25
  87. package/ui/components/wallet/AssetAmount.tsx +95 -0
  88. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  89. package/ui/components/wallet/tokenEviction.ts +65 -0
  90. package/ui/hooks/useExportWalletData.ts +39 -0
  91. package/ui/hooks/useMandala.ts +303 -0
  92. package/ui/hooks/useVaultBalance.ts +105 -7
  93. package/ui/hooks/useVaultCoverage.ts +52 -0
  94. package/ui/importDatabases.ts +7 -3
  95. package/ui/index.ts +50 -7
  96. package/ui/screens/ConnectionsScreen.tsx +46 -29
  97. package/ui/screens/PairScreen.tsx +12 -12
  98. package/ui/screens/PayScreen.tsx +130 -10
  99. package/ui/screens/SettingsScreen.tsx +18 -9
  100. package/ui/screens/VaultScreen.tsx +925 -171
  101. package/ui/screens/VaultTransferScreen.tsx +376 -123
  102. package/ui/screens/WalletCheckScreen.tsx +10 -1
  103. package/ui/screens/WalletConfigScreen.tsx +38 -16
  104. package/ui/screens/WalletHomeScreen.tsx +417 -86
  105. package/ui/screens/homeBadges.ts +9 -1
  106. package/ui/screens/tokenRowTitle.ts +68 -0
  107. package/ui/tokenFormat.ts +108 -0
  108. package/ui/tokenSeen.ts +75 -0
  109. package/ui/tokenStatus.ts +79 -0
  110. package/assets/sounds/vault-close.wav +0 -0
  111. package/assets/sounds/vault-open.wav +0 -0
  112. package/core/services/vault/k1.ts +0 -75
  113. package/core/services/vault/sealing.ts +0 -84
  114. package/core/services/vault/vaultDerivation.ts +0 -152
  115. package/core/services/vault/vaultPassphrase.ts +0 -287
  116. package/ui/components/vault/PassphraseField.tsx +0 -306
  117. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  118. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,4 +1,4 @@
1
- export type HomeBadgeKind = 'attention' | 'unsent' | 'offline'
1
+ export type HomeBadgeKind = 'attention' | 'unsent' | 'token_attention' | 'offline'
2
2
 
3
3
  export type HomeBadge = { kind: HomeBadgeKind; count: number }
4
4
 
@@ -8,10 +8,18 @@ export function homeBadges(input: {
8
8
  unsent: number
9
9
  offlineQueued: number
10
10
  offlineRejected: number
11
+ /**
12
+ * Token payments that have been waiting to settle past the stuck bound
13
+ * (FIX M). They are not failures — the money is credited and spendable — but
14
+ * "they said they sent it and it never confirmed" must have a surface, or the
15
+ * only way to notice is to not notice.
16
+ */
17
+ tokenAttention?: number
11
18
  }): HomeBadge[] {
12
19
  const badges: HomeBadge[] = []
13
20
  if (input.attention > 0) badges.push({ kind: 'attention', count: input.attention })
14
21
  if (input.unsent > 0) badges.push({ kind: 'unsent', count: input.unsent })
22
+ if ((input.tokenAttention ?? 0) > 0) badges.push({ kind: 'token_attention', count: input.tokenAttention as number })
15
23
  const offline = input.offlineQueued + input.offlineRejected
16
24
  if (offline > 0) badges.push({ kind: 'offline', count: offline })
17
25
  return badges
@@ -0,0 +1,68 @@
1
+ import { PEERPAY_LABEL } from '../../core/localpay/pending'
2
+
3
+ const NEARBY_FIXED: Record<'sent' | 'received', string> = {
4
+ sent: 'Sent token',
5
+ received: 'Received token'
6
+ }
7
+
8
+ /**
9
+ * The message-box rail's own fixed wording (`@bsv/mandala`'s `transfer.ts`
10
+ * `Send ${amount} of ${assetId}` / `receive.ts` `Receive ${amount} of
11
+ * ${assetId}`), reconstructed from the row's own fields so it can be told
12
+ * apart from a real note. Requires `assetId`/`baseUnits` — without them
13
+ * there is nothing to reconstruct against, so the caller below treats the
14
+ * rail as unrecognised rather than guess.
15
+ */
16
+ function messageBoxFixed(role: 'sent' | 'received', assetId?: string, baseUnits?: number): string | undefined {
17
+ if (assetId === undefined || baseUnits === undefined) return undefined
18
+ return `${role === 'sent' ? 'Send' : 'Receive'} ${baseUnits} of ${assetId}`
19
+ }
20
+
21
+ /**
22
+ * The fixed wording for whichever rail authored this action, or `undefined`
23
+ * when the action carries neither rail's marker label — in which case the
24
+ * description is never trusted as a note (see `tokenRowTitle`'s doc).
25
+ */
26
+ function fixedDescriptionFor(
27
+ role: 'sent' | 'received',
28
+ labels: string[] | undefined,
29
+ assetId: string | undefined,
30
+ baseUnits: number | undefined
31
+ ): string | undefined {
32
+ const set = new Set(labels ?? [])
33
+ if (set.has(PEERPAY_LABEL)) return NEARBY_FIXED[role]
34
+ if (set.has('transfer') || set.has('receive')) return messageBoxFixed(role, assetId, baseUnits)
35
+ return undefined
36
+ }
37
+
38
+ /**
39
+ * A token activity row's title. Normally the fixed "Sent/Received <ticker>"
40
+ * template (`token_row_sent`/`token_row_received`) — but a sender's own note
41
+ * overrides it, same as a BSV row's description already does.
42
+ *
43
+ * Two rails write a real note into `description` today: the nearby rail
44
+ * (label `'localpay'`, fixed wording "Sent/Received token") and the
45
+ * message-box rail (label `'transfer'`/`'receive'`, `@bsv/mandala`'s own
46
+ * fixed wording "Send/Receive N of assetId"). An action from neither rail —
47
+ * or a message-box action missing the `assetId`/`baseUnits` needed to
48
+ * reconstruct its fixed wording — never has its description shown: it may be
49
+ * an opaque developer string the lib wrote for some other purpose, not
50
+ * anything a user typed (the reason this override existed in the first
51
+ * place).
52
+ */
53
+ export function tokenRowTitle(args: {
54
+ role: 'sent' | 'received'
55
+ ticker: string
56
+ labels?: string[]
57
+ description?: string
58
+ /** The row's own asset id — needed to recognise the message-box rail's fixed wording. */
59
+ assetId?: string
60
+ /** The row's own amount, in base units — same reason as `assetId`. */
61
+ baseUnits?: number
62
+ t: (key: string, values?: Record<string, unknown>) => string
63
+ }): string {
64
+ const fixed = fixedDescriptionFor(args.role, args.labels, args.assetId, args.baseUnits)
65
+ const hasNote = fixed !== undefined && !!args.description && args.description !== fixed
66
+ if (hasNote) return args.description as string
67
+ return args.t(args.role === 'sent' ? 'token_row_sent' : 'token_row_received', { ticker: args.ticker })
68
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Token money, formatted so the wallet never prints a number it cannot stand
3
+ * behind (ux §1 principle 4).
4
+ *
5
+ * Two rules the BSV helpers do not enforce and cannot be bent to:
6
+ *
7
+ * 1. FIXED decimals, never trimmed. `1,240.00 USDX` is money; `1,240 USDX` is
8
+ * a quantity, and the difference is what a holder reads as "cents exist
9
+ * here". The lib's own `formatAmount` right-trims, so every figure in the
10
+ * design is unreachable through it.
11
+ * 2. Integer arithmetic only. A balance is base units; dividing by 10^decimals
12
+ * in floating point and then rounding is how a wallet prints 1,239.99 for
13
+ * 124000 at 2 dp. The split below is string surgery on the integer, so the
14
+ * printed digits are exactly the digits that are owned.
15
+ *
16
+ * There is deliberately no fiat path and no currency symbol: the wallet has no
17
+ * price for a token and a `$` beside a USD-ticker balance would be the wallet
18
+ * vouching for someone else's peg (ux §6.1).
19
+ */
20
+
21
+ /** Grouping separators for the integer part, in the device's own locale. */
22
+ function groupInteger(digits: string): string {
23
+ const n = Number(digits)
24
+ if (!Number.isFinite(n)) return digits
25
+ // Safe: the integer part of a base-unit figure is always smaller than the
26
+ // figure itself, and anything past 2^53 is already unrepresentable upstream.
27
+ return n.toLocaleString(undefined, { useGrouping: true, maximumFractionDigits: 0 })
28
+ }
29
+
30
+ /**
31
+ * `1240000` at 2 dp → `"1,240.00"`. Negative inputs keep their sign; a
32
+ * non-finite input is refused with `null` rather than rendered as `NaN`, so a
33
+ * caller that forgot to guard prints nothing instead of nonsense.
34
+ */
35
+ export function formatTokenAmount(
36
+ baseUnits: number,
37
+ decimals: number,
38
+ opts: { showPlus?: boolean } = {}
39
+ ): string | null {
40
+ if (!Number.isFinite(baseUnits) || !Number.isFinite(decimals) || decimals < 0) return null
41
+ const d = Math.floor(decimals)
42
+ const rounded = Math.round(Math.abs(baseUnits))
43
+ const digits = String(rounded).padStart(d + 1, '0')
44
+ const intPart = d === 0 ? digits : digits.slice(0, digits.length - d)
45
+ const fracPart = d === 0 ? '' : digits.slice(digits.length - d)
46
+ const body = d === 0 ? groupInteger(intPart) : `${groupInteger(intPart)}.${fracPart}`
47
+ const sign = baseUnits < 0 ? '−' : opts.showPlus ? '+' : ''
48
+ return `${sign}${body}`
49
+ }
50
+
51
+ /** `"1,240.00"` + `"USDX"` — the two halves a money figure is drawn from. */
52
+ export function tokenAmountParts(
53
+ baseUnits: number,
54
+ asset: { decimals: number; ticker: string },
55
+ opts: { showPlus?: boolean } = {}
56
+ ): { value: string; unit: string } | null {
57
+ const value = formatTokenAmount(baseUnits, asset.decimals, opts)
58
+ if (value === null) return null
59
+ return { value, unit: asset.ticker }
60
+ }
61
+
62
+ /** `"1,240.00 USDX"` — the one string VoiceOver reads for a token figure. */
63
+ export function formatTokenAmountWithUnit(
64
+ baseUnits: number,
65
+ asset: { decimals: number; ticker: string },
66
+ opts: { showPlus?: boolean } = {}
67
+ ): string | null {
68
+ const parts = tokenAmountParts(baseUnits, asset, opts)
69
+ return parts && `${parts.value} ${parts.unit}`
70
+ }
71
+
72
+ /**
73
+ * A typed display figure back to base units, for the amount field.
74
+ *
75
+ * Returns `null` for anything that is not a whole number of base units — blank,
76
+ * junk, or more decimal places than the asset has. The field never emits a
77
+ * fraction: the wire takes integers, and a rounded one would silently pay a
78
+ * different amount than the one on screen.
79
+ */
80
+ export function parseTokenAmount(text: string, decimals: number): number | null {
81
+ if (!Number.isFinite(decimals) || decimals < 0) return null
82
+ const trimmed = text.trim()
83
+ if (!trimmed) return null
84
+ const d = Math.floor(decimals)
85
+ const match = new RegExp(`^(\\d*)(?:\\.(\\d{0,${d}}))?$`).exec(trimmed)
86
+ if (!match) return null
87
+ const intPart = match[1] ?? ''
88
+ const fracPart = (match[2] ?? '').padEnd(d, '0')
89
+ if (!intPart && !match[2]) return null
90
+ const combined = `${intPart || '0'}${fracPart}`
91
+ const value = Number(combined)
92
+ return Number.isSafeInteger(value) ? value : null
93
+ }
94
+
95
+ /** The input mask for an asset's decimals: digits, one point, at most N places. */
96
+ export function tokenAmountMask(decimals: number): RegExp {
97
+ const d = Math.max(0, Math.floor(decimals))
98
+ return d === 0 ? /^\d*$/ : new RegExp(`^\\d*\\.?\\d{0,${d}}$`)
99
+ }
100
+
101
+ /** Base units → the exact display string the amount field should hold. */
102
+ export function tokenAmountInputText(baseUnits: number, decimals: number): string {
103
+ const formatted = formatTokenAmount(baseUnits, decimals)
104
+ if (formatted === null) return ''
105
+ // The field is typed, not read: no grouping separators, which a decimal-pad
106
+ // cannot produce and `parseTokenAmount` would refuse on the next keystroke.
107
+ return formatted.replace(/[^\d.]/g, '')
108
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * "Has the user already been told?" — two small persisted sets.
3
+ *
4
+ * · `mandala_seen_assets` clears an asset row's "New — tap to see who issues
5
+ * it" subtitle once the sheet has actually been opened. Disclosure that
6
+ * re-announces itself after it has been read is noise.
7
+ * · `mandala_seen_evictions` makes the withdrawal alert fire exactly once per
8
+ * transaction. An alert about money leaving is the most interruptive thing
9
+ * this feature does; raising it again on every foreground would train the
10
+ * user to dismiss it unread.
11
+ *
12
+ * AsyncStorage rather than the wallet database on purpose: this is a fact about
13
+ * what a person has seen on this device, not a fact about money, and it must
14
+ * never be able to block, delay or fail a payment path. Every read fails to the
15
+ * empty set, which errs toward telling the user again.
16
+ */
17
+ import { useCallback, useEffect, useState } from 'react'
18
+ import AsyncStorage from '@react-native-async-storage/async-storage'
19
+
20
+ export const SEEN_ASSETS_KEY = 'mandala_seen_assets'
21
+ export const SEEN_EVICTIONS_KEY = 'mandala_seen_evictions'
22
+
23
+ export async function readSeen(key: string): Promise<string[]> {
24
+ try {
25
+ const raw = await AsyncStorage.getItem(key)
26
+ if (!raw) return []
27
+ const parsed: unknown = JSON.parse(raw)
28
+ return Array.isArray(parsed) ? parsed.filter((v): v is string => typeof v === 'string') : []
29
+ } catch {
30
+ return []
31
+ }
32
+ }
33
+
34
+ export async function markSeen(key: string, id: string): Promise<void> {
35
+ try {
36
+ const current = await readSeen(key)
37
+ if (current.includes(id)) return
38
+ await AsyncStorage.setItem(key, JSON.stringify([...current, id]))
39
+ } catch {
40
+ // Cosmetic state. A write failure means one repeated subtitle or one
41
+ // repeated alert, never a wrong balance.
42
+ }
43
+ }
44
+
45
+ export interface SeenSet {
46
+ seen: string[]
47
+ isSeen: (id: string) => boolean
48
+ see: (id: string) => void
49
+ }
50
+
51
+ export function useSeenSet(key: string): SeenSet {
52
+ const [seen, setSeen] = useState<string[]>([])
53
+
54
+ useEffect(() => {
55
+ let live = true
56
+ void readSeen(key).then(ids => {
57
+ if (live) setSeen(ids)
58
+ })
59
+ return () => {
60
+ live = false
61
+ }
62
+ }, [key])
63
+
64
+ const see = useCallback(
65
+ (id: string) => {
66
+ setSeen(prev => (prev.includes(id) ? prev : [...prev, id]))
67
+ void markSeen(key, id)
68
+ },
69
+ [key]
70
+ )
71
+
72
+ const isSeen = useCallback((id: string) => seen.includes(id), [seen])
73
+
74
+ return { seen, isSeen, see }
75
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * What a token row's settlement state is called, and in what colour.
3
+ *
4
+ * Five states reach the UI (`TokenActivityStatus`), and the mapping is here
5
+ * rather than inside a component so the same word appears in the activity list,
6
+ * the Asset sheet and the home badge without three chances to disagree.
7
+ *
8
+ * Colour follows the app's one chroma rule: green means confirmed money and
9
+ * nothing else, so only `settled` earns it. `settling` is not a warning — it is
10
+ * the ordinary state of an offline payment that has not yet reached the issuer,
11
+ * and painting it amber would make the normal case look like a fault.
12
+ */
13
+ import type { TokenActivityStatus } from '../core/mandala/runtime'
14
+
15
+ export type TokenStatusTone = 'neutral' | 'positive' | 'warning' | 'error'
16
+
17
+ const KEYS: Record<TokenActivityStatus, string> = {
18
+ settling: 'token_status_settling',
19
+ settled: 'token_status_settled',
20
+ refused: 'token_status_refused',
21
+ reversed: 'token_status_reversed',
22
+ stuck: 'token_status_stuck'
23
+ }
24
+
25
+ const TONES: Record<TokenActivityStatus, TokenStatusTone> = {
26
+ settling: 'neutral',
27
+ settled: 'positive',
28
+ refused: 'error',
29
+ reversed: 'error',
30
+ stuck: 'warning'
31
+ }
32
+
33
+ export function tokenStatusKey(status: TokenActivityStatus): string {
34
+ return KEYS[status] ?? KEYS.settling
35
+ }
36
+
37
+ export function tokenStatusTone(status: TokenActivityStatus): TokenStatusTone {
38
+ return TONES[status] ?? 'neutral'
39
+ }
40
+
41
+ /**
42
+ * The sentence a finished-but-unhappy row explains itself with, or `null` when
43
+ * the status word is the whole story. Refusal and reversal are the two states a
44
+ * holder is owed an explanation for, because money moved back.
45
+ *
46
+ * `refusedCode` narrows a `stuck` or `received`-`refused` row to a more exact
47
+ * reason, the same way `tokenSendCopy.ts` narrows a live send failure — by
48
+ * substring match against the wire's `ERR_*` vocabulary
49
+ * (`docs/.../mandala-wire-contract-v2.md`), because the code space spans two
50
+ * overlay engines and the manager's own free-text reject reasons. Unmatched
51
+ * or absent falls back to the plain status sentence, which is true for every
52
+ * one of them.
53
+ */
54
+ export function tokenStatusDetailKey(
55
+ status: TokenActivityStatus,
56
+ role: 'sent' | 'received',
57
+ refusedCode?: string
58
+ ): string | null {
59
+ const code = (refusedCode ?? '').toLowerCase()
60
+ const has = (...needles: string[]) => needles.some(n => code.includes(n))
61
+
62
+ if (status === 'stuck') {
63
+ if (has('pause')) return 'token_settle_paused_retry'
64
+ return 'token_settle_unreachable_retry'
65
+ }
66
+ if (status === 'refused') {
67
+ if (role === 'sent') return 'token_err_refused'
68
+ // Received side: a chain-linkage reason means an ancestor in the transfer
69
+ // was the one refused, not this frame's own content; anything else that
70
+ // is a content-shape reason reads as an unreadable frame rather than a
71
+ // generic reversal. Both are narrower, truer sentences than the plain
72
+ // "could not be confirmed" fallback.
73
+ if (has('linkage')) return 'token_chain_reversed'
74
+ if (has('shape', 'conservation', 'satoshi')) return 'token_frame_unreadable'
75
+ return 'token_recv_reversed'
76
+ }
77
+ if (status === 'reversed') return 'token_settle_evicted'
78
+ return null
79
+ }
Binary file
Binary file
@@ -1,75 +0,0 @@
1
- /**
2
- * The K1 vault script: byte-length constants, the customInstructions codec,
3
- * and locking-script construction.
4
- *
5
- * Every K1 detail lives here so no other module needs to know the template's
6
- * shape. A K1 vault output is a plain P2PKH output — no R1/YubiKey leg, no
7
- * template contract — locked to a BIP32 child key derived per
8
- * services/vault/vaultDerivation.ts.
9
- *
10
- * SECURITY: nothing secret passes through this module — only public keys,
11
- * hashes, and script bytes.
12
- */
13
- import { LockingScript, P2PKH } from '@bsv/sdk'
14
-
15
- /** Exact: a P2PKH locking script is always
16
- * OP_DUP OP_HASH160 push(20) OP_EQUALVERIFY OP_CHECKSIG = 1+1+1+20+1+1 = 25 bytes. */
17
- export const K1_LOCK_LEN = 25
18
-
19
- /** Conservative estimate, not exact: a real P2PKH unlock measures ~107 bytes
20
- * (push(≤72-byte DER sig) + push(33-byte compressed pubkey)), matching the
21
- * staging-unlock shape the legacy reclaim still builds (see transfers.ts's
22
- * reclaimStagingOutputs). DER signatures
23
- * vary between 70 and 72 bytes, so this pins the ceiling rather than the
24
- * exact length. */
25
- export const K1_UNLOCK_LEN = 108
26
-
27
- /**
28
- * What a K1 vault output records about itself.
29
- *
30
- * `v` is the customInstructions format version and is a hard fork from the
31
- * old template-based line: v2 records carry a different type discriminator
32
- * entirely and must never decode as v3 — see decodeVaultInstructions.
33
- */
34
- export interface VaultInstructions {
35
- v: 3
36
- type: 'K1'
37
- /** BIP32 child key ID, e.g. 'bip32/7'. See vaultDerivation.ts's
38
- * BIP32_KEYID_PREFIX / bip32KeyID. */
39
- keyID: string
40
- }
41
-
42
- export function encodeVaultInstructions(i: VaultInstructions): string {
43
- return JSON.stringify(i)
44
- }
45
-
46
- /**
47
- * Parse an output's customInstructions, or null if it is not a well-formed
48
- * K1 v3 record.
49
- *
50
- * Fails closed on anything unrecognised — including old v2 R1-K1 records —
51
- * because a malformed record means an output we cannot construct a valid
52
- * spend for, and silently dropping it from the spendable set beats building
53
- * a transaction that cannot be signed.
54
- */
55
- export function decodeVaultInstructions(ci?: string): VaultInstructions | null {
56
- if (!ci) return null
57
- let parsed: unknown
58
- try {
59
- parsed = JSON.parse(ci)
60
- } catch {
61
- return null
62
- }
63
- if (!parsed || typeof parsed !== 'object') return null
64
- const p = parsed as Partial<VaultInstructions>
65
- if (p.v !== 3 || p.type !== 'K1') return null
66
- if (typeof p.keyID !== 'string' || !p.keyID.startsWith('bip32/')) return null
67
- return { v: 3, type: 'K1', keyID: p.keyID }
68
- }
69
-
70
- /** Build a K1 vault locking script: a plain P2PKH lock to the given public
71
- * key hash. Synchronous — there is no template to await; callers may still
72
- * `await` this without effect. */
73
- export function buildVaultLockingScript(a: { k1PublicKeyHash: number[] }): LockingScript {
74
- return new P2PKH().lock(a.k1PublicKeyHash)
75
- }
@@ -1,84 +0,0 @@
1
- /**
2
- * Vault sealing crypto — pure functions, no I/O, no logging.
3
- *
4
- * Scheme (`bsvb-vault-seal-v1`, the age-plugin-yubikey / systemd-cryptenroll
5
- * PKCS#11 pattern):
6
- *
7
- * seal : ephemeral P-256 keypair e/E; S = ECDH(e, yubiPub);
8
- * KEK = HKDF-SHA256(S, salt, info); C = AES-256-GCM(KEK, V)
9
- * unseal : S = on-token ECDH(slot, E) ← the touch-gated step;
10
- * KEK = HKDF(S, salt, info); V = AES-GCM-decrypt(KEK, C)
11
- *
12
- * The token returns the 32-byte x-coordinate of the shared point (PIV
13
- * KeyAgreement semantics); softwareEcdh mirrors that exactly so both sides
14
- * derive the same KEK.
15
- *
16
- * SECURITY: never log inputs or outputs of these functions.
17
- */
18
- import { p256 } from '@noble/curves/nist.js'
19
- import { Hash, SymmetricKey, Utils } from '@bsv/sdk'
20
- import { SealedBlob, VaultError } from './types'
21
- import { randomBytes } from './random'
22
- import { hkdfSha256 } from '../secrets/hkdf'
23
-
24
- export const SEAL_INFO = 'bsvb-vault-seal-v1'
25
-
26
- /** ECDH over P-256 returning the hex x-coordinate (32 bytes) — the same value
27
- * a YubiKey's PIV KeyAgreement operation produces. */
28
- export function softwareEcdh(privHex: string, pubHex: string): string {
29
- const priv = Uint8Array.from(Utils.toArray(privHex, 'hex'))
30
- const pub = Uint8Array.from(Utils.toArray(pubHex, 'hex'))
31
- const shared = p256.getSharedSecret(priv, pub, false) // 65B uncompressed point
32
- return Utils.toHex(Array.from(shared.slice(1, 33)))
33
- }
34
-
35
- /** Generate a fresh ephemeral P-256 scalar from our own entropy source
36
- * (avoids depending on a WebCrypto global under React Native). */
37
- function ephemeralKeypair(): { privHex: string; pubHex: string } {
38
- // Rejection-sample until the scalar is valid for the curve (overwhelmingly
39
- // first-try; the loop is belt-and-braces).
40
- for (;;) {
41
- const candidate = Uint8Array.from(randomBytes(32))
42
- try {
43
- const pub = p256.getPublicKey(candidate, false)
44
- return { privHex: Utils.toHex(Array.from(candidate)), pubHex: Utils.toHex(Array.from(pub)) }
45
- } catch {
46
- // invalid scalar (zero or >= order) — draw again
47
- }
48
- }
49
- }
50
-
51
- /** Seal the vault key V to a YubiKey's PIV public key. Software-only —
52
- * requires no token present, so re-sealing and enrollment never need touch. */
53
- export function sealVaultKey(
54
- v: number[],
55
- yubiPubHex: string,
56
- meta: { slot: number; serial: string }
57
- ): SealedBlob {
58
- const { privHex: ePriv, pubHex: ePub } = ephemeralKeypair()
59
- const salt = randomBytes(32)
60
- const shared = softwareEcdh(ePriv, yubiPubHex)
61
- const kek = hkdfSha256(Utils.toArray(shared, 'hex'), salt, SEAL_INFO)
62
- const c = new SymmetricKey(kek).encrypt(v) as number[]
63
- return {
64
- v: 1,
65
- slot: meta.slot,
66
- ePub,
67
- salt: Utils.toHex(salt),
68
- c: Utils.toHex(c),
69
- yubiSerial: meta.serial,
70
- yubiPubSha256: Utils.toHex(Hash.sha256(Utils.toArray(yubiPubHex, 'hex')))
71
- }
72
- }
73
-
74
- /** Recover V from a seal given the token-computed shared secret (hex
75
- * x-coordinate from the ceremony's ECDH). Throws `seal-corrupt` on any
76
- * mismatch — wrong secret, tampered ciphertext, malformed blob. */
77
- export function unsealVaultKey(blob: SealedBlob, sharedSecretHex: string): number[] {
78
- try {
79
- const kek = hkdfSha256(Utils.toArray(sharedSecretHex, 'hex'), Utils.toArray(blob.salt, 'hex'), SEAL_INFO)
80
- return new SymmetricKey(kek).decrypt(Utils.toArray(blob.c, 'hex')) as number[]
81
- } catch {
82
- throw new VaultError('seal-corrupt', 'Vault seal could not be opened')
83
- }
84
- }
@@ -1,152 +0,0 @@
1
- /**
2
- * Vault key derivation — pure functions, no I/O, no logging.
3
- *
4
- * V comes from the SAME mnemonic as the main wallet, domain-separated by a
5
- * non-empty BIP39 passphrase, and deposit addresses are plain BIP32 children:
6
- *
7
- * main wallet : HD.fromSeed(Mnemonic.toSeed(''))
8
- * vault HD node : HD.fromSeed(Mnemonic.toSeed(passphrase))
9
- * deposit addr n : vaultHD.deriveChild(n)
10
- *
11
- * This replaces two earlier designs at once:
12
- * - the second random 24-word mnemonic (the user now backs up ONE phrase)
13
- * - the precomputed queue of 64 deposit key hashes in vault meta
14
- *
15
- * There is no xpub anywhere in this design, and nothing about the vault is
16
- * ever public at rest: the vault stores a YubiKey-sealed seed and a bare
17
- * `nextKeyIndex` counter, nothing else. Deposit address n derives from the
18
- * private HD node, which exists only transiently, after one of the two
19
- * recovery routes below reaches it.
20
- *
21
- * Recovery paths, and there are exactly two:
22
- * 1. YubiKey-unseal of the sealed seed — the YubiKey unwraps the seed,
23
- * which reconstructs this same HD node; nothing to type.
24
- * 2. main mnemonic + passphrase — via this file; the same
25
- * mnemonic and passphrase reconstruct the same HD node offline.
26
- * Both routes reach the identical HD node. There is no third path. Nobody
27
- * can reset it. Deposit address n derives on demand from that node, once
28
- * per unseal, however many indices are needed — unlike the old 64-key
29
- * queue, which failed closed until a privileged ceremony refilled it.
30
- *
31
- * SECURITY: never log the seed, the HD node, the mnemonic, or the passphrase.
32
- */
33
- import { PrivateKey, HD, Mnemonic, Hash } from '@bsv/sdk'
34
- import { normalizeVaultPassphrase } from './vaultPassphrase'
35
- import { randomBytes } from './random'
36
- import { VaultError } from './types'
37
-
38
- /** BIP32 hardened-index boundary. Deposit indices stay below this so the
39
- * derivation path is uniform and predictable across every call site. */
40
- const HARDENED = 0x80000000
41
-
42
- function assertNonHardened(index: number): void {
43
- if (!Number.isInteger(index) || index < 0 || index >= HARDENED) {
44
- throw new VaultError(
45
- 'bad-derivation-index',
46
- `Deposit index must be a non-hardened BIP32 index (0..${HARDENED - 1})`
47
- )
48
- }
49
- }
50
-
51
- /**
52
- * The vault's 64-byte BIP39 seed.
53
- *
54
- * @throws VaultError if the passphrase is empty — an empty passphrase would
55
- * make the vault seed identical to the main wallet's, letting the hot wallet
56
- * spend the vault.
57
- */
58
- export function deriveVaultSeed(mnemonic: string, passphrase: string): number[] {
59
- const pass = normalizeVaultPassphrase(passphrase)
60
- if (pass.length === 0) {
61
- throw new VaultError('bad-passphrase', 'A vault passphrase is required and must not be empty')
62
- }
63
- const phrase = mnemonic.trim().replace(/\s+/g, ' ')
64
- if (!Mnemonic.isValid(phrase)) {
65
- throw new VaultError('bad-mnemonic', 'Invalid recovery phrase')
66
- }
67
- return Mnemonic.fromString(phrase).toSeed(pass)
68
- }
69
-
70
- /**
71
- * Prefix marking a keyID as a BIP32 child index.
72
- *
73
- * Legacy v1 outputs carry BRC-42 key ids of the form 'vault/<n>'. The two must
74
- * stay distinguishable: a signer that mistook one for the other would sign
75
- * with the wrong key and produce an invalid spend.
76
- */
77
- export const BIP32_KEYID_PREFIX = 'bip32/'
78
-
79
- export const bip32KeyID = (index: number): string => `${BIP32_KEYID_PREFIX}${index}`
80
-
81
- /** Index for a BIP32 keyID, or null if this is not one (e.g. a v1 keyID). */
82
- export function indexFromKeyID(keyID: string): number | null {
83
- if (!keyID.startsWith(BIP32_KEYID_PREFIX)) return null
84
- const raw = keyID.slice(BIP32_KEYID_PREFIX.length)
85
- if (!/^\d+$/.test(raw)) return null
86
- const n = Number(raw)
87
- return Number.isSafeInteger(n) && n < HARDENED ? n : null
88
- }
89
-
90
- /** Floor for an adopted vault's first deposit index — above any counter a
91
- * device that started at zero could plausibly have reached. */
92
- const ADOPT_INDEX_MIN = 1 << 20
93
- /** Width of the random span above that floor. Keeps every index well below the
94
- * hardened boundary, so a lifetime of increments can never reach it. */
95
- const ADOPT_INDEX_SPAN = 1 << 28
96
-
97
- /**
98
- * A random, non-hardened starting deposit index.
99
- *
100
- * Used when a device adopts a YubiKey that is already enrolled elsewhere: both
101
- * devices reach the SAME HD node (via the same mnemonic+passphrase, or the
102
- * same unsealed seed), and a device-local counter is the only thing choosing
103
- * indices, so two devices starting at zero would hand out the same deposit
104
- * addresses. Reusing an address does not risk funds — it links
105
- * two deposits and confuses the history — and coordinating counters across
106
- * devices would need a channel the vault deliberately does not have. A random
107
- * start in a 2^28-wide span makes a collision negligible instead.
108
- */
109
- export function randomDepositStartIndex(): number {
110
- const b = randomBytes(4)
111
- const r = ((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]) >>> 0
112
- return ADOPT_INDEX_MIN + (r % ADOPT_INDEX_SPAN)
113
- }
114
-
115
- /**
116
- * The vault's private HD node.
117
- *
118
- * The seed derived here is this function's OWN copy — enrollVault and
119
- * resealToNewKey zeroize the separate arrays they derive for sealing, and
120
- * neither of them can reach this one. Without the wipe below, every call
121
- * (recoverVaultHD, the sweep path, the spend-proof script) would hand a live
122
- * 64-byte seed to the garbage collector instead of overwriting it.
123
- *
124
- * Wiping is safe because `HD.fromSeed` does not retain the array: it
125
- * immediately HMAC-SHA512s it into the chain code and private key
126
- * (@bsv/sdk's compat/HD `fromSeed`) and keeps no reference. The `finally`
127
- * covers the throwing path too — `HD.fromSeed` rejects a seed outside
128
- * 16..64 bytes, and a seed must not survive that refusal either.
129
- */
130
- export function deriveVaultHD(mnemonic: string, passphrase: string): HD {
131
- const seed = deriveVaultSeed(mnemonic, passphrase)
132
- try {
133
- return HD.fromSeed(seed)
134
- } finally {
135
- seed.fill(0)
136
- }
137
- }
138
-
139
- /** Private key for deposit index n. Requires the private node. */
140
- export function depositPrivKey(hd: HD, index: number): PrivateKey {
141
- assertNonHardened(index)
142
- return hd.deriveChild(index).privKey
143
- }
144
-
145
- /**
146
- * Deposit address hash160 for index n. Requires the private node — there is
147
- * no xpub to derive this from without it.
148
- */
149
- export function depositPubKeyHash(hd: HD, index: number): number[] {
150
- assertNonHardened(index)
151
- return Hash.hash160(hd.deriveChild(index).pubKey.encode(true) as number[])
152
- }