@bsv/expo-wallet-toolbox 0.21.0 → 0.23.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 (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Encrypted wallet database export format ("Export Wallet Data" with
3
+ * `encrypt: true`).
4
+ *
5
+ * Envelope encryption: a fresh random 32-byte file key encrypts the database
6
+ * image, and the wallet itself encrypts (wraps) that file key with BRC-2
7
+ * `wallet.encrypt` under counterparty `self`. Only the wallet that exported a
8
+ * file can open it again — the same rule import already enforces on the
9
+ * plaintext image (its storageIdentityKey must match).
10
+ *
11
+ * The body is a STREAM-style chunked AES-256-GCM: every chunk is sealed on
12
+ * its own with nonce `prefix(7) || u32 BE chunk index || last-flag(1)`, so
13
+ * chunks can be encrypted, written and decrypted one at a time (memory stays
14
+ * at one chunk, never the whole database), and any reordered, dropped,
15
+ * duplicated or truncated chunk fails authentication. The header fields
16
+ * (version, chunk size, nonce prefix) ride inside the wallet-encrypted blob
17
+ * next to the file key, so they are authenticated by it rather than through
18
+ * AAD.
19
+ *
20
+ * Wire layout:
21
+ *
22
+ * magic "BSVWDBE1" (8) | u16 BE wrappedLen | wrapped (wrappedLen) | chunk*
23
+ * chunk = ciphertext (chunkSize, the last one 0..chunkSize) | GCM tag (16)
24
+ *
25
+ * wrapped = wallet.encrypt( version(1) | u32 BE chunkSize | prefix(7) | fileKey(32) )
26
+ *
27
+ * AES runs in native code: react-native-quick-crypto's OpenSSL backend that
28
+ * the host app installs as `globalThis.__bsvNativeCrypto` (Node's own crypto
29
+ * under Jest). Without one, encryption refuses rather than crawl through a
30
+ * pure-JS AES over a whole database.
31
+ */
32
+ import type { WalletInterface, WalletProtocol } from '@bsv/sdk'
33
+
34
+ export const ENCRYPTED_DB_MAGIC = [0x42, 0x53, 0x56, 0x57, 0x44, 0x42, 0x45, 0x31] // "BSVWDBE1"
35
+ export const ENCRYPTED_DB_EXTENSION = '.db.enc'
36
+ export const DB_EXPORT_PROTOCOL: WalletProtocol = [2, 'wallet db export']
37
+ export const DB_EXPORT_KEY_ID = '1'
38
+
39
+ const FORMAT_VERSION = 1
40
+ const DEFAULT_CHUNK_SIZE = 1024 * 1024
41
+ /** A decrypt never allocates more than this per chunk, whatever the header claims. */
42
+ const MAX_CHUNK_SIZE = 16 * 1024 * 1024
43
+ const TAG_LEN = 16
44
+ const KEY_LEN = 32
45
+ const PREFIX_LEN = 7
46
+ const HEADER_PLAIN_LEN = 1 + 4 + PREFIX_LEN + KEY_LEN
47
+ /** BRC-2 adds a 32-byte IV and a 16-byte tag; anything far outside that is not ours. */
48
+ const MAX_WRAPPED_LEN = 1024
49
+
50
+ export type EncryptedDbErrorCode = 'no-native-crypto' | 'not-encrypted' | 'wrong-wallet' | 'unsupported' | 'corrupt'
51
+
52
+ /** All the wallet this needs: a ProtoWallet or the permissions manager both fit. */
53
+ export type DbExportWallet = Pick<WalletInterface, 'encrypt' | 'decrypt'>
54
+
55
+ export class EncryptedDbError extends Error {
56
+ constructor(
57
+ readonly code: EncryptedDbErrorCode,
58
+ message: string
59
+ ) {
60
+ super(message)
61
+ this.name = 'EncryptedDbError'
62
+ }
63
+ }
64
+
65
+ /** Sequential reader over the input; `read` returns fewer bytes only at EOF. */
66
+ export interface ByteSource {
67
+ readonly size: number
68
+ read(length: number): Uint8Array
69
+ }
70
+
71
+ export interface ByteSink {
72
+ write(bytes: Uint8Array): void
73
+ }
74
+
75
+ export interface EncryptedDbOptions {
76
+ /** Origin the wallet call is made as — the admin originator, so it never prompts. */
77
+ originator?: string
78
+ /** Called after each chunk with the fraction done (0..1). */
79
+ onProgress?: (fraction: number) => void
80
+ /** Test seam; defaults to 1 MiB. */
81
+ chunkSize?: number
82
+ }
83
+
84
+ interface GcmCipher {
85
+ update(data: Uint8Array): ArrayBuffer | Uint8Array
86
+ final(): ArrayBuffer | Uint8Array
87
+ getAuthTag(): ArrayBuffer | Uint8Array
88
+ }
89
+ interface GcmDecipher {
90
+ setAuthTag(tag: Uint8Array): void
91
+ update(data: Uint8Array): ArrayBuffer | Uint8Array
92
+ final(): ArrayBuffer | Uint8Array
93
+ }
94
+ interface NativeCrypto {
95
+ createCipheriv(alg: 'aes-256-gcm', key: Uint8Array, iv: Uint8Array): GcmCipher
96
+ createDecipheriv(alg: 'aes-256-gcm', key: Uint8Array, iv: Uint8Array): GcmDecipher
97
+ randomBytes(n: number): ArrayBuffer | Uint8Array
98
+ }
99
+
100
+ /** Backends already seen to refuse a wrong GCM tag. */
101
+ const authenticating = new WeakSet<NativeCrypto>()
102
+
103
+ /**
104
+ * Every integrity property of this format rests on `final()` throwing for a
105
+ * wrong tag — which react-native-quick-crypto 0.7.17 did not do until this
106
+ * repo patched it (patches/react-native-quick-crypto+0.7.17.patch). A host
107
+ * app without that patch would accept a tampered file, so check once per
108
+ * backend and refuse rather than trust it.
109
+ */
110
+ function assertAuthenticates(backend: NativeCrypto): void {
111
+ if (authenticating.has(backend)) return
112
+ const key = toBuf(toU8(backend.randomBytes(KEY_LEN)))
113
+ const iv = toBuf(toU8(backend.randomBytes(12)))
114
+ const cipher = backend.createCipheriv('aes-256-gcm', key, iv)
115
+ const body = toU8(cipher.update(toBuf(new Uint8Array(16))))
116
+ cipher.final()
117
+ const tag = Uint8Array.from(toU8(cipher.getAuthTag()))
118
+ tag[0] ^= 1
119
+ const decipher = backend.createDecipheriv('aes-256-gcm', key, iv)
120
+ decipher.setAuthTag(toBuf(tag))
121
+ let refused = false
122
+ try {
123
+ decipher.update(toBuf(body))
124
+ decipher.final()
125
+ } catch {
126
+ refused = true
127
+ }
128
+ if (!refused) {
129
+ throw new EncryptedDbError('no-native-crypto', 'The crypto backend does not authenticate AES-GCM')
130
+ }
131
+ authenticating.add(backend)
132
+ }
133
+
134
+ function nativeCrypto(): NativeCrypto {
135
+ const g = globalThis as {
136
+ __bsvNativeCrypto?: NativeCrypto
137
+ process?: { getBuiltinModule?: (id: string) => unknown }
138
+ }
139
+ const backend = g.__bsvNativeCrypto ?? (g.process?.getBuiltinModule?.('node:crypto') as NativeCrypto | undefined)
140
+ if (!backend?.createCipheriv) {
141
+ throw new EncryptedDbError(
142
+ 'no-native-crypto',
143
+ 'Encrypted export needs the native crypto backend (react-native-quick-crypto installed as globalThis.__bsvNativeCrypto)'
144
+ )
145
+ }
146
+ assertAuthenticates(backend)
147
+ return backend
148
+ }
149
+
150
+ /** quick-crypto hands back ArrayBuffers and wants Buffers in; Node wants Buffers too. */
151
+ function toU8(x: ArrayBuffer | Uint8Array): Uint8Array {
152
+ return x instanceof Uint8Array ? x : new Uint8Array(x)
153
+ }
154
+ function toBuf(x: Uint8Array): Uint8Array {
155
+ const B = (globalThis as { Buffer?: { from(b: ArrayBufferLike, o: number, l: number): Uint8Array } }).Buffer
156
+ return B ? B.from(x.buffer, x.byteOffset, x.byteLength) : x
157
+ }
158
+
159
+ function concat(parts: Uint8Array[]): Uint8Array {
160
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
161
+ let off = 0
162
+ for (const p of parts) {
163
+ out.set(p, off)
164
+ off += p.length
165
+ }
166
+ return out
167
+ }
168
+
169
+ function chunkNonce(prefix: Uint8Array, index: number, last: boolean): Uint8Array {
170
+ const n = new Uint8Array(12)
171
+ n.set(prefix, 0)
172
+ new DataView(n.buffer).setUint32(PREFIX_LEN, index, false)
173
+ n[11] = last ? 1 : 0
174
+ return n
175
+ }
176
+
177
+ /** Let the UI thread render between chunks: every crypto/file call here is synchronous JSI. */
178
+ const yieldToUi = () => new Promise<void>(resolve => setTimeout(resolve, 0))
179
+
180
+ /** True when `head` (the first bytes of a file) starts with this format's magic. */
181
+ export function isEncryptedDbImage(head: Uint8Array): boolean {
182
+ if (head.length < ENCRYPTED_DB_MAGIC.length) return false
183
+ return ENCRYPTED_DB_MAGIC.every((b, i) => head[i] === b)
184
+ }
185
+
186
+ /** Stream `src` (a plaintext SQLite image) into `sink` as an encrypted export. */
187
+ export async function encryptDbImage(
188
+ wallet: DbExportWallet,
189
+ src: ByteSource,
190
+ sink: ByteSink,
191
+ opts: EncryptedDbOptions = {}
192
+ ): Promise<void> {
193
+ const crypto = nativeCrypto()
194
+ const chunkSize = opts.chunkSize ?? DEFAULT_CHUNK_SIZE
195
+ const fileKey = toU8(crypto.randomBytes(KEY_LEN))
196
+ const prefix = toU8(crypto.randomBytes(PREFIX_LEN))
197
+
198
+ const headerPlain = new Uint8Array(HEADER_PLAIN_LEN)
199
+ const hv = new DataView(headerPlain.buffer)
200
+ headerPlain[0] = FORMAT_VERSION
201
+ hv.setUint32(1, chunkSize, false)
202
+ headerPlain.set(prefix, 5)
203
+ headerPlain.set(fileKey, 5 + PREFIX_LEN)
204
+
205
+ const { ciphertext: wrapped } = await wallet.encrypt(
206
+ {
207
+ plaintext: Array.from(headerPlain),
208
+ protocolID: DB_EXPORT_PROTOCOL,
209
+ keyID: DB_EXPORT_KEY_ID,
210
+ counterparty: 'self',
211
+ seekPermission: false
212
+ },
213
+ opts.originator
214
+ )
215
+ headerPlain.fill(0)
216
+ if (wrapped.length > MAX_WRAPPED_LEN) throw new EncryptedDbError('unsupported', 'Wrapped key unexpectedly large')
217
+
218
+ const lead = new Uint8Array(ENCRYPTED_DB_MAGIC.length + 2)
219
+ lead.set(ENCRYPTED_DB_MAGIC, 0)
220
+ new DataView(lead.buffer).setUint16(ENCRYPTED_DB_MAGIC.length, wrapped.length, false)
221
+ sink.write(lead)
222
+ sink.write(Uint8Array.from(wrapped))
223
+
224
+ // An empty input still gets one (empty, final) chunk, so a decrypt can tell
225
+ // "nothing" apart from "cut off after the header".
226
+ const total = src.size
227
+ const chunks = Math.max(1, Math.ceil(total / chunkSize))
228
+ const key = toBuf(fileKey)
229
+ try {
230
+ for (let i = 0; i < chunks; i++) {
231
+ const last = i === chunks - 1
232
+ const plain = src.read(last ? total - i * chunkSize : chunkSize)
233
+ if (plain.length !== (last ? total - i * chunkSize : chunkSize)) {
234
+ throw new EncryptedDbError('corrupt', 'Database changed size while it was being exported')
235
+ }
236
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, toBuf(chunkNonce(prefix, i, last)))
237
+ const body = toU8(cipher.update(toBuf(plain)))
238
+ const tail = toU8(cipher.final())
239
+ sink.write(tail.length ? concat([body, tail]) : body)
240
+ sink.write(toU8(cipher.getAuthTag()))
241
+ opts.onProgress?.((i + 1) / chunks)
242
+ if (!last) await yieldToUi()
243
+ }
244
+ } finally {
245
+ fileKey.fill(0)
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Stream an encrypted export in `src` back into its plaintext SQLite image in
251
+ * `sink`. Plaintext reaches the sink a chunk at a time, each one only after
252
+ * its own tag verified; a failure part-way leaves a prefix in the sink, which
253
+ * the caller must discard (it throws, it never returns a partial image).
254
+ */
255
+ export async function decryptDbImage(
256
+ wallet: DbExportWallet,
257
+ src: ByteSource,
258
+ sink: ByteSink,
259
+ opts: EncryptedDbOptions = {}
260
+ ): Promise<void> {
261
+ const crypto = nativeCrypto()
262
+ const leadLen = ENCRYPTED_DB_MAGIC.length + 2
263
+ const lead = src.read(leadLen)
264
+ if (lead.length < leadLen || !isEncryptedDbImage(lead)) {
265
+ throw new EncryptedDbError('not-encrypted', 'Not an encrypted wallet database export')
266
+ }
267
+ const wrappedLen = new DataView(lead.buffer, lead.byteOffset).getUint16(ENCRYPTED_DB_MAGIC.length, false)
268
+ if (wrappedLen === 0 || wrappedLen > MAX_WRAPPED_LEN) throw new EncryptedDbError('corrupt', 'Bad key header')
269
+ const wrapped = src.read(wrappedLen)
270
+ if (wrapped.length !== wrappedLen) throw new EncryptedDbError('corrupt', 'File is truncated')
271
+
272
+ let headerPlain: Uint8Array
273
+ try {
274
+ const { plaintext } = await wallet.decrypt(
275
+ {
276
+ ciphertext: Array.from(wrapped),
277
+ protocolID: DB_EXPORT_PROTOCOL,
278
+ keyID: DB_EXPORT_KEY_ID,
279
+ counterparty: 'self'
280
+ },
281
+ opts.originator
282
+ )
283
+ headerPlain = Uint8Array.from(plaintext)
284
+ } catch {
285
+ throw new EncryptedDbError('wrong-wallet', 'This export was made by a different wallet')
286
+ }
287
+ if (headerPlain.length !== HEADER_PLAIN_LEN || headerPlain[0] !== FORMAT_VERSION) {
288
+ throw new EncryptedDbError('unsupported', 'Unsupported export format version')
289
+ }
290
+ const chunkSize = new DataView(headerPlain.buffer).getUint32(1, false)
291
+ if (chunkSize === 0 || chunkSize > MAX_CHUNK_SIZE) throw new EncryptedDbError('corrupt', 'Bad chunk size')
292
+ const prefix = headerPlain.slice(5, 5 + PREFIX_LEN)
293
+ const key = toBuf(headerPlain.slice(5 + PREFIX_LEN))
294
+ headerPlain.fill(0)
295
+
296
+ let remaining = src.size - leadLen - wrappedLen
297
+ const bodyTotal = remaining
298
+ try {
299
+ for (let i = 0; ; i++) {
300
+ const sealedLen = Math.min(chunkSize + TAG_LEN, remaining)
301
+ if (sealedLen < TAG_LEN) throw new EncryptedDbError('corrupt', 'File is truncated')
302
+ const last = sealedLen === remaining
303
+ const sealed = src.read(sealedLen)
304
+ if (sealed.length !== sealedLen) throw new EncryptedDbError('corrupt', 'File is truncated')
305
+ remaining -= sealedLen
306
+
307
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, toBuf(chunkNonce(prefix, i, last)))
308
+ decipher.setAuthTag(toBuf(sealed.subarray(sealedLen - TAG_LEN)))
309
+ let plain: Uint8Array
310
+ try {
311
+ const body = toU8(decipher.update(toBuf(sealed.subarray(0, sealedLen - TAG_LEN))))
312
+ const tail = toU8(decipher.final())
313
+ plain = tail.length ? concat([body, tail]) : body
314
+ } catch {
315
+ throw new EncryptedDbError('corrupt', 'File is damaged or was modified')
316
+ }
317
+ sink.write(plain)
318
+ opts.onProgress?.(bodyTotal ? (bodyTotal - remaining) / bodyTotal : 1)
319
+ if (last) break
320
+ await yieldToUi()
321
+ }
322
+ } finally {
323
+ key.fill(0)
324
+ }
325
+ }
@@ -32,8 +32,7 @@ import {
32
32
  type PostOutcome
33
33
  } from '../../offline/plan'
34
34
  import { descendantsOf, type OrderableTx } from '../../offline/order'
35
- import { postTokenStep, reconcileSettlements, type TokenFrameSource } from '../../mandala/drain'
36
- import type { AdmissionVerifier, CoverFn, SettlementStore, SubmitFn, TokenSettlementRow } from '../../mandala/types'
35
+ import { txHasColorOutput } from '../../mandala/colorGuard'
37
36
  import { devLog } from '../../logging'
38
37
  import { getOnline } from '../../net/online'
39
38
 
@@ -80,78 +79,15 @@ interface HeldAction {
80
79
  api: TableProvenTxReq
81
80
  }
82
81
 
83
- /**
84
- * Everything the Mandala settlement drain needs that this module cannot do
85
- * itself. Absent for a wallet with no token payments — then not one line of
86
- * behaviour below changes.
87
- *
88
- * `cover` and `submit` are injected rather than imported because one is a pure
89
- * verifier over local evidence and the other is a network call; keeping both
90
- * out of here is what leaves this file a database-and-ordering module.
91
- */
92
- export interface OfflineTokenDeps {
93
- store: SettlementStore
94
- cover: CoverFn
95
- submit: SubmitFn
96
- /**
97
- * FIX H / wire contract §9.10. THIS WALLET's configured overlay identity key
98
- * and the σ_I verifier that checks against it — the only thing that may let a
99
- * cached admission skip a `/submit`, and the filter on what the evidence
100
- * cache is allowed to keep at all. Absent and nothing is trusted: every
101
- * ancestor is submitted, which is free and always correct.
102
- */
103
- overlayIdentityKey?: string
104
- verifyAdmission?: AdmissionVerifier
105
- /**
106
- * Clear `@bsv/mandala`'s tx-journal entry for a tip this pass really
107
- * broadcast. See `TokenStepDeps.journalRemove`; passed straight through so
108
- * the drain's own broadcast is the only thing that can clear one.
109
- */
110
- journalRemove?: (txid: string) => Promise<void>
111
- /**
112
- * FIX G: every durable token frame this device holds, re-read each pass so
113
- * the evidence tables and the settlement rows are re-derived idempotently
114
- * before anything is decided. Supplied by the caller because only it can
115
- * open a payer-side sealed `framePayload`.
116
- */
117
- frames?: () => Promise<TokenFrameSource[]>
118
- }
119
-
120
82
  export async function processOfflineActions(args: {
121
83
  storage: StorageExpoSQLite
122
84
  /** Injected so tests can supply a missing ancestor without hitting the network. */
123
85
  refetchBeef?: (txid: string) => Promise<number[] | undefined>
124
- /** Mandala settlement. Omit entirely and the drain behaves exactly as before. */
125
- token?: OfflineTokenDeps
126
86
  }): Promise<ProcessOfflineActionsResult> {
127
- const { storage, refetchBeef, token } = args
87
+ const { storage, refetchBeef } = args
128
88
  const db = storage.sqliteDb
129
89
  if (!db) return { sent: 0, rejected: 0, stopped: true, stalledOn: 'the database is not open' }
130
90
 
131
- // Before anything is read or decided: re-derive the settlement evidence from
132
- // the frame bytes that are already durable (FIX G). Purely local, so it runs
133
- // even on a pass that turns out to be offline, and it is allowed to fail —
134
- // it is a cache-population step, and the next tick repeats it.
135
- if (token?.frames) {
136
- try {
137
- const r = await reconcileSettlements({
138
- store: token.store,
139
- sources: await token.frames(),
140
- overlayIdentityKey: token.overlayIdentityKey,
141
- verifyAdmission: token.verifyAdmission
142
- })
143
- if (r.errors.length > 0) devLog('[processOfflineActions] evidence reconciliation reported:', r.errors)
144
- if (r.dropped > 0) {
145
- // FIX H: counterparty-supplied σ_I that did not verify against this
146
- // wallet's configured overlay key. Not an error and not a decline —
147
- // the ancestors are simply submitted rather than skipped.
148
- devLog(`[processOfflineActions] dropped ${r.dropped} unverifiable admission(s) from frame evidence`)
149
- }
150
- } catch (e) {
151
- devLog('[processOfflineActions] could not reconcile token settlements:', e)
152
- }
153
- }
154
-
155
91
  // XQ-009 remainder: a row this device once honestly marked 'sent' (real
156
92
  // proof, or a real broadcast) can still have its backing request later
157
93
  // reclaimed by the toolbox's own proof-timeout machinery
@@ -191,7 +127,6 @@ export async function processOfflineActions(args: {
191
127
  if (api && outcomeFromReqStatus(api.status) === 'success') {
192
128
  devLog(`[processOfflineActions] storage already records '${api.status}' for ${row.txid}; closing its queue row`)
193
129
  await updateOfflineAction(db, row.txid, { status: 'sent' })
194
- if (token) await closeSettlementAsBroadcast(token.store, row.txid)
195
130
  sent++
196
131
  } else {
197
132
  rows.push(row)
@@ -294,36 +229,21 @@ export async function processOfflineActions(args: {
294
229
  }
295
230
  if (action) await updateOfflineAction(db, step.txid, { status: 'posting' })
296
231
 
297
- // The ONE token branch. A transaction with a `token_settlements` row may
298
- // not be broadcast until the issuer's overlay has admitted it and every
299
- // unadmitted token ancestor it spends — so the ordinary post becomes
300
- // `postTokenStep`'s injected `broadcast`, reached only after `/submit`
301
- // says yes. Everything after this line — applyOutcome, the cascade, the
302
- // requeue — is unchanged, because `postTokenStep` returns the same
303
- // `PostOutcome` shape a BSV post does.
304
- const read = token ? await readSettlement(token.store, step.txid) : { ok: true as const, row: undefined }
305
- const broadcast = async () =>
306
- action ? await postOwned(storage, action.api) : await postForeign(storage, merged, step.txid)
307
- const outcome = !read.ok
308
- ? // The read failed, so this step does not know whether it is a token
309
- // transaction. Stall it: `serviceError` leaves every row where it was
310
- // and retries the whole prefix next pass.
311
- ('serviceError' as PostOutcome)
312
- : read.row
313
- ? await postTokenStep(
314
- {
315
- store: token!.store,
316
- cover: token!.cover,
317
- submit: token!.submit,
318
- overlayIdentityKey: token!.overlayIdentityKey,
319
- verifyAdmission: token!.verifyAdmission,
320
- journalRemove: token!.journalRemove,
321
- broadcast
322
- },
323
- read.row,
324
- step
325
- )
326
- : await broadcast()
232
+ // The ONE color branch (plan 07 W1, IC §8.2). A transaction with a 1Color
233
+ // output is broadcast only once its `color_transfers` row reads `settled`:
234
+ // the color module's `settle` got a verified admission from the Mandala
235
+ // overlay, which itself broadcasts what it admits. Until then the step is a
236
+ // `serviceError` — its row stays queued and its subtree waits — exactly
237
+ // like a step that found no network. A read fault does the same: "I could
238
+ // not tell" never resolves to "go ahead". Everything after this line —
239
+ // applyOutcome, the cascade, the requeue — is unchanged.
240
+ const hold = await colorHold(storage, merged, txs, step.txid, action?.api.rawTx)
241
+ const outcome: PostOutcome =
242
+ hold !== 'release'
243
+ ? 'serviceError'
244
+ : action
245
+ ? await postOwned(storage, action.api)
246
+ : await postForeign(storage, merged, step.txid)
327
247
  // A cascade needs to see what spends the refused transaction, and beefs only
328
248
  // reach backwards, so the graph the queue built cannot contain a spender that
329
249
  // is not itself queued. Widened only when a cascade is actually about to run,
@@ -372,31 +292,66 @@ export async function processOfflineActions(args: {
372
292
  }
373
293
 
374
294
  /**
375
- * Whether this txid has a settlement row — or whether the question could not be
376
- * answered at all.
295
+ * Whether one step of the release plan may be posted now.
296
+ *
297
+ * · `release` — the tx carries no 1Color output (answered from its bytes, so a
298
+ * plain BSV step never touches the journal), this wallet's token custody is
299
+ * not in it (a decoy 1Color output on someone else's tx), or its
300
+ * `color_transfers` row reads `settled`.
301
+ * · `hold` — an unsettled 1Color tx of this wallet's custody (the hold's
302
+ * predicate, `colorHeldTxids`): a missing row holds a receipt the host
303
+ * ledger recorded and nothing has admitted yet.
304
+ * · `fault` — a custody read failed. The caller treats it exactly like
305
+ * `hold`; it is distinct only for the log.
377
306
  *
378
- * The three outcomes are deliberately distinct, and the third is the fix. A
379
- * thrown read (a locked database, a schema without these tables, a corrupt
380
- * page) USED to fall back to `undefined`, which the caller cannot tell from
381
- * "this is an ordinary BSV transaction" — so a read fault sent an unadmitted
382
- * token tip straight to `broadcast()`, defeating the whole §4.3 gate on exactly
383
- * the kind of transient fault the drain is built to survive. "I could not tell"
384
- * must never resolve to "go ahead": the caller turns it into `serviceError`,
385
- * the rows stay where they are, and the next pass asks again.
307
+ * A FOREIGN step (an ancestor that arrived inside a counterparty's BEEF, no
308
+ * request of ours) carries no custody of its own: the journal and the host
309
+ * ledger record this wallet's own sends and receipts, keyed by their tips. So
310
+ * a foreign 1Color step is held exactly while it is an unadmitted link in a
311
+ * chain this wallet holds: when some descendant of it in this graph is held
312
+ * by the predicate. Posting it then would put an unadmitted token tx under
313
+ * our pending receipt on chain. Once no descendant is held (each is settled,
314
+ * or not ours at all), it is released: a settled descendant was admitted and
315
+ * broadcast by the overlay, which it cannot do without its ancestors already
316
+ * on the network, and a decoy-only chain is not ours to hold. A foreign step
317
+ * that is itself custodial keeps the earlier rule: released when some 1Color
318
+ * descendant is not held.
386
319
  *
387
- * The token guard in `StorageExpoSQLite.attemptToPostReqsToNetwork` reads the
388
- * same table and would usually catch the same case — but it is reached only
389
- * from `shareReqsWithWorld`, and `postForeign` does not go through it at all.
390
- * Two independent barriers are worth having; one of them failing open is not.
320
+ * Bytes: an owned step uses its request's raw tx, a foreign one the merged
321
+ * graph's. A step with no bytes is held (`colorHeldTxids`).
391
322
  */
392
- type SettlementRead = { ok: true; row: TokenSettlementRow | undefined } | { ok: false }
323
+ type ColorHold = 'release' | 'hold' | 'fault'
393
324
 
394
- async function readSettlement(store: SettlementStore, txid: string): Promise<SettlementRead> {
325
+ async function colorHold(
326
+ storage: StorageExpoSQLite,
327
+ merged: Beef,
328
+ txs: OrderableTx[],
329
+ txid: string,
330
+ ownedRawTx: number[] | undefined
331
+ ): Promise<ColorHold> {
332
+ const owned = ownedRawTx !== undefined
333
+ const rawTx = ownedRawTx ?? merged.findTxid(txid)?.tx?.toBinary()
334
+ if (rawTx && rawTx.length > 0 && !txHasColorOutput(rawTx)) return 'release'
395
335
  try {
396
- return { ok: true, row: await store.getSettlement(txid) }
336
+ const held = await storage.colorHeldTxids([{ txid, rawTx }])
337
+ if (owned) return held.has(txid) ? 'hold' : 'release'
338
+
339
+ const colorDescendants: { txid: string; rawTx: number[] }[] = []
340
+ for (const d of descendantsOf(txid, txs)) {
341
+ const bytes = merged.findTxid(d)?.tx?.toBinary()
342
+ if (bytes && txHasColorOutput(bytes)) colorDescendants.push({ txid: d, rawTx: bytes })
343
+ }
344
+ const heldDescendants =
345
+ colorDescendants.length === 0 ? new Set<string>() : await storage.colorHeldTxids(colorDescendants)
346
+ if (!held.has(txid)) {
347
+ // Not ours by itself: held only under a chain of ours that is still held.
348
+ return colorDescendants.some(d => heldDescendants.has(d.txid)) ? 'hold' : 'release'
349
+ }
350
+ if (colorDescendants.length === 0) return 'hold'
351
+ return colorDescendants.some(d => !heldDescendants.has(d.txid)) ? 'release' : 'hold'
397
352
  } catch (e) {
398
- devLog(`[processOfflineActions] could not read the settlement row for ${txid}:`, e)
399
- return { ok: false }
353
+ devLog(`[processOfflineActions] could not read color_transfers for ${txid}; holding it:`, e)
354
+ return 'fault'
400
355
  }
401
356
  }
402
357
 
@@ -643,13 +598,17 @@ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Pro
643
598
  /**
644
599
  * `postOwned` for ONE txid, for a caller outside the queue loop.
645
600
  *
646
- * The Mandala runtime's `settleNow` needs a broadcast to hand `postTokenStep`
647
- * the moment a hand-over lands, and it must be the SAME broadcast the drain
648
- * uses — status transitions, history notes, `markStaleInputsAsSpent`, the
649
- * re-hold on a service error, and the "storage is the witness, not the reported
650
- * status" rule all live in `postOwned` and must not be reimplemented beside it.
651
- * So this is the whole of the new surface: find the request, post it, report
652
- * the same `PostOutcome`.
601
+ * The Mandala runtime may need to post one settled tx the moment it settles,
602
+ * and it must be the SAME broadcast the drain uses — status transitions,
603
+ * history notes, `markStaleInputsAsSpent`, the re-hold on a service error, and
604
+ * the "storage is the witness, not the reported status" rule all live in
605
+ * `postOwned` and must not be reimplemented beside it. So this is the whole of
606
+ * the new surface: find the request, post it, report the same `PostOutcome`.
607
+ *
608
+ * It carries the color hold itself. `postOwned` calls the toolbox's
609
+ * module-level post, past the `StorageExpoSQLite` override, so without the
610
+ * same check here this would be a way around the guard: an unsettled 1Color tx
611
+ * (or an unanswerable journal read) comes back `'serviceError'`, unposted.
653
612
  *
654
613
  * A txid with no request of this wallet's own comes back `'serviceError'`
655
614
  * rather than being posted some other way. That is deliberate: a FOREIGN
@@ -665,6 +624,10 @@ export async function postOwnedByTxid(storage: StorageExpoSQLite, txid: string):
665
624
  devLog(`[processOfflineActions] no request of our own for ${txid}; leaving its broadcast to the drain`)
666
625
  return 'serviceError'
667
626
  }
627
+ if ((await colorHold(storage, new Beef(), [], txid, api.rawTx)) !== 'release') {
628
+ devLog(`[processOfflineActions] ${txid} is an unsettled 1Color tx (or unreadable); not posting it`)
629
+ return 'serviceError'
630
+ }
668
631
  return await postOwned(storage, api)
669
632
  }
670
633
 
@@ -737,19 +700,6 @@ async function recordDeliveredElsewhere(storage: StorageExpoSQLite, api: TablePr
737
700
  }
738
701
  }
739
702
 
740
- /**
741
- * The settlement twin of closing a queue row on a recorded delivery: the same
742
- * advance `broadcastAdmittedTip` makes after a real post. Best-effort — the
743
- * queue row is the durable fact, and `reconcileSettlements` re-derives rows.
744
- */
745
- async function closeSettlementAsBroadcast(store: SettlementStore, txid: string): Promise<void> {
746
- try {
747
- await store.advanceSettlement(txid, ['admitted', 'submitting', 'held', 'handed_over'], 'broadcast')
748
- } catch (e) {
749
- devLog(`[processOfflineActions] could not close the settlement row of ${txid} as broadcast:`, e)
750
- }
751
- }
752
-
753
703
  /**
754
704
  * Post a foreign ancestor that arrived inside someone's BEEF.
755
705
  *