@smartledger/bsv 8.2.0 → 8.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,140 @@
1
+ 'use strict'
2
+
3
+ /* global describe, it */
4
+
5
+ // BRC-220 batch mode: what is in a Merkle leaf.
6
+ //
7
+ // The spec writes `leaf = SHA256(0x00 ‖ d)` and never binds `d`. That is RFC 6962's own
8
+ // generic notation for the construction, quoted to identify WHICH tree — domain
9
+ // separation, the power-of-two split, no duplicated last leaf — not to define the leaf's
10
+ // contents. `canonicalBytes` appears once in the whole document, in the proofHash
11
+ // definition, and nowhere in the batch text.
12
+ //
13
+ // This library reads `d` as proofHash. The alternative reading, d = canonicalBytes, is
14
+ // equally sound cryptographically and produces a DIFFERENT root — so the two do not
15
+ // interoperate, and the failure is silent: the fold just does not reach the root.
16
+ //
17
+ // These tests pin the choice, and pin the divergence too. A comment saying "we use
18
+ // proofHash" would not fail if someone changed it; this does.
19
+ //
20
+ // Reasoning and proposed spec text: docs/BRC220_BATCH_LEAF_AMENDMENT.md
21
+
22
+ require('chai').should()
23
+ var NotaryHash = require('../../lib/notaryhash')
24
+ var Merkle = require('../../lib/notaryhash/merkle')
25
+ var Hash = require('../../lib/crypto/hash')
26
+ var NotaryScript = require('../../lib/notaryhash/script')
27
+
28
+ // Four fixed proofHash values, standing in for a four-proof batch.
29
+ var PROOF_HASHES = [
30
+ '00'.repeat(31) + '01',
31
+ '00'.repeat(31) + '02',
32
+ 'ab'.repeat(32),
33
+ 'ff'.repeat(32)
34
+ ].map(function (h) { return Buffer.from(h, 'hex') })
35
+
36
+ function batchCertificate (index, leaves) {
37
+ return {
38
+ mode: NotaryScript.MODE.BATCH,
39
+ proofHash: leaves[index].toString('hex'),
40
+ merkle: {
41
+ root: Merkle.root(leaves).toString('hex'),
42
+ leafIndex: index,
43
+ leafCount: leaves.length,
44
+ path: Merkle.path(leaves, index).map(function (n) { return n.toString('hex') })
45
+ }
46
+ }
47
+ }
48
+
49
+ describe('BRC-220 batch leaf', function () {
50
+ describe('the leaf datum is proofHash', function () {
51
+ it('a leaf is SHA-256(0x00 || proofHash)', function () {
52
+ var proofHash = PROOF_HASHES[0]
53
+ Merkle.hashLeaf(proofHash).toString('hex').should.equal(
54
+ Hash.sha256(Buffer.concat([Buffer.from([0x00]), proofHash])).toString('hex')
55
+ )
56
+ })
57
+
58
+ // Stated the long way round, because this is the identity the spec leaves open.
59
+ it('is therefore SHA-256(0x00 || SHA-256(canonicalBytes))', function () {
60
+ var canonicalBytes = Buffer.from('any canonical proof bytes at all')
61
+ var proofHash = Hash.sha256(canonicalBytes)
62
+ Merkle.hashLeaf(proofHash).toString('hex').should.equal(
63
+ Hash.sha256(Buffer.concat([
64
+ Buffer.from([0x00]), Hash.sha256(canonicalBytes)
65
+ ])).toString('hex')
66
+ )
67
+ })
68
+
69
+ it('verifies inclusion for every leaf of a four-proof batch', function () {
70
+ for (var i = 0; i < PROOF_HASHES.length; i++) {
71
+ var report = NotaryHash.verifyBatchInclusion(batchCertificate(i, PROOF_HASHES))
72
+ report.valid.should.equal(true, 'leaf ' + i + ' should verify')
73
+ report.errors.should.deep.equal([])
74
+ }
75
+ })
76
+ })
77
+
78
+ describe('the two readings of `d` are not interchangeable', function () {
79
+ var canonicalBytesSet = [
80
+ Buffer.from('proof one canonical bytes'),
81
+ Buffer.from('proof two canonical bytes'),
82
+ Buffer.from('proof three canonical bytes'),
83
+ Buffer.from('proof four canonical bytes')
84
+ ]
85
+ var proofHashes = canonicalBytesSet.map(function (b) { return Hash.sha256(b) })
86
+
87
+ it('produces a different root under each reading', function () {
88
+ Merkle.root(proofHashes).toString('hex')
89
+ .should.not.equal(Merkle.root(canonicalBytesSet).toString('hex'))
90
+ })
91
+
92
+ // The interoperability failure, made concrete. This is what a batch built by an
93
+ // implementation using the other reading would look like to this verifier.
94
+ it('REJECTS a certificate whose tree was built over canonicalBytes', function () {
95
+ var certificate = {
96
+ mode: NotaryScript.MODE.BATCH,
97
+ proofHash: proofHashes[1].toString('hex'),
98
+ merkle: {
99
+ // Root and path from the canonicalBytes tree — the other reading.
100
+ root: Merkle.root(canonicalBytesSet).toString('hex'),
101
+ leafIndex: 1,
102
+ leafCount: 4,
103
+ path: Merkle.path(canonicalBytesSet, 1).map(function (n) { return n.toString('hex') })
104
+ }
105
+ }
106
+ var report = NotaryHash.verifyBatchInclusion(certificate)
107
+ report.valid.should.equal(false)
108
+ report.errors.should.deep.equal(['merkle inclusion proof does not fold to the batch root'])
109
+ })
110
+
111
+ // Both are sound; neither is being called wrong. The point is only that a choice had
112
+ // to be made and that it is checkable.
113
+ it('both readings are domain-separated and second-preimage resistant', function () {
114
+ var leafBytes = Buffer.alloc(64, 7)
115
+ Merkle.hashLeaf(leafBytes).toString('hex')
116
+ .should.not.equal(Merkle.hashNode(Buffer.alloc(32, 7), Buffer.alloc(32, 7)).toString('hex'))
117
+ })
118
+ })
119
+
120
+ describe('the verdict is a strict report, not a truthy object', function () {
121
+ it('reports valid:false rather than throwing on a malformed merkle object', function () {
122
+ var report = NotaryHash.verifyBatchInclusion({
123
+ mode: NotaryScript.MODE.BATCH,
124
+ proofHash: PROOF_HASHES[0].toString('hex'),
125
+ merkle: { root: 'not-hex', leafIndex: 0, leafCount: 1, path: [] }
126
+ })
127
+ report.valid.should.equal(false)
128
+ report.errors.length.should.be.above(0)
129
+ })
130
+
131
+ it('rejects a non-batch certificate by mode', function () {
132
+ var report = NotaryHash.verifyBatchInclusion({
133
+ mode: NotaryScript.MODE.FULL,
134
+ proofHash: PROOF_HASHES[0].toString('hex')
135
+ })
136
+ report.valid.should.equal(false)
137
+ report.errors.should.deep.equal(['certificate is not in batch mode'])
138
+ })
139
+ })
140
+ })
@@ -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
+ })