@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.
- package/CHANGELOG.md +292 -0
- package/README.md +0 -1
- package/assets/sounds/vault-deposit.wav +0 -0
- package/assets/sounds/vault-withdraw.wav +0 -0
- package/core/config.tsx +9 -1
- package/core/context/VaultContext.tsx +8 -11
- package/core/context/WalletConnectionContext.tsx +137 -52
- package/core/context/WalletContext.tsx +409 -20
- package/core/hooks/useConfirmationSound.ts +14 -8
- package/core/i18n/translations.tsx +3368 -952
- package/core/index.ts +97 -14
- package/core/localpay/build.ts +674 -37
- package/core/localpay/codec.ts +68 -5
- package/core/localpay/pending.ts +240 -22
- package/core/localpay/settlementAck.ts +149 -0
- package/core/localpay/types.ts +14 -1
- package/core/localpay/verify.ts +118 -69
- package/core/mandala/abortGuard.ts +134 -0
- package/core/mandala/basketMigration.ts +166 -0
- package/core/mandala/bundle.ts +244 -0
- package/core/mandala/createRuntime.ts +2437 -0
- package/core/mandala/drain.ts +670 -0
- package/core/mandala/permissionModule.ts +642 -0
- package/core/mandala/resendTransfer.ts +175 -0
- package/core/mandala/runtime.ts +357 -0
- package/core/mandala/settlementStore.ts +412 -0
- package/core/mandala/types.ts +290 -0
- package/core/offline/cancelParked.ts +94 -1
- package/core/offline/payerHold.ts +152 -12
- package/core/offline/tokenFrames.ts +197 -0
- package/core/parsePeerPayURI.ts +70 -17
- package/core/pay/rails/address.ts +51 -3
- package/core/pay/rails/handle.ts +88 -9
- package/core/pay/rails/index.ts +16 -6
- package/core/pay/rails/nearby.ts +114 -4
- package/core/services/capWalletArgs.ts +8 -9
- package/core/services/externalOrigin.ts +39 -0
- package/core/services/vault/VaultKeyService.ts +912 -251
- package/core/services/vault/ceremony.ts +435 -367
- package/core/services/vault/ceremonyHost.ts +27 -21
- package/core/services/vault/devMock.ts +30 -7
- package/core/services/vault/driver.ts +95 -41
- package/core/services/vault/guard.ts +514 -56
- package/core/services/vault/hardwareLease.ts +22 -0
- package/core/services/vault/mockYubiKey.ts +258 -90
- package/core/services/vault/pivReset.ts +145 -0
- package/core/services/vault/r1comb.ts +976 -0
- package/core/services/vault/session.ts +93 -26
- package/core/services/vault/transfers.ts +2617 -747
- package/core/services/vault/types.ts +100 -43
- package/core/services/vault/vaultStore.ts +991 -74
- package/core/services/walletConnectionValidation.ts +293 -0
- package/core/storage/StorageExpoSQLite.ts +382 -56
- package/core/storage/dbImage.ts +48 -0
- package/core/storage/methods/findSql.ts +0 -54
- package/core/storage/methods/listOutputsSql.ts +7 -3
- package/core/storage/methods/offlineActions.ts +15 -0
- package/core/storage/methods/processOfflineActions.ts +263 -6
- package/core/storage/methods/walletBalanceSql.ts +16 -4
- package/core/storage/schema/createTables.ts +123 -0
- package/core/storage/sqlUpdateValue.ts +24 -0
- package/core/toolboxConfig.ts +112 -1
- package/core/walletRepair/runWalletCheck.ts +19 -2
- package/package.json +25 -24
- package/ui/components/QRScanner.tsx +1 -1
- package/ui/components/pay/AdmissionNotice.tsx +99 -0
- package/ui/components/pay/AssetPicker.tsx +184 -0
- package/ui/components/pay/AvailableBalance.tsx +33 -2
- package/ui/components/pay/HandleReceive.tsx +213 -50
- package/ui/components/pay/NearbyFlow.tsx +616 -69
- package/ui/components/pay/PayForm.tsx +73 -8
- package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
- package/ui/components/pay/RecipientField.tsx +49 -4
- package/ui/components/pay/RequestHub.tsx +68 -8
- package/ui/components/pay/ResultBanner.tsx +41 -4
- package/ui/components/pay/UniversalSend.tsx +534 -30
- package/ui/components/pay/tokenSendCopy.ts +116 -0
- package/ui/components/pay/useRecipientInput.ts +36 -7
- package/ui/components/ui/PermissionSheet.tsx +65 -4
- package/ui/components/ui/Sheet.tsx +9 -2
- package/ui/components/vault/EnrollWizard.tsx +1432 -488
- package/ui/components/vault/KeyChooser.tsx +96 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
- package/ui/components/vault/vaultErrorCopy.ts +145 -0
- package/ui/components/wallet/ActivityRow.tsx +101 -17
- package/ui/components/wallet/AmountInput.tsx +77 -25
- package/ui/components/wallet/AssetAmount.tsx +95 -0
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
- package/ui/components/wallet/tokenEviction.ts +65 -0
- package/ui/hooks/useExportWalletData.ts +39 -0
- package/ui/hooks/useMandala.ts +303 -0
- package/ui/hooks/useVaultBalance.ts +105 -7
- package/ui/hooks/useVaultCoverage.ts +52 -0
- package/ui/importDatabases.ts +7 -3
- package/ui/index.ts +50 -7
- package/ui/screens/ConnectionsScreen.tsx +46 -29
- package/ui/screens/PairScreen.tsx +12 -12
- package/ui/screens/PayScreen.tsx +130 -10
- package/ui/screens/SettingsScreen.tsx +18 -9
- package/ui/screens/VaultScreen.tsx +925 -171
- package/ui/screens/VaultTransferScreen.tsx +376 -123
- package/ui/screens/WalletCheckScreen.tsx +10 -1
- package/ui/screens/WalletConfigScreen.tsx +38 -16
- package/ui/screens/WalletHomeScreen.tsx +417 -86
- package/ui/screens/homeBadges.ts +9 -1
- package/ui/screens/tokenRowTitle.ts +68 -0
- package/ui/tokenFormat.ts +108 -0
- package/ui/tokenSeen.ts +75 -0
- package/ui/tokenStatus.ts +79 -0
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/services/vault/k1.ts +0 -75
- package/core/services/vault/sealing.ts +0 -84
- package/core/services/vault/vaultDerivation.ts +0 -152
- package/core/services/vault/vaultPassphrase.ts +0 -287
- package/ui/components/vault/PassphraseField.tsx +0 -306
- package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
- package/ui/screens/VaultRecoverScreen.tsx +0 -226
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `SettlementStore` over the toolbox's own SQLite connection.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately logic-free, in the same spirit as `storage/methods/offlineActions.ts`:
|
|
5
|
+
* every decision about WHEN a row may move lives in `mandala/drain.ts`, which is
|
|
6
|
+
* unit-tested against a real in-memory SQLite. What is here is statements.
|
|
7
|
+
*
|
|
8
|
+
* Two rules the SQL itself enforces, because a convention would not survive a
|
|
9
|
+
* crash or a second drain tick:
|
|
10
|
+
*
|
|
11
|
+
* 1. **`state` belongs to `advanceSettlement` alone.** `upsertSettlement` is
|
|
12
|
+
* the re-derivation path (FIX G — the drain re-runs it on every pass from
|
|
13
|
+
* the durable frame bytes), so if it wrote `state` it would drag an
|
|
14
|
+
* `admitted` row back to `held` every tick and re-submit forever. It
|
|
15
|
+
* therefore sets `state` only on the INSERT, and on conflict updates the
|
|
16
|
+
* descriptive columns alone.
|
|
17
|
+
* 2. **`advanceSettlement` is one guarded UPDATE.** `... WHERE txid = ? AND
|
|
18
|
+
* state IN (...)` plus a changes-count check is a compare-and-swap: two
|
|
19
|
+
* interleaved drains cannot both believe they claimed the same row, and a
|
|
20
|
+
* row someone else already moved to a terminal state is never resurrected.
|
|
21
|
+
* There is no read-then-write anywhere in this file for that reason.
|
|
22
|
+
*
|
|
23
|
+
* Access pattern matches `StorageExpoSQLite`'s own use of `offline_actions`:
|
|
24
|
+
* the caller hands in `storage.sqliteDb` and this module only ever issues
|
|
25
|
+
* parameterised statements against it.
|
|
26
|
+
*/
|
|
27
|
+
import type {
|
|
28
|
+
SettlementStore,
|
|
29
|
+
TokenAdmissionEdge,
|
|
30
|
+
TokenAdmissionRow,
|
|
31
|
+
TokenLinkageRow,
|
|
32
|
+
TokenSettlementRole,
|
|
33
|
+
TokenSettlementRow,
|
|
34
|
+
TokenSettlementState
|
|
35
|
+
} from './types'
|
|
36
|
+
|
|
37
|
+
/** Everything these statements bind. BLOB columns are why `Uint8Array` is here. */
|
|
38
|
+
export type SettlementBindValue = string | number | null | Uint8Array
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Structurally satisfied by expo-sqlite's `SQLiteDatabase` and by the
|
|
42
|
+
* `node:sqlite` adapter the tests use. `runAsync` is narrowed to its result's
|
|
43
|
+
* `changes` because `advanceSettlement`'s whole contract depends on it.
|
|
44
|
+
*/
|
|
45
|
+
export interface SettlementDb {
|
|
46
|
+
runAsync(sql: string, params: SettlementBindValue[]): Promise<{ changes: number }>
|
|
47
|
+
getAllAsync(sql: string, params: SettlementBindValue[]): Promise<unknown[]>
|
|
48
|
+
getFirstAsync(sql: string, params: SettlementBindValue[]): Promise<unknown>
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The store, plus the one batch question the storage guard needs to ask. */
|
|
52
|
+
export interface SqlSettlementStore extends SettlementStore {
|
|
53
|
+
/**
|
|
54
|
+
* Which of `txids` have a `token_settlements` row. One statement, because the
|
|
55
|
+
* caller (`attemptToPostReqsToNetwork`'s token guard) asks this on the hot
|
|
56
|
+
* path of every broadcast.
|
|
57
|
+
*/
|
|
58
|
+
settlementTxidsIn(txids: string[]): Promise<Set<string>>
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface SettlementDbRow {
|
|
62
|
+
txid: string
|
|
63
|
+
role: string
|
|
64
|
+
assetId: string
|
|
65
|
+
state: string
|
|
66
|
+
counterpartyKey: string | null
|
|
67
|
+
amountBaseUnits: number | null
|
|
68
|
+
overlayUrl: string
|
|
69
|
+
overlayIdentityKey: string
|
|
70
|
+
admissionOutputsJson: string | null
|
|
71
|
+
admissionSignatureHex: string | null
|
|
72
|
+
refusedCode: string | null
|
|
73
|
+
refusedPayloadHash: string | null
|
|
74
|
+
poisonedByTxid: string | null
|
|
75
|
+
reference: string | null
|
|
76
|
+
createdAt: string
|
|
77
|
+
updatedAt: string
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A JSON array column that will not throw the caller's drain pass for one bad row. */
|
|
81
|
+
function readNumberArray(json: string | null): number[] | undefined {
|
|
82
|
+
if (!json) return undefined
|
|
83
|
+
try {
|
|
84
|
+
const parsed = JSON.parse(json) as unknown
|
|
85
|
+
if (!Array.isArray(parsed)) return undefined
|
|
86
|
+
return parsed.filter((n): n is number => typeof n === 'number')
|
|
87
|
+
} catch {
|
|
88
|
+
return undefined
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function toSettlement(row: SettlementDbRow): TokenSettlementRow {
|
|
93
|
+
return {
|
|
94
|
+
txid: row.txid,
|
|
95
|
+
role: row.role as TokenSettlementRole,
|
|
96
|
+
assetId: row.assetId,
|
|
97
|
+
state: row.state as TokenSettlementState,
|
|
98
|
+
counterpartyKey: row.counterpartyKey ?? undefined,
|
|
99
|
+
amountBaseUnits: row.amountBaseUnits ?? undefined,
|
|
100
|
+
overlayUrl: row.overlayUrl,
|
|
101
|
+
overlayIdentityKey: row.overlayIdentityKey,
|
|
102
|
+
admissionOutputs: readNumberArray(row.admissionOutputsJson),
|
|
103
|
+
admissionSignatureHex: row.admissionSignatureHex ?? undefined,
|
|
104
|
+
refusedCode: row.refusedCode ?? undefined,
|
|
105
|
+
refusedPayloadHash: row.refusedPayloadHash ?? undefined,
|
|
106
|
+
poisonedByTxid: row.poisonedByTxid ?? undefined,
|
|
107
|
+
reference: row.reference ?? undefined,
|
|
108
|
+
createdAt: row.createdAt,
|
|
109
|
+
updatedAt: row.updatedAt
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* `payloadBytes` comes back from expo-sqlite as a `Uint8Array` and from
|
|
115
|
+
* `node:sqlite` the same way, but a driver that hands back an ArrayBuffer or a
|
|
116
|
+
* number[] must not silently become an empty payload — these bytes are the only
|
|
117
|
+
* thing that lets a downstream device submit this txid at all.
|
|
118
|
+
*
|
|
119
|
+
* A TEXT value is the 2026-09-16 incident's residue: `putLinkage` was handed a
|
|
120
|
+
* JSON-rehydrated payload (an index-keyed object, not a `Uint8Array`), and
|
|
121
|
+
* expo-sqlite's Android binding stringified it as a java `Map` — `{0=1.0,
|
|
122
|
+
* 2=250.0, 1=2.0}`, hash-ordered, Double-valued. Rows like that are on devices
|
|
123
|
+
* and `INSERT OR IGNORE` would have kept them forever, so they are read back
|
|
124
|
+
* into the bytes they always meant. Anything else that is not bytes still
|
|
125
|
+
* throws, never becomes an empty payload.
|
|
126
|
+
*/
|
|
127
|
+
function toBytes(value: unknown): Uint8Array {
|
|
128
|
+
if (value instanceof Uint8Array) return value
|
|
129
|
+
if (value instanceof ArrayBuffer) return new Uint8Array(value)
|
|
130
|
+
if (Array.isArray(value)) return new Uint8Array(value as number[])
|
|
131
|
+
if (typeof value === 'string') {
|
|
132
|
+
const recovered = bytesFromJavaMapString(value)
|
|
133
|
+
if (recovered) return recovered
|
|
134
|
+
}
|
|
135
|
+
throw new Error('token_linkage_payloads.payloadBytes is not readable as bytes')
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function bytesFromJavaMapString(text: string): Uint8Array | undefined {
|
|
139
|
+
const braced = /^\{(.*)\}$/s.exec(text.trim())
|
|
140
|
+
if (!braced) return undefined
|
|
141
|
+
const body = braced[1].trim()
|
|
142
|
+
if (body === '') return new Uint8Array(0)
|
|
143
|
+
const pairs = body.split(',')
|
|
144
|
+
const out = new Uint8Array(pairs.length)
|
|
145
|
+
const seen = new Set<number>()
|
|
146
|
+
for (const pair of pairs) {
|
|
147
|
+
const kv = /^\s*(\d+)=(\d+)(?:\.0+)?\s*$/.exec(pair)
|
|
148
|
+
if (!kv) return undefined
|
|
149
|
+
const index = Number(kv[1])
|
|
150
|
+
const byte = Number(kv[2])
|
|
151
|
+
if (index >= out.length || seen.has(index) || byte > 255) return undefined
|
|
152
|
+
seen.add(index)
|
|
153
|
+
out[index] = byte
|
|
154
|
+
}
|
|
155
|
+
return out
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Columns `advanceSettlement` and `upsertSettlement` may write, and their SQL names. */
|
|
159
|
+
const PATCHABLE: { key: keyof TokenSettlementRow; column: string }[] = [
|
|
160
|
+
{ key: 'counterpartyKey', column: 'counterpartyKey' },
|
|
161
|
+
{ key: 'amountBaseUnits', column: 'amountBaseUnits' },
|
|
162
|
+
{ key: 'admissionOutputs', column: 'admissionOutputsJson' },
|
|
163
|
+
{ key: 'admissionSignatureHex', column: 'admissionSignatureHex' },
|
|
164
|
+
{ key: 'refusedCode', column: 'refusedCode' },
|
|
165
|
+
{ key: 'refusedPayloadHash', column: 'refusedPayloadHash' },
|
|
166
|
+
{ key: 'poisonedByTxid', column: 'poisonedByTxid' },
|
|
167
|
+
{ key: 'reference', column: 'reference' }
|
|
168
|
+
]
|
|
169
|
+
|
|
170
|
+
function patchValue(key: keyof TokenSettlementRow, value: unknown): SettlementBindValue {
|
|
171
|
+
if (value === undefined || value === null) return null
|
|
172
|
+
if (key === 'admissionOutputs') return JSON.stringify(value)
|
|
173
|
+
return value as SettlementBindValue
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function createSettlementStore(db: SettlementDb): SqlSettlementStore {
|
|
177
|
+
return {
|
|
178
|
+
async getSettlement(txid: string): Promise<TokenSettlementRow | undefined> {
|
|
179
|
+
const row = (await db.getFirstAsync('SELECT * FROM token_settlements WHERE txid = ?', [
|
|
180
|
+
txid
|
|
181
|
+
])) as SettlementDbRow | null
|
|
182
|
+
return row ? toSettlement(row) : undefined
|
|
183
|
+
},
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* One indexed lookup (`idx_token_settlements_reference`), because this is
|
|
187
|
+
* asked before EVERY `abortAction` the wallet makes — the overwhelming
|
|
188
|
+
* majority of which are plain BSV actions with no row here at all. An empty
|
|
189
|
+
* or absent reference can never match a row and is refused a query.
|
|
190
|
+
*/
|
|
191
|
+
async getSettlementByReference(reference: string): Promise<TokenSettlementRow | undefined> {
|
|
192
|
+
if (!reference) return undefined
|
|
193
|
+
const row = (await db.getFirstAsync('SELECT * FROM token_settlements WHERE reference = ?', [
|
|
194
|
+
reference
|
|
195
|
+
])) as SettlementDbRow | null
|
|
196
|
+
return row ? toSettlement(row) : undefined
|
|
197
|
+
},
|
|
198
|
+
|
|
199
|
+
async listSettlements(filter = {}): Promise<TokenSettlementRow[]> {
|
|
200
|
+
const where: string[] = []
|
|
201
|
+
const params: SettlementBindValue[] = []
|
|
202
|
+
if (filter.state && filter.state.length > 0) {
|
|
203
|
+
where.push(`state IN (${filter.state.map(() => '?').join(',')})`)
|
|
204
|
+
params.push(...filter.state)
|
|
205
|
+
}
|
|
206
|
+
if (filter.role !== undefined) {
|
|
207
|
+
where.push('role = ?')
|
|
208
|
+
params.push(filter.role)
|
|
209
|
+
}
|
|
210
|
+
const sql =
|
|
211
|
+
'SELECT * FROM token_settlements' +
|
|
212
|
+
(where.length ? ` WHERE ${where.join(' AND ')}` : '') +
|
|
213
|
+
' ORDER BY createdAt ASC, txid ASC'
|
|
214
|
+
return ((await db.getAllAsync(sql, params)) as SettlementDbRow[]).map(toSettlement)
|
|
215
|
+
},
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Insert the row, or refresh only what a re-derivation can legitimately
|
|
219
|
+
* know. `state`, `role` and the two terminal-verdict columns are never
|
|
220
|
+
* touched on conflict — see rule 1 at the top of this file.
|
|
221
|
+
*/
|
|
222
|
+
async upsertSettlement(row): Promise<void> {
|
|
223
|
+
const now = new Date().toISOString()
|
|
224
|
+
const createdAt = row.createdAt ?? now
|
|
225
|
+
await db.runAsync(
|
|
226
|
+
`INSERT INTO token_settlements
|
|
227
|
+
(txid, role, assetId, state, counterpartyKey, amountBaseUnits, overlayUrl, overlayIdentityKey,
|
|
228
|
+
admissionOutputsJson, admissionSignatureHex, refusedCode, refusedPayloadHash, poisonedByTxid,
|
|
229
|
+
reference, createdAt, updatedAt)
|
|
230
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
231
|
+
ON CONFLICT(txid) DO UPDATE SET
|
|
232
|
+
assetId = excluded.assetId,
|
|
233
|
+
counterpartyKey = COALESCE(excluded.counterpartyKey, token_settlements.counterpartyKey),
|
|
234
|
+
amountBaseUnits = COALESCE(excluded.amountBaseUnits, token_settlements.amountBaseUnits),
|
|
235
|
+
overlayUrl = excluded.overlayUrl,
|
|
236
|
+
overlayIdentityKey = excluded.overlayIdentityKey,
|
|
237
|
+
admissionOutputsJson = COALESCE(excluded.admissionOutputsJson, token_settlements.admissionOutputsJson),
|
|
238
|
+
admissionSignatureHex = COALESCE(excluded.admissionSignatureHex, token_settlements.admissionSignatureHex),
|
|
239
|
+
reference = COALESCE(excluded.reference, token_settlements.reference),
|
|
240
|
+
updatedAt = excluded.updatedAt`,
|
|
241
|
+
[
|
|
242
|
+
row.txid,
|
|
243
|
+
row.role,
|
|
244
|
+
row.assetId,
|
|
245
|
+
row.state,
|
|
246
|
+
row.counterpartyKey ?? null,
|
|
247
|
+
row.amountBaseUnits ?? null,
|
|
248
|
+
row.overlayUrl,
|
|
249
|
+
row.overlayIdentityKey,
|
|
250
|
+
row.admissionOutputs ? JSON.stringify(row.admissionOutputs) : null,
|
|
251
|
+
row.admissionSignatureHex ?? null,
|
|
252
|
+
row.refusedCode ?? null,
|
|
253
|
+
row.refusedPayloadHash ?? null,
|
|
254
|
+
row.poisonedByTxid ?? null,
|
|
255
|
+
row.reference ?? null,
|
|
256
|
+
createdAt,
|
|
257
|
+
now
|
|
258
|
+
]
|
|
259
|
+
)
|
|
260
|
+
},
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* One statement, compare-and-swap on `state`. False means the row was not
|
|
264
|
+
* in one of `from` — either someone else moved it, or it does not exist —
|
|
265
|
+
* and NOTHING was written, so a caller may treat false as "not mine to
|
|
266
|
+
* advance" without a compensating read.
|
|
267
|
+
*/
|
|
268
|
+
async advanceSettlement(
|
|
269
|
+
txid: string,
|
|
270
|
+
from: TokenSettlementState[],
|
|
271
|
+
to: TokenSettlementState,
|
|
272
|
+
patch: Partial<TokenSettlementRow> = {}
|
|
273
|
+
): Promise<boolean> {
|
|
274
|
+
const sets = ['state = ?', 'updatedAt = ?']
|
|
275
|
+
const params: SettlementBindValue[] = [to, new Date().toISOString()]
|
|
276
|
+
for (const { key, column } of PATCHABLE) {
|
|
277
|
+
if (patch[key] === undefined) continue
|
|
278
|
+
sets.push(`${column} = ?`)
|
|
279
|
+
params.push(patchValue(key, patch[key]))
|
|
280
|
+
}
|
|
281
|
+
params.push(txid, ...from)
|
|
282
|
+
const placeholders = from.length > 0 ? from.map(() => '?').join(',') : `''`
|
|
283
|
+
const result = await db.runAsync(
|
|
284
|
+
`UPDATE token_settlements SET ${sets.join(', ')} WHERE txid = ? AND state IN (${placeholders})`,
|
|
285
|
+
params
|
|
286
|
+
)
|
|
287
|
+
return (result?.changes ?? 0) > 0
|
|
288
|
+
},
|
|
289
|
+
|
|
290
|
+
async settlementTxidsIn(txids: string[]): Promise<Set<string>> {
|
|
291
|
+
if (txids.length === 0) return new Set()
|
|
292
|
+
const rows = (await db.getAllAsync(
|
|
293
|
+
`SELECT txid FROM token_settlements WHERE txid IN (${txids.map(() => '?').join(',')})`,
|
|
294
|
+
txids
|
|
295
|
+
)) as { txid: string }[]
|
|
296
|
+
return new Set(rows.map(r => r.txid))
|
|
297
|
+
},
|
|
298
|
+
|
|
299
|
+
async getAdmission(txid: string): Promise<TokenAdmissionRow | undefined> {
|
|
300
|
+
const row = (await db.getFirstAsync('SELECT * FROM token_admissions WHERE txid = ?', [txid])) as {
|
|
301
|
+
txid: string
|
|
302
|
+
outputsToAdmitJson: string
|
|
303
|
+
signatureHex: string
|
|
304
|
+
signerKey: string
|
|
305
|
+
source: TokenAdmissionRow['source']
|
|
306
|
+
obtainedAt: string
|
|
307
|
+
} | null
|
|
308
|
+
if (!row) return undefined
|
|
309
|
+
return {
|
|
310
|
+
txid: row.txid,
|
|
311
|
+
outputsToAdmit: readNumberArray(row.outputsToAdmitJson) ?? [],
|
|
312
|
+
signatureHex: row.signatureHex,
|
|
313
|
+
signerKey: row.signerKey,
|
|
314
|
+
source: row.source,
|
|
315
|
+
obtainedAt: row.obtainedAt
|
|
316
|
+
}
|
|
317
|
+
},
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Idempotent, and asymmetric on purpose: first-hand evidence (this device
|
|
321
|
+
* submitted, or fetched `GET /admin/admission/:txid` itself) replaces a
|
|
322
|
+
* cached bundle entry, but a counterparty-supplied bundle NEVER overwrites
|
|
323
|
+
* anything already on record. For a `bundle`/`minted` source against an
|
|
324
|
+
* existing row the `WHERE` makes this exactly an `INSERT OR IGNORE`, which
|
|
325
|
+
* is what the FIX G re-derivation pass needs.
|
|
326
|
+
*/
|
|
327
|
+
async putAdmission(row: TokenAdmissionRow): Promise<void> {
|
|
328
|
+
await db.runAsync(
|
|
329
|
+
`INSERT INTO token_admissions (txid, outputsToAdmitJson, signatureHex, signerKey, source, obtainedAt)
|
|
330
|
+
VALUES (?,?,?,?,?,?)
|
|
331
|
+
ON CONFLICT(txid) DO UPDATE SET
|
|
332
|
+
outputsToAdmitJson = excluded.outputsToAdmitJson,
|
|
333
|
+
signatureHex = excluded.signatureHex,
|
|
334
|
+
signerKey = excluded.signerKey,
|
|
335
|
+
source = excluded.source,
|
|
336
|
+
obtainedAt = excluded.obtainedAt
|
|
337
|
+
WHERE excluded.source IN ('submitted','fetched')`,
|
|
338
|
+
[row.txid, JSON.stringify(row.outputsToAdmit), row.signatureHex, row.signerKey, row.source, row.obtainedAt]
|
|
339
|
+
)
|
|
340
|
+
},
|
|
341
|
+
|
|
342
|
+
async putEdges(edges: TokenAdmissionEdge[]): Promise<void> {
|
|
343
|
+
for (const e of edges) {
|
|
344
|
+
await db.runAsync(
|
|
345
|
+
'INSERT OR IGNORE INTO token_admission_edges (childTxid, parentTxid, parentVout) VALUES (?,?,?)',
|
|
346
|
+
[e.childTxid, e.parentTxid, e.parentVout]
|
|
347
|
+
)
|
|
348
|
+
}
|
|
349
|
+
},
|
|
350
|
+
|
|
351
|
+
async parentsOf(childTxid: string): Promise<TokenAdmissionEdge[]> {
|
|
352
|
+
const rows = (await db.getAllAsync(
|
|
353
|
+
`SELECT childTxid, parentTxid, parentVout FROM token_admission_edges
|
|
354
|
+
WHERE childTxid = ? ORDER BY parentTxid ASC, parentVout ASC`,
|
|
355
|
+
[childTxid]
|
|
356
|
+
)) as TokenAdmissionEdge[]
|
|
357
|
+
return rows.map(r => ({ childTxid: r.childTxid, parentTxid: r.parentTxid, parentVout: r.parentVout }))
|
|
358
|
+
},
|
|
359
|
+
|
|
360
|
+
async getLinkage(txid: string): Promise<TokenLinkageRow | undefined> {
|
|
361
|
+
const row = (await db.getFirstAsync('SELECT * FROM token_linkage_payloads WHERE txid = ?', [txid])) as {
|
|
362
|
+
txid: string
|
|
363
|
+
payloadBytes: unknown
|
|
364
|
+
overlayUrl: string
|
|
365
|
+
overlayIdentityKey: string
|
|
366
|
+
source: TokenLinkageRow['source']
|
|
367
|
+
createdAt: string
|
|
368
|
+
} | null
|
|
369
|
+
if (!row) return undefined
|
|
370
|
+
return {
|
|
371
|
+
txid: row.txid,
|
|
372
|
+
payloadBytes: toBytes(row.payloadBytes),
|
|
373
|
+
overlayUrl: row.overlayUrl,
|
|
374
|
+
overlayIdentityKey: row.overlayIdentityKey,
|
|
375
|
+
source: row.source,
|
|
376
|
+
createdAt: row.createdAt
|
|
377
|
+
}
|
|
378
|
+
},
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Insert-or-ignore in effect: the payload for a txid is whatever its issuer
|
|
382
|
+
* minted, forwarded verbatim. A second copy arriving on a later hop is by
|
|
383
|
+
* construction the same bytes, and a *different* copy is a counterparty
|
|
384
|
+
* trying to rewrite evidence this device already holds — so an existing
|
|
385
|
+
* BLOB is never touched. The one row a new copy may replace is one that
|
|
386
|
+
* holds no evidence at all — not a blob (see `toBytes`), or an empty one:
|
|
387
|
+
* a driver stringifying a value this store should have refused, which it
|
|
388
|
+
* now does, and an empty payload is likewise refused here because an
|
|
389
|
+
* overlay cannot verify nothing and every reader already treats it as
|
|
390
|
+
* "nothing held".
|
|
391
|
+
*/
|
|
392
|
+
async putLinkage(row: TokenLinkageRow): Promise<void> {
|
|
393
|
+
if (!(row.payloadBytes instanceof Uint8Array) || row.payloadBytes.length === 0) {
|
|
394
|
+
throw new Error('token_linkage_payloads.payloadBytes must be a non-empty Uint8Array')
|
|
395
|
+
}
|
|
396
|
+
await db.runAsync(
|
|
397
|
+
`INSERT INTO token_linkage_payloads
|
|
398
|
+
(txid, payloadBytes, overlayUrl, overlayIdentityKey, source, createdAt)
|
|
399
|
+
VALUES (?,?,?,?,?,?)
|
|
400
|
+
ON CONFLICT(txid) DO UPDATE SET
|
|
401
|
+
payloadBytes = excluded.payloadBytes,
|
|
402
|
+
overlayUrl = excluded.overlayUrl,
|
|
403
|
+
overlayIdentityKey = excluded.overlayIdentityKey,
|
|
404
|
+
source = excluded.source,
|
|
405
|
+
createdAt = excluded.createdAt
|
|
406
|
+
WHERE typeof(token_linkage_payloads.payloadBytes) <> 'blob'
|
|
407
|
+
OR length(token_linkage_payloads.payloadBytes) = 0`,
|
|
408
|
+
[row.txid, row.payloadBytes, row.overlayUrl, row.overlayIdentityKey, row.source, row.createdAt]
|
|
409
|
+
)
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|