@bsv/expo-wallet-toolbox 0.3.1 → 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 (119) hide show
  1. package/CHANGELOG.md +311 -0
  2. package/README.md +52 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +21 -18
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +413 -23
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +107 -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/services/walletServiceConfig.ts +19 -24
  54. package/core/storage/StorageExpoSQLite.ts +382 -56
  55. package/core/storage/dbImage.ts +48 -0
  56. package/core/storage/methods/findSql.ts +0 -54
  57. package/core/storage/methods/listOutputsSql.ts +7 -3
  58. package/core/storage/methods/offlineActions.ts +15 -0
  59. package/core/storage/methods/processOfflineActions.ts +263 -6
  60. package/core/storage/methods/walletBalanceSql.ts +16 -4
  61. package/core/storage/schema/createTables.ts +123 -0
  62. package/core/storage/sqlUpdateValue.ts +24 -0
  63. package/core/toolboxConfig.ts +240 -0
  64. package/core/walletRepair/runWalletCheck.ts +19 -2
  65. package/package.json +25 -24
  66. package/ui/components/QRScanner.tsx +1 -1
  67. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  68. package/ui/components/pay/AssetPicker.tsx +184 -0
  69. package/ui/components/pay/AvailableBalance.tsx +33 -2
  70. package/ui/components/pay/HandleReceive.tsx +213 -50
  71. package/ui/components/pay/NearbyFlow.tsx +616 -69
  72. package/ui/components/pay/PayForm.tsx +73 -8
  73. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  74. package/ui/components/pay/RecipientField.tsx +49 -4
  75. package/ui/components/pay/RequestHub.tsx +68 -8
  76. package/ui/components/pay/ResultBanner.tsx +41 -4
  77. package/ui/components/pay/UniversalSend.tsx +534 -30
  78. package/ui/components/pay/tokenSendCopy.ts +116 -0
  79. package/ui/components/pay/useRecipientInput.ts +36 -7
  80. package/ui/components/ui/PermissionSheet.tsx +65 -4
  81. package/ui/components/ui/Sheet.tsx +9 -2
  82. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  83. package/ui/components/vault/KeyChooser.tsx +96 -0
  84. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  85. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  86. package/ui/components/wallet/ActivityRow.tsx +101 -17
  87. package/ui/components/wallet/AmountInput.tsx +77 -25
  88. package/ui/components/wallet/AssetAmount.tsx +95 -0
  89. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  90. package/ui/components/wallet/tokenEviction.ts +65 -0
  91. package/ui/hooks/useExportWalletData.ts +39 -0
  92. package/ui/hooks/useMandala.ts +303 -0
  93. package/ui/hooks/useVaultBalance.ts +105 -7
  94. package/ui/hooks/useVaultCoverage.ts +52 -0
  95. package/ui/importDatabases.ts +7 -3
  96. package/ui/index.ts +50 -7
  97. package/ui/screens/ConnectionsScreen.tsx +46 -29
  98. package/ui/screens/PairScreen.tsx +12 -12
  99. package/ui/screens/PayScreen.tsx +130 -10
  100. package/ui/screens/SettingsScreen.tsx +18 -9
  101. package/ui/screens/VaultScreen.tsx +925 -171
  102. package/ui/screens/VaultTransferScreen.tsx +376 -123
  103. package/ui/screens/WalletCheckScreen.tsx +10 -1
  104. package/ui/screens/WalletConfigScreen.tsx +42 -20
  105. package/ui/screens/WalletHomeScreen.tsx +417 -86
  106. package/ui/screens/homeBadges.ts +9 -1
  107. package/ui/screens/tokenRowTitle.ts +68 -0
  108. package/ui/tokenFormat.ts +108 -0
  109. package/ui/tokenSeen.ts +75 -0
  110. package/ui/tokenStatus.ts +79 -0
  111. package/assets/sounds/vault-close.wav +0 -0
  112. package/assets/sounds/vault-open.wav +0 -0
  113. package/core/services/vault/k1.ts +0 -75
  114. package/core/services/vault/sealing.ts +0 -84
  115. package/core/services/vault/vaultDerivation.ts +0 -152
  116. package/core/services/vault/vaultPassphrase.ts +0 -287
  117. package/ui/components/vault/PassphraseField.tsx +0 -306
  118. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  119. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -0,0 +1,244 @@
