psf-multisig-approval 2.2.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.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  This is an npm library for node.js. It implements the [PS009 specification for multisignature approval](https://github.com/Permissionless-Software-Foundation/specifications/blob/master/ps009-multisig-approval.md). The main consumers of this library is the [psffpp](https://github.com/Permissionless-Software-Foundation/psffpp) library and various [Cash Stack](https://cashstack.info) infrastructure.
4
4
 
5
+ As of **v3.0.0** this package also ships a **PS009 v2 (revision 2)** reference implementation: the Update/Approval transaction workflow scoped to the [File Pinning Protocol (PS010)](https://github.com/Permissionless-Software-Foundation/specifications/blob/master/ps010-file-pinning-protocol.md), where the approved datum is the on-chain `PSP1` registry record (`satsPerMb` + pool payout address) and council membership is proven by SLP NFTs. The PS009 v1 class API documented below is unchanged; the v2 surface is exported alongside it (see [PS009 v2 reference implementation](#ps009-v2-reference-implementation)). There is no PSF token anywhere in v2.
6
+
5
7
  ## Instancing Library
6
8
  This library depends on [minimal-slp-wallet](https://www.npmjs.com/package/minimal-slp-wallet). An instance of that library is expected to be injected into this this one when instantiated. Here is an example:
7
9
 
@@ -207,5 +209,146 @@ console.log(result)
207
209
  */
208
210
  ```
209
211
 
212
+ ## PS009 v2 reference implementation
213
+
214
+ Spec: [ps009-multisig-approval-v2.md](https://github.com/Permissionless-Software-Foundation/specifications/blob/master/ps009-multisig-approval-v2.md)
215
+ (PS009-R2, draft 2.0.0). The `PSP1` record layout is fixed by
216
+ [PS010 section 4.1](https://github.com/Permissionless-Software-Foundation/specifications/blob/master/ps010-file-pinning-protocol.md).
217
+
218
+ This is a **reference-first** implementation: it implements the consensus rules
219
+ and byte layouts faithfully and is testable against spec vectors, but it makes no
220
+ network calls of its own. Chain reads, IPFS fetches and NFT lookups are injected
221
+ providers. It is a pure library: no broadcasting, no wallet, no IPFS, no listeners.
222
+
223
+ The v2 surface is available two ways:
224
+
225
+ ```javascript
226
+ // ESM
227
+ import MultisigApproval, { ps009v2 } from 'psf-multisig-approval'
228
+ import { deriveCouncilAddress, validateApproval } from 'psf-multisig-approval'
229
+
230
+ // The v1 class remains the default export
231
+ const ps009 = new MultisigApproval({ wallet })
232
+ ```
233
+
234
+ ### Council address (section 2)
235
+
236
+ Compressed operator public keys are sorted lexicographically and turned into an
237
+ n-of-m P2SH multisig address, so every party recomputes the same address:
238
+
239
+ ```javascript
240
+ import { deriveCouncilAddress } from 'psf-multisig-approval'
241
+
242
+ const council = deriveCouncilAddress({
243
+ pubkeys: [
244
+ '021ca211a04a1d489ae77e01c28c97b02e733893890fda00a359ca8956c2e0d259',
245
+ '0361fd21512b9072e8f6b984d9b04c57e5779867c2ad002999372268770fcb2674',
246
+ '03b9bdc40c478ab0536be29c368b26c48a5e8d6867fc34b77c727ab690365aae91',
247
+ '033c930d4cff4ba68a70f7a21443e20ad4176173380d21f8c3ce27f7ce947f3246',
248
+ '024be54accec310c2636140336ae548d610ba9b7ce300b3f42494b4a6f2963731f'
249
+ ],
250
+ requiredSignatures: 3
251
+ })
252
+ // council.address -> 'bitcoincash:pqntzt6wcp38h8ud68wjnwh437uek76lhvhlwcm4fj'
253
+ // council.scriptHex -> P2SH scriptPubKey (a914...87)
254
+ // council.redeemScript -> sorted 3-of-5 multisig redeem script
255
+ ```
256
+
257
+ ### PSP1 registry record (PS010 section 4.1)
258
+
259
+ ```javascript
260
+ import { encodePsP1, parsePsP1Record } from 'psf-multisig-approval'
261
+
262
+ const record = encodePsP1({
263
+ poolCashAddr: 'bitcoincash:pzypdf3wv89zy75mvjj4aetn63nq8sc3cufmnkzzjq',
264
+ validFromHeight: 920000,
265
+ satsPerMb: 2000,
266
+ prevRegistryTxid: '00'.repeat(32) // genesis
267
+ })
268
+ // record.scriptHex is the exact vout[0] scriptPubKey bytes
269
+
270
+ parsePsP1Record(record.scriptHex)
271
+ // { version: 1, poolCashAddr, validFromHeight, satsPerMb, prevRegistryTxid, ... }
272
+ ```
273
+
274
+ `validFromHeight` and `satsPerMb` are uint64 **little-endian** (always 8 bytes).
275
+ `prevRegistryTxid` is 32 raw bytes in Bitcoin **internal byte order**; the codec
276
+ takes and returns the displayed txid and reverses it, matching PS010's
277
+ implementation note. Unknown versions and truncated pushes are rejected.
278
+
279
+ ### Update and Approval transactions (sections 4 and 5)
280
+
281
+ ```javascript
282
+ import { buildUpdateTransaction, buildApprovalTransaction } from 'psf-multisig-approval'
283
+
284
+ // Update Transaction: OP_RETURN { cid, endorses, ts } in vout[0], from a P2PKH.
285
+ const update = buildUpdateTransaction({
286
+ cid: 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
287
+ endorses: announcementTxid, // the PSP1 announcement being approved
288
+ ts: 1770000000000,
289
+ inputs: [{ txid, vout, satoshis, script, address }],
290
+ privKeys: [wif],
291
+ changeAddress: 'bitcoincash:...'
292
+ })
293
+
294
+ // Approval Transaction: OP_RETURN APPROVAL <updateTxid> in vout[0],
295
+ // 546 sats to vout[1] (Reference Address), change back to the council P2SH.
296
+ const approval = buildApprovalTransaction({
297
+ utxid: update.txid,
298
+ utxos: [{ txid, vout, satoshis }], // council P2SH UTXOs
299
+ council, // from deriveCouncilAddress()
300
+ privKeys: [wif1, wif2], // n-of-m subset; fewer -> partial tx
301
+ referenceAddress: 'bitcoincash:qrwe6kxhvu47ve6jvgrf2d93w0q38av7s5xm9xfehr'
302
+ })
303
+ // approval.hex, approval.txid, approval.complete, approval.signatures
304
+ ```
305
+
306
+ Passing the PSP1 epoch fields instead of `cid` to `buildUpdateTransaction()`
307
+ builds the `PSP1` announcement transaction itself (the record the Update
308
+ Transaction endorses), signed from a council UTXO.
309
+
310
+ ### Validation (section 6)
311
+
312
+ `validateApproval()` runs all ten section 6 steps. It never touches the network:
313
+ every chain/IPFS lookup is an injected provider, and a missing provider is a
314
+ validation failure (fail closed), not a silent pass.
315
+
316
+ ```javascript
317
+ const result = await validateApproval({
318
+ atxid: approvalTxid,
319
+ utxid: updateTxid,
320
+ psp1Txid: announcementTxid,
321
+ council: {
322
+ groupTokenId: '8e8d90eb...', // expected council Group Token
323
+ requiredSignatures: 3, // published n-of-m threshold
324
+ address: 'bitcoincash:pq...' // optional: assert the recomputed address
325
+ },
326
+ referenceAddress: 'bitcoincash:qrwe...',
327
+
328
+ // Injected providers (all optional except psp1FromChain once supplied):
329
+ psp1FromChain: async (txid) => txDetails,
330
+ getTx: async (txid) => txDetails,
331
+ getTxHistory: async (address) => [{ tx_hash, height }],
332
+ getCidData: async (cid) => membershipJson,
333
+ getNft: async (tokenId) => ({ tokenId, groupTokenId, holder }),
334
+ wasNftHeldBy: async ({ tokenId, address }) => true // historical NFT holding
335
+ })
336
+
337
+ // { valid: true, errors: [], checks: [...10 steps...], epoch: {...}, council: {...} }
338
+ // or
339
+ // { valid: false, errors: [{ step, code, message }], ... }
340
+ ```
341
+
342
+ Each failure carries a stable `code` distinguishable per step, e.g.
343
+ `PSP1_READ_FAILED`, `HEIGHT_NOT_MONOTONIC`, `AT_REFERENCES_DIFFERENT_UPDATE`,
344
+ `GROUP_TOKEN_MISMATCH`, `NFT_NOT_IN_GROUP`, `ADDRESS_PUBKEY_MISMATCH`,
345
+ `NFT_NOT_HELD`, `INSUFFICIENT_SIGNATURES`, `ENDORSES_MISMATCH`,
346
+ `PSP1_FIRST_VIN_NOT_COUNCIL` (PS010 F9). Signature checks use the BCH script
347
+ interpreter against the recomputed multisig redeem script, so "n-of-m" is
348
+ cryptographically verified, not merely counted.
349
+
350
+ See `lib/ps009v2/` for the implementation and `test/unit/ps009v2-*.js` for the
351
+ spec byte-layout vectors and the full Update → Approval → validate flow.
352
+
210
353
  # License
211
354
  [MIT](LICENSE.md)
package/index.js CHANGED
@@ -10,6 +10,7 @@ import axios from 'axios'
10
10
  // Local libraries
11
11
  import NFTs from './lib/nfts.js'
12
12
  import UtilLib from './lib/util.js'
13
+ import ps009v2 from './lib/ps009v2/index.js'
13
14
 
14
15
  class MultisigApproval {
15
16
  constructor (localConfig = {}) {
@@ -416,3 +417,29 @@ class MultisigApproval {
416
417
  }
417
418
 
418
419
  export default MultisigApproval
420
+
421
+ /*
422
+ PS009 v2 (Multisig Rate Approval, revision 2) exports.
423
+
424
+ The v1 class above is unchanged; the v2 reference implementation is exported
425
+ both as the `ps009v2` namespace and as named functions. See the PS009 v2
426
+ spec: https://github.com/Permissionless-Software-Foundation/specifications/blob/master/ps009-multisig-approval-v2.md
427
+ */
428
+ export { ps009v2 }
429
+
430
+ export {
431
+ deriveCouncilAddress,
432
+ deriveAddressFromPubkey,
433
+ normalizeAddress,
434
+ addressesEqual,
435
+ encodePsP1,
436
+ parsePsP1Record,
437
+ isPsP1Record,
438
+ buildUpdateTransaction,
439
+ parseUpdateRecord,
440
+ buildUpdateOpReturn,
441
+ buildApprovalTransaction,
442
+ parseApprovalRecord,
443
+ buildApprovalOpReturn,
444
+ validateApproval
445
+ } from './lib/ps009v2/index.js'
@@ -0,0 +1,261 @@
1
+ /*
2
+ PS009 v2 - Approval Transaction (AT) codec and builder.
3
+
4
+ PS009 v2 section 5:
5
+
6
+ The Approval Transaction must contain two pieces of information in its
7
+ OP_RETURN data:
8
+ 1. the word `APPROVAL`
9
+ 2. the TXID of the Update Transaction
10
+ ... and must include a dust output (546 satoshis) in its second output
11
+ (index 1) to a Reference Address.
12
+
13
+ Section 5.1 example:
14
+ OP_RETURN APPROVAL 6eaa12d2749cf15b00873551088975dd6748d9a6f867426db914735c58ad730a
15
+
16
+ Wire encoding used here (byte-compatible with PS009 v1 readers, which
17
+ rendered the OP_RETURN as ASCII and stripped the 2-byte script prefix plus
18
+ the word):
19
+
20
+ scriptPubKey = OP_RETURN (6a)
21
+ + push(utf8 'APPROVAL') (08 415050524f56414c)
22
+ + push(utf8 <64-char txid>) (40 <64 ASCII bytes>)
23
+
24
+ The parser also accepts the v1 `APPROVE` word and two other encodings seen in
25
+ the wild: a single push containing `APPROVAL` + txid ASCII, and a 32-byte raw
26
+ txid push.
27
+ */
28
+
29
+ import { deriveCouncilAddress, normalizeAddress } from './council.js'
30
+ import {
31
+ dataPushes,
32
+ extractVout0ScriptHex,
33
+ isOpReturn,
34
+ opReturnScript
35
+ } from './script.js'
36
+ import { DUST_SATOSHIS, buildTransaction } from './tx.js'
37
+ import { countMultisigSignatures } from './signatures.js'
38
+
39
+ const APPROVAL_WORD = 'APPROVAL'
40
+ // PS009 v1's on-chain word; accepted for read compatibility only.
41
+ const LEGACY_APPROVAL_WORD = 'APPROVE'
42
+ const APPROVAL_WORDS = [APPROVAL_WORD, LEGACY_APPROVAL_WORD]
43
+
44
+ const TXID_REGEX = /^[0-9a-fA-F]{64}$/
45
+
46
+ // Encode the Approval Transaction OP_RETURN for a given Update Transaction id.
47
+ function buildApprovalOpReturn (updateTxid) {
48
+ if (typeof updateTxid !== 'string' || !TXID_REGEX.test(updateTxid)) {
49
+ throw new Error('updateTxid must be a 64-character hex transaction id')
50
+ }
51
+
52
+ const txid = updateTxid.toLowerCase()
53
+
54
+ const scriptHex = opReturnScript([
55
+ Buffer.from(APPROVAL_WORD, 'utf8'),
56
+ Buffer.from(txid, 'utf8')
57
+ ])
58
+
59
+ return {
60
+ scriptHex,
61
+ updateTxid: txid,
62
+ word: APPROVAL_WORD,
63
+ opReturn: `OP_RETURN ${APPROVAL_WORD} ${txid}`
64
+ }
65
+ }
66
+
67
+ // Parse an Approval Transaction OP_RETURN.
68
+ // Returns null when vout[0] is not an approval record; throws on a malformed
69
+ // approval record.
70
+ function parseApprovalRecord (input) {
71
+ const scriptHex = extractVout0ScriptHex(input)
72
+
73
+ if (!isOpReturn(scriptHex)) return null
74
+
75
+ const pushes = dataPushes(scriptHex).filter(push => push.length > 0)
76
+ if (pushes.length === 0) return null
77
+
78
+ let word = null
79
+ let txid = null
80
+ let encoding = null
81
+
82
+ const first = pushes[0].toString('utf8')
83
+
84
+ const matchedWord = APPROVAL_WORDS.find(candidate => first === candidate)
85
+ if (matchedWord) {
86
+ word = matchedWord
87
+ if (pushes.length < 2) {
88
+ const err = new Error('Approval Transaction OP_RETURN is missing the Update Transaction txid')
89
+ err.code = 'ERR_APPROVAL_RECORD_MALFORMED'
90
+ throw err
91
+ }
92
+ const second = pushes[1]
93
+ if (second.length === 32) {
94
+ // Raw txid bytes in internal byte order.
95
+ txid = Buffer.from(second).reverse().toString('hex')
96
+ encoding = 'push-word+raw-txid'
97
+ } else {
98
+ const candidate = second.toString('utf8')
99
+ if (!TXID_REGEX.test(candidate)) {
100
+ const err = new Error(`Approval Transaction OP_RETURN txid push is not a 64-character hex txid: ${candidate.slice(0, 80)}`)
101
+ err.code = 'ERR_APPROVAL_RECORD_MALFORMED'
102
+ throw err
103
+ }
104
+ txid = candidate.toLowerCase()
105
+ encoding = 'push-word+ascii-txid'
106
+ }
107
+ } else {
108
+ // Legacy / single-push form: 'APPROVAL<txid>' or 'APPROVAL <txid>'.
109
+ const prefix = APPROVAL_WORDS.find(candidate => first.startsWith(candidate))
110
+ if (!prefix) return null
111
+
112
+ const candidate = first.slice(prefix.length).trim()
113
+ if (!TXID_REGEX.test(candidate)) {
114
+ const err = new Error('Approval Transaction OP_RETURN is malformed: expected APPROVAL followed by a 64-character hex txid')
115
+ err.code = 'ERR_APPROVAL_RECORD_MALFORMED'
116
+ throw err
117
+ }
118
+ word = prefix
119
+ txid = candidate.toLowerCase()
120
+ encoding = 'single-push'
121
+ }
122
+
123
+ return {
124
+ word,
125
+ updateTxid: txid,
126
+ encoding,
127
+ scriptHex,
128
+ opReturn: `OP_RETURN ${word} ${txid}`
129
+ }
130
+ }
131
+
132
+ /*
133
+ Build an Approval Transaction.
134
+
135
+ The AT spends a UTXO held by the council's P2SH multisig address and is
136
+ signed by the supplied subset of council keys (PS009 v2 section 6 step 9:
137
+ "the Approval Transaction's first input spends from that multisig address
138
+ (i.e. it was signed by the n-of-m council keys)").
139
+
140
+ Input:
141
+ utxid - Update Transaction txid being approved (required)
142
+ utxos | utxo - council UTXO(s) to spend: { txid, vout, satoshis,
143
+ script? }. `script` defaults to the council P2SH script.
144
+ council - output of deriveCouncilAddress() (optional if pubkeys +
145
+ requiredSignatures are given)
146
+ pubkeys - council public keys (used when `council` is omitted)
147
+ requiredSignatures- n-of-m threshold (used when `council` is omitted)
148
+ privKeys - array of WIFs / bitcore PrivateKeys. Supply fewer than n
149
+ to get a partially signed transaction for multi-party
150
+ signing.
151
+ referenceAddress - Reference Address for the 546-sat vout[1] dust output
152
+ (required, PS009 v2 section 5)
153
+ changeAddress - optional; defaults to the council P2SH address
154
+ fee - optional miner fee in sats (default 1000)
155
+
156
+ Output: { tx, hex, txid, signed, complete, signatures, council,
157
+ opReturnHex, updateTxid, referenceAddress, dust }
158
+ */
159
+ function buildApprovalTransaction (inObj = {}) {
160
+ const {
161
+ utxid,
162
+ updateTxid,
163
+ utxo,
164
+ utxos,
165
+ privKeys = [],
166
+ referenceAddress,
167
+ changeAddress,
168
+ fee,
169
+ network
170
+ } = inObj
171
+
172
+ const updateId = utxid || updateTxid
173
+
174
+ if (typeof updateId !== 'string' || !TXID_REGEX.test(updateId)) {
175
+ throw new Error('utxid is required (the Update Transaction txid being approved)')
176
+ }
177
+ if (typeof referenceAddress !== 'string' || referenceAddress.length === 0) {
178
+ throw new Error('referenceAddress is required (PS009 v2 section 5 mandates a 546-sat dust output to the Reference Address)')
179
+ }
180
+
181
+ let council = inObj.council
182
+ if (!council) {
183
+ council = deriveCouncilAddress({
184
+ pubkeys: inObj.pubkeys,
185
+ requiredSignatures: inObj.requiredSignatures,
186
+ network
187
+ })
188
+ } else if (!council.address || !council.scriptHex || !council.redeemScript) {
189
+ throw new Error('council must be the output of deriveCouncilAddress()')
190
+ }
191
+
192
+ let councilUtxos = utxos
193
+ if (!councilUtxos && utxo) councilUtxos = [utxo]
194
+ if (!Array.isArray(councilUtxos) || councilUtxos.length === 0) {
195
+ throw new Error('utxos (or utxo) is required: the council P2SH UTXO(s) the Approval Transaction spends')
196
+ }
197
+
198
+ // The first input must spend from the council P2SH address (section 6
199
+ // step 9 / PS010 section 4.2). Fill in the council script when omitted, and
200
+ // reject an explicit mismatch instead of silently signing the wrong coin.
201
+ councilUtxos = councilUtxos.map((entry, i) => {
202
+ const next = Object.assign({}, entry)
203
+ if (!next.script) {
204
+ next.script = council.scriptHex
205
+ } else if (i === 0 && next.script.toLowerCase() !== council.scriptHex.toLowerCase()) {
206
+ throw new Error(`utxos[0].script does not lock to the council P2SH address ${council.address}`)
207
+ }
208
+ if (i === 0 && next.address && normalizeAddress(next.address) !== normalizeAddress(council.address)) {
209
+ throw new Error(`utxos[0].address (${next.address}) is not the council P2SH address ${council.address}`)
210
+ }
211
+ return next
212
+ })
213
+
214
+ const opReturn = buildApprovalOpReturn(updateId)
215
+
216
+ const built = buildTransaction({
217
+ opReturnScriptHex: opReturn.scriptHex,
218
+ inputs: councilUtxos,
219
+ outputs: [{ address: referenceAddress, satoshis: DUST_SATOSHIS }],
220
+ privKeys,
221
+ council,
222
+ changeAddress: changeAddress || council.address,
223
+ fee,
224
+ network
225
+ })
226
+
227
+ const signatures = countMultisigSignatures(built.tx.inputs[0].script.toHex())
228
+ const complete = built.signed && signatures >= council.requiredSignatures
229
+
230
+ return {
231
+ tx: built.tx,
232
+ hex: built.hex,
233
+ txid: built.txid,
234
+ signed: built.signed,
235
+ complete,
236
+ signatures,
237
+ council,
238
+ opReturnHex: opReturn.scriptHex,
239
+ opReturn: opReturn.opReturn,
240
+ updateTxid: opReturn.updateTxid,
241
+ referenceAddress,
242
+ dust: DUST_SATOSHIS,
243
+ fee: built.fee,
244
+ network: built.network
245
+ }
246
+ }
247
+
248
+ export {
249
+ APPROVAL_WORD,
250
+ LEGACY_APPROVAL_WORD,
251
+ DUST_SATOSHIS,
252
+ buildApprovalOpReturn,
253
+ parseApprovalRecord,
254
+ buildApprovalTransaction
255
+ }
256
+
257
+ export default {
258
+ buildApprovalOpReturn,
259
+ parseApprovalRecord,
260
+ buildApprovalTransaction
261
+ }
@@ -0,0 +1,237 @@
1
+ /*
2
+ PS009 v2 - Council membership and P2SH multisig address derivation.
3
+
4
+ Implements PS009 v2 section 2 ("Multisig construction"):
5
+
6
+ - The council's P2SH multisig address is built from the current NFT-holder
7
+ public keys.
8
+ - The n-of-m threshold is chosen by the council and published in the
9
+ registry policy (e.g. 3-of-5).
10
+ - Public keys are compressed and **sorted lexicographically** before address
11
+ derivation, so that any party recomputes the same address.
12
+
13
+ This module is pure cryptography/encoding: it does not talk to a node and
14
+ does not read the blockchain.
15
+
16
+ https://github.com/Permissionless-Software-Foundation/specifications/blob/master/ps009-multisig-approval-v2.md
17
+ */
18
+
19
+ import bitcore from '@chris.troutner/bitcore-lib-cash'
20
+
21
+ // Cashaddr prefixes used by BCH (mainnet and chipnet/testnet).
22
+ const CASHADDR_PREFIX = 'bitcoincash:'
23
+ const TESTNET_CASHADDR_PREFIX = 'bchtest:'
24
+ const TOKEN_AWARE_PREFIX = 'simpleledger:'
25
+
26
+ // Default network for address derivation. Overridable per call.
27
+ const NETWORK_NAMES = ['mainnet', 'testnet', 'chipnet']
28
+
29
+ // Resolve a network input (name or bitcore network object) to a bitcore
30
+ // network object, plus its cashaddr prefix.
31
+ function resolveNetwork (network) {
32
+ if (!network) return { networkObj: bitcore.Networks.livenet, name: 'mainnet' }
33
+
34
+ if (typeof network === 'string') {
35
+ const name = network.toLowerCase()
36
+ if (name === 'mainnet' || name === 'livenet') {
37
+ return { networkObj: bitcore.Networks.livenet, name: 'mainnet' }
38
+ }
39
+ if (name === 'testnet' || name === 'chipnet' || name === 'test') {
40
+ return { networkObj: bitcore.Networks.testnet, name: 'testnet' }
41
+ }
42
+ throw new Error(`Unsupported network: ${network}. Expected one of: ${NETWORK_NAMES.join(', ')}`)
43
+ }
44
+
45
+ if (network === bitcore.Networks.testnet) {
46
+ return { networkObj: bitcore.Networks.testnet, name: 'testnet' }
47
+ }
48
+
49
+ if (network === bitcore.Networks.livenet) {
50
+ return { networkObj: bitcore.Networks.livenet, name: 'mainnet' }
51
+ }
52
+
53
+ throw new Error('Unsupported network object. Use \'mainnet\', \'testnet\', or a bitcore Networks member.')
54
+ }
55
+
56
+ // Return the cashaddr prefix for a resolved network name.
57
+ function cashaddrPrefix (networkName) {
58
+ return networkName === 'testnet' ? TESTNET_CASHADDR_PREFIX : CASHADDR_PREFIX
59
+ }
60
+
61
+ // Compressed public keys are 33 bytes: 0x02/0x03 followed by 32 bytes of X.
62
+ function isCompressedPubkeyHex (pubkey) {
63
+ return typeof pubkey === 'string' && /^0[23][0-9a-fA-F]{64}$/.test(pubkey)
64
+ }
65
+
66
+ // Validate a public key and return its canonical (lowercase) hex form.
67
+ function validatePubkey (pubkey, index) {
68
+ const where = `public key at index ${index}`
69
+
70
+ if (typeof pubkey !== 'string') {
71
+ throw new Error(`${where} must be a hex string`)
72
+ }
73
+
74
+ if (!isCompressedPubkeyHex(pubkey)) {
75
+ throw new Error(`${where} must be a 33-byte compressed public key (02/03 + 64 hex chars), got: ${pubkey}`)
76
+ }
77
+
78
+ const canonical = pubkey.toLowerCase()
79
+
80
+ // Let bitcore validate the curve point as well as the encoding.
81
+ try {
82
+ // eslint-disable-next-line no-new
83
+ new bitcore.PublicKey(canonical)
84
+ } catch (err) {
85
+ throw new Error(`${where} is not a valid public key: ${pubkey}`)
86
+ }
87
+
88
+ return canonical
89
+ }
90
+
91
+ /*
92
+ Derive the council's P2SH multisig address from operator public keys.
93
+
94
+ Input:
95
+ pubkeys - array of compressed public key hex strings (any
96
+ order; they are sorted lexicographically here).
97
+ requiredSignatures - n in the n-of-m threshold. Defaults to
98
+ floor(m / 2) + 1 (the PS009 v1 "50% + 1" default),
99
+ but the council is expected to publish the real
100
+ threshold in the registry policy.
101
+ network - 'mainnet' (default) or 'testnet'.
102
+
103
+ Output:
104
+ {
105
+ address, // cashaddr P2SH address
106
+ scriptHex, // P2SH scriptPubKey hex (OP_HASH160 <hash> OP_EQUAL)
107
+ redeemScript, // n-of-m multisig redeem script hex
108
+ publicKeys, // sorted, canonical compressed public keys
109
+ requiredSignatures,
110
+ threshold, // alias of requiredSignatures (spec wording)
111
+ m, n, // threshold / number of keys
112
+ network
113
+ }
114
+ */
115
+ function deriveCouncilAddress (inObj = {}) {
116
+ const { pubkeys } = inObj
117
+ let { requiredSignatures } = inObj
118
+
119
+ if (!Array.isArray(pubkeys) || pubkeys.length === 0) {
120
+ throw new Error('pubkeys must be a non-empty array of compressed public key hex strings')
121
+ }
122
+
123
+ const { networkObj, name } = resolveNetwork(inObj.network)
124
+
125
+ // Validate + canonicalize every key.
126
+ const keys = pubkeys.map((pubkey, i) => validatePubkey(pubkey, i))
127
+
128
+ // Reject duplicates: the same key twice would silently lower the effective
129
+ // threshold and corrupt the m-of-n accounting.
130
+ const seen = {}
131
+ for (const key of keys) {
132
+ if (seen[key]) {
133
+ throw new Error(`Duplicate public key in council: ${key}`)
134
+ }
135
+ seen[key] = true
136
+ }
137
+
138
+ // PS009 v2 section 2: public keys are sorted lexicographically before
139
+ // address derivation, so that every party recomputes the same address.
140
+ // (Lowercase hex sorts identically to raw byte order.)
141
+ const sortedKeys = keys.slice().sort()
142
+
143
+ if (requiredSignatures === undefined || requiredSignatures === null) {
144
+ requiredSignatures = Math.floor(sortedKeys.length / 2) + 1
145
+ }
146
+
147
+ if (!Number.isInteger(requiredSignatures)) {
148
+ throw new Error('requiredSignatures must be an integer')
149
+ }
150
+ if (requiredSignatures < 1) {
151
+ throw new Error('requiredSignatures must be at least 1')
152
+ }
153
+ if (requiredSignatures > sortedKeys.length) {
154
+ throw new Error(`requiredSignatures (${requiredSignatures}) can not exceed the number of public keys (${sortedKeys.length})`)
155
+ }
156
+
157
+ // The multisig redeem script (sorted keys, in order).
158
+ const redeemScript = bitcore.Script.buildMultisigOut(sortedKeys, requiredSignatures).toHex()
159
+
160
+ // The P2SH address + locking script.
161
+ const address = new bitcore.Address(sortedKeys, requiredSignatures, networkObj)
162
+ const scriptHex = new bitcore.Script(address).toHex()
163
+
164
+ return {
165
+ address: address.toString(),
166
+ scriptHex,
167
+ redeemScript,
168
+ publicKeys: sortedKeys,
169
+ requiredSignatures,
170
+ threshold: requiredSignatures,
171
+ m: requiredSignatures,
172
+ n: sortedKeys.length,
173
+ network: name,
174
+ cashaddrPrefix: cashaddrPrefix(name)
175
+ }
176
+ }
177
+
178
+ // Derive the P2PKH cashaddr that corresponds to a compressed public key.
179
+ // Used by PS009 v2 section 6 step 7 ("each address listed in the JSON is
180
+ // generated from the given public key").
181
+ function deriveAddressFromPubkey (pubkey, inObj = {}) {
182
+ const canonical = validatePubkey(pubkey, 0)
183
+ const { networkObj } = resolveNetwork(inObj.network)
184
+ const publicKey = new bitcore.PublicKey(canonical)
185
+ const address = bitcore.Address.fromPublicKey(publicKey, networkObj)
186
+ return address.toString()
187
+ }
188
+
189
+ // Normalize a BCH address so that two representations of the same address
190
+ // compare equal. Handles token-aware (`simpleledger:`) prefixes and case.
191
+ // Falls back to the trimmed, lowercased input when bitcore can not parse it
192
+ // (e.g. P2SH32 cashaddrs, which bitcore-lib-cash 8.25.x does not know about).
193
+ function normalizeAddress (address) {
194
+ if (typeof address !== 'string' || address.length === 0) {
195
+ throw new Error('address must be a non-empty string')
196
+ }
197
+
198
+ let candidate = address.trim()
199
+
200
+ if (candidate.toLowerCase().startsWith(TOKEN_AWARE_PREFIX)) {
201
+ candidate = CASHADDR_PREFIX + candidate.slice(TOKEN_AWARE_PREFIX.length)
202
+ }
203
+
204
+ try {
205
+ return bitcore.Address.fromString(candidate).toString()
206
+ } catch (err) {
207
+ // P2SH32 addresses and other forms bitcore can not decode: compare the
208
+ // lowercased string form with any known prefix.
209
+ return candidate.toLowerCase()
210
+ }
211
+ }
212
+
213
+ // Compare two BCH addresses after normalization.
214
+ function addressesEqual (a, b) {
215
+ return normalizeAddress(a) === normalizeAddress(b)
216
+ }
217
+
218
+ export {
219
+ CASHADDR_PREFIX,
220
+ TESTNET_CASHADDR_PREFIX,
221
+ TOKEN_AWARE_PREFIX,
222
+ deriveCouncilAddress,
223
+ deriveAddressFromPubkey,
224
+ isCompressedPubkeyHex,
225
+ validatePubkey,
226
+ normalizeAddress,
227
+ addressesEqual,
228
+ resolveNetwork,
229
+ cashaddrPrefix
230
+ }
231
+
232
+ export default {
233
+ deriveCouncilAddress,
234
+ deriveAddressFromPubkey,
235
+ normalizeAddress,
236
+ addressesEqual
237
+ }