@smartledger/bsv 8.1.0 → 8.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/README.md +38 -38
  3. package/bsv-ecies.min.js +1 -1
  4. package/bsv-gdaf.min.js +62 -62
  5. package/bsv-ltp.min.js +48 -48
  6. package/bsv-smartcontract.min.js +1 -1
  7. package/bsv.bundle.js +62 -62
  8. package/bsv.min.js +62 -62
  9. package/docs/AUDIT_SCOPE.md +8 -8
  10. package/docs/BRC220_ENCODING_AMENDMENT.md +100 -0
  11. package/docs/BRC220_PLAN.md +224 -0
  12. package/docs/MODULE_REFERENCE_COMPLETE.md +27 -27
  13. package/docs/advanced/UTXO_MANAGER_GUIDE.md +1 -1
  14. package/docs/getting-started/INSTALLATION.md +23 -23
  15. package/docs/getting-started/QUICK_START.md +7 -7
  16. package/docs/migration/FROM_BSV_1_5_6.md +5 -5
  17. package/index.js +5 -0
  18. package/index.mjs +1 -0
  19. package/lib/gdaf/attestation-signer.js +54 -2
  20. package/lib/gdaf/attestation-verifier.js +41 -25
  21. package/lib/gdaf/zk-prover.js +143 -46
  22. package/lib/notaryhash/certificate.js +282 -0
  23. package/lib/notaryhash/encoding.js +150 -0
  24. package/lib/notaryhash/index.js +334 -0
  25. package/lib/notaryhash/merkle.js +209 -0
  26. package/lib/notaryhash/script.js +261 -0
  27. package/lib/notaryhash/suites.js +156 -0
  28. package/lib/util/jcs.js +75 -0
  29. package/package.json +9 -6
  30. package/test/gdaf/canonicalization.js +106 -0
  31. package/test/gdaf/zk_prover.js +204 -0
  32. package/test/notaryhash/certificate.js +249 -0
  33. package/test/notaryhash/encoding.js +186 -0
  34. package/test/notaryhash/merkle.js +181 -0
  35. package/test/notaryhash/script.js +270 -0
  36. package/test/notaryhash/verify.js +339 -0
  37. package/tools/minimal_reproduction.js +119 -0
  38. package/tools/opcode_map.js +342 -0
  39. package/tools/server.js +97 -0
  40. package/tools/simple_real_tx.js +136 -0
  41. package/tools/sv-sighash-harness.js +123 -0
  42. package/tools/sv-sighash-report.js +71 -0
  43. package/tools/sv-tx-harness.js +172 -0
  44. package/tools/sv-tx-report.js +43 -0
  45. package/tools/sv-vector-harness.js +304 -0
  46. package/tools/sv-vector-report.js +88 -0
  47. package/version.js +1 -1
