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.
@@ -0,0 +1,111 @@
1
+ /*
2
+ PS009 v2 (Multisig Rate Approval, revision 2) - reference implementation.
3
+
4
+ Spec: https://github.com/Permissionless-Software-Foundation/specifications/blob/master/ps009-multisig-approval-v2.md
5
+
6
+ This namespace is the PS009 v2 surface:
7
+
8
+ deriveCouncilAddress() - section 2: sorted compressed pubkeys -> P2SH n-of-m
9
+ encodePsP1() / parsePsP1Record() - PS010 section 4.1 PSP1 announcement codec
10
+ buildUpdateTransaction() - section 4: Update Transaction (or PSP1 announcement)
11
+ buildApprovalTransaction() - section 5: Approval Transaction (APPROVAL + UT txid)
12
+ parseApprovalRecord() - section 5: read an Approval Transaction
13
+ validateApproval() - section 6: the ten-step validation checklist
14
+
15
+ The old (PS009 v1) `MultisigApproval` class remains the package default
16
+ export; this object is exported alongside it as `ps009v2`.
17
+ */
18
+
19
+ import {
20
+ deriveCouncilAddress,
21
+ deriveAddressFromPubkey,
22
+ normalizeAddress,
23
+ addressesEqual
24
+ } from './council.js'
25
+
26
+ import {
27
+ PSP1_LOKAD,
28
+ PSP1_DETECTION_PREFIX,
29
+ ZERO_TXID,
30
+ encodePsP1,
31
+ isPsP1Record,
32
+ parsePsP1Record
33
+ } from './psp1-codec.js'
34
+
35
+ import {
36
+ buildUpdateOpReturn,
37
+ parseUpdateRecord,
38
+ buildUpdateTransaction
39
+ } from './update.js'
40
+
41
+ import {
42
+ APPROVAL_WORD,
43
+ DUST_SATOSHIS,
44
+ buildApprovalOpReturn,
45
+ parseApprovalRecord,
46
+ buildApprovalTransaction
47
+ } from './approval.js'
48
+
49
+ import { validateApproval, normalizeMembership } from './validate.js'
50
+ import { countMultisigSignatures, verifyMultisigSpend } from './signatures.js'
51
+
52
+ const ps009v2 = {
53
+ // Section 2 - council membership.
54
+ deriveCouncilAddress,
55
+ deriveAddressFromPubkey,
56
+ normalizeAddress,
57
+ addressesEqual,
58
+
59
+ // PS010 section 4.1 - PSP1 registry record.
60
+ PSP1_LOKAD,
61
+ PSP1_DETECTION_PREFIX,
62
+ ZERO_TXID,
63
+ encodePsP1,
64
+ isPsP1Record,
65
+ parsePsP1Record,
66
+
67
+ // Section 4 - Update Transaction.
68
+ buildUpdateOpReturn,
69
+ parseUpdateRecord,
70
+ buildUpdateTransaction,
71
+
72
+ // Section 5 - Approval Transaction.
73
+ APPROVAL_WORD,
74
+ DUST_SATOSHIS,
75
+ buildApprovalOpReturn,
76
+ parseApprovalRecord,
77
+ buildApprovalTransaction,
78
+
79
+ // Section 6 - validation.
80
+ validateApproval,
81
+ normalizeMembership,
82
+ countMultisigSignatures,
83
+ verifyMultisigSpend
84
+ }
85
+
86
+ export {
87
+ deriveCouncilAddress,
88
+ deriveAddressFromPubkey,
89
+ normalizeAddress,
90
+ addressesEqual,
91
+ PSP1_LOKAD,
92
+ PSP1_DETECTION_PREFIX,
93
+ ZERO_TXID,
94
+ encodePsP1,
95
+ isPsP1Record,
96
+ parsePsP1Record,
97
+ buildUpdateOpReturn,
98
+ parseUpdateRecord,
99
+ buildUpdateTransaction,
100
+ APPROVAL_WORD,
101
+ DUST_SATOSHIS,
102
+ buildApprovalOpReturn,
103
+ parseApprovalRecord,
104
+ buildApprovalTransaction,
105
+ validateApproval,
106
+ normalizeMembership,
107
+ countMultisigSignatures,
108
+ verifyMultisigSpend
109
+ }
110
+
111
+ export default ps009v2
@@ -0,0 +1,213 @@
1
+ /*
2
+ PS009 v2 / PS010 section 4.1 - `PSP1` pool-registry announcement codec.
3
+
4
+ Wire layout (normative, PS010 section 4.1):
5
+
6
+ scriptPubKey ASM (vout[0]):
7
+ OP_RETURN
8
+ OP_PUSHDATA 50535031 # "PSP1"
9
+ OP_PUSHDATA 01 # version = 1 (1 byte)
10
+ OP_PUSHDATA <poolCashAddrUtf8>
11
+ OP_PUSHDATA <validFromHeightLE8>
12
+ OP_PUSHDATA <satsPerMbLE8>
13
+ OP_PUSHDATA <prevRegistryTxidBin32>
14
+
15
+ Detection: script hex contains 6a0450535031.
16
+
17
+ Field rules:
18
+ - version must be 0x01; unknown versions are rejected.
19
+ - poolCashAddr is UTF-8 cashaddr *with* the network prefix. P2SH32 pool
20
+ addresses are accepted (bitcore-lib-cash 8.25.x can not decode them, so
21
+ only the prefix/charset are validated here).
22
+ - validFromHeight and satsPerMb are uint64 little-endian, always 8 bytes.
23
+ - prevRegistryTxid is 32 raw bytes in Bitcoin internal byte order. This
24
+ codec takes/returns the *displayed* txid hex (the form explorers show)
25
+ and reverses to/from internal order, per PS010's implementation note.
26
+ */
27
+
28
+ import {
29
+ dataPushes,
30
+ decodeTxidInternal,
31
+ decodeUint64LE,
32
+ encodeTxidInternal,
33
+ encodeUint64LE,
34
+ extractVout0ScriptHex,
35
+ isOpReturn,
36
+ opReturnScript
37
+ } from './script.js'
38
+
39
+ const PSP1_LOKAD = 'PSP1'
40
+ const PSP1_LOKAD_HEX = '50535031'
41
+ const PSP1_VERSION = 1
42
+ const PSP1_DETECTION_PREFIX = '6a0450535031'
43
+ const ZERO_TXID = '0'.repeat(64)
44
+
45
+ // Cashaddr prefixes accepted in the poolCashAddr field. PS010 says
46
+ // 'bitcoincash:' (mainnet); testnet/chipnet use 'bchtest:'.
47
+ const POOL_ADDR_PREFIXES = ['bitcoincash:', 'bchtest:']
48
+
49
+ function psp1Error (code, message) {
50
+ const err = new Error(message)
51
+ err.code = code
52
+ return err
53
+ }
54
+
55
+ // Encode a PSP1 registry announcement into a vout[0] scriptPubKey hex string.
56
+ function encodePsP1 (inObj = {}) {
57
+ const {
58
+ poolCashAddr,
59
+ satsPerMb,
60
+ validFromHeight,
61
+ prevRegistryTxid = ZERO_TXID,
62
+ version = PSP1_VERSION
63
+ } = inObj
64
+
65
+ if (typeof poolCashAddr !== 'string') {
66
+ throw new Error('poolCashAddr is required (UTF-8 cashaddr, including the network prefix)')
67
+ }
68
+
69
+ const prefixOk = POOL_ADDR_PREFIXES.some(prefix => poolCashAddr.startsWith(prefix))
70
+ if (!prefixOk) {
71
+ throw new Error(`poolCashAddr must start with one of: ${POOL_ADDR_PREFIXES.join(', ')}`)
72
+ }
73
+ if (!/^[a-z0-9:]+$/.test(poolCashAddr)) {
74
+ throw new Error('poolCashAddr must be a lowercase cashaddr string')
75
+ }
76
+
77
+ if (version !== PSP1_VERSION) {
78
+ throw new Error(`Unsupported PSP1 version: ${version} (only ${PSP1_VERSION} is defined)`)
79
+ }
80
+
81
+ if (validFromHeight === undefined || validFromHeight === null) {
82
+ throw new Error('validFromHeight is required')
83
+ }
84
+
85
+ const pushes = [
86
+ Buffer.from(PSP1_LOKAD_HEX, 'hex'),
87
+ Buffer.from([version]),
88
+ Buffer.from(poolCashAddr, 'utf8'),
89
+ encodeUint64LE(validFromHeight, 'validFromHeight'),
90
+ encodeUint64LE(satsPerMb, 'satsPerMb'),
91
+ encodeTxidInternal(prevRegistryTxid, 'prevRegistryTxid')
92
+ ]
93
+
94
+ const scriptHex = opReturnScript(pushes)
95
+
96
+ return {
97
+ lokad: PSP1_LOKAD,
98
+ version,
99
+ poolCashAddr,
100
+ validFromHeight: Number(validFromHeight),
101
+ satsPerMb: Number(satsPerMb),
102
+ prevRegistryTxid: prevRegistryTxid.toLowerCase(),
103
+ scriptHex
104
+ }
105
+ }
106
+
107
+ // Cheap detection check, per PS010: 'OP_RETURN hex contains 6a0450535031'.
108
+ function isPsP1Record (input) {
109
+ try {
110
+ const scriptHex = extractVout0ScriptHex(input)
111
+ return scriptHex.toLowerCase().startsWith(PSP1_DETECTION_PREFIX)
112
+ } catch (err) {
113
+ return false
114
+ }
115
+ }
116
+
117
+ /*
118
+ Parse a PSP1 announcement.
119
+
120
+ Returns the decoded record, or null when vout[0] is not a PSP1 record.
121
+ Throws (with err.code set) when vout[0] *is* a PSP1 record but is malformed:
122
+ wrong number of pushes, unknown version, bad field lengths, bad UTF-8.
123
+ */
124
+ function parsePsP1Record (input) {
125
+ const scriptHex = extractVout0ScriptHex(input)
126
+
127
+ if (!isOpReturn(scriptHex)) return null
128
+
129
+ let pushes
130
+ try {
131
+ pushes = dataPushes(scriptHex)
132
+ } catch (err) {
133
+ // Only report a malformed record if it looks like PSP1; otherwise it is
134
+ // simply not a PSP1 record.
135
+ if (scriptHex.toLowerCase().includes(PSP1_LOKAD_HEX)) {
136
+ throw psp1Error('ERR_PSP1_MALFORMED', `Malformed PSP1 pushdata: ${err.message}`)
137
+ }
138
+ return null
139
+ }
140
+
141
+ if (pushes.length === 0) return null
142
+ if (pushes[0].toString('hex') !== PSP1_LOKAD_HEX) return null
143
+
144
+ if (pushes.length !== 6) {
145
+ throw psp1Error('ERR_PSP1_MALFORMED', `PSP1 record must contain exactly 6 pushes (lokad, version, poolCashAddr, validFromHeight, satsPerMb, prevRegistryTxid); found ${pushes.length}`)
146
+ }
147
+
148
+ const [, versionBuf, addrBuf, heightBuf, satsBuf, prevTxidBuf] = pushes
149
+
150
+ if (versionBuf.length !== 1) {
151
+ throw psp1Error('ERR_PSP1_MALFORMED', `PSP1 version push must be exactly 1 byte; found ${versionBuf.length}`)
152
+ }
153
+ if (versionBuf[0] !== PSP1_VERSION) {
154
+ throw psp1Error('ERR_PSP1_UNKNOWN_VERSION', `Unknown PSP1 version: ${versionBuf[0]}`)
155
+ }
156
+
157
+ let poolCashAddr
158
+ try {
159
+ poolCashAddr = addrBuf.toString('utf8')
160
+ } catch (err) {
161
+ throw psp1Error('ERR_PSP1_MALFORMED', errorMessage('PSP1 poolCashAddr is not valid UTF-8', err))
162
+ }
163
+
164
+ if (!POOL_ADDR_PREFIXES.some(prefix => poolCashAddr.startsWith(prefix))) {
165
+ throw psp1Error('ERR_PSP1_MALFORMED', `PSP1 poolCashAddr must start with one of: ${POOL_ADDR_PREFIXES.join(', ')}`)
166
+ }
167
+ if (!/^[a-z0-9:]+$/.test(poolCashAddr)) {
168
+ throw psp1Error('ERR_PSP1_MALFORMED', 'PSP1 poolCashAddr must be a lowercase cashaddr string')
169
+ }
170
+
171
+ if (heightBuf.length !== 8) {
172
+ throw psp1Error('ERR_PSP1_MALFORMED', `PSP1 validFromHeight must be 8 bytes; found ${heightBuf.length}`)
173
+ }
174
+ if (satsBuf.length !== 8) {
175
+ throw psp1Error('ERR_PSP1_MALFORMED', `PSP1 satsPerMb must be 8 bytes; found ${satsBuf.length}`)
176
+ }
177
+ if (prevTxidBuf.length !== 32) {
178
+ throw psp1Error('ERR_PSP1_MALFORMED', `PSP1 prevRegistryTxid must be 32 bytes; found ${prevTxidBuf.length}`)
179
+ }
180
+
181
+ return {
182
+ txid: null, // filled in by the validator/providers; not encoded on chain
183
+ lokad: PSP1_LOKAD,
184
+ version: versionBuf[0],
185
+ poolCashAddr,
186
+ validFromHeight: decodeUint64LE(heightBuf, 'validFromHeight'),
187
+ satsPerMb: decodeUint64LE(satsBuf, 'satsPerMb'),
188
+ prevRegistryTxid: decodeTxidInternal(prevTxidBuf, 'prevRegistryTxid'),
189
+ scriptHex
190
+ }
191
+ }
192
+
193
+ function errorMessage (prefix, err) {
194
+ return `${prefix}: ${err && err.message ? err.message : err}`
195
+ }
196
+
197
+ export {
198
+ PSP1_LOKAD,
199
+ PSP1_LOKAD_HEX,
200
+ PSP1_VERSION,
201
+ PSP1_DETECTION_PREFIX,
202
+ ZERO_TXID,
203
+ POOL_ADDR_PREFIXES,
204
+ encodePsP1,
205
+ isPsP1Record,
206
+ parsePsP1Record
207
+ }
208
+
209
+ export default {
210
+ encodePsP1,
211
+ isPsP1Record,
212
+ parsePsP1Record
213
+ }
@@ -0,0 +1,352 @@
1
+ /*
2
+ PS009 v2 - low-level Bitcoin script helpers.
3
+
4
+ No network access. Strict parsing: malformed pushdata is rejected rather
5
+ than truncated (the same rule PS010 section 5.3 applies to Pin Claims).
6
+ */
7
+
8
+ import bitcore from '@chris.troutner/bitcore-lib-cash'
9
+
10
+ // Bitcoin script opcodes used by this library.
11
+ const OP_RETURN = 0x6a
12
+ const OP_PUSHDATA1 = 0x4c
13
+ const OP_PUSHDATA2 = 0x4d
14
+ const OP_PUSHDATA4 = 0x4e
15
+
16
+ const MAX_UINT64 = BigInt('18446744073709551615')
17
+ const B256 = BigInt(256)
18
+
19
+ // Encode a Buffer as a Bitcoin script push (data push only).
20
+ function encodePushData (data) {
21
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data)
22
+ const len = buf.length
23
+
24
+ if (len < OP_PUSHDATA1) {
25
+ return Buffer.concat([Buffer.from([len]), buf])
26
+ }
27
+ if (len <= 0xff) {
28
+ return Buffer.concat([Buffer.from([OP_PUSHDATA1, len]), buf])
29
+ }
30
+ if (len <= 0xffff) {
31
+ const header = Buffer.alloc(3)
32
+ header[0] = OP_PUSHDATA2
33
+ header.writeUInt16LE(len, 1)
34
+ return Buffer.concat([header, buf])
35
+ }
36
+
37
+ const header = Buffer.alloc(5)
38
+ header[0] = OP_PUSHDATA4
39
+ header.writeUInt32LE(len, 1)
40
+ return Buffer.concat([header, buf])
41
+ }
42
+
43
+ // Read every push in a script hex string. Throws on truncated pushes.
44
+ function readScriptPushes (scriptHex) {
45
+ if (typeof scriptHex !== 'string' || !/^[0-9a-fA-F]*$/.test(scriptHex) || scriptHex.length % 2 !== 0) {
46
+ throw new Error('script must be an even-length hex string')
47
+ }
48
+
49
+ const buf = Buffer.from(scriptHex, 'hex')
50
+ const pushes = []
51
+ let i = 0
52
+
53
+ while (i < buf.length) {
54
+ const opcode = buf[i]
55
+ i++
56
+
57
+ let len = null
58
+ if (opcode < OP_PUSHDATA1) {
59
+ len = opcode
60
+ } else if (opcode === OP_PUSHDATA1) {
61
+ if (i + 1 > buf.length) throw new Error('truncated OP_PUSHDATA1 length')
62
+ len = buf[i]
63
+ i += 1
64
+ } else if (opcode === OP_PUSHDATA2) {
65
+ if (i + 2 > buf.length) throw new Error('truncated OP_PUSHDATA2 length')
66
+ len = buf.readUInt16LE(i)
67
+ i += 2
68
+ } else if (opcode === OP_PUSHDATA4) {
69
+ if (i + 4 > buf.length) throw new Error('truncated OP_PUSHDATA4 length')
70
+ len = buf.readUInt32LE(i)
71
+ i += 4
72
+ } else {
73
+ // Non-push opcode: keep it as a marker so callers can reject scripts
74
+ // that are not pure data pushes (OP_RETURN outputs must be push-only).
75
+ pushes.push({ opcode })
76
+ continue
77
+ }
78
+
79
+ if (i + len > buf.length) {
80
+ throw new Error('truncated script push data')
81
+ }
82
+
83
+ pushes.push({ opcode, data: buf.slice(i, i + len) })
84
+ i += len
85
+ }
86
+
87
+ return pushes
88
+ }
89
+
90
+ // Return only the data pushes of a script, ignoring non-push opcodes.
91
+ function dataPushes (scriptHex) {
92
+ const pushes = readScriptPushes(scriptHex)
93
+ const out = []
94
+ for (const push of pushes) {
95
+ if (push.data) out.push(push.data)
96
+ }
97
+ return out
98
+ }
99
+
100
+ // Build a script hex string from an array of data buffers (each becomes one
101
+ // data push).
102
+ function scriptFromPushes (pushes) {
103
+ return Buffer.concat(pushes.map(push => encodePushData(push))).toString('hex')
104
+ }
105
+
106
+ // Build an OP_RETURN script from an array of data buffers.
107
+ function opReturnScript (pushes) {
108
+ return '6a' + scriptFromPushes(pushes)
109
+ }
110
+
111
+ // Parse an ASM string (as produced by bitcore's Script#toASM) into a script.
112
+ // bitcore 8.25's own fromString() can not round-trip OP_RETURN data pushes, so
113
+ // accepted tokens are: a numeric length (ignored, the following token's own
114
+ // length is authoritative), `0x<hex>` data pushes, and bare hex data pushes.
115
+ function asmToScriptHex (asm) {
116
+ if (typeof asm !== 'string' || asm.length === 0) {
117
+ throw new Error('ASM string is required')
118
+ }
119
+
120
+ const tokens = asm.trim().split(/\s+/)
121
+
122
+ if (tokens[0] !== 'OP_RETURN') {
123
+ throw new Error('only OP_RETURN scripts can be parsed from ASM')
124
+ }
125
+
126
+ const pushes = []
127
+ for (let i = 1; i < tokens.length; i++) {
128
+ const token = tokens[i]
129
+
130
+ // Some tools print '<len> 0x<data>' for each push. Only treat a numeric
131
+ // token as a length when the following token is an explicit 0x push: a
132
+ // pushed payload can itself be all digits (e.g. ASCII-hex data).
133
+ if (/^[0-9]+$/.test(token) && tokens[i + 1] && tokens[i + 1].startsWith('0x')) {
134
+ continue
135
+ }
136
+
137
+ if (token.startsWith('0x') && isHexString(token.slice(2))) {
138
+ pushes.push(Buffer.from(token.slice(2), 'hex'))
139
+ continue
140
+ }
141
+
142
+ if (isHexString(token)) {
143
+ pushes.push(Buffer.from(token, 'hex'))
144
+ continue
145
+ }
146
+
147
+ throw new Error(`unsupported ASM token: ${token}`)
148
+ }
149
+
150
+ return opReturnScript(pushes)
151
+ }
152
+
153
+ function isHexString (str) {
154
+ return typeof str === 'string' && str.length % 2 === 0 && /^[0-9a-fA-F]*$/.test(str)
155
+ }
156
+
157
+ // Normalize any of the accepted "script or transaction" inputs into a
158
+ // vout[0] scriptPubKey hex string:
159
+ // - script hex
160
+ // - script ASM (e.g. 'OP_RETURN 50535031 ...')
161
+ // - a transaction details object (bch-api/Fulcrum shape or bitcore shape)
162
+ // - a raw transaction hex wrapped in { hex }
163
+ // - the output of buildUpdateTransaction()/buildApprovalTransaction()
164
+ function extractVout0ScriptHex (input) {
165
+ if (input === null || input === undefined) {
166
+ throw new Error('transaction or script is required')
167
+ }
168
+
169
+ if (typeof input === 'string') {
170
+ const str = input.trim()
171
+
172
+ if (str.startsWith('OP_')) {
173
+ return asmToScriptHex(str)
174
+ }
175
+
176
+ if (isHexString(str)) {
177
+ // A raw transaction hex (version byte first) is not a script; a vout[0]
178
+ // OP_RETURN script starts with 6a. Prefer the script interpretation only
179
+ // when it starts with OP_RETURN, otherwise try the transaction.
180
+ if (str.slice(0, 2).toLowerCase() === '6a') return str.toLowerCase()
181
+
182
+ try {
183
+ const tx = new bitcore.Transaction(str)
184
+ if (tx.outputs[0]) return tx.outputs[0].script.toHex()
185
+ } catch (err) {
186
+ // Fall through and treat it as a script.
187
+ }
188
+
189
+ return str.toLowerCase()
190
+ }
191
+
192
+ throw new Error('string input must be a script hex, transaction hex, or script ASM string')
193
+ }
194
+
195
+ if (typeof input !== 'object') {
196
+ throw new Error('transaction or script input must be a string or object')
197
+ }
198
+
199
+ // Unwrap builder output ({ tx, hex, ... }) and { txDetails } wrappers.
200
+ if (input.tx && typeof input.hex === 'string' && !input.vout && !input.outputs) {
201
+ return extractVout0ScriptHex(input.hex)
202
+ }
203
+ if (input.hex && !input.vout && !input.outputs) {
204
+ return extractVout0ScriptHex(input.hex)
205
+ }
206
+ if (input.tx && input.tx.vout) {
207
+ return extractVout0ScriptHex(input.tx)
208
+ }
209
+ if (input.txDetails && input.txDetails.vout) {
210
+ return extractVout0ScriptHex(input.txDetails)
211
+ }
212
+
213
+ if (Array.isArray(input.vout)) {
214
+ if (!input.vout[0]) throw new Error('transaction has no vout[0]')
215
+ return scriptHexFromVout(input.vout[0])
216
+ }
217
+
218
+ // bitcore Transaction#toObject() shape.
219
+ if (Array.isArray(input.outputs)) {
220
+ if (!input.outputs[0]) throw new Error('transaction has no outputs[0]')
221
+ return scriptHexFromVout(input.outputs[0])
222
+ }
223
+
224
+ throw new Error('could not find a vout[0] scriptPubKey in the supplied transaction object')
225
+ }
226
+
227
+ function scriptHexFromVout (vout) {
228
+ if (typeof vout.script === 'string') return vout.script.toLowerCase()
229
+ if (typeof vout.scriptPubKey === 'string') return vout.scriptPubKey.toLowerCase()
230
+ if (vout.scriptPubKey && typeof vout.scriptPubKey.hex === 'string') {
231
+ return vout.scriptPubKey.hex.toLowerCase()
232
+ }
233
+ if (vout.script && typeof vout.script.toHex === 'function') {
234
+ return vout.script.toHex()
235
+ }
236
+ throw new Error('vout entry has no scriptPubKey hex')
237
+ }
238
+
239
+ function isOpReturn (scriptHex) {
240
+ return typeof scriptHex === 'string' && scriptHex.slice(0, 2).toLowerCase() === '6a'
241
+ }
242
+
243
+ // ----- uint64 little-endian helpers (PS010 section 4.1) -----
244
+
245
+ // Encode a non-negative integer (Number, BigInt, or decimal string) as 8 bytes
246
+ // little-endian, per PS010 section 4.1 ("use 8 bytes even if height fits in 4").
247
+ function encodeUint64LE (value, fieldName) {
248
+ const name = fieldName || 'value'
249
+ let big
250
+
251
+ if (typeof value === 'bigint') {
252
+ big = value
253
+ } else if (typeof value === 'number' || typeof value === 'string') {
254
+ const str = String(value)
255
+ if (!/^[0-9]+$/.test(str)) {
256
+ throw new Error(`${name} must be a non-negative integer`)
257
+ }
258
+ if (typeof value === 'number' && !Number.isSafeInteger(value)) {
259
+ throw new Error(`${name} must be a safe integer (or pass a decimal string / BigInt)`)
260
+ }
261
+ big = BigInt(str)
262
+ } else {
263
+ throw new Error(`${name} must be a non-negative integer`)
264
+ }
265
+
266
+ if (big < BigInt(0) || big > MAX_UINT64) {
267
+ throw new Error(`${name} does not fit in a uint64`)
268
+ }
269
+
270
+ const buf = Buffer.alloc(8)
271
+ for (let i = 0; i < 8; i++) {
272
+ buf[i] = Number(big % B256)
273
+ big = big / B256
274
+ }
275
+
276
+ return buf
277
+ }
278
+
279
+ // Decode 8 little-endian bytes. Returns a Number when the value is a safe
280
+ // integer (all real heights and rates), otherwise a BigInt so no precision is
281
+ // silently lost.
282
+ function decodeUint64LE (buf, fieldName) {
283
+ const name = fieldName || 'value'
284
+ if (!Buffer.isBuffer(buf) || buf.length !== 8) {
285
+ throw new Error(`${name} must be an 8-byte buffer`)
286
+ }
287
+
288
+ let big = BigInt(0)
289
+ for (let i = 7; i >= 0; i--) {
290
+ big = big * B256 + BigInt(buf[i])
291
+ }
292
+
293
+ if (big <= BigInt(Number.MAX_SAFE_INTEGER)) return Number(big)
294
+ return big
295
+ }
296
+
297
+ // Encode a displayed txid (big-endian hex, the form explorers show) into the
298
+ // 32 raw bytes in Bitcoin internal byte order, as PS010 section 4.1 requires
299
+ // for prevRegistryTxid.
300
+ function encodeTxidInternal (txidHex, fieldName) {
301
+ const name = fieldName || 'txid'
302
+ if (typeof txidHex !== 'string' || !/^[0-9a-fA-F]{64}$/.test(txidHex)) {
303
+ throw new Error(`${name} must be a 64-character hex txid`)
304
+ }
305
+ return Buffer.from(txidHex, 'hex').reverse()
306
+ }
307
+
308
+ // Inverse of encodeTxidInternal(): raw internal bytes -> displayed txid hex.
309
+ function decodeTxidInternal (buf, fieldName) {
310
+ const name = fieldName || 'txid'
311
+ if (!Buffer.isBuffer(buf) || buf.length !== 32) {
312
+ throw new Error(`${name} must be a 32-byte buffer`)
313
+ }
314
+ return Buffer.from(buf).reverse().toString('hex')
315
+ }
316
+
317
+ export {
318
+ OP_RETURN,
319
+ OP_PUSHDATA1,
320
+ OP_PUSHDATA2,
321
+ OP_PUSHDATA4,
322
+ MAX_UINT64,
323
+ encodePushData,
324
+ readScriptPushes,
325
+ dataPushes,
326
+ scriptFromPushes,
327
+ opReturnScript,
328
+ asmToScriptHex,
329
+ extractVout0ScriptHex,
330
+ scriptHexFromVout,
331
+ isOpReturn,
332
+ isHexString,
333
+ encodeUint64LE,
334
+ decodeUint64LE,
335
+ encodeTxidInternal,
336
+ decodeTxidInternal
337
+ }
338
+
339
+ export default {
340
+ encodePushData,
341
+ readScriptPushes,
342
+ dataPushes,
343
+ scriptFromPushes,
344
+ opReturnScript,
345
+ asmToScriptHex,
346
+ extractVout0ScriptHex,
347
+ isOpReturn,
348
+ encodeUint64LE,
349
+ decodeUint64LE,
350
+ encodeTxidInternal,
351
+ decodeTxidInternal
352
+ }