1
+ /**
2
+ * The AdmissionBundle: the evidence a token payment carries with it.
3
+ *
4
+ * Offline settlement turns on one question the recipient must answer with no
5
+ * network: *is every token ancestor of this transaction either already
6
+ * admitted by the issuer's overlay, or present in bytes I can walk further?*
7
+ * The bundle is what makes that question answerable — σ_I signatures for the
8
+ * ancestors that bottom out, linkage payloads for the ones that do not (so
9
+ * whoever reconnects first can submit them), and the tip's own AtomicBEEF for
10
+ * everything in between.
11
+ *
12
+ * Two halves live here, and they are deliberately separate:
13
+ *
14
+ * · `assembleBundle` — the PAYER's side. Walks the transaction it just built
15
+ * and collects, from this device's own settlement tables, the evidence the
16
+ * recipient will need. Storage-facing, async, and best-effort: it never
17
+ * decides whether the result is sufficient.
18
+ *
19
+ * · `coverFromFrame` — the PAYEE's side. Rebuilds an in-memory bundle from a
20
+ * decoded frame and hands it to an injected pure verifier. The verdict is
21
+ * the verifier's, never this module's.
22
+ *
23
+ * The COVER walk itself (spec §1.2) is pure and belongs in `@bsv/mandala`,
24
+ * where the overlay's own σ_I digest lives beside it — one implementation, one
25
+ * set of test vectors, no chance of the wallet and the overlay disagreeing
26
+ * about what a signature covers. This package does not depend on it yet, so
27
+ * the verifier is INJECTED and its types are declared here to match
28
+ * `CoverResult` in `./types`. When the dependency lands, the injection site
29
+ * becomes a one-line import and nothing else here changes.
30
+ */
31
+ import { Beef, Transaction } from '@bsv/sdk'
32
+ import { MandalaToken } from '@bsv/templates'
33
+ import type { PaymentFrame } from '../localpay/codec'
34
+ import type { AdmissionEntryWire, CoverResult, SettlementStore } from './types'
35
+
36
+ export { MANDALA_ACTION_LABEL, MANDALA_BASKET } from './types'
37
+
38
+ /**
39
+ * The read side of the settlement store this walk needs.
40
+ *
41
+ * Narrowed from `SettlementStore` on purpose: the walk reads cached evidence
42
+ * and writes nothing, and a builder holding the full store could advance a
43
+ * settlement row halfway through assembling a frame.
44
+ */
45
+ export type BundleStore = Pick<SettlementStore, 'getAdmission' | 'getLinkage'>
46
+
47
+ /** The evidence a payer collected for one tip, ready to go onto the wire. */
48
+ export interface AdmissionBundle {
49
+ tipTxid: string
50
+ assetId: string
51
+ overlayIdentityKey: string
52
+ /** Frontier ancestors: unadmitted, so somebody must still submit them. */
53
+ linkage: Array<{ txid: string; payload: Uint8Array }>
54
+ /** Bottoms: ancestors this device holds the overlay's own σ_I for. */
55
+ admissions: AdmissionEntryWire[]
56
+ }
57
+
58
+ /** The tip the verifier is asked about. */
59
+ export interface CoverTip {
60
+ txid: string
61
+ tx: Transaction
62
+ }
63
+
64
+ /**
65
+ * Everything the pure COVER walk reads, as maps — the in-memory shape of
66
+ * §1.1's AdmissionBundle. Mirrors `@bsv/mandala`'s own input type; declared
67
+ * locally only until this package depends on it.
68
+ */
69
+ export interface CoverBundle {
70
+ assetId: string
71
+ overlayIdentityKey: string
72
+ /** Every transaction carried in the tip's AtomicBEEF, keyed by txid. */
73
+ beef: Map<string, Transaction>
74
+ linkage: Map<string, Uint8Array>
75
+ admissions: Map<string, AdmissionEntryWire>
76
+ }
77
+
78
+ /** The injected pure verifier: `cover(tip, bundle)` (spec §1.2). */
79
+ export type CoverVerifier = (tip: CoverTip, bundle: CoverBundle) => CoverResult | Promise<CoverResult>
80
+
81
+ /**
82
+ * The token inputs of `tx` for `assetId` — FIX K.
83
+ *
84
+ * Only inputs whose SOURCE OUTPUT decodes as a MandalaToken of this asset
85
+ * count. A fresh unconfirmed BSV output funding the fee is not a token
86
+ * ancestor: the payer's own change routinely funds the next offline payment
87
+ * (`allocateChangeInput` accepts `unproven`), and a walk that treated it as an
88
+ * ancestor with no σ_I would refuse the single most ordinary case there is.
89
+ * It is an ordinary broadcast-only parent, handled by the release engine.
90
+ *
91
+ * Returns the parent transactions, deduplicated by txid — a transaction with
92
+ * two inputs from the same parent is one ancestor, not two.
93
+ */
94
+ export function tokenParentsOf(tx: Transaction, assetId: string): Transaction[] {
95
+ const seen = new Set<string>()
96
+ const parents: Transaction[] = []
97
+ for (const input of tx.inputs) {
98
+ const source = input.sourceTransaction
99
+ if (!source) continue // txid-only ancestor: a hole for COVER, nothing to walk here
100
+ const output = source.outputs[input.sourceOutputIndex]
101
+ if (!output?.lockingScript) continue
102
+ let decoded: { assetId: string }
103
+ try {
104
+ decoded = MandalaToken.decode(output.lockingScript)
105
+ } catch {
106
+ continue // not a token script — a fee parent, per FIX K
107
+ }
108
+ if (decoded.assetId !== assetId) continue // another issuer's coin riding along
109
+ const txid = source.id('hex')
110
+ if (seen.has(txid)) continue
111
+ seen.add(txid)
112
+ parents.push(source)
113
+ }
114
+ return parents
115
+ }
116
+
117
+ function hexToBytes(hex: string): Uint8Array {
118
+ const clean = hex.length % 2 === 0 ? hex : ''
119
+ const out = new Uint8Array(clean.length / 2)
120
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16) || 0
121
+ return out
122
+ }
123
+
124
+ /**
125
+ * Collects the evidence for `tipTx`'s token ancestry (spec §1.1).
126
+ *
127
+ * One decision per ancestor, and it is the whole algorithm:
128
+ *
129
+ * · a cached admission signed by THIS session's overlay is a BOTTOM — emit an
130
+ * admissions entry and stop. The recipient can verify it offline and will
131
+ * never need to submit that transaction, so forwarding its linkage would be
132
+ * dead weight on the wire.
133
+ * · anything else is a FRONTIER — emit the stored linkage payload if this
134
+ * device holds one, then walk that ancestor's OWN token inputs. Forwarding
135
+ * linkage verbatim hop by hop is what lets whoever reconnects first settle
136
+ * a whole chain of offline hands.
137
+ *
138
+ * An admission signed by any other key is treated as ABSENT, not as a
139
+ * refusal (FIX H): it is not evidence for this overlay, and the ancestor is
140
+ * walked exactly as if the cache had been empty.
141
+ *
142
+ * A frontier this device holds no linkage for still emits nothing and is still
143
+ * walked. That is not a silent failure — the recipient's own COVER decides
144
+ * whether what arrived is sufficient, and inventing a payload here would put a
145
+ * guess where the overlay expects exact bytes.
146
+ *
147
+ * The tip's own linkage is NOT collected: the payer mints it as part of
148
+ * building the transfer and adds it at the call site, because only the builder
149
+ * knows which outputs it just created.
150
+ */
151
+ export async function assembleBundle(args: {
152
+ tipTx: Transaction
153
+ assetId: string
154
+ overlayIdentityKey: string
155
+ store: BundleStore
156
+ }): Promise<AdmissionBundle> {
157
+ const { tipTx, assetId, overlayIdentityKey, store } = args
158
+ const linkage: Array<{ txid: string; payload: Uint8Array }> = []
159
+ const admissions: AdmissionEntryWire[] = []
160
+ const visited = new Set<string>()
161
+
162
+ // Iterative, not recursive: a hostile or merely deep BEEF must not be able to
163
+ // blow the JS stack on a device. Termination is structural — a txid is the
164
+ // hash of its own bytes, so the spend graph is acyclic — and `visited` bounds
165
+ // the work at one expansion per distinct transaction regardless.
166
+ const queue: Transaction[] = [tipTx]
167
+ while (queue.length > 0) {
168
+ const tx = queue.shift() as Transaction
169
+ for (const parent of tokenParentsOf(tx, assetId)) {
170
+ const txid = parent.id('hex')
171
+ if (visited.has(txid)) continue
172
+ visited.add(txid)
173
+
174
+ const cached = await store.getAdmission(txid)
175
+ if (cached && cached.signerKey === overlayIdentityKey) {
176
+ admissions.push({
177
+ txid,
178
+ outputsToAdmit: [...cached.outputsToAdmit],
179
+ signature: hexToBytes(cached.signatureHex),
180
+ signerKey: cached.signerKey
181
+ })
182
+ continue
183
+ }
184
+
185
+ const stored = await store.getLinkage(txid)
186
+ if (stored && stored.payloadBytes.length > 0) linkage.push({ txid, payload: new Uint8Array(stored.payloadBytes) })
187
+ queue.push(parent)
188
+ }
189
+ }
190
+
191
+ return { tipTxid: tipTx.id('hex'), assetId, overlayIdentityKey, linkage, admissions }
192
+ }
193
+
194
+ /**
195
+ * Runs COVER for a delivered frame.
196
+ *
197
+ * A thin adapter, on purpose: it turns the frame's wire arrays into the maps
198
+ * the pure walk reads, and makes exactly no judgement of its own about whether
199
+ * the evidence is sufficient. Every verdict below that is not the verifier's
200
+ * own is a SHAPE refusal — there was nothing coherent to ask about:
201
+ *
202
+ * · not a token frame, or a token frame with no token block;
203
+ * · transaction bytes that are not readable AtomicBEEF;
204
+ * · a verifier that threw. The verifier is injected and may be a third
205
+ * party's; an exception escaping into the settle path would abort a credit
206
+ * somewhere between "refused" and "accepted", which is the one outcome a
207
+ * money path may never have.
208
+ */
209
+ export async function coverFromFrame(frame: PaymentFrame, cover: CoverVerifier): Promise<CoverResult> {
210
+ if (frame.kind !== 'token' || !frame.token) return { ok: false, reason: 'shape' }
211
+
212
+ let beef: Beef
213
+ let tipTxid: string
214
+ try {
215
+ beef = Beef.fromBinary(Array.from(frame.transaction))
216
+ const atomic = beef.atomicTxid
217
+ const tx = Transaction.fromAtomicBEEF(Array.from(frame.transaction))
218
+ tipTxid = atomic ?? tx.id('hex')
219
+ } catch {
220
+ return { ok: false, reason: 'shape' }
221
+ }
222
+
223
+ const txs = new Map<string, Transaction>()
224
+ for (const btx of beef.txs) {
225
+ const tx = btx.tx
226
+ if (tx) txs.set(btx.txid, tx)
227
+ }
228
+ const tip = txs.get(tipTxid)
229
+ if (!tip) return { ok: false, reason: 'shape' }
230
+
231
+ const bundle: CoverBundle = {
232
+ assetId: frame.token.assetId,
233
+ overlayIdentityKey: frame.token.overlayIdentityKey,
234
+ beef: txs,
235
+ linkage: new Map(frame.token.linkage.map(l => [l.txid, l.payload])),
236
+ admissions: new Map(frame.token.admissions.map(a => [a.txid, a]))
237
+ }
238
+
239
+ try {
240
+ return await cover({ txid: tipTxid, tx: tip }, bundle)
241
+ } catch {
242
+ return { ok: false, reason: 'shape' }
243
+ }
244
+ }