@@ -0,0 +1,204 @@
1
+ 'use strict'
2
+
3
+ /* global describe, it */
4
+
5
+ // This module had ZERO test coverage, and carried three defects that coverage would have
6
+ // caught immediately. Each is pinned below as the attack that worked, not as a paraphrase
7
+ // of the fix, so a regression reproduces the exploit rather than merely failing a check.
8
+ //
9
+ // It is also not zero-knowledge, and the tests say so where it matters: the range and age
10
+ // commitments can only be verified by opening them, which reveals the committed value.
11
+
12
+ require('chai').should()
13
+ var bsv = require('../..')
14
+ var ZK = require('../../lib/gdaf/zk-prover')
15
+ var Hash = require('../../lib/crypto/hash')
16
+
17
+ var CRED = {
18
+ id: 'urn:x',
19
+ credentialSubject: { name: 'Alice', partyAffiliation: 'DEM', eligible: true }
20
+ }
21
+
22
+ describe('ZKProver', function () {
23
+ describe('range proofs', function () {
24
+ // The original read `return proof.inRange === true` — a boolean the prover writes
25
+ // about itself. valueCommitment was never consulted, so this forgery verified.
26
+ it('rejects a forged proof that merely claims inRange', function () {
27
+ var forged = {
28
+ type: 'RangeProof',
29
+ range: { min: 18, max: 120 },
30
+ valueCommitment: '00'.repeat(32),
31
+ proofHash: 'de'.repeat(32),
32
+ inRange: true
33
+ }
34
+ ZK.verifyRangeProof(forged, 18, 120).should.equal(false)
35
+ })
36
+
37
+ it('rejects an honest proof presented without its opening', function () {
38
+ var proof = ZK.generateRangeProof(41, 18, 120)
39
+ ZK.verifyRangeProof(proof, 18, 120).should.equal(false)
40
+ })
41
+
42
+ it('accepts an honest proof with its opening', function () {
43
+ var proof = ZK.generateRangeProof(41, 18, 120)
44
+ ZK.verifyRangeProof(proof, 18, 120, proof.opening).should.equal(true)
45
+ })
46
+
47
+ // The commitment must actually bind the value: a lie about what was committed to
48
+ // has to fail even though the range and structure are right.
49
+ it('rejects an opening that does not match the commitment', function () {
50
+ var proof = ZK.generateRangeProof(41, 18, 120)
51
+ var lie = { value: 12, salt: proof.opening.salt }
52
+ ZK.verifyRangeProof(proof, 18, 120, lie).should.equal(false)
53
+ })
54
+
55
+ it('rejects a value outside the stated range even if the commitment opens', function () {
56
+ var proof = ZK.generateRangeProof(41, 18, 120)
57
+ ZK.verifyRangeProof(proof, 50, 120, proof.opening).should.equal(false)
58
+ })
59
+
60
+ it('returns a strict boolean', function () {
61
+ var proof = ZK.generateRangeProof(41, 18, 120)
62
+ ZK.verifyRangeProof(proof, 18, 120, proof.opening).should.be.a('boolean')
63
+ ZK.verifyRangeProof({}, 18, 120).should.be.a('boolean')
64
+ })
65
+ })
66
+
67
+ describe('age proofs', function () {
68
+ var BIRTH = new Date('1985-01-01T00:00:00Z')
69
+
70
+ it('rejects a forged proof that merely claims meetsRequirement', function () {
71
+ var forged = {
72
+ type: 'AgeProof',
73
+ minimumAge: 18,
74
+ meetsRequirement: true,
75
+ birthDateCommitment: '00'.repeat(32),
76
+ challengeResponse: 'anything-non-empty'
77
+ }
78
+ ZK.verifyAgeProof(forged, 18).should.equal(false)
79
+ })
80
+
81
+ it('rejects an honest proof presented without its opening', function () {
82
+ var proof = ZK.generateAgeProof(BIRTH, 18)
83
+ ZK.verifyAgeProof(proof, 18).should.equal(false)
84
+ })
85
+
86
+ it('accepts an honest proof with its opening', function () {
87
+ var proof = ZK.generateAgeProof(BIRTH, 18)
88
+ ZK.verifyAgeProof(proof, 18, proof.opening).should.equal(true)
89
+ })
90
+
91
+ it('rejects an opening that does not match the commitment', function () {
92
+ var proof = ZK.generateAgeProof(BIRTH, 18)
93
+ ZK.verifyAgeProof(proof, 18, { birthDate: '2015-01-01', salt: proof.opening.salt })
94
+ .should.equal(false)
95
+ })
96
+ })
97
+
98
+ describe('selective disclosure', function () {
99
+ // THE LEAK. One salt covered every leaf and travelled in the proof, so the sibling
100
+ // hashes on the Merkle path could be brute-forced back into the withheld fields.
101
+ // Disclosing only the name recovered id, partyAffiliation and eligible.
102
+ it('does not leak the withheld fields to someone holding the proof', function () {
103
+ var proof = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'], 'aa'.repeat(16))
104
+
105
+ // Everything an attacker gets: the proof's salts and the Merkle path.
106
+ var salts = proof.disclosedFields.map(function (f) { return f.salt })
107
+ var siblings = []
108
+ proof.merkleProofs.forEach(function (mp) {
109
+ mp.proof.forEach(function (n) { siblings.push(n.hash) })
110
+ })
111
+
112
+ function leaf (p, v, s) {
113
+ return Hash.sha256(Buffer.from(p + ':' + JSON.stringify(v) + ':' + s, 'utf8')).toString('hex')
114
+ }
115
+ function node (a, b) {
116
+ return Hash.sha256(Buffer.from(a + b, 'hex')).toString('hex')
117
+ }
118
+
119
+ var paths = ['id', 'credentialSubject.partyAffiliation', 'credentialSubject.eligible']
120
+ var values = ['urn:x', 'DEM', 'REP', 'IND', true, false]
121
+ var recovered = []
122
+
123
+ salts.forEach(function (s) {
124
+ // Direct leaf siblings.
125
+ paths.forEach(function (p) {
126
+ values.forEach(function (v) {
127
+ if (siblings.indexOf(leaf(p, v, s)) !== -1) recovered.push(p)
128
+ })
129
+ })
130
+ // Internal nodes: brute-force the pair beneath them.
131
+ paths.forEach(function (p1) {
132
+ values.forEach(function (v1) {
133
+ paths.forEach(function (p2) {
134
+ values.forEach(function (v2) {
135
+ if (siblings.indexOf(node(leaf(p1, v1, s), leaf(p2, v2, s))) !== -1) {
136
+ recovered.push(p1, p2)
137
+ }
138
+ })
139
+ })
140
+ })
141
+ })
142
+ })
143
+
144
+ recovered.should.deep.equal([], 'recovered withheld fields: ' + recovered.join(', '))
145
+ })
146
+
147
+ it('never ships the master salt, which would reopen every leaf', function () {
148
+ var proof = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'], 'aa'.repeat(16))
149
+ ;(proof.salt === undefined).should.equal(true)
150
+ })
151
+
152
+ // The generated salt used to be dropped on the floor: the proof returned the
153
+ // (undefined) `salt` ARGUMENT rather than the one createMerkleTree produced, so a
154
+ // proof made without an explicit salt could never verify.
155
+ it('verifies a proof generated without an explicit salt', function () {
156
+ var proof = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'])
157
+ var result = ZK.verifySelectiveProof(proof, proof.credentialRoot)
158
+ result.valid.should.equal(true, JSON.stringify(result.errors))
159
+ })
160
+
161
+ it('verifies a proof generated with an explicit salt', function () {
162
+ var proof = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'], 'aa'.repeat(16))
163
+ ZK.verifySelectiveProof(proof, proof.credentialRoot).valid.should.equal(true)
164
+ })
165
+
166
+ it('rejects a tampered disclosed value', function () {
167
+ var proof = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'], 'aa'.repeat(16))
168
+ proof.disclosedFields[0].value = 'Mallory'
169
+ ZK.verifySelectiveProof(proof, proof.credentialRoot).valid.should.equal(false)
170
+ })
171
+
172
+ it('rejects a proof checked against the wrong root', function () {
173
+ var proof = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'], 'aa'.repeat(16))
174
+ ZK.verifySelectiveProof(proof, '00'.repeat(32)).valid.should.equal(false)
175
+ })
176
+
177
+ it('rejects a field whose salt has been stripped', function () {
178
+ var proof = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'], 'aa'.repeat(16))
179
+ delete proof.disclosedFields[0].salt
180
+ ZK.verifySelectiveProof(proof, proof.credentialRoot).valid.should.equal(false)
181
+ })
182
+
183
+ // Deterministic trees are still available for callers that need them, without the
184
+ // single-salt weakness that made them dangerous.
185
+ it('is deterministic given the same master salt', function () {
186
+ var a = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'], 'bb'.repeat(16))
187
+ var b = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'], 'bb'.repeat(16))
188
+ a.credentialRoot.should.equal(b.credentialRoot)
189
+ })
190
+
191
+ it('gives different roots for different master salts', function () {
192
+ var a = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'], 'bb'.repeat(16))
193
+ var b = ZK.generateSelectiveProof(CRED, ['credentialSubject.name'], 'cc'.repeat(16))
194
+ a.credentialRoot.should.not.equal(b.credentialRoot)
195
+ })
196
+ })
197
+
198
+ // The module is reachable from the public GDAF surface, so the fixes above are not
199
+ // internal-only.
200
+ it('is exposed on the GDAF instance', function () {
201
+ var g = new bsv.GDAF()
202
+ ;(typeof g.zkProver.verifyRangeProof).should.equal('function')
203
+ })
204
+ })
@@ -0,0 +1,249 @@
1
+ 'use strict'
2
+
3
+ /* global describe, it */
4
+
5
+ // BRC-220 certificate. This is validity check 2 of the three the spec requires — proof
6
+ // integrity — plus the object a verifier is actually handed.
7
+ //
8
+ // The tests below concentrate on three things the spec makes explicit and that would fail
9
+ // silently if got wrong: the certificate carries FULL blobs even when the chain carries
10
+ // digests; the SPV envelope never disturbs proofHash; and proofHash is over the binary
11
+ // proof bytes, NOT over the certificate JSON.
12
+
13
+ require('chai').should()
14
+ var Certificate = require('../../lib/notaryhash/certificate')
15
+ var Encoding = require('../../lib/notaryhash/encoding')
16
+ var NS = require('../../lib/notaryhash/script')
17
+ var Hash = require('../../lib/crypto/hash')
18
+ var JCS = require('../../lib/util/jcs')
19
+
20
+ var PARAMS = {
21
+ mode: NS.MODE.FULL,
22
+ algorithm: 'ECDSA-secp256k1',
23
+ hashAlgorithm: 'SHA-256',
24
+ payloadHash: Buffer.alloc(32, 0x11),
25
+ publicKey: Buffer.alloc(33, 0x02),
26
+ signature: Buffer.alloc(64, 0x30),
27
+ createdAt: '2026-08-16T00:00:00.000Z',
28
+ anchor: { txid: 'ab'.repeat(32), blockHeight: 800000 }
29
+ }
30
+
31
+ var SPV = {
32
+ rawTx: 'deadbeef',
33
+ blockHash: 'cc'.repeat(32),
34
+ blockHeight: 800000,
35
+ merkleProof: { index: 0, nodes: ['aa'.repeat(32), '*'] }
36
+ }
37
+
38
+ describe('BRC-220 certificate', function () {
39
+ describe('build', function () {
40
+ it('carries every field the spec requires', function () {
41
+ var cert = Certificate.build(PARAMS)
42
+ Certificate.REQUIRED_FIELDS.forEach(function (field) {
43
+ ;(cert[field] === undefined).should.equal(false, 'missing ' + field)
44
+ })
45
+ })
46
+
47
+ it('defaults encoding to raw', function () {
48
+ Certificate.build(PARAMS).encoding.should.equal('raw')
49
+ })
50
+
51
+ it('accepts der for Bitcoin-native signers', function () {
52
+ Certificate.build(Object.assign({}, PARAMS, { encoding: 'der' })).encoding.should.equal('der')
53
+ })
54
+
55
+ it('rejects an unknown encoding rather than passing it through', function () {
56
+ ;(function () {
57
+ Certificate.build(Object.assign({}, PARAMS, { encoding: 'base64' }))
58
+ }).should.throw(/encoding must be/)
59
+ })
60
+
61
+ it('hex-encodes the byte fields', function () {
62
+ var cert = Certificate.build(PARAMS)
63
+ cert.payloadHash.should.equal(PARAMS.payloadHash.toString('hex'))
64
+ cert.publicKey.should.equal(PARAMS.publicKey.toString('hex'))
65
+ cert.signature.should.equal(PARAMS.signature.toString('hex'))
66
+ })
67
+
68
+ // proofHash is computed, never accepted. A caller cannot hand in a value that
69
+ // disagrees with the fields beside it — which is precisely the artefact this protocol
70
+ // exists to make impossible.
71
+ it('computes proofHash rather than accepting one', function () {
72
+ var cert = Certificate.build(Object.assign({}, PARAMS, { proofHash: 'ff'.repeat(32) }))
73
+ cert.proofHash.should.not.equal('ff'.repeat(32))
74
+ Certificate.proofHashMatches(cert).should.equal(true)
75
+ })
76
+
77
+ it('requires a merkle proof for batch mode', function () {
78
+ ;(function () {
79
+ Certificate.build(Object.assign({}, PARAMS, { mode: NS.MODE.BATCH }))
80
+ }).should.throw(/merkle/)
81
+ })
82
+
83
+ it('carries the merkle proof when batched', function () {
84
+ var cert = Certificate.build(Object.assign({}, PARAMS, {
85
+ mode: NS.MODE.BATCH,
86
+ merkle: { root: 'aa'.repeat(32), leafIndex: 2, leafCount: 8, path: [] }
87
+ }))
88
+ cert.merkle.leafIndex.should.equal(2)
89
+ cert.merkle.leafCount.should.equal(8)
90
+ })
91
+
92
+ // Hybrid puts only digests on chain; the certificate keeps the originals. That
93
+ // asymmetry is the whole point of the mode.
94
+ it('keeps the FULL key and signature in hybrid mode', function () {
95
+ var cert = Certificate.build(Object.assign({}, PARAMS, { mode: NS.MODE.HYBRID }))
96
+ cert.publicKey.should.equal(PARAMS.publicKey.toString('hex'))
97
+ cert.signature.should.equal(PARAMS.signature.toString('hex'))
98
+ // What goes on chain is the digest of each — different values entirely.
99
+ var onChain = NS.parse(NS.build(Object.assign({}, PARAMS, { mode: NS.MODE.HYBRID, proofHash: Buffer.alloc(32) })))
100
+ onChain.publicKeyHash.toString('hex').should.equal(Hash.sha256(PARAMS.publicKey).toString('hex'))
101
+ onChain.publicKeyHash.toString('hex').should.not.equal(cert.publicKey)
102
+ })
103
+ })
104
+
105
+ describe('proof integrity (validity check 2)', function () {
106
+ it('matches for a well-formed certificate', function () {
107
+ Certificate.proofHashMatches(Certificate.build(PARAMS)).should.equal(true)
108
+ })
109
+
110
+ // Each field is inside the canonical proof bytes, so tampering with any of them must
111
+ // be detected. This is the certificate-level counterpart of the encoding module's
112
+ // coverage test.
113
+ it('detects tampering with any covered field', function () {
114
+ var cert = Certificate.build(PARAMS)
115
+ var tampers = {
116
+ algorithm: 'ML-DSA-65',
117
+ hashAlgorithm: 'SHA-512',
118
+ payloadHash: 'ff'.repeat(32),
119
+ publicKey: '03' + '11'.repeat(32),
120
+ signature: 'aa'.repeat(64),
121
+ createdAt: '2026-08-17T00:00:00.000Z'
122
+ }
123
+ Object.keys(tampers).forEach(function (field) {
124
+ var bad = Object.assign({}, cert)
125
+ bad[field] = tampers[field]
126
+ Certificate.proofHashMatches(bad)
127
+ .should.equal(false, 'tampering with ' + field + ' was not detected')
128
+ })
129
+ })
130
+
131
+ // Fields NOT in the canonical proof bytes must not affect it — otherwise the SPV
132
+ // envelope could not be additive.
133
+ it('is unaffected by fields outside the canonical bytes', function () {
134
+ var cert = Certificate.build(PARAMS)
135
+ var moved = Object.assign({}, cert, {
136
+ anchor: { txid: 'ff'.repeat(32), blockHeight: 999999 },
137
+ mode: NS.MODE.HYBRID
138
+ })
139
+ Certificate.proofHashMatches(moved).should.equal(true)
140
+ })
141
+
142
+ it('returns a strict boolean, never a truthy object', function () {
143
+ Certificate.proofHashMatches(Certificate.build(PARAMS)).should.be.a('boolean')
144
+ Certificate.proofHashMatches(null).should.equal(false)
145
+ Certificate.proofHashMatches({}).should.equal(false)
146
+ Certificate.proofHashMatches({ proofHash: 'nonsense' }).should.equal(false)
147
+ })
148
+
149
+ // The hex fields decode to bytes before hashing. Hashing the strings would be twice
150
+ // as many bytes and produce something that still looks like a hash.
151
+ it('hashes the decoded bytes, not the hex strings', function () {
152
+ var cert = Certificate.build(PARAMS)
153
+ var overHex = Hash.sha256(Encoding.canonicalBytes({
154
+ algorithm: cert.algorithm,
155
+ hashAlgorithm: cert.hashAlgorithm,
156
+ payloadHash: Buffer.from(cert.payloadHash, 'utf8'), // the STRING, wrongly
157
+ publicKey: Buffer.from(cert.publicKey, 'hex'),
158
+ signature: Buffer.from(cert.signature, 'hex'),
159
+ createdAtUnix: Encoding.toUnixSeconds(cert.createdAt)
160
+ })).toString('hex')
161
+ overHex.should.not.equal(cert.proofHash)
162
+ })
163
+ })
164
+
165
+ describe('SPV envelope', function () {
166
+ // The spec's explicit guarantee. If it ever broke, every previously issued
167
+ // certificate would become unverifiable.
168
+ it('never changes proofHash', function () {
169
+ var cert = Certificate.build(PARAMS)
170
+ var withSPV = Certificate.attachSPV(cert, SPV)
171
+ withSPV.proofHash.should.equal(cert.proofHash)
172
+ Certificate.proofHashMatches(withSPV).should.equal(true)
173
+ })
174
+
175
+ it('does not mutate the certificate it was given', function () {
176
+ var cert = Certificate.build(PARAMS)
177
+ Certificate.attachSPV(cert, SPV)
178
+ ;(cert.spv === undefined).should.equal(true)
179
+ })
180
+
181
+ it('defaults format to TSC', function () {
182
+ Certificate.attachSPV(Certificate.build(PARAMS), SPV).spv.format.should.equal('TSC')
183
+ })
184
+
185
+ it('keeps an explicit format, for BUMP or BEEF', function () {
186
+ var withSPV = Certificate.attachSPV(Certificate.build(PARAMS),
187
+ Object.assign({}, SPV, { format: 'BUMP' }))
188
+ withSPV.spv.format.should.equal('BUMP')
189
+ })
190
+ })
191
+
192
+ describe('validateShape', function () {
193
+ it('passes a well-formed certificate', function () {
194
+ Certificate.validateShape(Certificate.build(PARAMS)).should.deep.equal([])
195
+ })
196
+
197
+ it('names every missing required field', function () {
198
+ var problems = Certificate.validateShape({})
199
+ problems.length.should.equal(Certificate.REQUIRED_FIELDS.length)
200
+ problems[0].should.match(/missing required field/)
201
+ })
202
+
203
+ it('rejects a foreign protocol or version', function () {
204
+ var cert = Certificate.build(PARAMS)
205
+ Certificate.validateShape(Object.assign({}, cert, { protocol: 'Other' }))
206
+ .should.include('protocol must be "NotaryHash"')
207
+ Certificate.validateShape(Object.assign({}, cert, { version: 2 }))
208
+ .should.include('unsupported version: 2')
209
+ })
210
+
211
+ it('rejects a hash field of the wrong length or that is not hex', function () {
212
+ var cert = Certificate.build(PARAMS)
213
+ Certificate.validateShape(Object.assign({}, cert, { payloadHash: 'ab' }))
214
+ .should.include('payloadHash must be 32 bytes (64 hex chars)')
215
+ Certificate.validateShape(Object.assign({}, cert, { proofHash: 'zz'.repeat(32) }))
216
+ .should.include('proofHash must be a hex string')
217
+ })
218
+
219
+ // Shape is not verification, and a test says so — otherwise it gets used as one.
220
+ it('says nothing about whether the proofHash is correct', function () {
221
+ var cert = Certificate.build(PARAMS)
222
+ var lying = Object.assign({}, cert, { proofHash: '00'.repeat(32) })
223
+ Certificate.validateShape(lying).should.deep.equal([])
224
+ Certificate.proofHashMatches(lying).should.equal(false)
225
+ })
226
+ })
227
+
228
+ describe('canonicalize', function () {
229
+ it('is RFC 8785 over the certificate', function () {
230
+ var cert = Certificate.build(PARAMS)
231
+ Certificate.canonicalize(cert).should.equal(JCS.stringify(cert))
232
+ })
233
+
234
+ it('sorts keys, so transport order does not matter', function () {
235
+ var cert = Certificate.build(PARAMS)
236
+ var reordered = {}
237
+ Object.keys(cert).reverse().forEach(function (k) { reordered[k] = cert[k] })
238
+ Certificate.canonicalize(reordered).should.equal(Certificate.canonicalize(cert))
239
+ })
240
+
241
+ // proofHash is over the length-prefixed BINARY proof bytes, not over this JSON.
242
+ // Confusing the two produces a value that looks like a proofHash and is not one.
243
+ it('is not what proofHash is computed over', function () {
244
+ var cert = Certificate.build(PARAMS)
245
+ Hash.sha256(Buffer.from(Certificate.canonicalize(cert), 'utf8')).toString('hex')
246
+ .should.not.equal(cert.proofHash)
247
+ })
248
+ })
249
+ })
@@ -0,0 +1,186 @@
1
+ 'use strict'
2
+
3
+ /* global describe, it */
4
+
5
+ // BRC-220 canonical encoding. The property that matters is not that these bytes are
6
+ // stable for us — it is that another implementation reading the spec produces the same
7
+ // ones. So the tests assert the byte layout the spec dictates, field by field, rather
8
+ // than only pinning our own output.
9
+ //
10
+ // The failure this module is most exposed to is a proofHash that is self-consistent and
11
+ // wrong: it verifies against itself, every local test passes, and nobody finds out until
12
+ // a third party tries to verify a certificate. Several tests below exist only to make
13
+ // that shape impossible.
14
+
15
+ require('chai').should()
16
+ var Encoding = require('../../lib/notaryhash/encoding')
17
+ var Hash = require('../../lib/crypto/hash')
18
+
19
+ var FIELDS = {
20
+ algorithm: 'ECDSA-secp256k1',
21
+ hashAlgorithm: 'SHA-256',
22
+ payloadHash: Buffer.alloc(32, 0x11),
23
+ publicKey: Buffer.alloc(33, 0x02),
24
+ signature: Buffer.alloc(71, 0x30),
25
+ createdAtUnix: 1786838400
26
+ }
27
+
28
+ describe('BRC-220 encoding', function () {
29
+ describe('lp()', function () {
30
+ it('is u32be(len) followed by the bytes', function () {
31
+ Encoding.lp(Buffer.from([0xaa, 0xbb])).toString('hex').should.equal('00000002aabb')
32
+ })
33
+
34
+ it('encodes an empty value as a bare zero length', function () {
35
+ Encoding.lp(Buffer.alloc(0)).toString('hex').should.equal('00000000')
36
+ })
37
+
38
+ it('measures BYTES, not characters, for text', function () {
39
+ // 'é' is one character and two UTF-8 bytes. Using .length here would prefix 1,
40
+ // and every proof containing a non-ASCII algorithm name would be unverifiable.
41
+ Encoding.lp('é').toString('hex').should.equal('00000002c3a9')
42
+ Encoding.lp('abc').toString('hex').should.equal('00000003616263')
43
+ })
44
+
45
+ // Length-prefixing exists to make field boundaries unambiguous. If it did not, these
46
+ // two field pairs would concatenate to identical bytes.
47
+ it('keeps ambiguous field splits distinct', function () {
48
+ var a = Buffer.concat([Encoding.lp('ab'), Encoding.lp('c')])
49
+ var b = Buffer.concat([Encoding.lp('a'), Encoding.lp('bc')])
50
+ a.toString('hex').should.not.equal(b.toString('hex'))
51
+ })
52
+ })
53
+
54
+ describe('u64be()', function () {
55
+ it('is 8 bytes, big-endian', function () {
56
+ Encoding.u64be(1).toString('hex').should.equal('0000000000000001')
57
+ Encoding.u64be(1786838400).toString('hex').should.equal('000000006a80fd80')
58
+ })
59
+
60
+ // Date.now() is milliseconds. A caller who forgets to divide gets a timestamp about
61
+ // a thousand years in the future that still encodes cleanly, so the guard is on the
62
+ // input rather than the output.
63
+ it('rejects a fractional value, which is what a millisecond mistake looks like', function () {
64
+ ;(function () { Encoding.u64be(1786838400.5) }).should.throw(/whole seconds/)
65
+ })
66
+
67
+ it('rejects non-finite and negative values', function () {
68
+ ;(function () { Encoding.u64be(NaN) }).should.throw(/finite/)
69
+ ;(function () { Encoding.u64be(-1) }).should.throw(/negative/)
70
+ })
71
+ })
72
+
73
+ describe('toUnixSeconds()', function () {
74
+ it('converts an ISO 8601 string to whole seconds', function () {
75
+ Encoding.toUnixSeconds('2026-08-16T00:00:00.000Z').should.equal(1786838400)
76
+ })
77
+
78
+ // Certificates carry millisecond precision in createdAt; the canonical bytes do not.
79
+ // Two implementations must agree on the fractional part, and truncation is the only
80
+ // choice that never moves a timestamp forward.
81
+ it('truncates rather than rounds', function () {
82
+ Encoding.toUnixSeconds('2026-08-16T00:00:00.999Z').should.equal(1786838400)
83
+ })
84
+
85
+ it('rejects an unparseable date', function () {
86
+ ;(function () { Encoding.toUnixSeconds('not-a-date') }).should.throw(/not a valid date/)
87
+ })
88
+ })
89
+
90
+ describe('canonicalBytes()', function () {
91
+ // The layout, asserted against a hand-built expectation rather than against the
92
+ // function's own output — otherwise this only proves the function is deterministic.
93
+ it('lays the fields out exactly as the spec specifies', function () {
94
+ var expected = Buffer.concat([
95
+ Encoding.lp('NotaryHash/1.0'),
96
+ Buffer.from([1]),
97
+ Encoding.lp('ECDSA-secp256k1'),
98
+ Encoding.lp('SHA-256'),
99
+ Encoding.lp(FIELDS.payloadHash),
100
+ Encoding.lp(FIELDS.publicKey),
101
+ Encoding.lp(FIELDS.signature),
102
+ Encoding.u64be(FIELDS.createdAtUnix)
103
+ ])
104
+ Encoding.canonicalBytes(FIELDS).toString('hex').should.equal(expected.toString('hex'))
105
+ })
106
+
107
+ it('opens with the protocol prefix and the version byte', function () {
108
+ var bytes = Encoding.canonicalBytes(FIELDS)
109
+ bytes.slice(0, 4).readUInt32BE(0).should.equal(14) // len('NotaryHash/1.0')
110
+ bytes.slice(4, 18).toString('utf8').should.equal('NotaryHash/1.0')
111
+ bytes[18].should.equal(1) // u8(version)
112
+ })
113
+
114
+ it('ends with the timestamp', function () {
115
+ var bytes = Encoding.canonicalBytes(FIELDS)
116
+ bytes.slice(-8).toString('hex').should.equal(Encoding.u64be(FIELDS.createdAtUnix).toString('hex'))
117
+ })
118
+
119
+ // THE test for this module. GDAF once signed a serialization that silently omitted
120
+ // credentialSubject, so a forger could rewrite the claims without breaking the proof.
121
+ // Every field must move the hash, or it is not covered by it.
122
+ it('covers every field — changing any one changes the hash', function () {
123
+ var base = Encoding.proofHash(FIELDS).toString('hex')
124
+ var mutations = {
125
+ algorithm: 'ML-DSA-65',
126
+ hashAlgorithm: 'SHA-512',
127
+ payloadHash: Buffer.alloc(32, 0x12),
128
+ publicKey: Buffer.alloc(33, 0x03),
129
+ signature: Buffer.alloc(71, 0x31),
130
+ createdAtUnix: FIELDS.createdAtUnix + 1
131
+ }
132
+ Object.keys(mutations).forEach(function (field) {
133
+ var altered = Object.assign({}, FIELDS)
134
+ altered[field] = mutations[field]
135
+ Encoding.proofHash(altered).toString('hex')
136
+ .should.not.equal(base, field + ' does not affect proofHash, so it is not covered by it')
137
+ })
138
+ })
139
+
140
+ // Hex is what certificates carry, and hex is twice as long as the bytes it encodes.
141
+ // Accepting it here would produce a proof that verifies locally and nowhere else.
142
+ it('refuses a hex string where raw bytes are required', function () {
143
+ var withHex = Object.assign({}, FIELDS, { payloadHash: FIELDS.payloadHash.toString('hex') })
144
+ ;(function () { Encoding.canonicalBytes(withHex) }).should.throw(/must be a Buffer/)
145
+ })
146
+
147
+ it('names the offending field and points at the hex trap', function () {
148
+ var withHex = Object.assign({}, FIELDS, { signature: FIELDS.signature.toString('hex') })
149
+ ;(function () { Encoding.canonicalBytes(withHex) }).should.throw(/signature.*hex/)
150
+ })
151
+
152
+ it('requires the string fields to be present and non-empty', function () {
153
+ ;(function () {
154
+ Encoding.canonicalBytes(Object.assign({}, FIELDS, { algorithm: '' }))
155
+ }).should.throw(/algorithm/)
156
+ ;(function () {
157
+ Encoding.canonicalBytes(Object.assign({}, FIELDS, { hashAlgorithm: undefined }))
158
+ }).should.throw(/hashAlgorithm/)
159
+ })
160
+
161
+ it('handles a post-quantum-sized signature', function () {
162
+ // SLH-DSA signatures run to tens of kilobytes; the u32be length prefix must carry
163
+ // them without truncation.
164
+ var big = Object.assign({}, FIELDS, { signature: Buffer.alloc(49856, 0x7f) })
165
+ var bytes = Encoding.canonicalBytes(big)
166
+ var sigLenOffset = bytes.length - 8 - 49856 - 4
167
+ bytes.readUInt32BE(sigLenOffset).should.equal(49856)
168
+ })
169
+ })
170
+
171
+ describe('proofHash()', function () {
172
+ it('is SHA-256 of the canonical bytes', function () {
173
+ Encoding.proofHash(FIELDS).toString('hex')
174
+ .should.equal(Hash.sha256(Encoding.canonicalBytes(FIELDS)).toString('hex'))
175
+ })
176
+
177
+ it('is 32 bytes', function () {
178
+ Encoding.proofHash(FIELDS).length.should.equal(32)
179
+ })
180
+
181
+ it('is deterministic', function () {
182
+ Encoding.proofHash(FIELDS).toString('hex')
183
+ .should.equal(Encoding.proofHash(Object.assign({}, FIELDS)).toString('hex'))
184
+ })
185
+ })
186
+ })