psf-multisig-approval 2.1.0 → 2.3.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.
@@ -0,0 +1,834 @@
1
+ /*
2
+ PS009 v2 - validateApproval(): the section 6 validation checklist.
3
+
4
+ A PS010 node (or any interested party) validates an approved registry epoch
5
+ in ten steps. This module implements them, in order, reference-first:
6
+
7
+ 1. Read the PSP1 announcement under consideration from the chain
8
+ (injected `psp1FromChain` provider - required; the validator does not
9
+ make network calls of its own).
10
+ 2. Monotonicity of validFromHeight versus the previous epoch.
11
+ 3. Retrieve the Approval Transaction, parse its APPROVAL record, and check
12
+ it names the Update Transaction. When a Reference Address history
13
+ provider is supplied, the AT must also be the latest APPROVAL tx and
14
+ carry the 546-sat dust output from section 5.
15
+ 4. Retrieve the Update Transaction, extract its CID, fetch the membership
16
+ JSON (injected `getCidData` provider or pre-fetched `updateData`).
17
+ 5. Group Token ID matches the council's expected Group Token.
18
+ 6. Every operator NFT is a child of that Group Token.
19
+ 7. Every listed address is generated from the listed public key.
20
+ 8. Every listed address holds (or held) the listed NFT.
21
+ 9. Recompute the P2SH multisig address from the keys + published threshold,
22
+ assert it is the AT's first-vin address, and verify the n-of-m
23
+ signatures over the AT.
24
+ 10. Assert the Update Transaction's `endorses` field equals the PSP1
25
+ announcement txid, and the announcement's first vin spends from the
26
+ council P2SH address (PS010 F9).
27
+
28
+ Failure semantics:
29
+ - Missing/invalid *arguments* throw (programmer error).
30
+ - Anything the spec calls a validation failure is returned as
31
+ { valid: false, errors: [{ step, code, message }] } - never thrown - so a
32
+ caller can log a distinguishable reason per PS010 section 7.3's spirit.
33
+ - No network access. No wall clock. No IPFS gateway default.
34
+ */
35
+
36
+ import bitcore from '@chris.troutner/bitcore-lib-cash'
37
+
38
+ import {
39
+ deriveAddressFromPubkey,
40
+ deriveCouncilAddress,
41
+ addressesEqual
42
+ } from './council.js'
43
+ import { parsePsP1Record } from './psp1-codec.js'
44
+ import { parseUpdateRecord } from './update.js'
45
+ import { parseApprovalRecord } from './approval.js'
46
+ import { countMultisigSignatures, verifyMultisigSpend } from './signatures.js'
47
+ import { DUST_SATOSHIS } from './tx.js'
48
+
49
+ const TXID_REGEX = /^[0-9a-fA-F]{64}$/
50
+
51
+ function normalizeHex (value) {
52
+ return typeof value === 'string' ? value.toLowerCase() : value
53
+ }
54
+
55
+ function makeError (step, code, message) {
56
+ return { step, code, message }
57
+ }
58
+
59
+ function errorText (err) {
60
+ return err && err.message ? err.message : String(err)
61
+ }
62
+
63
+ // ---------------------------------------------------------------- providers
64
+
65
+ // Accept either getTx (single tx) or getTxData (the existing repo util returns
66
+ // an array). Returns null on a miss.
67
+ async function readTx (inObj, txid) {
68
+ const provider = inObj.getTx || inObj.getTxData
69
+ if (typeof provider !== 'function') return null
70
+
71
+ const raw = await provider(txid)
72
+
73
+ if (!raw) return null
74
+ if (Array.isArray(raw)) {
75
+ if (raw.length === 0) return null
76
+ return raw[0]
77
+ }
78
+ if (raw.txid && Array.isArray(raw.vout)) return raw
79
+ if (raw.txid && raw.hex && !raw.vout) return raw
80
+ if (raw[txid]) return raw[txid]
81
+
82
+ return raw
83
+ }
84
+
85
+ // Normalize a raw transaction (tx-details object, builder output, or hex) into
86
+ // the shape this module reads: { txid, hex, vin[], vout[] }.
87
+ function normalizeTx (raw) {
88
+ if (!raw) return null
89
+
90
+ let obj = raw
91
+ if (typeof raw === 'string') obj = { hex: raw }
92
+ if (obj.tx && obj.hex && !obj.vout) {
93
+ obj = { txid: obj.txid, hex: obj.hex, vin: obj.vin, vout: obj.vout }
94
+ }
95
+
96
+ if (Array.isArray(obj.vin) && Array.isArray(obj.vout)) {
97
+ return Object.assign({}, obj, { txid: obj.txid || obj.hash })
98
+ }
99
+
100
+ if (typeof obj.hex !== 'string') return obj
101
+
102
+ let parsed
103
+ try {
104
+ parsed = new bitcore.Transaction(obj.hex)
105
+ } catch (err) {
106
+ return obj
107
+ }
108
+
109
+ const vin = parsed.inputs.map((input) => {
110
+ return {
111
+ txid: input.prevTxId ? input.prevTxId.toString('hex') : null,
112
+ vout: input.outputIndex,
113
+ scriptSig: { hex: input.script ? input.script.toHex() : '' }
114
+ }
115
+ })
116
+
117
+ const vout = parsed.outputs.map((output, n) => {
118
+ return {
119
+ n,
120
+ satoshis: output.satoshis,
121
+ scriptPubKey: { hex: output.script.toHex() }
122
+ }
123
+ })
124
+
125
+ return {
126
+ txid: obj.txid || parsed.hash,
127
+ hash: parsed.hash,
128
+ hex: obj.hex,
129
+ blockheight: obj.blockheight,
130
+ height: obj.height,
131
+ vin: obj.vin || vin,
132
+ vout: obj.vout || vout
133
+ }
134
+ }
135
+
136
+ // ------------------------------------------------------- tx field accessors
137
+
138
+ function vinAddress (vin) {
139
+ if (!vin) return null
140
+ if (typeof vin.address === 'string') return vin.address
141
+ if (vin.prevout) {
142
+ if (typeof vin.prevout.address === 'string') return vin.prevout.address
143
+ const prevScript = vin.prevout.scriptPubKey
144
+ if (prevScript) {
145
+ if (Array.isArray(prevScript.addresses) && prevScript.addresses[0]) return prevScript.addresses[0]
146
+ if (prevScript.addresses && typeof prevScript.addresses === 'string') return prevScript.addresses
147
+ if (typeof prevScript.hex === 'string') return addressFromScriptHex(prevScript.hex)
148
+ }
149
+ }
150
+ if (vin.scriptPubKey) {
151
+ if (Array.isArray(vin.scriptPubKey.addresses) && vin.scriptPubKey.addresses[0]) return vin.scriptPubKey.addresses[0]
152
+ if (typeof vin.scriptPubKey.hex === 'string') return addressFromScriptHex(vin.scriptPubKey.hex)
153
+ }
154
+ return null
155
+ }
156
+
157
+ function addressFromScriptHex (scriptHex) {
158
+ try {
159
+ const script = new bitcore.Script(scriptHex)
160
+ const address = script.toAddress()
161
+ return address ? address.toString() : null
162
+ } catch (err) {
163
+ return null
164
+ }
165
+ }
166
+
167
+ function vinSatoshis (vin) {
168
+ if (!vin) return null
169
+ if (Number.isInteger(vin.satoshis)) return vin.satoshis
170
+ if (Number.isFinite(vin.value)) return Math.round(vin.value * 1e8)
171
+ if (vin.prevout) {
172
+ if (Number.isInteger(vin.prevout.satoshis)) return vin.prevout.satoshis
173
+ if (Number.isFinite(vin.prevout.value)) return Math.round(vin.prevout.value * 1e8)
174
+ }
175
+ return null
176
+ }
177
+
178
+ function vinScriptSigHex (vin) {
179
+ if (!vin) return null
180
+ if (vin.scriptSig) {
181
+ if (typeof vin.scriptSig === 'string') return vin.scriptSig
182
+ if (typeof vin.scriptSig.hex === 'string') return vin.scriptSig.hex
183
+ }
184
+ if (typeof vin.scriptSigHex === 'string') return vin.scriptSigHex
185
+ return null
186
+ }
187
+
188
+ function voutSatoshis (vout) {
189
+ if (!vout) return null
190
+ if (Number.isInteger(vout.satoshis)) return vout.satoshis
191
+ if (Number.isFinite(vout.value)) return Math.round(vout.value * 1e8)
192
+ return null
193
+ }
194
+
195
+ function voutAddresses (vout) {
196
+ if (!vout || !vout.scriptPubKey) return []
197
+ const spk = vout.scriptPubKey
198
+ if (Array.isArray(spk.addresses)) return spk.addresses
199
+ if (typeof spk.addresses === 'string') return [spk.addresses]
200
+ if (typeof spk.address === 'string') return [spk.address]
201
+ if (typeof spk.hex === 'string') {
202
+ const addr = addressFromScriptHex(spk.hex)
203
+ return addr ? [addr] : []
204
+ }
205
+ return []
206
+ }
207
+
208
+ // -------------------------------------------------------- membership JSON
209
+
210
+ // Normalize the Update Transaction membership document. Supports the v2 shape
211
+ // ({ groupTokenId, nfts: [{ tokenId, address, pubKey }], requiredSignatures })
212
+ // and the PS009 v1 shape ({ groupId, keys: [{ nft, addr, pubKey }],
213
+ // walletObj: { publicKeys, requiredSigners, address } }).
214
+ function normalizeMembership (doc) {
215
+ if (!doc || typeof doc !== 'object') {
216
+ throw new Error('membership document must be a JSON object')
217
+ }
218
+
219
+ const groupTokenId = doc.groupTokenId || doc.groupId || doc.group || null
220
+
221
+ let list = doc.nfts || doc.operators || doc.keys
222
+ if (!Array.isArray(list)) list = []
223
+
224
+ const entries = list.map((entry) => {
225
+ return {
226
+ tokenId: entry.tokenId || entry.nft || entry.token || entry.tokenIdHex || null,
227
+ address: entry.address || entry.addr || null,
228
+ pubKey: entry.pubKey || entry.pubkey || entry.publicKey || null,
229
+ groupTokenId: entry.groupTokenId || entry.groupId || entry.group || null
230
+ }
231
+ })
232
+
233
+ // v1 walletObj fallback: public keys only. Addresses are derived in step 7.
234
+ const walletObj = doc.walletObj || {}
235
+ if (entries.length === 0 && Array.isArray(walletObj.publicKeys)) {
236
+ for (const pubKey of walletObj.publicKeys) {
237
+ entries.push({ tokenId: null, address: null, pubKey, groupTokenId: null })
238
+ }
239
+ }
240
+
241
+ const threshold = doc.requiredSignatures !== undefined
242
+ ? doc.requiredSignatures
243
+ : (doc.threshold !== undefined ? doc.threshold : walletObj.requiredSigners)
244
+
245
+ const address = doc.multisigAddr || doc.multisigAddress || doc.address || walletObj.address || null
246
+
247
+ return {
248
+ groupTokenId,
249
+ entries,
250
+ threshold: threshold === undefined ? null : threshold,
251
+ address,
252
+ endorses: doc.endorses ? normalizeHex(doc.endorses) : null,
253
+ raw: doc
254
+ }
255
+ }
256
+
257
+ // --------------------------------------------------------------- validation
258
+
259
+ async function validateApproval (inObj = {}) {
260
+ const atxid = inObj.atxid || inObj.approvalTxid
261
+ const councilConfig = inObj.council || {}
262
+ const network = inObj.network || councilConfig.network || 'mainnet'
263
+
264
+ if (typeof atxid !== 'string' || !TXID_REGEX.test(atxid)) {
265
+ throw new Error('atxid is required (the Approval Transaction txid to validate)')
266
+ }
267
+ if (typeof councilConfig.groupTokenId !== 'string' || councilConfig.groupTokenId.length === 0) {
268
+ throw new Error('council.groupTokenId is required (the expected council Group Token ID)')
269
+ }
270
+
271
+ const requestedUtxid = inObj.utxid || inObj.updateTxid || null
272
+ if (requestedUtxid && !TXID_REGEX.test(requestedUtxid)) {
273
+ throw new Error('utxid must be a 64-character hex transaction id when supplied')
274
+ }
275
+
276
+ const psp1Txid = inObj.psp1Txid || (inObj.psp1 && inObj.psp1.txid) || null
277
+ if (typeof psp1Txid !== 'string' || !TXID_REGEX.test(psp1Txid)) {
278
+ throw new Error('psp1Txid is required (the on-chain PSP1 announcement under consideration)')
279
+ }
280
+
281
+ const result = {
282
+ valid: false,
283
+ atxid: atxid.toLowerCase(),
284
+ psp1Txid: psp1Txid.toLowerCase(),
285
+ utxid: requestedUtxid ? requestedUtxid.toLowerCase() : null,
286
+ errors: [],
287
+ checks: []
288
+ }
289
+
290
+ const errors = result.errors
291
+ const checks = result.checks
292
+
293
+ function finish () {
294
+ result.valid = errors.length === 0
295
+ if (result.valid) result.error = null
296
+ else result.error = errors[0].message
297
+ return result
298
+ }
299
+
300
+ // ---- step 1: read the PSP1 announcement from the chain ----------------
301
+ if (typeof inObj.psp1FromChain !== 'function') {
302
+ errors.push(makeError(1, 'PSP1_PROVIDER_REQUIRED',
303
+ 'psp1FromChain provider is required: the validator must read the PSP1 record from the chain'))
304
+ return finish()
305
+ }
306
+
307
+ let psp1
308
+ try {
309
+ const raw = await inObj.psp1FromChain(psp1Txid)
310
+ if (!raw) {
311
+ throw new Error('psp1FromChain returned no record')
312
+ }
313
+ psp1 = normalizePsP1(raw, psp1Txid)
314
+ } catch (err) {
315
+ const code = err && err.code === 'ERR_PSP1_UNKNOWN_VERSION'
316
+ ? 'PSP1_UNKNOWN_VERSION'
317
+ : (err && typeof err.code === 'string' && err.code.startsWith('ERR_PSP1')
318
+ ? 'PSP1_MALFORMED'
319
+ : 'PSP1_READ_FAILED')
320
+ errors.push(makeError(1, code, `Could not read the PSP1 announcement ${psp1Txid}: ${errorText(err)}`))
321
+ return finish()
322
+ }
323
+
324
+ result.epoch = {
325
+ txid: psp1.txid,
326
+ poolCashAddr: psp1.poolCashAddr,
327
+ satsPerMb: psp1.satsPerMb,
328
+ validFromHeight: psp1.validFromHeight,
329
+ prevRegistryTxid: psp1.prevRegistryTxid
330
+ }
331
+ checks.push({ step: 1, ok: true, code: 'PSP1_READ', details: result.epoch })
332
+
333
+ // A supplied previous epoch must be older than the new one (monotonicity).
334
+ let previousHeight = inObj.prevEpochHeight
335
+ if (previousHeight === undefined && inObj.previousEpoch) {
336
+ previousHeight = inObj.previousEpoch.validFromHeight
337
+ }
338
+ if (previousHeight !== undefined && previousHeight !== null) {
339
+ if (!(psp1.validFromHeight > previousHeight)) {
340
+ errors.push(makeError(2, 'HEIGHT_NOT_MONOTONIC',
341
+ `PSP1 validFromHeight (${psp1.validFromHeight}) is not greater than the previous epoch height (${previousHeight})`))
342
+ return finish()
343
+ }
344
+ }
345
+ checks.push({ step: 2, ok: true, code: 'HEIGHT_MONOTONIC' })
346
+
347
+ // ---- step 3: the Approval Transaction --------------------------------
348
+ let atx
349
+ try {
350
+ atx = normalizeTx(await readTx(inObj, atxid))
351
+ } catch (err) {
352
+ errors.push(makeError(3, 'APPROVAL_TX_READ_FAILED', `Could not read the Approval Transaction ${atxid}: ${errorText(err)}`))
353
+ return finish()
354
+ }
355
+ if (!atx) {
356
+ errors.push(makeError(3, 'APPROVAL_TX_READ_FAILED', `Approval Transaction ${atxid} was not supplied by the getTx provider`))
357
+ return finish()
358
+ }
359
+
360
+ let atRecord
361
+ try {
362
+ atRecord = parseApprovalRecord(atx)
363
+ } catch (err) {
364
+ errors.push(makeError(3, err.code || 'APPROVAL_RECORD_MALFORMED', `Malformed Approval Transaction OP_RETURN: ${errorText(err)}`))
365
+ return finish()
366
+ }
367
+ if (!atRecord) {
368
+ errors.push(makeError(3, 'NOT_AN_APPROVAL_TX', `Transaction ${atxid} has no APPROVAL record in vout[0]`))
369
+ return finish()
370
+ }
371
+
372
+ const effectiveUtxid = atRecord.updateTxid
373
+ result.utxid = effectiveUtxid
374
+
375
+ // The AT must reference the UT we were asked to validate. When no utxid was
376
+ // supplied, the AT's own reference is taken as authoritative (that is how a
377
+ // walker discovers it, per section 6 step 3).
378
+ if (requestedUtxid && atRecord.updateTxid !== requestedUtxid.toLowerCase()) {
379
+ errors.push(makeError(3, 'AT_REFERENCES_DIFFERENT_UPDATE',
380
+ `Approval Transaction references ${atRecord.updateTxid}, not the expected Update Transaction ${requestedUtxid}`))
381
+ return finish()
382
+ }
383
+
384
+ // Section 5: the 546-sat dust output must be vout[1], to the Reference Address.
385
+ if (inObj.referenceAddress) {
386
+ const dustVout = atx.vout && atx.vout[1]
387
+ const dustSats = voutSatoshis(dustVout)
388
+ const dustAddrs = voutAddresses(dustVout)
389
+ if (dustSats !== DUST_SATOSHIS || dustAddrs.length === 0 ||
390
+ !addressesEqual(dustAddrs[0], inObj.referenceAddress)) {
391
+ errors.push(makeError(3, 'APPROVAL_DUST_OUTPUT_INVALID',
392
+ `Approval Transaction vout[1] must be ${DUST_SATOSHIS} sats to Reference Address ${inObj.referenceAddress}`))
393
+ return finish()
394
+ }
395
+ }
396
+
397
+ // Section 6 step 2: the AT must be the *latest* APPROVAL transaction in the
398
+ // Reference Address history (only enforced when a history provider exists).
399
+ if (typeof inObj.getTxHistory === 'function' && inObj.referenceAddress) {
400
+ try {
401
+ const latest = await findLatestApproval(inObj, inObj.referenceAddress)
402
+ if (latest && latest.txid !== atxid.toLowerCase()) {
403
+ errors.push(makeError(3, 'NOT_LATEST_APPROVAL',
404
+ `Approval Transaction ${atxid} is not the latest APPROVAL transaction for ${inObj.referenceAddress} (latest is ${latest.txid})`))
405
+ return finish()
406
+ }
407
+ } catch (err) {
408
+ errors.push(makeError(3, 'APPROVAL_HISTORY_READ_FAILED',
409
+ `Could not walk the Reference Address history: ${errorText(err)}`))
410
+ return finish()
411
+ }
412
+ }
413
+
414
+ checks.push({ step: 3, ok: true, code: 'APPROVAL_TX_VALID', details: { updateTxid: atRecord.updateTxid, word: atRecord.word } })
415
+
416
+ // ---- step 4: Update Transaction, CID, membership JSON -----------------
417
+ let utx
418
+ try {
419
+ utx = normalizeTx(await readTx(inObj, effectiveUtxid))
420
+ } catch (err) {
421
+ errors.push(makeError(4, 'UPDATE_TX_READ_FAILED', `Could not read Update Transaction ${effectiveUtxid}: ${errorText(err)}`))
422
+ return finish()
423
+ }
424
+ if (!utx) {
425
+ errors.push(makeError(4, 'UPDATE_TX_READ_FAILED', `Update Transaction ${effectiveUtxid} was not supplied by the getTx provider`))
426
+ return finish()
427
+ }
428
+
429
+ let utRecord
430
+ try {
431
+ utRecord = parseUpdateRecord(utx)
432
+ } catch (err) {
433
+ errors.push(makeError(4, 'UPDATE_RECORD_MALFORMED', `Malformed Update Transaction OP_RETURN: ${errorText(err)}`))
434
+ return finish()
435
+ }
436
+ if (!utRecord) {
437
+ errors.push(makeError(4, 'NOT_AN_UPDATE_TX', `Transaction ${effectiveUtxid} has no CID record in vout[0]`))
438
+ return finish()
439
+ }
440
+ if (!utRecord.cid) {
441
+ errors.push(makeError(4, 'UPDATE_CID_MISSING', `Update Transaction ${effectiveUtxid} does not carry a CID`))
442
+ return finish()
443
+ }
444
+
445
+ let updateData = inObj.updateData
446
+ if (!updateData) {
447
+ if (typeof inObj.getCidData !== 'function') {
448
+ errors.push(makeError(4, 'CID_PROVIDER_REQUIRED',
449
+ 'getCidData provider (or a pre-fetched updateData object) is required to read the membership proof'))
450
+ return finish()
451
+ }
452
+ try {
453
+ updateData = await inObj.getCidData(utRecord.cid)
454
+ } catch (err) {
455
+ errors.push(makeError(4, 'CID_FETCH_FAILED', `Could not fetch CID ${utRecord.cid}: ${errorText(err)}`))
456
+ return finish()
457
+ }
458
+ if (!updateData) {
459
+ errors.push(makeError(4, 'CID_FETCH_FAILED', `CID gateway returned no data for ${utRecord.cid}`))
460
+ return finish()
461
+ }
462
+ }
463
+
464
+ let membership
465
+ try {
466
+ membership = normalizeMembership(updateData)
467
+ } catch (err) {
468
+ errors.push(makeError(4, 'MEMBERSHIP_MALFORMED', `Membership document is malformed: ${errorText(err)}`))
469
+ return finish()
470
+ }
471
+
472
+ checks.push({ step: 4, ok: true, code: 'UPDATE_TX_VALID', details: { cid: utRecord.cid, endorses: utRecord.endorses } })
473
+
474
+ // ---- step 5: expected Group Token -------------------------------------
475
+ if (!membership.groupTokenId) {
476
+ errors.push(makeError(5, 'GROUP_TOKEN_MISSING', 'Membership document does not list a Group Token ID'))
477
+ return finish()
478
+ }
479
+ if (normalizeHex(membership.groupTokenId) !== normalizeHex(councilConfig.groupTokenId)) {
480
+ errors.push(makeError(5, 'GROUP_TOKEN_MISMATCH',
481
+ `Membership Group Token ${membership.groupTokenId} does not match the expected council Group Token ${councilConfig.groupTokenId}`))
482
+ return finish()
483
+ }
484
+ checks.push({ step: 5, ok: true, code: 'GROUP_TOKEN_MATCH', details: { groupTokenId: membership.groupTokenId } })
485
+
486
+ if (membership.entries.length === 0) {
487
+ errors.push(makeError(6, 'NO_OPERATOR_NFTS', 'Membership document lists no operator NFTs'))
488
+ return finish()
489
+ }
490
+
491
+ // ---- steps 6, 7, 8: per-operator checks -------------------------------
492
+ const nftFetcher = typeof inObj.getNft === 'function' ? inObj.getNft : null
493
+ const nftMap = inObj.nftData && typeof inObj.nftData === 'object' ? inObj.nftData : null
494
+
495
+ const step6Errors = []
496
+ const step7Errors = []
497
+ const step8Errors = []
498
+ const operatorPubKeys = []
499
+ const nftProofs = []
500
+
501
+ for (const entry of membership.entries) {
502
+ // -- step 6: the NFT is a child of the council Group Token --
503
+ let nft = null
504
+ if (entry.tokenId) {
505
+ if (nftMap && nftMap[entry.tokenId]) {
506
+ nft = nftMap[entry.tokenId]
507
+ } else if (nftFetcher) {
508
+ try {
509
+ nft = await nftFetcher(entry.tokenId)
510
+ } catch (err) {
511
+ step6Errors.push(makeError(6, 'NFT_READ_FAILED',
512
+ `Could not read NFT ${entry.tokenId}: ${errorText(err)}`))
513
+ }
514
+ }
515
+ }
516
+
517
+ const nftGroup = (nft && (nft.groupTokenId || nft.groupId || nft.group)) || entry.groupTokenId
518
+ if (!entry.tokenId) {
519
+ step6Errors.push(makeError(6, 'NFT_TOKEN_ID_MISSING', 'Membership entry is missing an operator NFT token ID'))
520
+ } else if (!nftGroup) {
521
+ step6Errors.push(makeError(6, 'NFT_GROUP_UNKNOWN',
522
+ `Could not establish the Group Token of NFT ${entry.tokenId} (no getNft provider or group field)`))
523
+ } else if (normalizeHex(nftGroup) !== normalizeHex(councilConfig.groupTokenId)) {
524
+ step6Errors.push(makeError(6, 'NFT_NOT_IN_GROUP',
525
+ `NFT ${entry.tokenId} belongs to Group Token ${nftGroup}, not ${councilConfig.groupTokenId}`))
526
+ }
527
+
528
+ // -- step 7: the address is derived from the public key --
529
+ if (!entry.address || !entry.pubKey) {
530
+ step7Errors.push(makeError(7, 'ADDRESS_PUBKEY_MISSING',
531
+ 'Membership entry must list both an address and a public key'))
532
+ } else {
533
+ let derived
534
+ try {
535
+ derived = deriveAddressFromPubkey(entry.pubKey, { network })
536
+ } catch (err) {
537
+ step7Errors.push(makeError(7, 'INVALID_PUBKEY',
538
+ `Membership entry has an invalid public key (${entry.pubKey}): ${errorText(err)}`))
539
+ }
540
+ if (derived && !addressesEqual(derived, entry.address)) {
541
+ step7Errors.push(makeError(7, 'ADDRESS_PUBKEY_MISMATCH',
542
+ `Listed address ${entry.address} is not derived from public key ${entry.pubKey} (expected ${derived})`))
543
+ }
544
+ if (derived) operatorPubKeys.push(entry.pubKey)
545
+ }
546
+
547
+ // -- step 8: the address holds the NFT --
548
+ if (!entry.tokenId) {
549
+ step8Errors.push(makeError(8, 'NFT_TOKEN_ID_MISSING', 'Membership entry is missing an operator NFT token ID'))
550
+ } else if (!nft && !nftFetcher && !nftMap) {
551
+ step8Errors.push(makeError(8, 'NFT_PROVIDER_REQUIRED',
552
+ 'getNft provider is required to verify that each address holds its NFT'))
553
+ } else if (!nft) {
554
+ step8Errors.push(makeError(8, 'NFT_READ_FAILED', `Could not read NFT ${entry.tokenId}`))
555
+ } else {
556
+ const holder = nft.holder || nft.address || nft.nftHolder
557
+ let held = Boolean(holder) && Boolean(entry.address) && addressesEqual(holder, entry.address)
558
+
559
+ if (!held && typeof inObj.wasNftHeldBy === 'function' && entry.address) {
560
+ try {
561
+ held = Boolean(await inObj.wasNftHeldBy({ tokenId: entry.tokenId, address: entry.address }))
562
+ } catch (err) {
563
+ held = false
564
+ }
565
+ }
566
+
567
+ if (!held) {
568
+ step8Errors.push(makeError(8, 'NFT_NOT_HELD',
569
+ `Address ${entry.address} does not hold NFT ${entry.tokenId} (current holder: ${holder || 'unknown'})`))
570
+ } else {
571
+ nftProofs.push({ tokenId: entry.tokenId, address: entry.address, holder: holder || entry.address })
572
+ }
573
+ }
574
+ }
575
+
576
+ if (step6Errors.length > 0) {
577
+ errors.push.apply(errors, step6Errors)
578
+ return finish()
579
+ }
580
+ checks.push({ step: 6, ok: true, code: 'NFTS_IN_GROUP' })
581
+
582
+ if (step7Errors.length > 0) {
583
+ errors.push.apply(errors, step7Errors)
584
+ return finish()
585
+ }
586
+ checks.push({ step: 7, ok: true, code: 'ADDRESSES_MATCH_PUBKEYS' })
587
+
588
+ if (step8Errors.length > 0) {
589
+ errors.push.apply(errors, step8Errors)
590
+ return finish()
591
+ }
592
+ checks.push({ step: 8, ok: true, code: 'NFTS_HELD', details: nftProofs })
593
+
594
+ // ---- step 9: P2SH multisig + n-of-m signatures -----------------------
595
+ let threshold = councilConfig.requiredSignatures
596
+ if (threshold === undefined || threshold === null) threshold = membership.threshold
597
+ if (threshold === undefined || threshold === null) {
598
+ errors.push(makeError(9, 'THRESHOLD_MISSING',
599
+ 'The council n-of-m threshold is required (council.requiredSignatures or the membership document)'))
600
+ return finish()
601
+ }
602
+ if (councilConfig.requiredSignatures !== undefined && membership.threshold !== null &&
603
+ membership.threshold !== councilConfig.requiredSignatures) {
604
+ errors.push(makeError(9, 'THRESHOLD_MISMATCH',
605
+ `Membership threshold (${membership.threshold}) does not match the published council threshold (${councilConfig.requiredSignatures})`))
606
+ return finish()
607
+ }
608
+
609
+ let derivedCouncil
610
+ try {
611
+ derivedCouncil = deriveCouncilAddress({
612
+ pubkeys: operatorPubKeys,
613
+ requiredSignatures: threshold,
614
+ network
615
+ })
616
+ } catch (err) {
617
+ errors.push(makeError(9, 'COUNCIL_DERIVATION_FAILED', `Could not derive the council multisig address: ${errorText(err)}`))
618
+ return finish()
619
+ }
620
+
621
+ result.council = {
622
+ address: derivedCouncil.address,
623
+ scriptHex: derivedCouncil.scriptHex,
624
+ redeemScript: derivedCouncil.redeemScript,
625
+ publicKeys: derivedCouncil.publicKeys,
626
+ requiredSignatures: derivedCouncil.requiredSignatures,
627
+ n: derivedCouncil.n
628
+ }
629
+
630
+ if (councilConfig.address && !addressesEqual(councilConfig.address, derivedCouncil.address)) {
631
+ errors.push(makeError(9, 'COUNCIL_ADDRESS_MISMATCH',
632
+ `Recomputed council address ${derivedCouncil.address} does not match the published council address ${councilConfig.address}`))
633
+ return finish()
634
+ }
635
+
636
+ if (membership.address && !addressesEqual(membership.address, derivedCouncil.address)) {
637
+ errors.push(makeError(9, 'MULTISIG_ADDRESS_MISMATCH',
638
+ `Membership document multisig address ${membership.address} does not match the recomputed address ${derivedCouncil.address}`))
639
+ return finish()
640
+ }
641
+
642
+ const atFirstVin = atx.vin && atx.vin[0]
643
+ if (!atFirstVin) {
644
+ errors.push(makeError(9, 'AT_FIRST_VIN_MISSING', 'Approval Transaction has no inputs'))
645
+ return finish()
646
+ }
647
+
648
+ const atFirstVinAddress = vinAddress(atFirstVin)
649
+ if (!atFirstVinAddress) {
650
+ errors.push(makeError(9, 'AT_FIRST_VIN_UNKNOWN',
651
+ 'Could not determine the prevout address of the Approval Transaction\'s first input'))
652
+ return finish()
653
+ }
654
+ if (!addressesEqual(atFirstVinAddress, derivedCouncil.address)) {
655
+ errors.push(makeError(9, 'AT_FIRST_VIN_NOT_COUNCIL',
656
+ `Approval Transaction first input spends from ${atFirstVinAddress}, not the council address ${derivedCouncil.address}`))
657
+ return finish()
658
+ }
659
+
660
+ const scriptSigHex = vinScriptSigHex(atFirstVin)
661
+ const signatures = countMultisigSignatures(scriptSigHex)
662
+ if (signatures < derivedCouncil.requiredSignatures) {
663
+ errors.push(makeError(9, 'INSUFFICIENT_SIGNATURES',
664
+ `Approval Transaction has ${signatures} signature(s); ${derivedCouncil.requiredSignatures}-of-${derivedCouncil.n} are required`))
665
+ return finish()
666
+ }
667
+
668
+ // Cryptographic verification of the n-of-m spend, when the tx hex and
669
+ // prevout amount are available.
670
+ if (atx.hex) {
671
+ const satoshis = vinSatoshis(atFirstVin)
672
+ if (satoshis) {
673
+ const verification = verifyMultisigSpend({
674
+ txHex: atx.hex,
675
+ inputIndex: 0,
676
+ scriptPubKeyHex: derivedCouncil.scriptHex,
677
+ satoshis
678
+ })
679
+ if (!verification.valid) {
680
+ errors.push(makeError(9, 'INVALID_SIGNATURES',
681
+ `Approval Transaction multisig spend failed script verification (${verification.reason}${verification.error ? ': ' + verification.error : ''})`))
682
+ return finish()
683
+ }
684
+ }
685
+ }
686
+
687
+ checks.push({
688
+ step: 9,
689
+ ok: true,
690
+ code: 'MULTISIG_SPEND_VALID',
691
+ details: {
692
+ councilAddress: derivedCouncil.address,
693
+ requiredSignatures: derivedCouncil.requiredSignatures,
694
+ signatures
695
+ }
696
+ })
697
+
698
+ // ---- step 10: `endorses` binds the UT to this PSP1 announcement ------
699
+ const onChainEndorses = utRecord.endorses ? normalizeHex(utRecord.endorses) : null
700
+ const offChainEndorses = membership.endorses ? normalizeHex(membership.endorses) : null
701
+
702
+ if (onChainEndorses && offChainEndorses && onChainEndorses !== offChainEndorses) {
703
+ errors.push(makeError(10, 'ENDORSES_CONFLICT',
704
+ `Update Transaction endorses ${onChainEndorses} but the membership JSON endorses ${offChainEndorses}`))
705
+ return finish()
706
+ }
707
+
708
+ const endorses = onChainEndorses || offChainEndorses
709
+ if (!endorses) {
710
+ errors.push(makeError(10, 'ENDORSES_MISSING',
711
+ 'Update Transaction does not carry an `endorses` field naming the PSP1 announcement'))
712
+ return finish()
713
+ }
714
+ if (endorses !== result.psp1Txid) {
715
+ errors.push(makeError(10, 'ENDORSES_MISMATCH',
716
+ `Update Transaction endorses ${endorses}, but the PSP1 announcement under consideration is ${result.psp1Txid} (PS010 F9)`))
717
+ return finish()
718
+ }
719
+
720
+ // PS010 section 4.2 / F9: the announcement itself must spend from the
721
+ // council's P2SH address in its first vin.
722
+ const psp1FirstVin = psp1.vin && psp1.vin[0]
723
+ if (!psp1FirstVin) {
724
+ errors.push(makeError(10, 'PSP1_FIRST_VIN_UNKNOWN',
725
+ 'Could not determine the PSP1 announcement\'s first input address (PS010 F9)'))
726
+ return finish()
727
+ }
728
+ const psp1FirstVinAddress = vinAddress(psp1FirstVin)
729
+ if (!psp1FirstVinAddress) {
730
+ errors.push(makeError(10, 'PSP1_FIRST_VIN_UNKNOWN',
731
+ 'Could not determine the PSP1 announcement\'s first input address (PS010 F9)'))
732
+ return finish()
733
+ }
734
+ if (!addressesEqual(psp1FirstVinAddress, derivedCouncil.address)) {
735
+ errors.push(makeError(10, 'PSP1_FIRST_VIN_NOT_COUNCIL',
736
+ `PSP1 announcement first input spends from ${psp1FirstVinAddress}, not the council address ${derivedCouncil.address} (PS010 F9)`))
737
+ return finish()
738
+ }
739
+
740
+ checks.push({ step: 10, ok: true, code: 'ENDORSES_LINKED', details: { endorses, psp1Txid: result.psp1Txid } })
741
+
742
+ return finish()
743
+ }
744
+
745
+ // --------------------------------------------------------------- helpers
746
+
747
+ // Normalize the psp1FromChain provider's return value into a PSP1 record with
748
+ // txid + vin attached.
749
+ function normalizePsP1 (raw, expectedTxid) {
750
+ let record
751
+
752
+ if (raw && typeof raw.scriptHex === 'string') {
753
+ // The provider supplied the raw OP_RETURN bytes: the bytes are
754
+ // authoritative, not any decoded fields alongside them.
755
+ record = parsePsP1Record(raw.scriptHex)
756
+ if (!record) {
757
+ const err = new Error('scriptHex is not a PSP1 registry record')
758
+ err.code = 'ERR_PSP1_MALFORMED'
759
+ throw err
760
+ }
761
+ } else if (raw && raw.lokad === 'PSP1' && typeof raw.poolCashAddr === 'string') {
762
+ if (raw.version !== undefined && raw.version !== 1) {
763
+ const err = new Error(`Unknown PSP1 version: ${raw.version}`)
764
+ err.code = 'ERR_PSP1_UNKNOWN_VERSION'
765
+ throw err
766
+ }
767
+ record = Object.assign({}, raw, { version: 1 })
768
+ if (raw.validFromHeight === undefined || raw.satsPerMb === undefined) {
769
+ const err = new Error('PSP1 record is missing validFromHeight or satsPerMb')
770
+ err.code = 'ERR_PSP1_MALFORMED'
771
+ throw err
772
+ }
773
+ } else {
774
+ // A transaction object, builder output, or raw script hex.
775
+ record = parsePsP1Record(raw)
776
+ if (!record) {
777
+ const err = new Error('vout[0] is not a PSP1 registry record')
778
+ err.code = 'ERR_PSP1_MALFORMED'
779
+ throw err
780
+ }
781
+ }
782
+
783
+ const tx = normalizeTx(raw)
784
+ const txid = (raw && raw.txid) || (tx && tx.txid) || expectedTxid
785
+
786
+ record.txid = normalizeHex(txid)
787
+ record.vin = (raw && raw.vin) || (tx && tx.vin) || record.vin || null
788
+
789
+ return record
790
+ }
791
+
792
+ // Walk the Reference Address history (descending by height) and return the
793
+ // first transaction whose vout[0] carries an APPROVAL record.
794
+ async function findLatestApproval (inObj, referenceAddress) {
795
+ const history = await inObj.getTxHistory(referenceAddress)
796
+ if (!Array.isArray(history)) return null
797
+
798
+ const sorted = history.slice().sort((a, b) => {
799
+ const ha = typeof a.height === 'number' ? a.height : -1
800
+ const hb = typeof b.height === 'number' ? b.height : -1
801
+ return hb - ha
802
+ })
803
+
804
+ for (const entry of sorted) {
805
+ const txid = entry.tx_hash || entry.txid || entry.hash
806
+ if (!txid) continue
807
+
808
+ const tx = normalizeTx(await readTx(inObj, txid))
809
+ if (!tx) continue
810
+
811
+ let record
812
+ try {
813
+ record = parseApprovalRecord(tx)
814
+ } catch (err) {
815
+ continue
816
+ }
817
+ if (record) {
818
+ return { txid: txid.toLowerCase(), record, tx }
819
+ }
820
+ }
821
+
822
+ return null
823
+ }
824
+
825
+ export {
826
+ validateApproval,
827
+ normalizeMembership,
828
+ normalizeTx,
829
+ vinAddress,
830
+ vinSatoshis,
831
+ findLatestApproval
832
+ }
833
+
834
+ export default { validateApproval }