@bsv/expo-wallet-toolbox 0.23.0 → 0.24.1

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 (86) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +1 -4
  3. package/android/build.gradle +15 -0
  4. package/android/src/main/AndroidManifest.xml +3 -0
  5. package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
  6. package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
  7. package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
  8. package/core/backup/RemoteSyncReader.ts +71 -46
  9. package/core/backup/client.ts +6 -15
  10. package/core/backup/codec.ts +78 -13
  11. package/core/backup/constants.ts +3 -9
  12. package/core/backup/cursor.ts +8 -0
  13. package/core/backup/push.ts +26 -16
  14. package/core/backup/restore.ts +6 -5
  15. package/core/bridge/inbox.ts +169 -64
  16. package/core/bridge/memoryInboxStore.ts +10 -1
  17. package/core/constants.ts +7 -11
  18. package/core/context/WalletConnectionContext.tsx +85 -48
  19. package/core/context/WalletContext.tsx +30 -32
  20. package/core/context/usePairingAttempt.ts +31 -0
  21. package/core/e2e/broadcaster.ts +25 -0
  22. package/core/e2e/consentFixture.ts +46 -0
  23. package/core/e2e/mode.ts +42 -0
  24. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  25. package/core/headers/headerConsensus.ts +230 -0
  26. package/core/headers/headerStore.ts +344 -122
  27. package/core/headers/prewarm.ts +4 -7
  28. package/core/headers/syncHeaders.ts +82 -12
  29. package/core/i18n/translations.tsx +47 -12
  30. package/core/identity/handleRegistry/client.ts +4 -2
  31. package/core/identity/handleRegistry/resolver.ts +7 -11
  32. package/core/index.ts +2 -0
  33. package/core/localpay/pending.ts +39 -4
  34. package/core/network/boundedFetch.ts +101 -0
  35. package/core/networks.ts +11 -13
  36. package/core/pay/rails/address.ts +5 -4
  37. package/core/pay/rails/handle.ts +3 -1
  38. package/core/pay/rails/sweep.ts +791 -0
  39. package/core/peerpay/brc29.ts +4 -0
  40. package/core/peerpay/handleResendRequests.ts +15 -2
  41. package/core/peerpay/outbox.ts +115 -2
  42. package/core/profiles/assertProfileEmpty.ts +2 -2
  43. package/core/profiles/profileStore.ts +3 -2
  44. package/core/services/arcadeBroadcastProvider.ts +260 -114
  45. package/core/services/secrets/kek.ts +5 -0
  46. package/core/services/secrets/migration.ts +27 -2
  47. package/core/services/secrets/policy.ts +6 -0
  48. package/core/services/vault/VaultKeyService.ts +5 -2
  49. package/core/services/vault/ceremony.ts +2 -2
  50. package/core/services/vault/ceremonyHost.ts +1 -1
  51. package/core/services/vault/guard.ts +10 -0
  52. package/core/services/vault/outputAuthority.ts +76 -0
  53. package/core/services/vault/transfers.ts +52 -28
  54. package/core/services/vault/vaultStore.ts +60 -14
  55. package/core/services/walletConnectionValidation.ts +13 -1
  56. package/core/services/walletServiceConfig.ts +8 -7
  57. package/core/stores/ConnectionStore.ts +17 -0
  58. package/core/toolboxConfig.ts +60 -1
  59. package/expo-module.config.json +5 -0
  60. package/ios/BoundedBody.swift +15 -0
  61. package/ios/BsvBoundedFetch.podspec +17 -0
  62. package/ios/BsvBoundedFetchModule.swift +134 -0
  63. package/package.json +7 -3
  64. package/ui/components/pay/AddressReceive.tsx +6 -2
  65. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  66. package/ui/components/pay/PayCellRow.tsx +3 -1
  67. package/ui/components/pay/PayForm.tsx +12 -2
  68. package/ui/components/pay/RecipientField.tsx +1 -0
  69. package/ui/components/pay/RequestHub.tsx +1 -0
  70. package/ui/components/pay/UniversalSend.tsx +110 -42
  71. package/ui/components/ui/ListRow.tsx +10 -2
  72. package/ui/components/vault/KeyChooser.tsx +1 -1
  73. package/ui/components/wallet/AmountInput.tsx +4 -1
  74. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  75. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  76. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  77. package/ui/components/wallet/ProfileButton.tsx +1 -0
  78. package/ui/importDatabases.ts +31 -6
  79. package/ui/screens/ConnectionsScreen.tsx +12 -3
  80. package/ui/screens/PairScreen.tsx +10 -3
  81. package/ui/screens/PayScreen.tsx +1 -0
  82. package/ui/screens/TrustScreen.tsx +6 -3
  83. package/ui/screens/VaultScreen.tsx +13 -3
  84. package/ui/screens/VaultTransferScreen.tsx +6 -3
  85. package/ui/screens/WalletConfigScreen.tsx +17 -2
  86. package/ui/screens/WalletHomeScreen.tsx +7 -1
