@smartledger/bsv 8.2.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.
@@ -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
+ })
@@ -0,0 +1,181 @@
1
+ 'use strict'
2
+
3
+ /* global describe, it */
4
+
5
+ // RFC 6962 Merkle trees, for BRC-220 batch mode.
6
+ //
7
+ // The first version of foldPath here descended from the root by splitting at the largest
8
+ // power of two, mirroring how root() builds the tree. It round-tripped perfectly for
9
+ // powers of two and failed for 21 of the 45 leaves in trees of size 1..9 — which is
10
+ // exactly why the published vectors below matter more than any round-trip test. A tree
11
+ // that agrees with itself is not evidence.
12
+
13
+ require('chai').should()
14
+ var Merkle = require('../../lib/notaryhash/merkle')
15
+ var Hash = require('../../lib/crypto/hash')
16
+
17
+ // The canonical RFC 6962 / Certificate Transparency inputs.
18
+ var D = ['', '00', '10', '2021', '3031', '40414243', '5051525354555657',
19
+ '606162636465666768696a6b6c6d6e6f'].map(function (h) { return Buffer.from(h, 'hex') })
20
+
21
+ describe('RFC 6962 Merkle tree', function () {
22
+ describe('published vectors', function () {
23
+ // External validation. Everything else in this file could be internally consistent
24
+ // and wrong; these numbers come from outside this codebase.
25
+ var EXPECTED = {
26
+ 0: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
27
+ 1: '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d',
28
+ 2: 'fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125',
29
+ 4: 'd37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7',
30
+ 7: 'ddb89be403809e325750d3d263cd78929c2942b7942a34b77e122c9594a74c8c',
31
+ 8: '5dc9da79a70659a9ad559cb701ded9a2ab9d823aad2f4960cfe370eff4604328'
32
+ }
33
+
34
+ Object.keys(EXPECTED).forEach(function (n) {
35
+ it('MTH of ' + n + ' leaves matches the published root', function () {
36
+ Merkle.root(D.slice(0, Number(n))).toString('hex').should.equal(EXPECTED[n])
37
+ })
38
+ })
39
+ })
40
+
41
+ describe('construction', function () {
42
+ it('hashes the empty tree as SHA-256 of the empty string, not zeroes', function () {
43
+ Merkle.root([]).toString('hex').should.equal(Hash.sha256(Buffer.alloc(0)).toString('hex'))
44
+ Merkle.root([]).toString('hex').should.not.equal('00'.repeat(32))
45
+ })
46
+
47
+ it('domain-separates leaves from internal nodes', function () {
48
+ Merkle.hashLeaf(Buffer.from('ab', 'hex')).toString('hex')
49
+ .should.equal(Hash.sha256(Buffer.from('00ab', 'hex')).toString('hex'))
50
+ Merkle.hashNode(Buffer.alloc(32, 1), Buffer.alloc(32, 2)).toString('hex')
51
+ .should.equal(Hash.sha256(Buffer.concat([
52
+ Buffer.from([0x01]), Buffer.alloc(32, 1), Buffer.alloc(32, 2)
53
+ ])).toString('hex'))
54
+ })
55
+
56
+ // Without the 0x00/0x01 prefixes an internal node could be reinterpreted as a leaf,
57
+ // which is the second-preimage attack Bitcoin's tree is open to.
58
+ it('gives a leaf and a node over the same bytes different hashes', function () {
59
+ var payload = Buffer.alloc(64, 7)
60
+ Merkle.hashLeaf(payload).toString('hex')
61
+ .should.not.equal(Merkle.hashNode(Buffer.alloc(32, 7), Buffer.alloc(32, 7)).toString('hex'))
62
+ })
63
+
64
+ // The split point, not the midpoint. For n=5 the RFC splits 4/1.
65
+ it('splits at the largest power of two below n', function () {
66
+ var expected = { 2: 1, 3: 2, 4: 2, 5: 4, 6: 4, 7: 4, 8: 4, 9: 8, 16: 8, 17: 16 }
67
+ Object.keys(expected).forEach(function (n) {
68
+ Merkle.largestPowerOfTwoBelow(Number(n)).should.equal(expected[n])
69
+ })
70
+ })
71
+ })
72
+
73
+ // The property the plan named as the one that would ship silently: a Bitcoin-style
74
+ // tree over the same leaves must produce a DIFFERENT root.
75
+ describe('is not the Bitcoin tree', function () {
76
+ function bitcoinStyleRoot (leaves) {
77
+ var level = leaves.map(function (l) { return Hash.sha256sha256(l) })
78
+ while (level.length > 1) {
79
+ var next = []
80
+ for (var i = 0; i < level.length; i += 2) {
81
+ var left = level[i]
82
+ var right = i + 1 < level.length ? level[i + 1] : left // duplicated
83
+ next.push(Hash.sha256sha256(Buffer.concat([left, right])))
84
+ }
85
+ level = next
86
+ }
87
+ return level[0]
88
+ }
89
+
90
+ it('produces a different root over the same leaves', function () {
91
+ var leaves = D.slice(0, 4)
92
+ Merkle.root(leaves).toString('hex')
93
+ .should.not.equal(bitcoinStyleRoot(leaves).toString('hex'))
94
+ })
95
+
96
+ it('differs for an odd leaf count, where Bitcoin duplicates and RFC 6962 does not', function () {
97
+ var leaves = D.slice(0, 3)
98
+ Merkle.root(leaves).toString('hex')
99
+ .should.not.equal(bitcoinStyleRoot(leaves).toString('hex'))
100
+ })
101
+ })
102
+
103
+ describe('inclusion proofs', function () {
104
+ it('round-trips every leaf for every tree size 1..33', function () {
105
+ var failures = []
106
+ for (var n = 1; n <= 33; n++) {
107
+ var leaves = []
108
+ for (var i = 0; i < n; i++) leaves.push(Buffer.from([i & 0xff, n & 0xff]))
109
+ var root = Merkle.root(leaves)
110
+ for (var j = 0; j < n; j++) {
111
+ if (!Merkle.verifyInclusion(leaves[j], j, n, Merkle.path(leaves, j), root)) {
112
+ failures.push('n=' + n + ' i=' + j)
113
+ }
114
+ }
115
+ }
116
+ failures.should.deep.equal([])
117
+ })
118
+
119
+ it('rejects a proof for the wrong leaf', function () {
120
+ var leaves = D.slice(0, 8)
121
+ var root = Merkle.root(leaves)
122
+ Merkle.verifyInclusion(D[1], 0, 8, Merkle.path(leaves, 0), root).should.equal(false)
123
+ })
124
+
125
+ it('rejects a proof at the wrong index', function () {
126
+ var leaves = D.slice(0, 8)
127
+ var root = Merkle.root(leaves)
128
+ Merkle.verifyInclusion(leaves[3], 4, 8, Merkle.path(leaves, 3), root).should.equal(false)
129
+ })
130
+
131
+ // leafCount changes the tree shape — but only for SOME indices. On an 8-leaf tree
132
+ // claimed as 7, indices 0..5 fold identically and only 6 and 7 differ, because the
133
+ // left region of the tree is the same shape either way.
134
+ //
135
+ // That is a property worth knowing rather than a defect: it means an inclusion proof
136
+ // alone cannot be trusted to detect a wrong leafCount, which is why
137
+ // NotaryHash.recordMatchesCertificate compares the certificate's count against the
138
+ // authoritative u32be in the on-chain record instead of assuming the fold implies it.
139
+ it('rejects a wrong leafCount where the shape differs', function () {
140
+ var leaves = D.slice(0, 8)
141
+ var root = Merkle.root(leaves)
142
+ Merkle.verifyInclusion(leaves[6], 6, 7, Merkle.path(leaves, 6), root).should.equal(false)
143
+ Merkle.verifyInclusion(leaves[7], 7, 7, Merkle.path(leaves, 7), root).should.equal(false)
144
+ })
145
+
146
+ it('does NOT catch a wrong leafCount where the shape is the same', function () {
147
+ var leaves = D.slice(0, 8)
148
+ var root = Merkle.root(leaves)
149
+ // Documented, not desired. The on-chain leafCount is what closes this.
150
+ Merkle.verifyInclusion(leaves[3], 3, 7, Merkle.path(leaves, 3), root).should.equal(true)
151
+ })
152
+
153
+ it('rejects a truncated or padded path', function () {
154
+ var leaves = D.slice(0, 8)
155
+ var root = Merkle.root(leaves)
156
+ var path = Merkle.path(leaves, 3)
157
+ Merkle.verifyInclusion(leaves[3], 3, 8, path.slice(0, -1), root).should.equal(false)
158
+ Merkle.verifyInclusion(leaves[3], 3, 8, path.concat([Buffer.alloc(32)]), root).should.equal(false)
159
+ })
160
+
161
+ it('rejects a tampered sibling', function () {
162
+ var leaves = D.slice(0, 8)
163
+ var root = Merkle.root(leaves)
164
+ var path = Merkle.path(leaves, 3)
165
+ path[0] = Buffer.alloc(32, 0xff)
166
+ Merkle.verifyInclusion(leaves[3], 3, 8, path, root).should.equal(false)
167
+ })
168
+
169
+ it('returns a strict boolean and never throws on malformed input', function () {
170
+ Merkle.verifyInclusion(D[0], 0, 1, [], Merkle.root([D[0]])).should.be.a('boolean')
171
+ Merkle.verifyInclusion(null, 0, 1, [], Buffer.alloc(32)).should.equal(false)
172
+ Merkle.verifyInclusion(D[0], 5, 1, [], Buffer.alloc(32)).should.equal(false)
173
+ Merkle.verifyInclusion(D[0], 0, 1, [], 'not-a-buffer').should.equal(false)
174
+ })
175
+
176
+ it('gives an empty path for a single-leaf tree', function () {
177
+ Merkle.path([D[0]], 0).should.deep.equal([])
178
+ Merkle.verifyInclusion(D[0], 0, 1, [], Merkle.hashLeaf(D[0])).should.equal(true)
179
+ })
180
+ })
181
+ })