@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 +2000 -0
- package/README.md +66 -1
- package/core/amountFormatHelpers.ts +258 -36
- package/core/backup/RemoteSyncReader.ts +133 -24
- package/core/backup/appData.ts +157 -0
- package/core/backup/client.ts +15 -1
- package/core/backup/codec.ts +149 -11
- package/core/backup/constants.ts +30 -1
- package/core/backup/cursor.ts +31 -2
- package/core/backup/push.ts +71 -5
- package/core/backup/restore.ts +104 -16
- package/core/backup/restoreOnImport.ts +94 -30
- package/core/backup/status.ts +13 -8
- package/core/config.tsx +12 -5
- package/core/constants.ts +14 -1
- package/core/contacts/contactActivity.ts +153 -0
- package/core/contacts/contactCache.ts +41 -0
- package/core/contacts/contactsStore.ts +183 -0
- package/core/context/ExchangeRateContext.tsx +34 -27
- package/core/context/LocalStorageProvider.tsx +43 -40
- package/core/context/UserContext.tsx +18 -7
- package/core/context/VaultContext.tsx +49 -2
- package/core/context/WalletConnectionContext.tsx +203 -11
- package/core/context/WalletContext.tsx +685 -171
- package/core/demo/demoAssets.ts +60 -0
- package/core/demo/demoLedger.ts +240 -0
- package/core/demo/demoMandalaRuntime.ts +96 -0
- package/core/demo/demoMode.ts +38 -0
- package/core/demo/demoWallet.ts +25 -0
- package/core/demo/index.ts +26 -0
- package/core/demo/useDemo.ts +59 -0
- package/core/headers/OfflineFirstChaintracks.ts +99 -17
- package/core/headers/headerStore.ts +33 -14
- package/core/headers/syncHeaders.ts +12 -1
- package/core/i18n/translations.tsx +2186 -98
- package/core/identity/contactLink.ts +36 -0
- package/core/identity/handleRegistry/client.ts +314 -0
- package/core/identity/handleRegistry/keyPinStore.ts +70 -0
- package/core/identity/handleRegistry/profileCert.ts +254 -0
- package/core/identity/handleRegistry/registration.ts +559 -0
- package/core/identity/handleRegistry/resolver.ts +315 -0
- package/core/identity/handleRegistry/rules.ts +104 -0
- package/core/index.ts +53 -5
- package/core/localpay/build.ts +225 -24
- package/core/localpay/pending.ts +110 -7
- package/core/localpay/pendingAbortAuthority.ts +95 -0
- package/core/localpay/pendingAborts.ts +266 -26
- package/core/localpay/session.ts +42 -17
- package/core/localpay/settlementAck.ts +10 -1
- package/core/localpay/transport/socket.ts +52 -3
- package/core/localpay/verify.ts +100 -10
- package/core/mandala/abortGuard.ts +96 -20
- package/core/mandala/createRuntime.ts +206 -33
- package/core/mandala/drain.ts +89 -11
- package/core/mandala/inboxPrehold.ts +186 -0
- package/core/mandala/permissionModule.ts +202 -20
- package/core/mandala/settlementStore.ts +24 -2
- package/core/mandala/types.ts +40 -5
- package/core/monitor/MonitorSupervisor.ts +121 -0
- package/core/monitor/TaskBackupPush.ts +15 -1
- package/core/monitor/TaskCreditInbox.ts +1 -1
- package/core/monitor/TaskDrainOutbox.ts +15 -1
- package/core/monitor/TaskSendOffline.ts +15 -1
- package/core/net/online.ts +49 -0
- package/core/net/publicDestination.ts +91 -0
- package/core/net/validateArcUrl.ts +22 -0
- package/core/numberFormat.ts +19 -0
- package/core/offline/cancelParked.ts +134 -13
- package/core/offline/payerHold.ts +100 -24
- package/core/offline/plan.ts +37 -8
- package/core/pay/beefRepair.ts +6 -2
- package/core/pay/damagedInbox.ts +24 -0
- package/core/pay/rails/address.ts +107 -12
- package/core/pay/rails/handle.ts +117 -22
- package/core/pay/rails/index.ts +45 -7
- package/core/pay/rails/nativeIntent.ts +61 -0
- package/core/pay/receiveHistory.ts +93 -0
- package/core/pay/recordProof.ts +21 -7
- package/core/pay/refreshProofGuard.ts +42 -1
- package/core/pay/watchlist.ts +5 -2
- package/core/peerpay/control.ts +17 -18
- package/core/peerpay/handleResendRequests.ts +58 -4
- package/core/peerpay/outbox.ts +3 -1
- package/core/recovery/backupMaterial.ts +61 -0
- package/core/recovery/createWallet.ts +95 -0
- package/core/recovery/recoverWallet.ts +120 -0
- package/core/recovery/restoreWallet.ts +170 -0
- package/core/recovery/secret.ts +92 -0
- package/core/recovery/shareCollector.ts +71 -0
- package/core/recovery/shareParsing.ts +87 -0
- package/core/recovery/shares.ts +116 -0
- package/core/recovery/useRecoveryDeps.ts +70 -0
- package/core/services/arcTokenStorage.ts +52 -0
- package/core/services/arcadeBroadcastProvider.ts +233 -52
- package/core/services/autoApprovePolicy.ts +105 -0
- package/core/services/callbackToken.ts +19 -0
- package/core/services/capWalletArgs.ts +14 -2
- package/core/services/connectionAuthority.ts +98 -0
- package/core/services/exchangeRate.ts +36 -13
- package/core/services/externalOrigin.ts +16 -2
- package/core/services/secrets/kek.ts +126 -29
- package/core/services/secrets/migration.ts +16 -4
- package/core/services/secrets/store.ts +42 -14
- package/core/services/vault/VaultKeyService.ts +228 -45
- package/core/services/vault/chainRecovery.ts +483 -0
- package/core/services/vault/driver.ts +9 -1
- package/core/services/vault/enrolledSerialRegistry.ts +150 -0
- package/core/services/vault/guard.ts +218 -32
- package/core/services/vault/hardwareLease.ts +19 -0
- package/core/services/vault/metaAuthority.ts +210 -0
- package/core/services/vault/pivReset.ts +64 -23
- package/core/services/vault/r1comb.ts +139 -3
- package/core/services/vault/session.ts +25 -4
- package/core/services/vault/transfers.ts +868 -172
- package/core/services/vault/types.ts +19 -4
- package/core/services/vault/vaultStore.ts +256 -29
- package/core/services/walletArgLimits.ts +45 -2
- package/core/services/walletConnectionValidation.ts +76 -6
- package/core/services/walletServiceConfig.ts +40 -27
- package/core/storage/StorageExpoSQLite.ts +88 -47
- package/core/storage/methods/findSql.ts +24 -2
- package/core/storage/methods/listActionsSql.ts +8 -5
- package/core/storage/methods/listOutputsSql.ts +2 -2
- package/core/storage/methods/offlineActions.ts +10 -1
- package/core/storage/methods/processOfflineActions.ts +117 -25
- package/core/storage/methods/reviewStatusSql.ts +7 -2
- package/core/storage/schema/createTables.ts +155 -2
- package/core/stores/ConnectionStore.ts +34 -0
- package/core/toolboxConfig.ts +104 -0
- package/core/toolboxTypes.ts +40 -0
- package/core/userAvatar.ts +79 -0
- package/core/walletDbRegistry.ts +63 -0
- package/core/walletMonitor.ts +25 -4
- package/core/walletRepair/releaseStuckReservations.ts +72 -0
- package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
- package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
- package/package.json +7 -7
- package/ui/activityFilter.ts +115 -0
- package/ui/backupShares.ts +26 -169
- package/ui/components/pay/AddressReceive.tsx +13 -6
- package/ui/components/pay/AssetPicker.tsx +30 -9
- package/ui/components/pay/MessageBoxConfig.tsx +16 -0
- package/ui/components/pay/NearbyFlow.tsx +480 -243
- package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
- package/ui/components/pay/RecipientField.tsx +84 -70
- package/ui/components/pay/StepBar.tsx +32 -0
- package/ui/components/pay/UniversalSend.tsx +827 -205
- package/ui/components/ui/AlertCard.tsx +38 -5
- package/ui/components/ui/PencilEditField.tsx +109 -0
- package/ui/components/ui/PermissionSheet.tsx +197 -66
- package/ui/components/ui/SlideOverFromRight.tsx +86 -0
- package/ui/components/vault/EnrollWizard.tsx +61 -13
- package/ui/components/vault/vaultErrorCopy.ts +3 -1
- package/ui/components/wallet/ActivityRow.tsx +227 -123
- package/ui/components/wallet/AmountInput.tsx +26 -8
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
- package/ui/components/wallet/Balance.tsx +42 -23
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
- package/ui/components/wallet/ContactActivityList.tsx +149 -0
- package/ui/components/wallet/ContactSigil.tsx +49 -0
- package/ui/components/wallet/EditPictureSheet.tsx +99 -0
- package/ui/components/wallet/FitAmount.tsx +148 -0
- package/ui/components/wallet/IconPickerSheet.tsx +168 -0
- package/ui/components/wallet/IdentifierRow.tsx +69 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
- package/ui/components/wallet/ProfileButton.tsx +62 -0
- package/ui/components/wallet/UserAvatar.tsx +85 -0
- package/ui/components/wallet/avatarIcons.ts +122 -0
- package/ui/exportTransactions.ts +36 -4
- package/ui/hooks/useContactsStore.ts +10 -0
- package/ui/hooks/useExportWalletData.ts +25 -2
- package/ui/hooks/useMandala.ts +18 -1
- package/ui/hooks/useOnline.ts +65 -20
- package/ui/importDatabases.ts +339 -24
- package/ui/index.ts +33 -2
- package/ui/isImageUrl.ts +6 -0
- package/ui/printRecoveryShares.ts +9 -10
- package/ui/recoveryPrompts.ts +91 -0
- package/ui/resolveIdentity.ts +31 -9
- package/ui/screens/ConnectionsScreen.tsx +86 -19
- package/ui/screens/ContactScreen.tsx +289 -0
- package/ui/screens/ContactsScreen.tsx +373 -0
- package/ui/screens/IdentifierScreen.tsx +256 -0
- package/ui/screens/NewContactScreen.tsx +362 -0
- package/ui/screens/PairScreen.tsx +74 -2
- package/ui/screens/PayScreen.tsx +20 -7
- package/ui/screens/ProfileScreen.tsx +783 -0
- package/ui/screens/SettingsScreen.tsx +10 -4
- package/ui/screens/TransactionDetailScreen.tsx +419 -0
- package/ui/screens/TrustScreen.tsx +100 -5
- package/ui/screens/VaultScreen.tsx +410 -61
- package/ui/screens/VaultTransferScreen.tsx +59 -7
- package/ui/screens/WalletCheckScreen.tsx +17 -6
- package/ui/screens/WalletConfigScreen.tsx +124 -28
- package/ui/screens/WalletHomeScreen.tsx +640 -104
- package/ui/screens/detailActionKeys.ts +55 -0
- package/ui/tokenFormat.ts +44 -4
- package/ui/tokenStatus.ts +21 -0
- package/ui/txStatus.ts +48 -5
- package/core/storage/LocalStorageAdapter.ts +0 -58
|
@@ -14,9 +14,11 @@
|
|
|
14
14
|
* whose ancestry we resolved once should verify offline forever after.
|
|
15
15
|
*/
|
|
16
16
|
import { Utils } from '@bsv/sdk'
|
|
17
|
-
import type
|
|
17
|
+
import { utils as chaintracksUtils, type Chain, type ChaintracksClientApi } from '@bsv/wallet-toolbox-mobile'
|
|
18
18
|
import type { HeaderStore } from './headerStore'
|
|
19
19
|
|
|
20
|
+
const { blockHash, validateHeaderProofOfWork } = chaintracksUtils
|
|
21
|
+
|
|
20
22
|
/** A merkle root as display-order hex, whether the source gave us a hex string
|
|
21
23
|
* or raw bytes. The remote's `findHeaderForHeight` may return either; plain
|
|
22
24
|
* `String(bytes)` yields "1,2,3,…" which never matches a real root — the source
|
|
@@ -26,6 +28,9 @@ function rootHex(v: unknown): string {
|
|
|
26
28
|
return typeof v === 'string' ? v : Utils.toHex(Array.from(v as ArrayLike<number>))
|
|
27
29
|
}
|
|
28
30
|
|
|
31
|
+
/** Handed out when the remote cannot subscribe; never reaches the remote. */
|
|
32
|
+
const INERT_SUBSCRIPTION_PREFIX = 'offline-first:inert:'
|
|
33
|
+
|
|
29
34
|
export class OfflineFirstChaintracks implements ChaintracksClientApi {
|
|
30
35
|
private store: HeaderStore | undefined
|
|
31
36
|
/**
|
|
@@ -35,9 +40,16 @@ export class OfflineFirstChaintracks implements ChaintracksClientApi {
|
|
|
35
40
|
*/
|
|
36
41
|
lastMissHeight: number | undefined
|
|
37
42
|
|
|
43
|
+
private inertSubscriptions = 0
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param chain The chain the remote serves. When given, `getChain` answers
|
|
47
|
+
* from it instead of asking the network.
|
|
48
|
+
*/
|
|
38
49
|
constructor(
|
|
39
50
|
private readonly remote: ChaintracksClientApi,
|
|
40
|
-
private readonly online: () => Promise<boolean
|
|
51
|
+
private readonly online: () => Promise<boolean>,
|
|
52
|
+
private readonly chain?: Chain
|
|
41
53
|
) {}
|
|
42
54
|
|
|
43
55
|
/** Consume the most recent unresolved height, if any. Kept for tests; classifiers must peek. */
|
|
@@ -58,12 +70,30 @@ export class OfflineFirstChaintracks implements ChaintracksClientApi {
|
|
|
58
70
|
|
|
59
71
|
async isValidRootForHeight(root: string, height: number): Promise<boolean> {
|
|
60
72
|
// Fast path: a local root that AGREES is trusted offline forever (validated
|
|
61
|
-
// window headers, or a previously-resolved root).
|
|
62
|
-
// DISAGREEMENT — it can be a stale/poisoned cache entry or an index error —
|
|
63
|
-
// so a miss OR a mismatch both fall through to the authoritative network.
|
|
73
|
+
// window headers, or a previously-resolved root).
|
|
64
74
|
const local = this.store?.rootForHeight(height)
|
|
65
75
|
if (local === root) return true
|
|
66
76
|
|
|
77
|
+
// A DISAGREEMENT for a height the window has already PoW-validated (its
|
|
78
|
+
// body — everything except the last 6 heights) is refused outright: no
|
|
79
|
+
// remote lookup, no putExtraRoot. Either the window is right and the BEEF
|
|
80
|
+
// is lying, or the window is corrupt — deferring to an unauthenticated
|
|
81
|
+
// network answer and caching it over headers we linked ourselves is
|
|
82
|
+
// exactly the hole this closes (misc-p2-02; a MITM has the same power as a
|
|
83
|
+
// compromised chaintracks deployment absent TLS pinning, misc-p2-13).
|
|
84
|
+
// Everything else — the last-6 reorg tail, and any height the window does
|
|
85
|
+
// not cover at all — keeps the old behaviour below: a disagreement can be
|
|
86
|
+
// a stale/poisoned cache entry or a legitimate reorg, so it falls through
|
|
87
|
+
// to the authoritative network.
|
|
88
|
+
if (local !== undefined && this.store?.isWindowBody(height)) {
|
|
89
|
+
console.warn(
|
|
90
|
+
`[OfflineFirstChaintracks] REFUSED height ${height}: window-covered mismatch ` +
|
|
91
|
+
`(local=${local} wanted=${root}); not consulting the network.`
|
|
92
|
+
)
|
|
93
|
+
this.lastMissHeight = height
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
|
|
67
97
|
if (!(await this.online())) {
|
|
68
98
|
// Logged, because this branch is otherwise indistinguishable from a bad
|
|
69
99
|
// proof: it returns false without consulting anything, and the caller
|
|
@@ -89,6 +119,30 @@ export class OfflineFirstChaintracks implements ChaintracksClientApi {
|
|
|
89
119
|
this.lastMissHeight = height
|
|
90
120
|
return false
|
|
91
121
|
}
|
|
122
|
+
|
|
123
|
+
// XR-068: outside the PoW-validated window body (a miss entirely, or the
|
|
124
|
+
// last-6 reorg tail) this response is otherwise a bare, unauthenticated
|
|
125
|
+
// claim from a single chaintracks call — exactly what a compromised or
|
|
126
|
+
// MITM'd deployment would need to make a forged BEEF root verify. Never
|
|
127
|
+
// trust the remote's self-reported `header.hash`: recompute it from the
|
|
128
|
+
// header's own fields (the same way HeaderStore.append does for window
|
|
129
|
+
// headers) and require it to satisfy its own declared difficulty. This
|
|
130
|
+
// does not establish chain-of-custody back to a trusted anchor — it
|
|
131
|
+
// only turns a zero-cost forgery into one that needs a real,
|
|
132
|
+
// difficulty-valid header.
|
|
133
|
+
let computedHash: string
|
|
134
|
+
try {
|
|
135
|
+
computedHash = blockHash(header)
|
|
136
|
+
validateHeaderProofOfWork({ ...header, hash: computedHash })
|
|
137
|
+
} catch (e: any) {
|
|
138
|
+
console.warn(
|
|
139
|
+
`[OfflineFirstChaintracks] REFUSED height ${height}: chaintracks-reported header failed ` +
|
|
140
|
+
`proof-of-work validation (${e?.message ?? e}).`
|
|
141
|
+
)
|
|
142
|
+
this.lastMissHeight = height
|
|
143
|
+
return false
|
|
144
|
+
}
|
|
145
|
+
|
|
92
146
|
const remoteRoot = rootHex(header.merkleRoot)
|
|
93
147
|
// Refresh the cache with the authoritative value (self-heals a poisoned
|
|
94
148
|
// extra entry from an earlier bad conversion).
|
|
@@ -124,10 +178,47 @@ export class OfflineFirstChaintracks implements ChaintracksClientApi {
|
|
|
124
178
|
return this.store?.tipHeight ?? 0
|
|
125
179
|
}
|
|
126
180
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
181
|
+
/**
|
|
182
|
+
* The remote's own answer. `false` (the HTTP ChaintracksServiceClient) tells
|
|
183
|
+
* the Monitor and other toolbox consumers not to subscribe at all.
|
|
184
|
+
*/
|
|
185
|
+
get supportsReorgEvents(): boolean | undefined {
|
|
186
|
+
return this.remote.supportsReorgEvents
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// The toolbox Monitor passes this object as `chaintracksWithEvents` and, unless
|
|
190
|
+
// `supportsReorgEvents` is false, calls `getChain` and both subscriptions from
|
|
191
|
+
// every `runOnce` (via `Monitor.ready`) until they succeed. A rejection there
|
|
192
|
+
// stopped the whole task loop in 2.13 and is retried, with a network
|
|
193
|
+
// `getChain`, on every tick since 2.14, so these three answer offline and
|
|
194
|
+
// never reject. TaskReviewProvenTxs remains the reorg audit without live events.
|
|
195
|
+
async getChain(): Promise<Chain> {
|
|
196
|
+
return this.chain ?? (await this.remote.getChain())
|
|
197
|
+
}
|
|
198
|
+
async subscribeHeaders(listener: Parameters<ChaintracksClientApi['subscribeHeaders']>[0]): Promise<string> {
|
|
199
|
+
try {
|
|
200
|
+
return await this.remote.subscribeHeaders(listener)
|
|
201
|
+
} catch (e: any) {
|
|
202
|
+
return this.inertSubscription('headers', e)
|
|
203
|
+
}
|
|
130
204
|
}
|
|
205
|
+
async subscribeReorgs(listener: Parameters<ChaintracksClientApi['subscribeReorgs']>[0]): Promise<string> {
|
|
206
|
+
try {
|
|
207
|
+
return await this.remote.subscribeReorgs(listener)
|
|
208
|
+
} catch (e: any) {
|
|
209
|
+
return this.inertSubscription('reorgs', e)
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
async unsubscribe(subscriptionId: string): Promise<boolean> {
|
|
213
|
+
if (subscriptionId.startsWith(INERT_SUBSCRIPTION_PREFIX)) return true
|
|
214
|
+
return await this.remote.unsubscribe(subscriptionId)
|
|
215
|
+
}
|
|
216
|
+
private inertSubscription(kind: string, e: any): string {
|
|
217
|
+
console.warn(`[OfflineFirstChaintracks] ${kind} subscription unavailable, no live events: ${e?.message ?? e}`)
|
|
218
|
+
return `${INERT_SUBSCRIPTION_PREFIX}${kind}:${++this.inertSubscriptions}`
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ── Everything below is pure delegation ───────────────────────────────────
|
|
131
222
|
getInfo() {
|
|
132
223
|
return this.remote.getInfo()
|
|
133
224
|
}
|
|
@@ -164,13 +255,4 @@ export class OfflineFirstChaintracks implements ChaintracksClientApi {
|
|
|
164
255
|
isSynchronized() {
|
|
165
256
|
return this.remote.isSynchronized()
|
|
166
257
|
}
|
|
167
|
-
subscribeHeaders(listener: Parameters<ChaintracksClientApi['subscribeHeaders']>[0]) {
|
|
168
|
-
return this.remote.subscribeHeaders(listener)
|
|
169
|
-
}
|
|
170
|
-
subscribeReorgs(listener: Parameters<ChaintracksClientApi['subscribeReorgs']>[0]) {
|
|
171
|
-
return this.remote.subscribeReorgs(listener)
|
|
172
|
-
}
|
|
173
|
-
unsubscribe(subscriptionId: string) {
|
|
174
|
-
return this.remote.unsubscribe(subscriptionId)
|
|
175
|
-
}
|
|
176
258
|
}
|
|
@@ -20,14 +20,12 @@
|
|
|
20
20
|
* helper checks linkage but not difficulty.
|
|
21
21
|
*/
|
|
22
22
|
import { Utils } from '@bsv/sdk'
|
|
23
|
-
import {
|
|
24
|
-
blockHash,
|
|
25
|
-
deserializeBaseBlockHeader,
|
|
26
|
-
validateHeaderDifficulty
|
|
27
|
-
} from '@bsv/wallet-toolbox-mobile/out/src/services/chaintracker/chaintracks/util/blockHeaderUtilities'
|
|
23
|
+
import { utils as chaintracksUtils } from '@bsv/wallet-toolbox-mobile'
|
|
28
24
|
import type { HeaderCheckpoint } from './checkpoints'
|
|
29
25
|
import type { HeaderFs } from './fs'
|
|
30
26
|
|
|
27
|
+
const { blockHash, deserializeBaseBlockHeader, validateHeaderProofOfWork } = chaintracksUtils
|
|
28
|
+
|
|
31
29
|
const HEADER_BYTES = 80
|
|
32
30
|
const ROOT_BYTES = 32
|
|
33
31
|
|
|
@@ -148,17 +146,39 @@ export class HeaderStore {
|
|
|
148
146
|
}
|
|
149
147
|
|
|
150
148
|
rootForHeight(height: number): string | undefined {
|
|
151
|
-
|
|
152
|
-
|
|
149
|
+
const index = height - this.baseHeight
|
|
150
|
+
const inWindow = index >= 0 && index < this.headerCount
|
|
151
|
+
// The window's own PoW-linked root is authoritative for its validated BODY
|
|
152
|
+
// (every height except the last 6, which can still legitimately reorg): an
|
|
153
|
+
// extra entry there is ignored outright, never consulted, because letting
|
|
154
|
+
// it win is exactly how an unauthenticated remote answer could overwrite a
|
|
155
|
+
// root this device already validated for itself off linked headers — see
|
|
156
|
+
// misc-p2-02 / OfflineFirstChaintracks.isValidRootForHeight.
|
|
157
|
+
if (inWindow && !this.inReorgWindow(height)) {
|
|
158
|
+
return Utils.toHex(Array.from(this.roots.subarray(index * ROOT_BYTES, (index + 1) * ROOT_BYTES)))
|
|
159
|
+
}
|
|
160
|
+
// Outside the body — either the last-6 reorg tail, or a height the window
|
|
161
|
+
// does not cover at all — a heal written to extra is the value to consult;
|
|
162
|
+
// falling through to the window covers the tail case where no heal exists.
|
|
153
163
|
const extra = this.extra[String(height)]
|
|
154
164
|
if (extra !== undefined) return extra
|
|
155
|
-
|
|
156
|
-
if (index >= 0 && index < this.headerCount) {
|
|
165
|
+
if (inWindow) {
|
|
157
166
|
return Utils.toHex(Array.from(this.roots.subarray(index * ROOT_BYTES, (index + 1) * ROOT_BYTES)))
|
|
158
167
|
}
|
|
159
168
|
return undefined
|
|
160
169
|
}
|
|
161
170
|
|
|
171
|
+
/**
|
|
172
|
+
* True when `height` sits in the window's validated BODY — inside
|
|
173
|
+
* `[baseHeight, tipHeight]` but outside the last-6 reorg tail — where the
|
|
174
|
+
* window's own root is authoritative and a network answer must never be
|
|
175
|
+
* allowed to override it. Used by `OfflineFirstChaintracks` to decide
|
|
176
|
+
* whether a mismatch may fall through to the remote at all.
|
|
177
|
+
*/
|
|
178
|
+
isWindowBody(height: number): boolean {
|
|
179
|
+
return height >= this.baseHeight && height <= this.tipHeight - 6
|
|
180
|
+
}
|
|
181
|
+
|
|
162
182
|
/**
|
|
163
183
|
* Validates and appends a chunk. Returns the number of headers added.
|
|
164
184
|
*
|
|
@@ -195,11 +215,10 @@ export class HeaderStore {
|
|
|
195
215
|
}
|
|
196
216
|
const hash = blockHash(header)
|
|
197
217
|
// Throws on failure — a header that does not meet its own target is not a
|
|
198
|
-
// header, and accepting it would let anyone mint merkle roots.
|
|
199
|
-
//
|
|
200
|
-
//
|
|
201
|
-
|
|
202
|
-
validateHeaderDifficulty(hash as unknown as Buffer, parsed.bits)
|
|
218
|
+
// header, and accepting it would let anyone mint merkle roots. Takes the
|
|
219
|
+
// display-order hex hash blockHash returns, validates the compact target
|
|
220
|
+
// encoding, and honours the toolbox's consensus proof-of-work exceptions.
|
|
221
|
+
validateHeaderProofOfWork({ ...parsed, height: firstHeight + i, hash })
|
|
203
222
|
newRoots.set(new Uint8Array(Utils.toArray(parsed.merkleRoot, 'hex')), i * ROOT_BYTES)
|
|
204
223
|
prev = hash
|
|
205
224
|
}
|
|
@@ -26,6 +26,9 @@ export interface SyncHeadersResult {
|
|
|
26
26
|
/** Walk back at most this many headers before giving up and resetting. */
|
|
27
27
|
const REWIND_CAP = 144
|
|
28
28
|
|
|
29
|
+
/** Bytes in one serialized block header. */
|
|
30
|
+
const HEADER_BYTES = 80
|
|
31
|
+
|
|
29
32
|
function isFirstHeaderPrevHashError(err: unknown, firstHeight: number): boolean {
|
|
30
33
|
const msg = err instanceof Error ? err.message : String(err)
|
|
31
34
|
return /previous hash/i.test(msg) && msg.includes(`header at height ${firstHeight} `)
|
|
@@ -49,8 +52,16 @@ export async function syncHeaders(args: {
|
|
|
49
52
|
const want = Math.min(chunkSize, presentHeight - store.tipHeight)
|
|
50
53
|
const hex = await client.getHeaders(from, want)
|
|
51
54
|
if (!hex) break
|
|
52
|
-
|
|
55
|
+
let bytes = new Uint8Array(Utils.toArray(hex, 'hex'))
|
|
53
56
|
if (bytes.length === 0) break
|
|
57
|
+
// XR-060: each header still has to pass real PoW and chain-linkage
|
|
58
|
+
// validation below, so a compromised/misbehaving chaintracks endpoint
|
|
59
|
+
// cannot inject fabricated headers this way — but it could still hand
|
|
60
|
+
// back a far larger batch of genuine headers than `want`, forcing
|
|
61
|
+
// unbounded validation work and disk persistence in one call. Never
|
|
62
|
+
// accept more than was actually requested.
|
|
63
|
+
const maxBytes = want * HEADER_BYTES
|
|
64
|
+
if (bytes.length > maxBytes) bytes = bytes.subarray(0, maxBytes)
|
|
54
65
|
try {
|
|
55
66
|
added += await store.append(bytes, from)
|
|
56
67
|
onProgress?.(store.tipHeight, presentHeight)
|