@smartledger/bsv 7.0.2 → 7.2.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.
@@ -23,47 +23,118 @@ var ORD = Buffer.from('ord', 'utf8')
23
23
  function scriptClass () { return bsv.Script }
24
24
  function op () { return bsv.Opcode }
25
25
 
26
+ /** Describe a rejected value for an error message, without dumping its contents. */
27
+ function typeName (v) {
28
+ if (v === null) return 'null'
29
+ if (v === undefined) return 'undefined'
30
+ if (Array.isArray(v)) return 'an array'
31
+ var t = typeof v
32
+ return (t === 'object' ? 'an ' : 'a ') + t
33
+ }
34
+
35
+ /**
36
+ * Coerce a caller-supplied field to bytes.
37
+ *
38
+ * Only strings and Buffers are accepted. Everything else is rejected rather than run
39
+ * through `String(v)`: an inscription is permanent, and stringifying an object writes
40
+ * the literal text `[object Object]` to the chain, which is never what the caller meant.
41
+ */
42
+ function toBuf (v, name) {
43
+ if (Buffer.isBuffer(v)) return v
44
+ if (typeof v === 'string') return Buffer.from(v, 'utf8')
45
+ throw new Error(name + ' must be a string or Buffer, got ' + typeName(v))
46
+ }
47
+
48
+ /** Fields callers reach for when they mean `content`; named back to them on error. */
49
+ var CONTENT_ALIASES = ['data', 'body', 'payload', 'text', 'message']
50
+
26
51
  /** Resolve a base locking script from a Script, an Address, or an address string. */