@@ -9,24 +9,14 @@
9
9
  * `Services.getChainTracker()`, which wraps whatever sits in
10
10
  * `options.chaintracks` (`services/Services.js:149-154`).
11
11
  *
12
- * On a miss it calls `findHeaderForHeight` rather than the remote's own
13
- * `isValidRootForHeight`, because we want the root itself to cache — a coin
14
- * whose ancestry we resolved once should verify offline forever after.
12
+ * Misses require a complete expected-difficulty/work-validated extension, or
13
+ * a historical hash-link proof ending at a trusted checkpoint. Authenticated
14
+ * roots remain available offline; isolated provider headers never suffice.
15
15
  */
16
+ import type { Chain, ChaintracksClientApi } from '@bsv/wallet-toolbox-mobile'
17
+ import { HeaderStore } from './headerStore'
18
+ import { syncHeaders } from './syncHeaders'
16
19
  import { Utils } from '@bsv/sdk'
17
- import { utils as chaintracksUtils, type Chain, type ChaintracksClientApi } from '@bsv/wallet-toolbox-mobile'
18
- import type { HeaderStore } from './headerStore'
19
-
20
- const { blockHash, validateHeaderProofOfWork } = chaintracksUtils
21
-
22
- /** A merkle root as display-order hex, whether the source gave us a hex string
23
- * or raw bytes. The remote's `findHeaderForHeight` may return either; plain
24
- * `String(bytes)` yields "1,2,3,…" which never matches a real root — the source
25
- * of a chain-tracker that rejects valid proofs. Mirrors the toolbox's own
26
- * `asString(merkleRoot)`. */
27
- function rootHex(v: unknown): string {
28
- return typeof v === 'string' ? v : Utils.toHex(Array.from(v as ArrayLike<number>))
29
- }
30
20
 
31
21
  /** Handed out when the remote cannot subscribe; never reaches the remote. */
32
22
  const INERT_SUBSCRIPTION_PREFIX = 'offline-first:inert:'
@@ -65,117 +55,77 @@ export class OfflineFirstChaintracks implements ChaintracksClientApi {
65
55
  }
66
56
 
67
57
  setStore(store: HeaderStore): void {
58
+ if (this.chain && store.chain !== this.chain) throw new Error('Header store belongs to a different network')
68
59
  this.store = store
69
60
  }
70
61
 
71
62
  async isValidRootForHeight(root: string, height: number): Promise<boolean> {
72
- // Fast path: a local root that AGREES is trusted offline forever (validated
73
- // window headers, or a previously-resolved root).
74
- const local = this.store?.rootForHeight(height)
63
+ if (!Number.isSafeInteger(height) || height < 0 || !/^[0-9a-f]{64}$/.test(root)) return false
64
+ const store = this.store
65
+ const local = store?.rootForHeight(height)
75
66
  if (local === root) return true
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
- )
67
+ // Both checkpoint ancestors and the stable window body are authenticated.
68
+ // An isolated network answer cannot override either commitment.
69
+ if (local !== undefined && (height <= store!.anchor.height || store!.isWindowBody(height))) {
93
70
  this.lastMissHeight = height
94
71
  return false
95
72
  }
