@bsv/expo-wallet-toolbox 0.23.0 → 0.24.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 +133 -0
- package/README.md +1 -4
- package/android/build.gradle +15 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
- package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
- package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
- package/core/backup/RemoteSyncReader.ts +71 -46
- package/core/backup/client.ts +6 -15
- package/core/backup/codec.ts +78 -13
- package/core/backup/constants.ts +3 -9
- package/core/backup/cursor.ts +8 -0
- package/core/backup/push.ts +26 -16
- package/core/backup/restore.ts +6 -5
- package/core/bridge/inbox.ts +169 -64
- package/core/bridge/memoryInboxStore.ts +10 -1
- package/core/constants.ts +7 -11
- package/core/context/WalletConnectionContext.tsx +85 -48
- package/core/context/WalletContext.tsx +30 -32
- package/core/context/usePairingAttempt.ts +31 -0
- package/core/e2e/broadcaster.ts +25 -0
- package/core/e2e/consentFixture.ts +46 -0
- package/core/e2e/mode.ts +42 -0
- package/core/headers/OfflineFirstChaintracks.ts +57 -107
- package/core/headers/headerConsensus.ts +230 -0
- package/core/headers/headerStore.ts +344 -122
- package/core/headers/prewarm.ts +4 -7
- package/core/headers/syncHeaders.ts +82 -12
- package/core/i18n/translations.tsx +47 -12
- package/core/identity/handleRegistry/client.ts +4 -2
- package/core/identity/handleRegistry/resolver.ts +7 -11
- package/core/index.ts +2 -0
- package/core/localpay/pending.ts +39 -4
- package/core/network/boundedFetch.ts +101 -0
- package/core/networks.ts +11 -13
- package/core/pay/rails/address.ts +5 -4
- package/core/pay/rails/handle.ts +3 -1
- package/core/pay/rails/sweep.ts +791 -0
- package/core/peerpay/brc29.ts +4 -0
- package/core/peerpay/handleResendRequests.ts +15 -2
- package/core/peerpay/outbox.ts +115 -2
- package/core/profiles/assertProfileEmpty.ts +2 -2
- package/core/profiles/profileStore.ts +3 -2
- package/core/services/arcadeBroadcastProvider.ts +260 -114
- package/core/services/secrets/kek.ts +5 -0
- package/core/services/secrets/migration.ts +27 -2
- package/core/services/secrets/policy.ts +6 -0
- package/core/services/vault/VaultKeyService.ts +5 -2
- package/core/services/vault/ceremony.ts +2 -2
- package/core/services/vault/ceremonyHost.ts +1 -1
- package/core/services/vault/guard.ts +10 -0
- package/core/services/vault/outputAuthority.ts +76 -0
- package/core/services/vault/transfers.ts +52 -28
- package/core/services/vault/vaultStore.ts +60 -14
- package/core/services/walletConnectionValidation.ts +13 -1
- package/core/services/walletServiceConfig.ts +8 -7
- package/core/stores/ConnectionStore.ts +17 -0
- package/core/toolboxConfig.ts +60 -1
- package/expo-module.config.json +5 -0
- package/ios/BoundedBody.swift +15 -0
- package/ios/BsvBoundedFetch.podspec +17 -0
- package/ios/BsvBoundedFetchModule.swift +121 -0
- package/package.json +7 -3
- package/ui/components/pay/AddressReceive.tsx +6 -2
- package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
- package/ui/components/pay/PayCellRow.tsx +3 -1
- package/ui/components/pay/PayForm.tsx +12 -2
- package/ui/components/pay/RecipientField.tsx +1 -0
- package/ui/components/pay/RequestHub.tsx +1 -0
- package/ui/components/pay/UniversalSend.tsx +110 -42
- package/ui/components/ui/ListRow.tsx +10 -2
- package/ui/components/vault/KeyChooser.tsx +1 -1
- package/ui/components/wallet/AmountInput.tsx +4 -1
- package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
- package/ui/components/wallet/ProfileButton.tsx +1 -0
- package/ui/importDatabases.ts +31 -6
- package/ui/screens/ConnectionsScreen.tsx +12 -3
- package/ui/screens/PairScreen.tsx +10 -3
- package/ui/screens/PayScreen.tsx +1 -0
- package/ui/screens/TrustScreen.tsx +6 -3
- package/ui/screens/VaultScreen.tsx +13 -3
- package/ui/screens/VaultTransferScreen.tsx +6 -3
- package/ui/screens/WalletConfigScreen.tsx +17 -2
- package/ui/screens/WalletHomeScreen.tsx +7 -1
|
@@ -7,35 +7,24 @@
|
|
|
7
7
|
* payments follows from being able to answer that with no network.
|
|
8
8
|
*
|
|
9
9
|
* SHAPE: `<chain>.bin` holds contiguous 80-byte headers starting at
|
|
10
|
-
* `anchor.height + 1`; `<chain>.json` holds
|
|
11
|
-
*
|
|
10
|
+
* `anchor.height + 1`; `<chain>.json` holds metadata. Historical roots are
|
|
11
|
+
* derived from bounded raw-header pages linked backwards to the checkpoint.
|
|
12
|
+
* Legacy extra-root files carry no membership proof and are never trusted. On open, one pass over
|
|
12
13
|
* the .bin builds a packed Uint8Array of 32-byte roots — ~1.7 MB for a year,
|
|
13
14
|
* versus ~3.4 MB if they were kept as hex strings — so a lookup is an array
|
|
14
15
|
* slice and a hex encode rather than file I/O.
|
|
15
16
|
*
|
|
16
|
-
* VALIDATION
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* helper checks linkage but not difficulty.
|
|
17
|
+
* VALIDATION checks checkpoint-authenticated difficulty history, network
|
|
18
|
+
* expected bits, proof of work, MTP, future time and version in one pass.
|
|
19
|
+
* Reorg candidates must exceed the existing locally computed accumulated work.
|
|
20
|
+
* The toolbox own-target-only helper is insufficient for consensus validation.
|
|
21
21
|
*/
|
|
22
22
|
import { Utils } from '@bsv/sdk'
|
|
23
23
|
import { utils as chaintracksUtils } from '@bsv/wallet-toolbox-mobile'
|
|
24
24
|
import type { HeaderCheckpoint } from './checkpoints'
|
|
25
25
|
import type { HeaderFs } from './fs'
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* The toolbox's proof-of-work check, given this store's chain. From
|
|
30
|
-
* @bsv/wallet-toolbox 2.15.0 (bsv-blockchain/ts-stack#819) the chain selects
|
|
31
|
-
* the proof-of-work limit — regtest's is far higher than mainnet's — and an
|
|
32
|
-
* omitted chain keeps mainnet's. Older releases take one argument and ignore
|
|
33
|
-
* the second, which changes nothing for the chains they support.
|
|
34
|
-
*/
|
|
35
|
-
const validateHeaderProofOfWork = chaintracksUtils.validateHeaderProofOfWork as (
|
|
36
|
-
header: Parameters<typeof chaintracksUtils.validateHeaderProofOfWork>[0],
|
|
37
|
-
chain?: string
|
|
38
|
-
) => true
|
|
26
|
+
import { HeaderConsensus, parseHeader } from './headerConsensus'
|
|
27
|
+
import type { WalletChain } from '../networks'
|
|
39
28
|
|
|
40
29
|
const HEADER_BYTES = 80
|
|
41
30
|
const ROOT_BYTES = 32
|
|
@@ -54,28 +43,157 @@ export class HeaderStore {
|
|
|
54
43
|
yieldEvery = HeaderStore.DEFAULT_YIELD_EVERY
|
|
55
44
|
|
|
56
45
|
private roots: Uint8Array
|
|
57
|
-
private
|
|
46
|
+
private consensus: HeaderConsensus | undefined
|
|
47
|
+
private contextBytes: Uint8Array | undefined
|
|
48
|
+
private history: { firstHeight: number; roots: Uint8Array }[] = []
|
|
49
|
+
private nextHistoryHeight: number
|
|
50
|
+
private nextHistoryHash: string
|
|
51
|
+
private pendingUpdate: Promise<void> = Promise.resolve()
|
|
52
|
+
static readonly HISTORICAL_PAGE_HEADERS = 2000
|
|
53
|
+
private recoveryRequired = false
|
|
54
|
+
private reopenRequired = false
|
|
58
55
|
private constructor(
|
|
59
56
|
private readonly fs: HeaderFs,
|
|
60
57
|
readonly chain: string,
|
|
61
58
|
readonly anchor: HeaderCheckpoint,
|
|
62
59
|
private headerCount: number,
|
|
63
60
|
private currentTipHash: string,
|
|
64
|
-
roots: Uint8Array
|
|
65
|
-
extra: Record<string, string>
|
|
61
|
+
roots: Uint8Array
|
|
66
62
|
) {
|
|
67
63
|
this.roots = roots
|
|
68
|
-
this.
|
|
64
|
+
this.nextHistoryHeight = anchor.height
|
|
65
|
+
this.nextHistoryHash = anchor.hash
|
|
69
66
|
}
|
|
70
67
|
|
|
71
68
|
private get binPath(): string {
|
|
72
69
|
return `${this.chain}.bin`
|
|
73
70
|
}
|
|
71
|
+
private get contextPath(): string {
|
|
72
|
+
return `${this.chain}-context.bin`
|
|
73
|
+
}
|
|
74
|
+
get needsContext(): boolean {
|
|
75
|
+
return this.consensus == null
|
|
76
|
+
}
|
|
77
|
+
get contextStartHeight(): number {
|
|
78
|
+
return HeaderConsensus.contextStart(this.anchor)
|
|
79
|
+
}
|
|
80
|
+
get contextCount(): number {
|
|
81
|
+
return this.anchor.height - this.contextStartHeight + 1
|
|
82
|
+
}
|
|
83
|
+
get chainWork(): bigint {
|
|
84
|
+
return this.consensus?.chainWork ?? 0n
|
|
85
|
+
}
|
|
86
|
+
hashForHeight(height: number): string | undefined {
|
|
87
|
+
if (this.reopenRequired) return undefined
|
|
88
|
+
return height === this.anchor.height ? this.anchor.hash : this.consensus?.hashForHeight(height)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The bootstrap is peer-supplied bytes, authenticated by the pinned terminal hash. */
|
|
92
|
+
async initializeContext(bytes: Uint8Array): Promise<void> {
|
|
93
|
+
await this.recoverReplacement()
|
|
94
|
+
if (this.headerCount !== 0) throw new Error('Cannot replace live header consensus context')
|
|
95
|
+
const consensus = HeaderConsensus.fromContext(this.chain as WalletChain, this.anchor, bytes)
|
|
96
|
+
await this.fs.writeBytes(this.contextPath, bytes)
|
|
97
|
+
this.consensus = consensus
|
|
98
|
+
this.contextBytes = bytes.slice()
|
|
99
|
+
}
|
|
100
|
+
|
|
74
101
|
private get metaPath(): string {
|
|
75
102
|
return `${this.chain}.json`
|
|
76
103
|
}
|
|
77
|
-
private get
|
|
78
|
-
return `${this.chain}-
|
|
104
|
+
private get historyIndexPath(): string {
|
|
105
|
+
return `${this.chain}-history.json`
|
|
106
|
+
}
|
|
107
|
+
private historyPagePath(first: number, last: number): string {
|
|
108
|
+
return `${this.chain}-history-${first}-${last}.bin`
|
|
109
|
+
}
|
|
110
|
+
get nextHistoricalHeight(): number {
|
|
111
|
+
return this.nextHistoryHeight
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Serialize background sync and proof-triggered updates against the same store. */
|
|
115
|
+
withUpdateLock<T>(operation: () => Promise<T>): Promise<T> {
|
|
116
|
+
const pending = this.pendingUpdate.then(operation)
|
|
117
|
+
this.pendingUpdate = pending.then(
|
|
118
|
+
() => undefined,
|
|
119
|
+
() => undefined
|
|
120
|
+
)
|
|
121
|
+
return pending
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private async verifyHistoryPage(bytes: Uint8Array, firstHeight: number) {
|
|
125
|
+
const count = Math.min(HeaderStore.HISTORICAL_PAGE_HEADERS, this.nextHistoryHeight + 1)
|
|
126
|
+
if (firstHeight !== this.nextHistoryHeight - count + 1 || bytes.length !== count * HEADER_BYTES) {
|
|
127
|
+
throw new Error('Historical header page has the wrong height or length')
|
|
128
|
+
}
|
|
129
|
+
const roots = new Uint8Array(count * ROOT_BYTES)
|
|
130
|
+
let previous: ReturnType<typeof parseHeader> | undefined
|
|
131
|
+
let firstPreviousHash = ''
|
|
132
|
+
for (let i = 0; i < count; i++) {
|
|
133
|
+
if (i > 0 && i % this.yieldEvery === 0) await yieldToEventLoop()
|
|
134
|
+
const header = parseHeader(bytes.subarray(i * HEADER_BYTES, (i + 1) * HEADER_BYTES))
|
|
135
|
+
if (previous && header.previousHash !== previous.hash) throw new Error('Historical header page linkage failed')
|
|
136
|
+
if (i === 0) firstPreviousHash = header.previousHash
|
|
137
|
+
roots.set(new Uint8Array(Utils.toArray(header.merkleRoot, 'hex')), i * ROOT_BYTES)
|
|
138
|
+
previous = header
|
|
139
|
+
}
|
|
140
|
+
if (previous?.hash !== this.nextHistoryHash)
|
|
141
|
+
throw new Error('Historical header page is not committed to the authenticated chain')
|
|
142
|
+
return { segment: { firstHeight, roots }, nextHeight: firstHeight - 1, nextHash: firstPreviousHash }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Historical headers need no guessed old difficulty rules: their complete
|
|
147
|
+
* hash linkage ends at the explicitly trusted checkpoint. Only fixed-size
|
|
148
|
+
* pages cross this boundary, and raw bytes are reauthenticated on reopen.
|
|
149
|
+
*/
|
|
150
|
+
async addHistoricalPage(bytes: Uint8Array, firstHeight: number): Promise<void> {
|
|
151
|
+
const page = await this.verifyHistoryPage(bytes, firstHeight)
|
|
152
|
+
await this.fs.writeBytes(this.historyPagePath(firstHeight, this.nextHistoryHeight), bytes)
|
|
153
|
+
await this.fs.writeText(
|
|
154
|
+
this.historyIndexPath,
|
|
155
|
+
JSON.stringify({
|
|
156
|
+
version: 1,
|
|
157
|
+
chain: this.chain,
|
|
158
|
+
anchorHeight: this.anchor.height,
|
|
159
|
+
anchorHash: this.anchor.hash,
|
|
160
|
+
pages: this.history.length + 1
|
|
161
|
+
})
|
|
162
|
+
)
|
|
163
|
+
this.history.push(page.segment)
|
|
164
|
+
this.nextHistoryHeight = page.nextHeight
|
|
165
|
+
this.nextHistoryHash = page.nextHash
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private async loadHistory(): Promise<void> {
|
|
169
|
+
const raw = await this.fs.readText(this.historyIndexPath)
|
|
170
|
+
if (!raw) return
|
|
171
|
+
try {
|
|
172
|
+
const index = JSON.parse(raw)
|
|
173
|
+
if (
|
|
174
|
+
index.version !== 1 ||
|
|
175
|
+
index.chain !== this.chain ||
|
|
176
|
+
index.anchorHeight !== this.anchor.height ||
|
|
177
|
+
index.anchorHash !== this.anchor.hash ||
|
|
178
|
+
!Number.isSafeInteger(index.pages) ||
|
|
179
|
+
index.pages < 0 ||
|
|
180
|
+
index.pages > Math.ceil((this.anchor.height + 1) / HeaderStore.HISTORICAL_PAGE_HEADERS)
|
|
181
|
+
)
|
|
182
|
+
return
|
|
183
|
+
for (let i = 0; i < index.pages; i++) {
|
|
184
|
+
const count = Math.min(HeaderStore.HISTORICAL_PAGE_HEADERS, this.nextHistoryHeight + 1)
|
|
185
|
+
const first = this.nextHistoryHeight - count + 1
|
|
186
|
+
const bytes = await this.fs.readBytes(this.historyPagePath(first, this.nextHistoryHeight))
|
|
187
|
+
if (!bytes) break
|
|
188
|
+
const page = await this.verifyHistoryPage(bytes, first)
|
|
189
|
+
this.history.push(page.segment)
|
|
190
|
+
this.nextHistoryHeight = page.nextHeight
|
|
191
|
+
this.nextHistoryHash = page.nextHash
|
|
192
|
+
await yieldToEventLoop()
|
|
193
|
+
}
|
|
194
|
+
} catch {
|
|
195
|
+
/* A corrupt page and all ancestors below it remain unverified. */
|
|
196
|
+
}
|
|
79
197
|
}
|
|
80
198
|
|
|
81
199
|
/** First height held by the window. */
|
|
@@ -95,17 +213,7 @@ export class HeaderStore {
|
|
|
95
213
|
}
|
|
96
214
|
|
|
97
215
|
static async open(fs: HeaderFs, chain: string, anchor: HeaderCheckpoint): Promise<HeaderStore> {
|
|
98
|
-
|
|
99
|
-
let extra: Record<string, string> = {}
|
|
100
|
-
if (extraRaw) {
|
|
101
|
-
try {
|
|
102
|
-
const parsed = JSON.parse(extraRaw) as unknown
|
|
103
|
-
if (parsed && typeof parsed === 'object') extra = parsed as Record<string, string>
|
|
104
|
-
} catch {
|
|
105
|
-
// A corrupt cache of roots is a cache miss, never a load failure.
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
216
|
+
await HeaderStore.recoverReplacement(fs, chain)
|
|
109
217
|
const metaRaw = await fs.readText(`${chain}.json`)
|
|
110
218
|
let meta: StoredMeta | undefined
|
|
111
219
|
if (metaRaw) {
|
|
@@ -116,7 +224,26 @@ export class HeaderStore {
|
|
|
116
224
|
}
|
|
117
225
|
}
|
|
118
226
|
|
|
119
|
-
const empty = new HeaderStore(fs, chain, anchor, 0, anchor.hash, new Uint8Array(0)
|
|
227
|
+
const empty = new HeaderStore(fs, chain, anchor, 0, anchor.hash, new Uint8Array(0))
|
|
228
|
+
let context = await fs.readBytes(`${chain}-context.bin`)
|
|
229
|
+
if (!context && anchor.height === 0) {
|
|
230
|
+
try {
|
|
231
|
+
context = new Uint8Array(chaintracksUtils.genesisBuffer(chain as never))
|
|
232
|
+
} catch {
|
|
233
|
+
/* Unsupported network fails closed. */
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (context) {
|
|
237
|
+
try {
|
|
238
|
+
empty.consensus = HeaderConsensus.fromContext(chain as WalletChain, anchor, context)
|
|
239
|
+
empty.contextBytes = context.slice()
|
|
240
|
+
} catch {
|
|
241
|
+
// Old or corrupt context cannot make persisted roots authoritative.
|
|
242
|
+
await fs.deleteFile(`${chain}-context.bin`)
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
await empty.loadHistory()
|
|
120
247
|
|
|
121
248
|
// A shipped checkpoint that moved (app update) invalidates the window: its
|
|
122
249
|
// first header no longer links to anything we trust. Start over rather than
|
|
@@ -126,6 +253,7 @@ export class HeaderStore {
|
|
|
126
253
|
meta.chain !== chain ||
|
|
127
254
|
meta.anchorHeight !== anchor.height ||
|
|
128
255
|
meta.anchorHash !== anchor.hash ||
|
|
256
|
+
!Number.isSafeInteger(meta.count) ||
|
|
129
257
|
meta.count <= 0
|
|
130
258
|
) {
|
|
131
259
|
await empty.reset()
|
|
@@ -145,36 +273,66 @@ export class HeaderStore {
|
|
|
145
273
|
await fs.writeBytes(`${chain}.bin`, bin)
|
|
146
274
|
}
|
|
147
275
|
|
|
276
|
+
if (!empty.consensus) {
|
|
277
|
+
await empty.reset()
|
|
278
|
+
return empty
|
|
279
|
+
}
|
|
148
280
|
const roots = new Uint8Array(meta.count * ROOT_BYTES)
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
281
|
+
try {
|
|
282
|
+
for (let i = 0; i < meta.count; i++) {
|
|
283
|
+
if (i > 0 && i % HeaderStore.DEFAULT_YIELD_EVERY === 0) await yieldToEventLoop()
|
|
284
|
+
const parsed = empty.consensus.append(
|
|
285
|
+
bin.subarray(i * HEADER_BYTES, (i + 1) * HEADER_BYTES),
|
|
286
|
+
anchor.height + i + 1
|
|
287
|
+
)
|
|
288
|
+
roots.set(new Uint8Array(Utils.toArray(parsed.merkleRoot, 'hex')), i * ROOT_BYTES)
|
|
289
|
+
}
|
|
290
|
+
} catch {
|
|
291
|
+
// Rebuild rather than trust windows accepted by the old own-target-only
|
|
292
|
+
// validator or inconsistent disk metadata. Offline verification fails closed.
|
|
293
|
+
empty.consensus = undefined
|
|
294
|
+
if (context) {
|
|
295
|
+
try {
|
|
296
|
+
empty.consensus = HeaderConsensus.fromContext(chain as WalletChain, anchor, context)
|
|
297
|
+
} catch {
|
|
298
|
+
/* Needs online bootstrap. */
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
await empty.reset()
|
|
302
|
+
return empty
|
|
155
303
|
}
|
|
156
|
-
|
|
304
|
+
empty.roots = roots
|
|
305
|
+
empty.headerCount = meta.count
|
|
306
|
+
empty.currentTipHash = empty.consensus.tipHash
|
|
307
|
+
await empty.writeMeta()
|
|
308
|
+
return empty
|
|
157
309
|
}
|
|
158
310
|
|
|
159
311
|
rootForHeight(height: number): string | undefined {
|
|
312
|
+
if (this.reopenRequired) return undefined
|
|
313
|
+
if (!Number.isSafeInteger(height) || height < 0) return undefined
|
|
314
|
+
// Genesis is an independent, shipped network commitment. It does not need
|
|
315
|
+
// a download of the entire historical chain to establish membership.
|
|
316
|
+
if (height === 0) {
|
|
317
|
+
try {
|
|
318
|
+
return parseHeader(new Uint8Array(chaintracksUtils.genesisBuffer(this.chain as never))).merkleRoot
|
|
319
|
+
} catch {
|
|
320
|
+
return undefined
|
|
321
|
+
}
|
|
322
|
+
}
|
|
160
323
|
const index = height - this.baseHeight
|
|
161
|
-
|
|
162
|
-
// The window's own PoW-linked root is authoritative for its validated BODY
|
|
163
|
-
// (every height except the last 6, which can still legitimately reorg): an
|
|
164
|
-
// extra entry there is ignored outright, never consulted, because letting
|
|
165
|
-
// it win is exactly how an unauthenticated remote answer could overwrite a
|
|
166
|
-
// root this device already validated for itself off linked headers — see
|
|
167
|
-
// misc-p2-02 / OfflineFirstChaintracks.isValidRootForHeight.
|
|
168
|
-
if (inWindow && !this.inReorgWindow(height)) {
|
|
324
|
+
if (index >= 0 && index < this.headerCount) {
|
|
169
325
|
return Utils.toHex(Array.from(this.roots.subarray(index * ROOT_BYTES, (index + 1) * ROOT_BYTES)))
|
|
170
326
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
327
|
+
const contextIndex = height - this.contextStartHeight
|
|
328
|
+
if (this.contextBytes && contextIndex >= 0 && height <= this.anchor.height) {
|
|
329
|
+
const at = contextIndex * HEADER_BYTES + 36
|
|
330
|
+
return Utils.toHex(Array.from(this.contextBytes.slice(at, at + ROOT_BYTES).reverse()))
|
|
331
|
+
}
|
|
332
|
+
for (const segment of this.history) {
|
|
333
|
+
const at = (height - segment.firstHeight) * ROOT_BYTES
|
|
334
|
+
if (at >= 0 && at < segment.roots.length)
|
|
335
|
+
return Utils.toHex(Array.from(segment.roots.subarray(at, at + ROOT_BYTES)))
|
|
178
336
|
}
|
|
179
337
|
return undefined
|
|
180
338
|
}
|
|
@@ -198,6 +356,7 @@ export class HeaderStore {
|
|
|
198
356
|
* its declared target.
|
|
199
357
|
*/
|
|
200
358
|
async append(bytes: Uint8Array, firstHeight: number): Promise<number> {
|
|
359
|
+
await this.recoverReplacement()
|
|
201
360
|
if (bytes.length === 0) return 0
|
|
202
361
|
if (bytes.length % HEADER_BYTES !== 0) {
|
|
203
362
|
throw new Error(`header chunk must be a multiple of 80 bytes, got ${bytes.length}`)
|
|
@@ -206,41 +365,24 @@ export class HeaderStore {
|
|
|
206
365
|
throw new Error(`header chunk starts at height ${firstHeight}, expected ${this.tipHeight + 1}`)
|
|
207
366
|
}
|
|
208
367
|
|
|
368
|
+
if (!this.consensus)
|
|
369
|
+
throw new Error('Header difficulty context unavailable; synchronize authenticated bootstrap first')
|
|
370
|
+
const candidate = this.consensus.forkAt(this.tipHeight)
|
|
209
371
|
const added = bytes.length / HEADER_BYTES
|
|
210
372
|
const newRoots = new Uint8Array(added * ROOT_BYTES)
|
|
211
|
-
let prev = this.currentTipHash
|
|
212
|
-
|
|
213
373
|
for (let i = 0; i < added; i++) {
|
|
214
|
-
// Two SHA-256 passes and a difficulty check per header, on the JS thread.
|
|
215
|
-
// A 2,000-header chunk was ~2.8s of solid JS on a mid-range Android and a
|
|
216
|
-
// first-launch sync repeats that ~30 times; nothing else — a nearby
|
|
217
|
-
// payment's ack, a tap — could run. Hand the loop back periodically.
|
|
218
374
|
if (i > 0 && i % this.yieldEvery === 0) await yieldToEventLoop()
|
|
219
|
-
const
|
|
220
|
-
const header = bytes.slice(offset, offset + HEADER_BYTES)
|
|
221
|
-
const parsed = deserializeBaseBlockHeader(bytes, offset)
|
|
222
|
-
if (parsed.previousHash !== prev) {
|
|
223
|
-
throw new Error(
|
|
224
|
-
`header at height ${firstHeight + i} names previous hash ${parsed.previousHash}, expected ${prev}`
|
|
225
|
-
)
|
|
226
|
-
}
|
|
227
|
-
const hash = blockHash(header)
|
|
228
|
-
// Throws on failure — a header that does not meet its own target is not a
|
|
229
|
-
// header, and accepting it would let anyone mint merkle roots. Takes the
|
|
230
|
-
// display-order hex hash blockHash returns, validates the compact target
|
|
231
|
-
// encoding, and honours the toolbox's consensus proof-of-work exceptions.
|
|
232
|
-
validateHeaderProofOfWork({ ...parsed, height: firstHeight + i, hash }, this.chain)
|
|
375
|
+
const parsed = candidate.append(bytes.subarray(i * HEADER_BYTES, (i + 1) * HEADER_BYTES), firstHeight + i)
|
|
233
376
|
newRoots.set(new Uint8Array(Utils.toArray(parsed.merkleRoot, 'hex')), i * ROOT_BYTES)
|
|
234
|
-
prev = hash
|
|
235
377
|
}
|
|
236
|
-
|
|
237
378
|
await this.fs.appendBytes(this.binPath, bytes)
|
|
238
379
|
const merged = new Uint8Array(this.roots.length + newRoots.length)
|
|
239
380
|
merged.set(this.roots, 0)
|
|
240
381
|
merged.set(newRoots, this.roots.length)
|
|
241
382
|
this.roots = merged
|
|
242
383
|
this.headerCount += added
|
|
243
|
-
this.currentTipHash =
|
|
384
|
+
this.currentTipHash = candidate.tipHash
|
|
385
|
+
this.consensus = candidate
|
|
244
386
|
await this.writeMeta()
|
|
245
387
|
return added
|
|
246
388
|
}
|
|
@@ -250,6 +392,7 @@ export class HeaderStore {
|
|
|
250
392
|
* header can link. Rebuilds the on-disk `.bin` and the in-memory root index.
|
|
251
393
|
*/
|
|
252
394
|
async truncateToCount(count: number): Promise<void> {
|
|
395
|
+
await this.recoverReplacement()
|
|
253
396
|
if (count === this.headerCount) return
|
|
254
397
|
if (count < 0 || count > this.headerCount) {
|
|
255
398
|
throw new Error(`truncateToCount(${count}) out of range 0..${this.headerCount}`)
|
|
@@ -268,42 +411,122 @@ export class HeaderStore {
|
|
|
268
411
|
await this.fs.writeBytes(this.binPath, sliced)
|
|
269
412
|
this.roots = new Uint8Array(this.roots.subarray(0, count * ROOT_BYTES))
|
|
270
413
|
this.headerCount = count
|
|
271
|
-
this.currentTipHash =
|
|
414
|
+
this.currentTipHash = parseHeader(sliced.subarray(keep - HEADER_BYTES, keep)).hash
|
|
415
|
+
this.consensus = this.consensus?.forkAt(this.anchor.height + count)
|
|
272
416
|
await this.writeMeta()
|
|
273
417
|
}
|
|
274
418
|
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
this.
|
|
279
|
-
|
|
419
|
+
/** Adopt a fully validated competing branch only when it has strictly more work. */
|
|
420
|
+
async replaceBranch(firstHeight: number, bytes: Uint8Array): Promise<number> {
|
|
421
|
+
await this.recoverReplacement()
|
|
422
|
+
if (!this.consensus) throw new Error('Header difficulty context unavailable')
|
|
423
|
+
if (bytes.length === 0 || bytes.length % HEADER_BYTES !== 0) throw new Error('Invalid replacement header bytes')
|
|
424
|
+
const forkHeight = firstHeight - 1
|
|
425
|
+
const candidate = this.consensus.forkAt(forkHeight)
|
|
426
|
+
const replacementRoots = new Uint8Array((bytes.length / HEADER_BYTES) * ROOT_BYTES)
|
|
427
|
+
for (let offset = 0; offset < bytes.length; offset += HEADER_BYTES) {
|
|
428
|
+
const i = offset / HEADER_BYTES
|
|
429
|
+
if (i > 0 && i % this.yieldEvery === 0) await yieldToEventLoop()
|
|
430
|
+
const parsed = candidate.append(bytes.subarray(offset, offset + HEADER_BYTES), firstHeight + i)
|
|
431
|
+
replacementRoots.set(new Uint8Array(Utils.toArray(parsed.merkleRoot, 'hex')), i * ROOT_BYTES)
|
|
432
|
+
}
|
|
433
|
+
if (candidate.chainWork <= this.consensus.chainWork)
|
|
434
|
+
throw new Error('Replacement header branch does not have greater accumulated work')
|
|
435
|
+
const old = await this.fs.readBytes(this.binPath)
|
|
436
|
+
const keep = (forkHeight - this.anchor.height) * HEADER_BYTES
|
|
437
|
+
if (this.headerCount > 0 && (!old || old.length < this.headerCount * HEADER_BYTES))
|
|
438
|
+
throw new Error('Stored header prefix unavailable')
|
|
439
|
+
const combined = new Uint8Array(keep + bytes.length)
|
|
440
|
+
if (keep > 0) combined.set(old!.subarray(0, keep))
|
|
441
|
+
combined.set(bytes, keep)
|
|
442
|
+
const roots = new Uint8Array((keep / HEADER_BYTES) * ROOT_BYTES + replacementRoots.length)
|
|
443
|
+
roots.set(this.roots.subarray(0, (keep / HEADER_BYTES) * ROOT_BYTES))
|
|
444
|
+
roots.set(replacementRoots, (keep / HEADER_BYTES) * ROOT_BYTES)
|
|
445
|
+
// Preserve the complete old pair before overwriting either live file. The
|
|
446
|
+
// marker is published last and removed only after both new files exist.
|
|
447
|
+
// An orphan snapshot is harmless and is reused by the next replacement.
|
|
448
|
+
const journalPath = `${this.chain}-replace.json`
|
|
449
|
+
await this.fs.writeBytes(
|
|
450
|
+
`${this.chain}-replace.bin`,
|
|
451
|
+
old?.subarray(0, this.headerCount * HEADER_BYTES) ?? new Uint8Array(0)
|
|
452
|
+
)
|
|
453
|
+
this.recoveryRequired = true
|
|
454
|
+
try {
|
|
455
|
+
await this.fs.writeText(journalPath, JSON.stringify(this.storedMeta()))
|
|
456
|
+
await this.fs.writeBytes(this.binPath, combined)
|
|
457
|
+
await this.fs.writeText(
|
|
458
|
+
this.metaPath,
|
|
459
|
+
JSON.stringify({
|
|
460
|
+
...this.storedMeta(),
|
|
461
|
+
count: combined.length / HEADER_BYTES,
|
|
462
|
+
tipHash: candidate.tipHash
|
|
463
|
+
})
|
|
464
|
+
)
|
|
465
|
+
try {
|
|
466
|
+
await this.fs.deleteFile(journalPath)
|
|
467
|
+
} catch (error) {
|
|
468
|
+
// A filesystem may report failure after the commit delete completed.
|
|
469
|
+
let marker: string | undefined
|
|
470
|
+
try {
|
|
471
|
+
marker = await this.fs.readText(journalPath)
|
|
472
|
+
} catch {
|
|
473
|
+
// Neither branch can be published in memory while the commit result
|
|
474
|
+
// is unknown. A fresh open will recover or validate the disk pair.
|
|
475
|
+
this.reopenRequired = true
|
|
476
|
+
throw error
|
|
477
|
+
}
|
|
478
|
+
if (marker !== undefined) throw error
|
|
479
|
+
}
|
|
480
|
+
} catch (error) {
|
|
481
|
+
// Keep the in-memory old chain until commit. If rollback also fails,
|
|
482
|
+
// every later window mutation retries it before touching live files.
|
|
483
|
+
await this.recoverReplacement()
|
|
484
|
+
throw error
|
|
485
|
+
}
|
|
486
|
+
this.recoveryRequired = false
|
|
487
|
+
this.roots = roots
|
|
488
|
+
this.headerCount = combined.length / HEADER_BYTES
|
|
489
|
+
this.consensus = candidate
|
|
490
|
+
this.currentTipHash = candidate.tipHash
|
|
491
|
+
return bytes.length / HEADER_BYTES
|
|
280
492
|
}
|
|
281
493
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
added++
|
|
494
|
+
private async recoverReplacement(): Promise<void> {
|
|
495
|
+
if (this.reopenRequired) throw new Error('Header replacement commit uncertain; reopen store')
|
|
496
|
+
if (!this.recoveryRequired) return
|
|
497
|
+
await HeaderStore.recoverReplacement(this.fs, this.chain)
|
|
498
|
+
this.recoveryRequired = false
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
private static async recoverReplacement(fs: HeaderFs, chain: string): Promise<void> {
|
|
502
|
+
const journalPath = `${chain}-replace.json`
|
|
503
|
+
const raw = await fs.readText(journalPath)
|
|
504
|
+
if (raw === undefined) return
|
|
505
|
+
let meta: StoredMeta
|
|
506
|
+
try {
|
|
507
|
+
meta = JSON.parse(raw) as StoredMeta
|
|
508
|
+
} catch {
|
|
509
|
+
// Torn marker publication precedes all live-file writes. The previous
|
|
510
|
+
// pair is still intact; an empty marker is also an interrupted write.
|
|
511
|
+
await fs.deleteFile(journalPath)
|
|
512
|
+
return
|
|
302
513
|
}
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
514
|
+
const snapshot = await fs.readBytes(`${chain}-replace.bin`)
|
|
515
|
+
if (!snapshot || snapshot.length !== meta.count * HEADER_BYTES)
|
|
516
|
+
throw new Error('Header replacement undo snapshot unavailable')
|
|
517
|
+
await fs.writeBytes(`${chain}.bin`, snapshot)
|
|
518
|
+
await fs.writeText(`${chain}.json`, raw)
|
|
519
|
+
await fs.deleteFile(journalPath)
|
|
520
|
+
// open() subsequently applies checkpoint/context checks and validates all
|
|
521
|
+
// restored headers. Recovery metadata does not authenticate their roots.
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** Legacy API retained for callers; a raw root provides no chain-membership proof. */
|
|
525
|
+
async putExtraRoot(_height: number, _root: string): Promise<void> {}
|
|
526
|
+
|
|
527
|
+
/** Proven-tx/prewarm rows are hints, never an authority for canonical membership. */
|
|
528
|
+
async putExtraRoots(_entries: { height: number; root: string }[]): Promise<number> {
|
|
529
|
+
return 0
|
|
307
530
|
}
|
|
308
531
|
|
|
309
532
|
/**
|
|
@@ -325,35 +548,34 @@ export class HeaderStore {
|
|
|
325
548
|
* unavailable header store as "no offline verification this launch" and tries
|
|
326
549
|
* again on the next one, which self-heals; serving wrong roots would not.
|
|
327
550
|
*
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
* anchored to, and re-earning them costs a full prewarm over `proven_txs`.
|
|
551
|
+
* Historical pages remain valid only for this exact pinned checkpoint;
|
|
552
|
+
* open reauthenticates them and ignores pages for a different anchor.
|
|
331
553
|
*
|
|
332
554
|
* Public so a sync that cannot rewind onto the remote chain (cap 144) can
|
|
333
555
|
* start over from the checkpoint.
|
|
334
556
|
*/
|
|
335
557
|
async reset(): Promise<void> {
|
|
558
|
+
await this.recoverReplacement()
|
|
336
559
|
await this.fs.deleteFile(this.binPath)
|
|
337
560
|
this.roots = new Uint8Array(0)
|
|
338
561
|
this.headerCount = 0
|
|
339
562
|
this.currentTipHash = this.anchor.hash
|
|
563
|
+
this.consensus = this.consensus?.forkAt(this.anchor.height)
|
|
340
564
|
await this.writeMeta()
|
|
341
565
|
}
|
|
342
566
|
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
return height <= this.tipHeight && height > this.tipHeight - 6
|
|
567
|
+
private async writeMeta(): Promise<void> {
|
|
568
|
+
await this.fs.writeText(this.metaPath, JSON.stringify(this.storedMeta()))
|
|
346
569
|
}
|
|
347
570
|
|
|
348
|
-
private
|
|
349
|
-
|
|
571
|
+
private storedMeta(): StoredMeta {
|
|
572
|
+
return {
|
|
350
573
|
chain: this.chain,
|
|
351
574
|
anchorHeight: this.anchor.height,
|
|
352
575
|
anchorHash: this.anchor.hash,
|
|
353
576
|
count: this.headerCount,
|
|
354
577
|
tipHash: this.currentTipHash
|
|
355
578
|
}
|
|
356
|
-
await this.fs.writeText(this.metaPath, JSON.stringify(meta))
|
|
357
579
|
}
|
|
358
580
|
}
|
|
359
581
|
|
package/core/headers/prewarm.ts
CHANGED
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* server's unverified word — they are our own past verifications. Copying them
|
|
7
|
-
* costs no network and covers exactly the heights a counterparty's BEEF will
|
|
8
|
-
* reference, because our outputs become their inputs.
|
|
2
|
+
* Legacy prewarm seam for proven-tx root hints. Stored transactions may have
|
|
3
|
+
* been verified by a build that trusted isolated provider headers, so their
|
|
4
|
+
* raw roots cannot authenticate network membership. Unknown roots remain
|
|
5
|
+
* unverified until checkpoint-linked header proofs are synchronized.
|
|
9
6
|
*/
|
|
10
7
|
import type { HeaderStore } from './headerStore'
|
|
11
8
|
|