27
52
  function resolveLock (params) {
28
53
  var Script = scriptClass()
29
- if (params.lock) {
30
- if (params.lock instanceof Script) return params.lock
31
- if (Buffer.isBuffer(params.lock)) return Script.fromBuffer(params.lock)
32
- if (typeof params.lock === 'string') return Script.fromHex(params.lock)
33
- throw new Error('lock must be a Script, Buffer, or hex string')
54
+ var hasLock = params.lock != null
55
+ var hasAddress = params.address != null
56
+
57
+ // `lock` used to win silently. Two different owners in one call is a mistake worth
58
+ // surfacing, not resolving by precedence.
59
+ if (hasLock && hasAddress) {
60
+ throw new Error('buildInscription accepts `lock` or `address`, not both — they name ' +
61
+ 'different owners and one would be silently ignored')
62
+ }
63
+
64
+ if (hasLock) {
65
+ var lock
66
+ if (params.lock instanceof Script) lock = params.lock
67
+ else if (Buffer.isBuffer(params.lock)) lock = Script.fromBuffer(params.lock)
68
+ else if (typeof params.lock === 'string') lock = Script.fromHex(params.lock)
69
+ else throw new Error('lock must be a Script, Buffer, or hex string, got ' + typeName(params.lock))
70
+
71
+ // An empty base lock leaves nothing but the inert envelope, and the envelope is
72
+ // skipped at execution — so whatever the spender pushes is the final stack and the
73
+ // ordinal is anyone-can-spend. Only a caller appending the envelope to a lock it
74
+ // supplies itself (as ordlock.js does) legitimately wants this.
75
+ if (!lock.chunks.length && !params.allowEmptyLock) {
76
+ throw new Error('lock is empty: the inscription would carry no locking script at ' +
77
+ 'all and the ordinal would be spendable by anyone. Pass a real lock, or ' +
78
+ '{ allowEmptyLock: true } if you are appending this envelope to your own script')
79
+ }
80
+ return lock
34
81
  }
35
- if (params.address) {
82
+
83
+ if (hasAddress) {
36
84
  var addr = (params.address instanceof bsv.Address)
37
85
  ? params.address
38
86
  : bsv.Address.fromString(String(params.address))
39
87
  return Script.buildPublicKeyHashOut(addr)
40
88
  }
41
- throw new Error('buildInscription requires an address or a lock script')
42
- }
43
89
 
44
- function toBuf (v, enc) {
45
- if (Buffer.isBuffer(v)) return v
46
- if (v == null) return Buffer.alloc(0)
47
- return Buffer.from(String(v), enc || 'utf8')
90
+ throw new Error('buildInscription requires an address or a lock script')
48
91
  }
49
92
 
50
93
  /**
51
94
  * Build a 1Sat Ordinals inscription locking script: a base lock followed by the
52
95
  * inert `OP_FALSE OP_IF ... OP_ENDIF` envelope carrying the content.
53
96
  *
97
+ * `content` is required. An inscription with no body is a well-formed script that
98
+ * inscribes nothing, so omitting it throws rather than silently producing one; pass an
99
+ * explicit `''` if an empty payload is genuinely what you want.
100
+ *
54
101
  * @param {object} params
55
- * @param {string|Buffer} params.contentType e.g. 'text/plain', 'image/png'
56
- * @param {string|Buffer} params.content the inscription body
57
- * @param {Script|Buffer|string} [params.lock] base locking script (overrides address)
58
- * @param {Address|string} [params.address] P2PKH owner (used if no `lock`)
102
+ * @param {string|Buffer} params.content the inscription body (required)
103
+ * @param {string|Buffer} [params.contentType] e.g. 'text/plain', 'image/png'.
104
+ * Defaults to 'text/plain' for string content; required for Buffer content, which
105
+ * carries no hint about what it is.
106
+ * @param {Script|Buffer|string} [params.lock] base locking script (mutually exclusive
107
+ * with `address`)
108
+ * @param {Address|string} [params.address] P2PKH owner (mutually exclusive with `lock`)
109
+ * @param {boolean} [params.allowEmptyLock] permit an empty base lock; see resolveLock
59
110
  * @returns {Script} the full inscription locking script
60
111
  */
61
112
  function buildInscription (params) {
62
113
  params = params || {}
63
114
  var Opcode = op()
64
115
  var lock = resolveLock(params)
65
- var contentType = toBuf(params.contentType || 'text/plain')
66
- var content = toBuf(params.content)
116
+
117
+ if (params.content == null) {
118
+ var alias = CONTENT_ALIASES.filter(function (k) { return params[k] != null })[0]
119
+ throw new Error('buildInscription requires `content`' +
120
+ (alias ? ' — received `' + alias + '`, which is not read' : '') +
121
+ '. Omitting it would inscribe an empty payload; pass content: \'\' if that is intended')
122
+ }
123
+ var content = toBuf(params.content, 'content')
124
+
125
+ var contentType
126
+ if (params.contentType == null) {
127
+ // A Buffer is opaque — defaulting it to text/plain mislabels binary content on a
128
+ // permanent record, so make the caller declare it.
129
+ if (Buffer.isBuffer(params.content)) {
130
+ throw new Error('contentType is required when content is a Buffer (e.g. ' +
131
+ "'image/png', 'application/octet-stream') — it cannot be inferred from bytes")
132
+ }
133
+ contentType = Buffer.from('text/plain', 'utf8')
134
+ } else {
135
+ contentType = toBuf(params.contentType, 'contentType')
136
+ if (!contentType.length) throw new Error('contentType must not be empty')
137
+ }
67
138
 
68
139
  // Clone the base lock so we never mutate the caller's Script.
69
140
  var s = scriptClass().fromBuffer(lock.toBuffer())
@@ -84,6 +155,14 @@ function chunkIsOp (chunk, opcodenum) {
84
155
 
85
156
  /**
86
157
  * Parse a 1Sat Ordinals inscription out of a locking script.
158
+ *
159
+ * The 1Sat spec allows the locking script to be *prepended or appended* to the
160
+ * envelope ("A locking script (typically P2PKH) is then prepended/appended to the
161
+ * inscription script, optionally separated by OP_CODESEPARATOR"). `lock` is therefore
162
+ * the whole script minus the envelope, in script order — not merely what precedes it.
163
+ * A separating OP_CODESEPARATOR is kept, because it is genuinely part of the script
164
+ * that runs and affects the sighash.
165
+ *
87
166
  * @param {Script|Buffer|string} script
88
167
  * @returns {null|{ contentType: string, content: Buffer, contentText: string, lock: Script }}
89
168
  * null if the script carries no inscription envelope.
@@ -108,16 +187,13 @@ function parseInscription (script) {
108
187
  }
109
188
  if (start === -1) return null
110
189
 
111
- // Everything before the envelope is the base lock.
112
- var lock = new Script()
113
- for (var k = 0; k < start; k++) lock.chunks.push(chunks[k])
114
-
115
190
  // Walk fields after "ord" until OP_ENDIF: OP_1 => content-type, OP_0 => body.
116
191
  var contentType = Buffer.alloc(0)
117
192
  var content = Buffer.alloc(0)
193
+ var end = chunks.length // index of OP_ENDIF, or past the end if the envelope is unterminated
118
194
  for (var j = start + 3; j < chunks.length; j++) {
119
195
  var c = chunks[j]
120
- if (chunkIsOp(c, Opcode.OP_ENDIF)) break
196
+ if (chunkIsOp(c, Opcode.OP_ENDIF)) { end = j; break }
121
197
  if (chunkIsOp(c, Opcode.OP_1) && chunks[j + 1] && chunks[j + 1].buf) {
122
198
  contentType = chunks[j + 1].buf; j++
123
199
  } else if (chunkIsOp(c, Opcode.OP_0) && chunks[j + 1] && chunks[j + 1].buf) {
@@ -125,6 +201,13 @@ function parseInscription (script) {
125
201
  }
126
202
  }
127
203
 
204
+ // The lock is everything outside the envelope. Taking only what precedes it dropped
205
+ // the lock entirely for the spec-legal appended form, reporting an owned ordinal as
206
+ // having no locking script at all.
207
+ var lock = new Script()
208
+ for (var k = 0; k < start; k++) lock.chunks.push(chunks[k])
209
+ for (var m = end + 1; m < chunks.length; m++) lock.chunks.push(chunks[m])
210
+
128
211
  return {
129
212
  contentType: contentType.toString('utf8'),
130
213
  content: content,
@@ -140,11 +223,18 @@ function isInscription (script) {
140
223
 
141
224
  /**
142
225
  * Build the 1-satoshi Transaction.Output carrying an inscription.
226
+ * @param {object} params as buildInscription, plus:
227
+ * @param {number} [params.satoshis] defaults to 1 (the 1Sat Ordinals convention)
143
228
  * @returns {Transaction.Output}
144
229
  */
145
230
  function createInscriptionOutput (params) {
146
231
  params = params || {}
147
232
  var satoshis = params.satoshis != null ? params.satoshis : 1
233
+ // Output rejects negatives and fractions, but 0 and the string '1' slipped through:
234
+ // a 0-sat output carries no ordinal at all.
235
+ if (typeof satoshis !== 'number' || !Number.isInteger(satoshis) || satoshis < 1) {
236
+ throw new Error('satoshis must be a positive integer (1 for a standard 1Sat ordinal)')
237
+ }
148
238
  return new bsv.Transaction.Output({
149
239
  script: buildInscription(params),
150
240
  satoshis: satoshis
@@ -182,6 +182,7 @@ function buildOrdLock (params) {
182
182
  if (params.inscription) {
183
183
  var env = inscription.buildInscription({
184
184
  lock: new Script(), // envelope only; the covenant above is the real lock
185
+ allowEmptyLock: true, // ...which is why the empty-lock guard does not apply here
185
186
  contentType: params.inscription.contentType,
186
187
  content: params.inscription.content
187
188
  })
package/lib/util/id.js ADDED
@@ -0,0 +1,48 @@
1
+ 'use strict'
2
+
3
+ var Random = require('../crypto/random')
4
+
5
+ /**
6
+ * RFC 4122 version 4 UUID, drawn from the CSPRNG.
7
+ *
8
+ * The engine's built-in PRNG is not an acceptable source here: V8 implements it
9
+ * with xorshift128+, whose internal state is recoverable from a handful of
10
+ * outputs, so one emitted identifier can expose every later id from the same
11
+ * process.
12
+ *
13
+ * @returns {String} e.g. '1b4e28ba-2fa1-4d9b-b6f7-1e3c9a8d5c02'
14
+ */
15
+ function uuid4 () {
16
+ var bytes = Random.getRandomBuffer(16)
17
+
18
+ bytes[6] = (bytes[6] & 0x0f) | 0x40 // version 4
19
+ bytes[8] = (bytes[8] & 0x3f) | 0x80 // variant 10x
20
+
21
+ var hex = bytes.toString('hex')
22
+ return [
23
+ hex.substring(0, 8),
24
+ hex.substring(8, 12),
25
+ hex.substring(12, 16),
26
+ hex.substring(16, 20),
27
+ hex.substring(20, 32)
28
+ ].join('-')
29
+ }
30
+
31
+ /**
32
+ * Opaque identifier of `length` hex characters, drawn from the CSPRNG.
33
+ * Entropy is 4 bits per character, so callers choose `length` to bound
34
+ * collision probability across the population of ids they expect to mint.
35
+ *
36
+ * @param {Number} length - number of hex characters
37
+ * @returns {String}
38
+ */
39
+ function randomHex (length) {
40
+ return Random.getRandomBuffer(Math.ceil(length / 2))
41
+ .toString('hex')
42
+ .substring(0, length)
43
+ }
44
+
45
+ module.exports = {
46
+ uuid4: uuid4,
47
+ randomHex: randomHex
48
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smartledger/bsv",
3
- "version": "7.0.2",
3
+ "version": "7.2.0",
4
4
  "description": "🚀 Complete Bitcoin SV development framework with legally-recognizable DID:web + W3C VC-JWT toolkit, Legal Token Protocol (LTP), Global Digital Attestation Framework (GDAF), StatusList2021 revocation, and 16 flexible loading options. Standards-based credentials with ES256/ES256K support, on-chain BSV anchoring, and comprehensive Bitcoin SV API. Perfect for legal tokens, verifiable credentials, DeFi, smart contracts, and secure Bitcoin applications.",
5
5
  "author": "SmartLedger Technology <hello@smartledger.technology> (https://smartledger.technology)",
6
6
  "homepage": "https://github.com/codenlighten/smartledger-bsv#readme",
@@ -16,23 +16,30 @@ var fs = require('fs')
16
16
  var path = require('path')
17
17
  var execFileSync = require('child_process').execFileSync
18
18
  var spawnSync = require('child_process').spawnSync
19
- var gen = require('../../scripts/gen-esm-wrapper')
20
19
 
21
20
  var ROOT = path.resolve(__dirname, '../..')
22
21
  var MJS = path.join(ROOT, 'index.mjs')
23
22
 
23
+ // scripts/ is dev tooling and is not published, so the two checks that
24
+ // regenerate index.mjs can only run from a checkout. The ESM import checks below
25
+ // run everywhere, including against an installed copy. Presence is tested rather
26
+ // than try/catch'd so a broken generator still fails loudly in the repo.
27
+ var GEN = path.join(ROOT, 'scripts', 'gen-esm-wrapper.js')
28
+ var gen = fs.existsSync(GEN) ? require(GEN) : null
29
+ var itFromCheckout = gen ? it : it.skip
30
+
24
31
  function runEsm (body) {
25
32
  return execFileSync(process.execPath, ['--input-type=module', '-e', body],
26
33
  { cwd: ROOT, stdio: 'pipe' })
27
34
  }
28
35
 
29
36
  describe('ESM wrapper (index.mjs)', function () {
30
- it('is in sync with the CJS surface (no drift)', function () {
37
+ itFromCheckout('is in sync with the CJS surface (no drift)', function () {
31
38
  var onDisk = fs.readFileSync(MJS, 'utf8')
32
39
  onDisk.should.equal(gen.generate())
33
40
  })
34
41
 
35
- it('exports every non-accessor top-level member as a named binding', function () {
42
+ itFromCheckout('exports every non-accessor top-level member as a named binding', function () {
36
43
  var bsv = require('../..')
37
44
  var names = gen.exportableNames(bsv)
38
45
  names.length.should.be.above(100)
@@ -117,6 +117,79 @@ describe('ECDSA', function () {
117
117
  })
118
118
  })
119
119
 
120
+ describe('nonce reuse', function () {
121
+ // Signing two different messages under one nonce reveals the private key.
122
+ var N = point.getN()
123
+ var h1 = Hash.sha256(Buffer.from('pay alice 1 coin'))
124
+ var h2 = Hash.sha256(Buffer.from('pay bob 2 coins'))
125
+
126
+ var freshSigner = function () {
127
+ return ECDSA().set({
128
+ privkey: new Privkey(BN.fromBuffer(Buffer.from(
129
+ 'fee0a1f7afebf9d2a5a80c0c98a31c709681cce195cbcd06342b517970c0be1e', 'hex')))
130
+ })
131
+ }
132
+
133
+ it('does not reuse k when one instance signs two different messages', function () {
134
+ var e = freshSigner()
135
+ var sig1 = e.set({ hashbuf: h1 }).sign().sig
136
+ var k1 = e.k
137
+ var sig2 = e.set({ hashbuf: h2 }).sign().sig
138
+ var k2 = e.k;
139
+ (k1.cmp(k2) === 0).should.equal(false)
140
+ sig1.r.eq(sig2.r).should.equal(false)
141
+ })
142
+
143
+ it('does not reuse k across signRandomK calls on one instance', function () {
144
+ var e = freshSigner()
145
+ var sig1 = e.set({ hashbuf: h1 }).signRandomK().sig
146
+ var sig2 = e.set({ hashbuf: h2 }).sign().sig
147
+ sig1.r.eq(sig2.r).should.equal(false)
148
+ })
149
+
150
+ it('does not leak the private key from two signatures by one instance', function () {
151
+ var e = freshSigner()
152
+ var d = e.privkey.bn
153
+ var sig1 = e.set({ hashbuf: h1 }).sign().sig
154
+ var sig2 = e.set({ hashbuf: h2 }).sign().sig
155
+
156
+ // toLowS may have flipped either s, so try every sign combination.
157
+ var red = BN.red(N)
158
+ var inv = function (x) { return x.toRed(red).redInvm().fromRed() }
159
+ var mul = function (a, b) { return a.toRed(red).redMul(b.toRed(red)).fromRed() }
160
+ var e1 = BN.fromBuffer(h1)
161
+ var e2 = BN.fromBuffer(h2)
162
+ var recovered = false
163
+ ;[1, -1].forEach(function (f1) {
164
+ ;[1, -1].forEach(function (f2) {
165
+ var S1 = f1 === 1 ? sig1.s : N.sub(sig1.s)
166
+ var S2 = f2 === 1 ? sig2.s : N.sub(sig2.s)
167
+ var diff = S1.sub(S2).umod(N)
168
+ if (diff.isZero()) return
169
+ var k = mul(e1.sub(e2).umod(N), inv(diff))
170
+ var guess = mul(S1.mul(k).umod(N).sub(e1).umod(N), inv(sig1.r))
171
+ if (guess.toString(16) === d.toString(16)) recovered = true
172
+ })
173
+ })
174
+ recovered.should.equal(false)
175
+ })
176
+
177
+ it('still honours an explicitly supplied k for a single signature', function () {
178
+ var k = new BN('114860389168127852803919605627759231199925249596762615988727970217268189974335', 10)
179
+ var a = freshSigner().set({ hashbuf: h1, k: k })
180
+ var b = freshSigner().set({ hashbuf: h1, k: k })
181
+ a.sign().sig.r.eq(b.sign().sig.r).should.equal(true)
182
+ a.k.eq(k).should.equal(true)
183
+ })
184
+
185
+ it('signs the same message deterministically across instances', function () {
186
+ var a = freshSigner().set({ hashbuf: h1 }).sign().sig
187
+ var b = freshSigner().set({ hashbuf: h1 }).sign().sig
188
+ a.r.eq(b.r).should.equal(true)
189
+ a.s.eq(b.s).should.equal(true)
190
+ })
191
+ })
192
+
120
193
  describe('#toPublicKey', function () {
121
194
  it('should calculate the correct public key', function () {
122
195
  ecdsa.k = new BN('114860389168127852803919605627759231199925249596762615988727970217268189974335', 10)
@@ -69,6 +69,52 @@ describe('SmartLedger Security Patches', function () {
69
69
  // change which key/message the signature is valid for.
70
70
  canonical.r.cmp(highS.r).should.equal(0)
71
71
  })
72
+
73
+ it('toCanonical() returns a new signature and leaves the original alone', function () {
74
+ var sig = ECDSA.sign(hash, privateKey)
75
+ var n = Point.getN()
76
+ var lowS = sig.s.lte(n.shrn(1)) ? sig.s : n.sub(sig.s)
77
+ var highS = new Signature({ r: sig.r, s: n.sub(lowS) })
78
+ var before = highS.s.toString()
79
+
80
+ var canonical = highS.toCanonical()
81
+ canonical.should.not.equal(highS)
82
+ highS.s.toString().should.equal(before)
83
+ })
84
+ })
85
+
86
+ describe('applySecurityPatches', function () {
87
+ var highSig = function () {
88
+ var sig = ECDSA.sign(hash, privateKey)
89
+ var n = Point.getN()
90
+ var lowS = sig.s.lte(n.shrn(1)) ? sig.s : n.sub(sig.s)
91
+ return new Signature({ r: sig.r, s: n.sub(lowS) })
92
+ }
93
+
94
+ it('accepts a canonical signature and returns it for chaining', function () {
95
+ var sig = ECDSA.sign(hash, privateKey)
96
+ sig.applySecurityPatches().should.equal(sig)
97
+ })
98
+
99
+ it('rejects a non-canonical (high-S) signature rather than rewriting it', function () {
100
+ // Rewriting s to n-s cannot protect against malleability: the rewritten
101
+ // signature verifies exactly as the original, so silently normalizing only
102
+ // hides from the caller that the signature was malleated.
103
+ var highS = highSig()
104
+ var before = highS.s.toString()
105
+
106
+ expect(function () { highS.applySecurityPatches() }).to.throw(/non-canonical/)
107
+ highS.s.toString().should.equal(before)
108
+ })
109
+
110
+ it('rejects zero and out-of-range components', function () {
111
+ expect(function () {
112
+ new Signature({ r: new BN(0), s: new BN(1) }).applySecurityPatches()
113
+ }).to.throw(/zero r or s/)
114
+ expect(function () {
115
+ new Signature({ r: new BN(1), s: Point.getN() }).applySecurityPatches()
116
+ }).to.throw(/out of range/)
117
+ })
72
118
  })
73
119
 
74
120
  describe('SmartVerify Enhanced Validation', function () {
@@ -77,12 +123,15 @@ describe('SmartLedger Security Patches', function () {
77
123
  SmartVerify.smartVerify(hash, sig, publicKey).should.equal(true)
78
124
  })
79
125
 
80
- it('accepts a malleated (high-S) signature as valid but canonicalizes it', function () {
126
+ it('rejects a malleated (high-S) signature', function () {
81
127
  var sig = ECDSA.sign(hash, privateKey)
82
128
  var n = Point.getN()
83
129
  var lowS = sig.s.lte(n.shrn(1)) ? sig.s : n.sub(sig.s)
84
130
  var highS = new Signature({ r: sig.r, s: n.sub(lowS) })
85
- SmartVerify.smartVerify(hash, highS, publicKey).should.equal(true)
131
+ SmartVerify.isCanonical(highS).should.equal(false)
132
+ SmartVerify.smartVerify(hash, highS, publicKey).should.equal(false)
133
+ // ...while the canonical form of the same signature still verifies.
134
+ SmartVerify.smartVerify(hash, new Signature({ r: sig.r, s: lowS }), publicKey).should.equal(true)
86
135
  })
87
136
 
88
137
  it('throws on an invalid (non-32-byte) message hash', function () {
@@ -2,9 +2,13 @@
2
2
 
3
3
  var _ = require('../../lib/util/_')
4
4
  var should = require('chai').should()
5
+ var expect = require('chai').expect
5
6
  var bsv = require('../..')
6
7
  var BN = bsv.crypto.BN
7
8
  var Signature = bsv.crypto.Signature
9
+ var ECDSA = bsv.crypto.ECDSA
10
+ var Hash = bsv.crypto.Hash
11
+ var PrivateKey = bsv.PrivateKey
8
12
  var JSUtil = bsv.util.js
9
13
  var Interpreter = bsv.Script.Interpreter
10
14
 
@@ -189,6 +193,83 @@ describe('Signature', function () {
189
193
  var parsed = Signature.parseDER(sig, false)
190
194
  should.exist(parsed)
191
195
  })
196
+
197
+ it('reports sneg for a padded s', function () {
198
+ // 02 21 00ab.. — s carries the pad that clears its high bit.
199
+ var sighex = '304502203e4516da7253cf068effec6b95c41221c0cf3a8e6ccb8cbf1725b562e9afde2c' +
200
+ '022100ab1e3da73d67e32045a20e0b999e049978ea8d6ee5480d485fcf2ce0d03b2ef0'
201
+ var parsed = Signature.parseDER(Buffer.from(sighex, 'hex'))
202
+ parsed.sbuf[0].should.equal(0x00)
203
+ parsed.sneg.should.equal(true)
204
+ parsed.rneg.should.equal(false)
205
+ })
206
+ })
207
+
208
+ describe('#parseDER canonicality', function () {
209
+ // A non-canonical INTEGER is a second encoding of the same number, i.e. a
210
+ // malleable signature. Strict (the default, used by fromDER/fromString and
211
+ // so by credential/proof verification) rejects them; non-strict must keep
212
+ // accepting them, because signatures already on chain are not canonical and
213
+ // fromTxFormat has to parse them.
214
+ var cases = [
215
+ { name: 'r negative (high bit set, unpadded)', hex: '3006' + '0201ff' + '020101', err: /Value of r is negative/ },
216
+ { name: 's negative (high bit set, unpadded)', hex: '3006' + '020101' + '0201ff', err: /Value of s is negative/ },
217
+ { name: 'r excessively padded', hex: '3007' + '02020011' + '020101', err: /Value of r is excessively padded/ },
218
+ { name: 's excessively padded', hex: '3007' + '020101' + '02020011', err: /Value of s is excessively padded/ },
219
+ { name: 'r zero-length', hex: '3005' + '0200' + '020101', err: /Length of r is zero/ },
220
+ { name: 's zero-length', hex: '3005' + '020101' + '0200', err: /Length of s is zero/ }
221
+ ]
222
+
223
+ cases.forEach(function (c) {
224
+ it('strict rejects ' + c.name, function () {
225
+ expect(function () {
226
+ Signature.parseDER(Buffer.from(c.hex, 'hex'))
227
+ }).to.throw(c.err)
228
+ })
229
+
230
+ it('non-strict still accepts ' + c.name + ' (chain compatibility)', function () {
231
+ should.exist(Signature.parseDER(Buffer.from(c.hex, 'hex'), false))
232
+ })
233
+ })
234
+
235
+ it('strict accepts a minimally padded integer', function () {
236
+ // 0x00ff is canonical: the pad is required to clear the high bit.
237
+ should.exist(Signature.parseDER(Buffer.from('3008020200ff020200ff', 'hex')))
238
+ })
239
+
240
+ it('strict accepts a canonical zero integer', function () {
241
+ should.exist(Signature.parseDER(Buffer.from('3006020100020100', 'hex')))
242
+ })
243
+
244
+ it('rejects a malleated re-encoding while the original still verifies', function () {
245
+ var privkey = new PrivateKey()
246
+ var hashbuf = Hash.sha256(Buffer.from('der canonicality'))
247
+ var sig = ECDSA.sign(hashbuf, privkey)
248
+ var der = sig.toDER()
249
+
250
+ ECDSA.verify(hashbuf, Signature.fromDER(der), privkey.toPublicKey()).should.equal(true)
251
+
252
+ // Re-encode r with one pad byte more than DER allows: same r, different
253
+ // bytes. The extra zero goes on top of the canonical encoding, so this is
254
+ // excess padding whether or not r needed a pad to begin with.
255
+ var canonical = function (nbuf) {
256
+ return (nbuf[0] & 0x80) ? Buffer.concat([Buffer.from([0x00]), nbuf]) : nbuf
257
+ }
258
+ var padded = Buffer.concat([Buffer.from([0x00]), canonical(sig.r.toBuffer())])
259
+ var sEnc = canonical(sig.s.toBuffer())
260
+ var body = Buffer.concat([
261
+ Buffer.from([0x02, padded.length]), padded,
262
+ Buffer.from([0x02, sEnc.length]), sEnc
263
+ ])
264
+ var malleated = Buffer.concat([Buffer.from([0x30, body.length]), body])
265
+
266
+ malleated.toString('hex').should.not.equal(der.toString('hex'))
267
+ expect(function () {
268
+ Signature.fromDER(malleated)
269
+ }).to.throw(/excessively padded/)
270
+ // The same bytes remain parseable on the non-strict (chain) path.
271
+ Signature.parseDER(malleated, false).r.eq(sig.r).should.equal(true)
272
+ })
192
273
  })
193
274
 
194
275
  describe('#toDER', function () {
@@ -0,0 +1,74 @@
1
+ 'use strict'
2
+
3
+ /* global describe, it */
4
+
5
+ require('chai').should()
6
+ var expect = require('chai').expect
7
+
8
+ var bsv = require('../../index.js')
9
+
10
+ var UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
11
+
12
+ // A token id is covered by the credential's signature, keys the registry's
13
+ // registration/revocation maps, and feeds proof material — so it must be
14
+ // unpredictable, not merely distinct.
15
+ describe('LTP identifiers', function () {
16
+ var generators = [
17
+ { name: 'Right._generateUUID', fn: function () { return bsv.LTP.Right._generateUUID() }, format: UUID_V4 },
18
+ { name: 'Obligation._generateUUID', fn: function () { return bsv.LTP.Obligation._generateUUID() }, format: UUID_V4 },
19
+ { name: 'Registry._generateRegistryId', fn: function () { return bsv.LTP.Registry._generateRegistryId() }, format: /^reg_[0-9a-f]{16}$/ },
20
+ { name: 'Registry._generateAuditId', fn: function () { return bsv.LTP.Registry._generateAuditId() }, format: /^audit_[0-9a-f]{32}$/ },
21
+ { name: 'Claim._generateBatchId', fn: function () { return bsv.LTP.Claim._generateBatchId() }, format: /^[0-9a-f]{16}$/ }
22
+ ]
23
+
24
+ var withFrozenMathRandom = function (fn) {
25
+ var original = Math.random
26
+ Math.random = function () { return 0.5 }
27
+ try { return fn() } finally { Math.random = original }
28
+ }
29
+
30
+ generators.forEach(function (g) {
31
+ describe(g.name, function () {
32
+ it('keeps its documented format', function () {
33
+ g.fn().should.match(g.format)
34
+ })
35
+
36
+ it('does not repeat', function () {
37
+ var seen = {}
38
+ for (var i = 0; i < 500; i++) {
39
+ var id = g.fn()
40
+ expect(seen[id], 'duplicate id: ' + id).to.equal(undefined)
41
+ seen[id] = true
42
+ }
43
+ })
44
+
45
+ it('does not draw from the engine PRNG', function () {
46
+ withFrozenMathRandom(function () {
47
+ var seen = {}
48
+ for (var i = 0; i < 100; i++) {
49
+ var id = g.fn()
50
+ expect(seen[id], 'id is predictable from the engine PRNG: ' + id).to.equal(undefined)
51
+ seen[id] = true
52
+ }
53
+ })
54
+ })
55
+ })
56
+ })
57
+
58
+ it('issues unpredictable ids on real tokens', function () {
59
+ var type = Object.values(bsv.LTP.Right.RightTypes)[0]
60
+ var ids = {}
61
+ for (var i = 0; i < 25; i++) {
62
+ var token = bsv.LTP.Right.create(
63
+ type,
64
+ 'did:example:issuer',
65
+ 'did:example:subject',
66
+ { description: 'test right' }
67
+ )
68
+ token.id.should.match(/^urn:uuid:/)
69
+ token.id.replace('urn:uuid:', '').should.match(UUID_V4)
70
+ expect(ids[token.id], 'duplicate token id').to.equal(undefined)
71
+ ids[token.id] = true
72
+ }
73
+ })
74
+ })