96
-
97
- if (!(await this.online())) {
98
- // Logged, because this branch is otherwise indistinguishable from a bad
99
- // proof: it returns false without consulting anything, and the caller
100
- // (`Beef.verify` -> the toolbox's validateAtomicBeef) reports that as
101
- // "The tx parameter must be valid AtomicBEEF". A device whose NetInfo
102
- // says not-connected therefore rejects every incoming payment with an
103
- // error blaming the sender's transaction, silently and forever.
104
- console.warn(
105
- `[OfflineFirstChaintracks] REFUSED height ${height}: offline (getOnline() false), no lookup attempted. ` +
106
- 'BEEF verification will fail and be reported as an invalid transaction.'
107
- )
73
+ if (!store || !(await this.online())) {
108
74
  this.lastMissHeight = height
109
75
  return false
110
76
  }
111
-
112
77
  try {
113
- const header = await this.remote.findHeaderForHeight(height)
114
- if (!header) {
115
- console.warn(
116
- `[OfflineFirstChaintracks] REFUSED height ${height}: the chaintracks service has no header ` +
117
- 'for it (behind the chain tip, or pruned).'
118
- )
119
- this.lastMissHeight = height
120
- return false
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
-
146
- const remoteRoot = rootHex(header.merkleRoot)
147
- // Refresh the cache with the authoritative value (self-heals a poisoned
148
- // extra entry from an earlier bad conversion).
149
- await this.store?.putExtraRoot(height, remoteRoot)
150
- if (local !== undefined && local !== remoteRoot) {
151
- console.warn(
152
- `[OfflineFirstChaintracks] local root disagreed with network at height ${height} (local=${local} network=${remoteRoot}); healed`
153
- )
154
- }
155
- const agrees = remoteRoot === root
156
- if (!agrees) {
157
- // The comparison is ===, so a root that is "correct" to the eye still
158
- // fails on hex case or byte order. Print both to make which one it is
159
- // obvious from a device log.
160
- console.warn(
161
- `[OfflineFirstChaintracks] REFUSED height ${height}: root mismatch\n` +
162
- ` wanted (from the BEEF's merkle path): ${root}\n` +
163
- ` got (from chaintracks) : ${remoteRoot}`
164
- )
78
+ if (height > store.anchor.height) {
79
+ // Forward misses and reorg-tail disagreements share the full expected-
80
+ // difficulty / accumulated-work synchronization path. A claimed height,
81
+ // standalone header hash or provider chainWork is never an authority.
82
+ await syncHeaders({ store, client: this.remote })
83
+ } else {
84
+ await store.withUpdateLock(async () => {
85
+ while (store.rootForHeight(height) === undefined && store.nextHistoricalHeight >= height) {
86
+ const end = store.nextHistoricalHeight
87
+ const from = Math.max(0, end - HeaderStore.HISTORICAL_PAGE_HEADERS + 1)
88
+ const count = end - from + 1
89
+ const hex = await this.remote.getHeaders(from, count)
90
+ if (hex.length !== count * 160 || !/^[0-9a-f]+$/i.test(hex)) {
91
+ throw new Error('Historical chain proof unavailable or malformed')
92
+ }
93
+ await store.addHistoricalPage(new Uint8Array(Utils.toArray(hex, 'hex')), from)
94
+ }
95
+ })
165
96
  }
97
+ const agrees = store.rootForHeight(height) === root
98
+ if (!agrees) this.lastMissHeight = height
166
99
  return agrees
167
- } catch (e: any) {
168
- // A verification path must never throw a network error at the caller:
169
- // `Beef.verify` treats false as "not proven", which is the truth here.
170
- console.warn('[OfflineFirstChaintracks] isValidRootForHeight lookup failed:', e?.message)
100
+ } catch (error) {
101
+ console.warn(
102
+ '[OfflineFirstChaintracks] anchored header verification failed:',
103
+ error instanceof Error ? error.message : String(error)
104
+ )
171
105
  this.lastMissHeight = height
172
106
  return false
173
107
  }
174
108
  }
175
109
 
110
+ /**
111
+ * Verification height is the locally validated chain tip. An online refresh
112
+ * can advance it only through consensus synchronization; a missing/failed
113
+ * refresh leaves a conservative, potentially stale validated height.
114
+ */
176
115
  async currentHeight(): Promise<number> {
177
- if (await this.online()) return await this.remote.currentHeight()
178
- return this.store?.tipHeight ?? 0
116
+ const store = this.store
117
+ if (!store) throw new Error('Validated header store unavailable for verification height')
118
+ if (await this.online()) {
119
+ try {
120
+ await syncHeaders({ store, client: this.remote })
121
+ } catch (error) {
122
+ console.warn(
123
+ '[OfflineFirstChaintracks] height refresh unavailable; retaining validated tip:',
124
+ error instanceof Error ? error.message : String(error)
125
+ )
126
+ }
127
+ }
128
+ return store.tipHeight
179
129
  }
180
130
 
181
131
  /**
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Header consensus, not transaction/script validation. Difficulty and median3
3
+ * ordering follow BSV Node src/pow.cpp / src/validation.cpp:
4
+ * https://github.com/bitcoin-sv/bitcoin-sv/blob/master/src/pow.cpp
5
+ * TTN bootstrap rules follow Teranode services/blockchain/Difficulty.go and
6
+ * network parameters follow bsv-blockchain/go-chaincfg/params.go.
7
+ * Main/test anchors are post-CW144. Earlier headers are only used when their
8
+ * complete linkage commits to a trusted checkpoint, never as new extensions.
9
+ */
10
+ import { Hash, Utils } from '@bsv/sdk'
11
+ import type { HeaderCheckpoint } from './checkpoints'
12
+ import type { WalletChain } from '../networks'
13
+
14
+ const TWO_256 = 1n << 256n
15
+ const MASK_256 = TWO_256 - 1n
16
+ const MAIN_LIMIT = (1n << 224n) - 1n
17
+ const SPACING = 600
18
+ export const HEADER_CONTEXT_COUNT = 147
19
+
20
+ export interface WorkHeader {
21
+ height: number
22
+ time: number
23
+ bits: number
24
+ work: bigint
25
+ }
26
+
27
+ export interface ParsedHeader {
28
+ version: number
29
+ previousHash: string
30
+ merkleRoot: string
31
+ time: number
32
+ bits: number
33
+ nonce: number
34
+ hash: string
35
+ }
36
+
37
+ type HistoryHeader = WorkHeader & { hash: string }
38
+
39
+ function parameters(chain: WalletChain) {
40
+ switch (chain) {
41
+ case 'main':
42
+ return { limit: MAIN_LIMIT, minDifficulty: false, daaHeight: 504031, versions: [227931, 363725, 388381] }
43
+ case 'test':
44
+ return { limit: MAIN_LIMIT, minDifficulty: true, daaHeight: 1188697, versions: [21111, 330776, 581885] }
45
+ case 'ttn':
46
+ return { limit: MAIN_LIMIT, minDifficulty: true, daaHeight: 0, versions: [0, 0, 0] }
47
+ case 'regtest':
48
+ return { limit: (1n << 255n) - 1n, minDifficulty: true, daaHeight: 0, versions: [100000000, 1251, 1351] }
49
+ default:
50
+ throw new Error(`Unsupported header consensus network: ${String(chain)}`)
51
+ }
52
+ }
53
+
54
+ /** Bitcoin SetCompact's sign/zero/overflow checks, before any shifting. */
55
+ export function bitsToTarget(bits: number): bigint {
56
+ if (!Number.isInteger(bits) || bits < 0 || bits > 0xffffffff) throw new Error('Invalid compact target')
57
+ const size = bits >>> 24
58
+ const word = bits & 0x007fffff
59
+ if (!word || (bits & 0x00800000) !== 0 || size > 34 || (word > 0xff && size > 33) || (word > 0xffff && size > 32))
60
+ throw new Error('Invalid compact target')
61
+ const value = size <= 3 ? BigInt(word) >> BigInt(8 * (3 - size)) : BigInt(word) << BigInt(8 * (size - 3))
62
+ if (value === 0n || value > MASK_256) throw new Error('Invalid compact target')
63
+ return value
64
+ }
65
+
66
+ /** Bitcoin GetCompact, with its sign-bit carry and integer truncation. */
67
+ export function targetToBits(target: bigint): number {
68
+ if (target <= 0n || target > MASK_256) throw new Error('Invalid target')
69
+ let size = Math.ceil(target.toString(16).length / 2)
70
+ let word = Number(size <= 3 ? target << BigInt(8 * (3 - size)) : target >> BigInt(8 * (size - 3)))
71
+ if ((word & 0x00800000) !== 0) {
72
+ word >>>= 8
73
+ size++
74
+ }
75
+ return ((size << 24) | word) >>> 0
76
+ }
77
+
78
+ export function headerWork(bits: number): bigint {
79
+ return TWO_256 / (bitsToTarget(bits) + 1n)
80
+ }
81
+
82
+ function suitable(history: readonly WorkHeader[], at: number): WorkHeader {
83
+ if (at < 2 || !history[at]) throw new Error('Header difficulty context unavailable')
84
+ // Preserve the node's exact sorting network, including equal timestamps.
85
+ const blocks = [history[at - 2], history[at - 1], history[at]]
86
+ if (blocks[0].time > blocks[2].time) [blocks[0], blocks[2]] = [blocks[2], blocks[0]]
87
+ if (blocks[0].time > blocks[1].time) [blocks[0], blocks[1]] = [blocks[1], blocks[0]]
88
+ if (blocks[1].time > blocks[2].time) [blocks[1], blocks[2]] = [blocks[2], blocks[1]]
89
+ return blocks[1]
90
+ }
91
+
92
+ /** Expected bits from already authenticated history; no peer difficulty/work claims. */
93
+ export function nextWorkRequired(chain: WalletChain, history: readonly WorkHeader[], nextTime: number): number {
94
+ const params = parameters(chain)
95
+ const previous = history[history.length - 1]
96
+ if (!previous) throw new Error('Header difficulty context unavailable')
97
+ if (chain === 'regtest') return previous.bits
98
+ if (params.minDifficulty && nextTime > previous.time + 2 * SPACING) return 0x1d00ffff
99
+ // TTN activates DAA at genesis; its actual node keeps the start difficulty
100
+ // until there are enough headers (previous height148 is the first DAA case).
101
+ if (chain === 'ttn' && previous.height < 148) return 0x1d00ffff
102
+ if (previous.height < params.daaHeight)
103
+ throw new Error('Historical fork difficulty context is not supported by this checkpoint')
104
+ const last = suitable(history, history.length - 1)
105
+ const first = suitable(history, history.length - 1 - 144)
106
+ const span = Math.max(72 * SPACING, Math.min(288 * SPACING, last.time - first.time))
107
+ let work = ((last.work - first.work) * BigInt(SPACING)) & MASK_256
108
+ work /= BigInt(span)
109
+ if (work <= 0n) throw new Error('Invalid header work context')
110
+ // Node ComputeTarget uses uint256 two's-complement negation, not a rounded
111
+ // floating point inverse or (2^256/work)-1.
112
+ const target = (TWO_256 - work) / work
113
+ return targetToBits(target > params.limit ? params.limit : target)
114
+ }
115
+
116
+ export function parseHeader(bytes: Uint8Array): ParsedHeader {
117
+ if (bytes.length !== 80) throw new Error('Header must contain exactly 80 bytes')
118
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
119
+ const hex = (from: number, to: number) => Utils.toHex(Array.from(bytes.slice(from, to).reverse()))
120
+ return {
121
+ version: view.getUint32(0, true),
122
+ previousHash: hex(4, 36),
123
+ merkleRoot: hex(36, 68),
124
+ time: view.getUint32(68, true),
125
+ bits: view.getUint32(72, true),
126
+ nonce: view.getUint32(76, true),
127
+ hash: Utils.toHex(Hash.hash256(Array.from(bytes)).reverse())
128
+ }
129
+ }
130
+
131
+ function proofOfWork(header: ParsedHeader, chain: WalletChain): void {
132
+ const target = bitsToTarget(header.bits)
133
+ if (target > parameters(chain).limit || BigInt(`0x${header.hash}`) > target)
134
+ throw new Error('Header proof of work failed')
135
+ }
136
+
137
+ export class HeaderConsensus {
138
+ private constructor(
139
+ readonly chain: WalletChain,
140
+ readonly anchor: HeaderCheckpoint,
141
+ private history: HistoryHeader[],
142
+ private readonly now: () => number
143
+ ) {}
144
+
145
+ static contextStart(anchor: HeaderCheckpoint): number {
146
+ return Math.max(0, anchor.height - HEADER_CONTEXT_COUNT + 1)
147
+ }
148
+
149
+ /** Authenticate ancestors backwards by their terminal pinned checkpoint hash. */
150
+ static fromContext(
151
+ chain: WalletChain,
152
+ anchor: HeaderCheckpoint,
153
+ bytes: Uint8Array,
154
+ now: () => number = () => Math.floor(Date.now() / 1000)
155
+ ): HeaderConsensus {
156
+ const params = parameters(chain)
157
+ if ((chain === 'main' || chain === 'test') && anchor.height < params.daaHeight) {
158
+ throw new Error('A post-DAA trusted checkpoint is required for forward header validation')
159
+ }
160
+ const from = HeaderConsensus.contextStart(anchor)
161
+ if (bytes.length !== (anchor.height - from + 1) * 80)
162
+ throw new Error('Header bootstrap context has the wrong length')
163
+ const history: HistoryHeader[] = []
164
+ let work = 0n
165
+ for (let offset = 0; offset < bytes.length; offset += 80) {
166
+ const header = parseHeader(bytes.subarray(offset, offset + 80))
167
+ proofOfWork(header, chain)
168
+ if (history.length && header.previousHash !== history[history.length - 1].hash)
169
+ throw new Error('Header context linkage failed')
170
+ work += headerWork(header.bits)
171
+ history.push({ height: from + history.length, time: header.time, bits: header.bits, hash: header.hash, work })
172
+ }
173
+ if (history[history.length - 1]?.hash !== anchor.hash)
174
+ throw new Error('Header context does not commit to the trusted checkpoint')
175
+ return new HeaderConsensus(chain, anchor, history, now)
176
+ }
177
+
178
+ get tipHeight(): number {
179
+ return this.history[this.history.length - 1].height
180
+ }
181
+ get tipHash(): string {
182
+ return this.history[this.history.length - 1].hash
183
+ }
184
+ get chainWork(): bigint {
185
+ return this.history[this.history.length - 1].work
186
+ }
187
+
188
+ hashForHeight(height: number): string | undefined {
189
+ return this.history[height - this.history[0].height]?.hash
190
+ }
191
+
192
+ forkAt(height: number): HeaderConsensus {
193
+ if (height < this.anchor.height || height > this.tipHeight || !Number.isInteger(height))
194
+ throw new Error('Header fork is outside authenticated history')
195
+ return new HeaderConsensus(
196
+ this.chain,
197
+ this.anchor,
198
+ this.history.slice(0, height - this.history[0].height + 1),
199
+ this.now
200
+ )
201
+ }
202
+
203
+ /** All checks finish before the history is mutated. */
204
+ append(bytes: Uint8Array, height: number): ParsedHeader {
205
+ if (height !== this.tipHeight + 1) throw new Error(`Unexpected header height ${height}`)
206
+ const header = parseHeader(bytes)
207
+ if (header.previousHash !== this.tipHash)
208
+ throw new Error(`header at height ${height} names previous hash ${header.previousHash}, expected ${this.tipHash}`)
209
+ const expected = nextWorkRequired(this.chain, this.history, header.time)
210
+ if (header.bits !== expected)
211
+ throw new Error(`Header difficulty mismatch at height ${height}: ${header.bits} expected ${expected}`)
212
+ const times = this.history
213
+ .slice(-11)
214
+ .map(h => h.time)
215
+ .sort((a, b) => a - b)
216
+ if (header.time <= times[Math.floor(times.length / 2)])
217
+ throw new Error(`Header time is not after median time past at height ${height}`)
218
+ if (header.time > this.now() + 2 * 60 * 60)
219
+ throw new Error(`Header time is too far in the future at height ${height}`)
220
+ const version = header.version | 0
221
+ const heights = parameters(this.chain).versions
222
+ if (heights.some((activation, i) => height >= activation && version < i + 2))
223
+ throw new Error(`Obsolete header version at height ${height}`)
224
+ proofOfWork(header, this.chain)
225
+ const work = this.chainWork + headerWork(header.bits)
226
+ if (work > MASK_256) throw new Error('Header chain work overflow')
227
+ this.history.push({ height, time: header.time, bits: header.bits, work, hash: header.hash })
228
+ return header
229
+ }
230
+ }