@smartledger/bsv 7.1.0 → 7.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.
@@ -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
  })
@@ -204,7 +205,19 @@ function splitPayBlob (blob) {
204
205
 
205
206
  /**
206
207
  * Parse an OrdLock listing script into its economic terms. Returns null if `script`
207
- * is not a recognizable OrdLock (so it doubles as a detector).
208
+ * is not an OrdLock (so it doubles as a detector).
209
+ *
210
+ * The terms are recovered from the script's shape and then **verified by reconstruction**:
211
+ * the listing is rebuilt from the recovered seller / payment outputs / inscription and must
212
+ * match the input byte-for-byte. A script that merely wears the same arrangement of opcodes
213
+ * — without the OP_PUSH_TX covenant that actually binds the payment into `hashOutputs` —
214
+ * is rejected, so a non-null result means the purchase branch genuinely enforces payment.
215
+ *
216
+ * Note this is *this library's* OrdLock. It is semantically the widely-deployed
217
+ * ordinal-lock pattern (`hash256(destOutput ‖ payOutput ‖ trailingOutputs) == hashOutputs`
218
+ * under SIGHASH_ALL|ANYONECANPAY), generalized to multiple payment outputs, but it is built
219
+ * on our OP_PUSH_TX core rather than compiled from the sCrypt contract — so the bytes differ
220
+ * and listings are not interchangeable with that template.
208
221
  *
209
222
  * @param {Script|Buffer|string} script
210
223
  * @param {object} [opts] { network } network for the returned address strings
@@ -268,6 +281,20 @@ function parseOrdLock (script, opts) {
268
281
  insc = { contentType: parsedInsc.contentType, content: parsedInsc.content, contentText: parsedInsc.contentText }
269
282
  }
270
283
 
284
+ // Everything above recovers terms from the script's SHAPE. Shape alone proves nothing:
285
+ // a script carrying this arrangement of opcodes but no OP_PUSH_TX covenant enforces no
286
+ // payment at all, and reporting a seller and a price for it invents a listing that does
287
+ // not exist. So rebuild the listing from the recovered terms and require it to match
288
+ // byte-for-byte — the only way to know the purchase branch really binds the payment.
289
+ var rebuilt = buildOrdLock({
290
+ seller: sellerPKH,
291
+ payOutputs: splitPayBlob(payBlob),
292
+ inscription: parsedInsc
293
+ ? { contentType: parsedInsc.contentType, content: parsedInsc.content }
294
+ : undefined
295
+ })
296
+ if (rebuilt.toHex() !== s.toHex()) return null
297
+
271
298
  return {
272
299
  seller: { pubKeyHash: sellerPKH, address: bsv.Address.fromPublicKeyHash(sellerPKH, network).toString() },
273
300
  payOutputs: payOutputs,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smartledger/bsv",
3
- "version": "7.1.0",
3
+ "version": "7.3.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",
@@ -56,7 +56,9 @@ describe('Ordinals BSV-20 fungible tokens', function () {
56
56
  })
57
57
 
58
58
  it('preserves integer amounts larger than 2^53 exactly (string, never a JS number)', function () {
59
- var huge = '99999999999999999999999999'
59
+ // uint64 max: far beyond 2^53, and the largest amount the spec allows. The value this
60
+ // used to test (26 digits) exceeded uint64 and would have been burned by an indexer.
61
+ var huge = '18446744073709551615'
60
62
  var p = B.parseBsv20(B.buildMint({ address: address, tick: 'BIG', amt: huge }))
61
63
  p.amt.should.equal(huge)
62
64
  })
@@ -72,7 +74,7 @@ describe('Ordinals BSV-20 fungible tokens', function () {
72
74
  B.parseBsv20(B.buildMint({ address: address, tick: 'ORDI', amt: '007' })).amt.should.equal('7')
73
75
  B.parseBsv20(B.buildDeploy({ address: address, tick: 'ORDI', max: '000100' })).max.should.equal('100')
74
76
  // canonicalization does not corrupt a huge value
75
- var huge = '90000000000000000000000000'
77
+ var huge = '18446744073709551615'
76
78
  B.parseBsv20(B.buildMint({ address: address, tick: 'ORDI', amt: '0' + huge })).amt.should.equal(huge)
77
79
  })
78
80
 
@@ -123,4 +125,98 @@ describe('Ordinals BSV-20 fungible tokens', function () {
123
125
  ;(function () { B.buildMint({ tick: 'ORDI', amt: '1' }) }).should.throw(/address or a lock/)
124
126
  })
125
127
  })
128
+
129
+ // Checked against the BSV-20 / BSV-21 specification at docs.1satordinals.com.
130
+ describe('specification conformance', function () {
131
+ var OUTPOINT = '3b31'.repeat(16) + '_0'
132
+ var UINT64_MAX = '18446744073709551615'
133
+
134
+ it('accepts lim: 0, which the spec defines as unlimited', function () {
135
+ // "lim | No | String | Per-mint limit; 0 or omitted = unlimited"
136
+ B.parseBsv20(B.buildDeploy({ address: address, tick: 'ORDI', max: '21000000', lim: 0 }))
137
+ .lim.should.equal('0')
138
+ B.parseBsv20(B.buildDeploy({ address: address, tick: 'ORDI', max: '21000000', lim: '0' }))
139
+ .lim.should.equal('0')
140
+ })
141
+
142
+ it('accepts an amount of exactly uint64 max but rejects one above it', function () {
143
+ // "Amounts in BSV-21: strings representing uint64" — larger values are emitted
144
+ // happily as JSON and then discarded by indexers, burning the tokens.
145
+ B.parseBsv20(B.buildDeploy({ address: address, tick: 'ORDI', max: UINT64_MAX }))
146
+ .max.should.equal(UINT64_MAX)
147
+ ;(function () {
148
+ B.buildDeploy({ address: address, tick: 'ORDI', max: '18446744073709551616' })
149
+ }).should.throw(/exceeds the uint64 maximum/)
150
+ ;(function () {
151
+ B.buildMint({ address: address, tick: 'ORDI', amt: '9'.repeat(26) })
152
+ }).should.throw(/exceeds the uint64 maximum/)
153
+ })
154
+
155
+ it('rejects a numeric amount past 2^53, which is already imprecise', function () {
156
+ (function () {
157
+ B.buildMint({ address: address, tick: 'ORDI', amt: 1e17 })
158
+ }).should.throw(/MAX_SAFE_INTEGER/)
159
+ })
160
+
161
+ it('rejects non-string sym / icon instead of stringifying them', function () {
162
+ (function () {
163
+ B.buildDeployMint({ address: address, amt: '100', sym: {} })
164
+ }).should.throw(/sym must be a string, got an object/)
165
+ ;(function () {
166
+ B.buildDeployMint({ address: address, amt: '100', icon: 42 })
167
+ }).should.throw(/icon must be a string/)
168
+ })
169
+
170
+ it('requires icon to be an outpoint reference, as the spec defines it', function () {
171
+ (function () {
172
+ B.buildDeployMint({ address: address, amt: '100', icon: 'https://example.com/i.png' })
173
+ }).should.throw(/outpoint reference/)
174
+ B.parseBsv20(B.buildDeployMint({ address: address, amt: '100', icon: OUTPOINT }))
175
+ .icon.should.equal(OUTPOINT)
176
+ })
177
+
178
+ // parseBsv20/isBsv20 are documented to report VALIDITY. They previously returned any
179
+ // JSON object carrying p:'bsv-20' and a string op, including payloads no indexer acts on.
180
+ describe('parseBsv20 enforces the validity it reports', function () {
181
+ function rejects (label, payload) {
182
+ it('rejects ' + label, function () {
183
+ var json = JSON.stringify(payload)
184
+ B.isBsv20(json).should.equal(false)
185
+ ;(B.parseBsv20(json) === null).should.equal(true)
186
+ })
187
+ }
188
+ rejects('a transfer with no amount and no token', { p: 'bsv-20', op: 'transfer' })
189
+ rejects('a mint with no amount', { p: 'bsv-20', op: 'mint', tick: 'ORDI' })
190
+ rejects('a deploy with no max', { p: 'bsv-20', op: 'deploy', tick: 'ORDI' })
191
+ rejects('an operation the spec does not define', { p: 'bsv-20', op: 'not-an-op' })
192
+ rejects('a transfer naming both tick and id', { p: 'bsv-20', op: 'transfer', tick: 'A', id: OUTPOINT, amt: '1' })
193
+ rejects('an auth carrying amt, which the spec forbids', { p: 'bsv-20', op: 'auth', id: OUTPOINT, amt: '1' })
194
+ rejects('a deploy+auth carrying amt, which the spec forbids', { p: 'bsv-20', op: 'deploy+auth', amt: '1' })
195
+ rejects('a ticker longer than 4 bytes', { p: 'bsv-20', op: 'mint', tick: 'TOOLONG', amt: '1' })
196
+ rejects('a malformed token id', { p: 'bsv-20', op: 'transfer', id: 'nope', amt: '1' })
197
+ rejects('an amount above uint64', { p: 'bsv-20', op: 'mint', tick: 'A', amt: '9'.repeat(26) })
198
+ rejects('dec out of range', { p: 'bsv-20', op: 'deploy', tick: 'A', max: '1', dec: '19' })
199
+
200
+ it('accepts the spec operations this library does not yet emit', function () {
201
+ // Reading the chain is not the same as writing it: burn/auth/deploy+auth are valid
202
+ // BSV-21 and must be recognised even though there is no builder for them yet.
203
+ B.isBsv20(JSON.stringify({ p: 'bsv-20', op: 'burn', id: OUTPOINT, amt: '5' })).should.equal(true)
204
+ B.isBsv20(JSON.stringify({ p: 'bsv-20', op: 'auth', id: OUTPOINT })).should.equal(true)
205
+ B.isBsv20(JSON.stringify({ p: 'bsv-20', op: 'deploy+auth', sym: 'STABLE' })).should.equal(true)
206
+ })
207
+
208
+ it('tolerates a non-canonical on-chain amount when reading', function () {
209
+ // Our builder emits canonical amounts, but other people's payloads are not ours
210
+ // to reject over leading zeros.
211
+ B.isBsv20(JSON.stringify({ p: 'bsv-20', op: 'mint', tick: 'A', amt: '007' })).should.equal(true)
212
+ })
213
+
214
+ it('still round-trips everything this library builds', function () {
215
+ B.isBsv20(B.buildDeploy({ address: address, tick: 'ORDI', max: '21000000' })).should.equal(true)
216
+ B.isBsv20(B.buildMint({ address: address, tick: 'ORDI', amt: '1' })).should.equal(true)
217
+ B.isBsv20(B.buildTransfer({ address: address, id: OUTPOINT, amt: '1' })).should.equal(true)
218
+ B.isBsv20(B.buildDeployMint({ address: address, amt: '1000' })).should.equal(true)
219
+ })
220
+ })
221
+ })
126
222
  })
@@ -68,4 +68,158 @@ describe('Ordinals inscriptions', function () {
68
68
  Ord.parseInscription(outs[0].script).contentText.should.equal('a')
69
69
  Ord.parseInscription(outs[1].script).contentText.should.equal('b')
70
70
  })
71
+
72
+ // The 1Sat spec allows the locking script to be prepended OR appended to the
73
+ // envelope. The parser only ever looked before it, so an appended lock was dropped
74
+ // and an owned ordinal was reported as carrying no locking script at all.
75
+ describe('recovers the lock wherever the spec allows it to sit', function () {
76
+ var p2pkh = bsv.Script.buildPublicKeyHashOut(address)
77
+
78
+ function concat () {
79
+ var out = new bsv.Script()
80
+ Array.prototype.slice.call(arguments).forEach(function (part) {
81
+ part.chunks.forEach(function (c) { out.chunks.push(c) })
82
+ })
83
+ return out
84
+ }
85
+
86
+ function envelope () {
87
+ return Ord.buildInscription({
88
+ lock: new bsv.Script(), allowEmptyLock: true, contentType: 'text/plain', content: 'hello'
89
+ })
90
+ }
91
+
92
+ it('recovers a lock that precedes the envelope', function () {
93
+ var parsed = Ord.parseInscription(concat(p2pkh, envelope()))
94
+ parsed.lock.toHex().should.equal(p2pkh.toHex())
95
+ parsed.contentText.should.equal('hello')
96
+ })
97
+
98
+ it('recovers a lock that follows the envelope', function () {
99
+ var parsed = Ord.parseInscription(concat(envelope(), p2pkh))
100
+ parsed.lock.toHex().should.equal(p2pkh.toHex())
101
+ parsed.contentText.should.equal('hello')
102
+ })
103
+
104
+ it('keeps a separating OP_CODESEPARATOR, which really does run', function () {
105
+ var sep = concat(p2pkh, new bsv.Script().add(bsv.Opcode.OP_CODESEPARATOR), envelope())
106
+ var parsed = Ord.parseInscription(sep)
107
+ parsed.lock.chunks.length.should.equal(p2pkh.chunks.length + 1)
108
+ parsed.contentText.should.equal('hello')
109
+ })
110
+
111
+ it('still reports no lock when there genuinely is none', function () {
112
+ Ord.parseInscription(envelope()).lock.chunks.length.should.equal(0)
113
+ })
114
+ })
115
+
116
+ // Every case below used to succeed and emit a well-formed script that inscribed
117
+ // something other than what the caller asked for. An inscription is permanent, so
118
+ // each one now fails loudly at build time instead of on-chain.
119
+ describe('rejects arguments that would silently inscribe the wrong thing', function () {
120
+ it('throws when content is omitted rather than inscribing an empty payload', function () {
121
+ (function () {
122
+ Ord.buildInscription({ address: address, contentType: 'text/plain' })
123
+ }).should.throw(/requires `content`/)
124
+ })
125
+
126
+ it('names the field the caller actually passed', function () {
127
+ // The real-world report: a wallet whose own builder calls the field `data`.
128
+ (function () {
129
+ Ord.buildInscription({ address: address, contentType: 'text/plain', data: 'hello world' })
130
+ }).should.throw(/received `data`, which is not read/)
131
+ })
132
+
133
+ it('still allows an explicitly empty payload', function () {
134
+ var s = Ord.buildInscription({ address: address, contentType: 'text/plain', content: '' })
135
+ Ord.parseInscription(s).content.length.should.equal(0)
136
+ })
137
+
138
+ it('throws rather than stringifying an object into the payload', function () {
139
+ // String({}) is '[object Object]' — permanent, and never intended.
140
+ (function () {
141
+ Ord.buildInscription({ address: address, contentType: 'text/plain', content: { a: 1 } })
142
+ }).should.throw(/content must be a string or Buffer, got an object/)
143
+ })
144
+
145
+ it('throws on any non-string, non-Buffer content', function () {
146
+ [42, true, null, ['a'], undefined].forEach(function (v) {
147
+ (function () {
148
+ Ord.buildInscription({ address: address, contentType: 'text/plain', content: v })
149
+ }).should.throw(Error)
150
+ })
151
+ })
152
+
153
+ it('requires a contentType for Buffer content instead of labelling it text/plain', function () {
154
+ var png = Buffer.from([0x89, 0x50, 0x4e, 0x47])
155
+ ;(function () {
156
+ Ord.buildInscription({ address: address, content: png })
157
+ }).should.throw(/contentType is required when content is a Buffer/)
158
+ // Declared explicitly, it builds.
159
+ var s = Ord.buildInscription({ address: address, contentType: 'image/png', content: png })
160
+ Ord.parseInscription(s).contentType.should.equal('image/png')
161
+ })
162
+
163
+ it('keeps the text/plain default for string content', function () {
164
+ var s = Ord.buildInscription({ address: address, content: 'hi' })
165
+ Ord.parseInscription(s).contentType.should.equal('text/plain')
166
+ })
167
+
168
+ it('throws on an empty or non-string contentType', function () {
169
+ (function () {
170
+ Ord.buildInscription({ address: address, contentType: '', content: 'x' })
171
+ }).should.throw(/contentType must not be empty/)
172
+ ;(function () {
173
+ Ord.buildInscription({ address: address, contentType: {}, content: 'x' })
174
+ }).should.throw(/contentType must be a string or Buffer/)
175
+ })
176
+
177
+ it('throws on an empty base lock, which would be anyone-can-spend', function () {
178
+ // With no base lock the script is just the inert envelope: OP_FALSE OP_IF skips
179
+ // to OP_ENDIF, so whatever the spender pushed is the final stack and any spender
180
+ // succeeds. Proven below rather than asserted.
181
+ (function () {
182
+ Ord.buildInscription({ lock: Buffer.alloc(0), contentType: 'text/plain', content: 'x' })
183
+ }).should.throw(/spendable by anyone/)
184
+ })
185
+
186
+ it('proves the empty-lock script really is anyone-can-spend', function () {
187
+ var envelope = Ord.buildInscription({
188
+ lock: new bsv.Script(), allowEmptyLock: true, contentType: 'text/plain', content: 'x'
189
+ })
190
+ // An unlocking script from a key unrelated to `address` satisfies it.
191
+ var unlock = new bsv.Script().add(bsv.Opcode.OP_1)
192
+ var interp = new bsv.Script.Interpreter()
193
+ var ok = interp.verify(unlock, envelope, new bsv.Transaction(), 0, 0)
194
+ ok.should.equal(true)
195
+ })
196
+
197
+ it('permits an empty lock only when the caller opts in', function () {
198
+ var s = Ord.buildInscription({
199
+ lock: new bsv.Script(), allowEmptyLock: true, contentType: 'text/plain', content: 'x'
200
+ })
201
+ Ord.isInscription(s).should.equal(true)
202
+ })
203
+
204
+ it('throws when both lock and address are given instead of ignoring one', function () {
205
+ var lock = bsv.Script.buildPublicKeyHashOut(address)
206
+ var other = bsv.PrivateKey.fromRandom().toAddress()
207
+ ;(function () {
208
+ Ord.buildInscription({ lock: lock, address: other, contentType: 'text/plain', content: 'x' })
209
+ }).should.throw(/not both/)
210
+ })
211
+
212
+ it('rejects a satoshi amount that carries no ordinal', function () {
213
+ [0, '1', 1.5, -1].forEach(function (v) {
214
+ (function () {
215
+ Ord.createInscriptionOutput({
216
+ address: address, contentType: 'text/plain', content: 'x', satoshis: v
217
+ })
218
+ }).should.throw(Error)
219
+ })
220
+ Ord.createInscriptionOutput({
221
+ address: address, contentType: 'text/plain', content: 'x'
222
+ }).satoshis.should.equal(1)
223
+ })
224
+ })
71
225
  })
@@ -549,4 +549,75 @@ describe('Ordinals OrdLock — code-review regressions', function () {
549
549
  })
550
550
  Ord.parseOrdLock(lock).totalPrice.should.equal(777)
551
551
  })
552
+
553
+ // parseOrdLock recovers terms from the script's shape. Shape alone proves nothing: a
554
+ // script wearing the same opcode arrangement without the OP_PUSH_TX covenant enforces no
555
+ // payment, and reporting a seller and a price for it invents a listing that does not
556
+ // exist. The terms are therefore verified by rebuilding the listing and comparing bytes.
557
+ describe('is a verifier, not a shape matcher', function () {
558
+ var attacker = bsv.PrivateKey.fromBuffer(Buffer.alloc(32, 9))
559
+
560
+ // Wears the fingerprint parseOrdLock keys off: a top-level OP_IF with a 20-byte push,
561
+ // and OP_TOALTSTACK <blob> OP_CAT OP_SWAP in the OP_ELSE branch. Enforces nothing.
562
+ function fabricatedListing () {
563
+ var payout = new bsv.Transaction.Output({
564
+ script: bsv.Script.buildPublicKeyHashOut(attacker.toAddress()),
565
+ satoshis: 100000000
566
+ })
567
+ var s = new bsv.Script()
568
+ s.add(bsv.Opcode.OP_IF)
569
+ s.add(attacker.toAddress().hashBuffer)
570
+ s.add(bsv.Opcode.OP_DROP)
571
+ s.add(bsv.Opcode.OP_ELSE)
572
+ s.add(bsv.Opcode.OP_TOALTSTACK)
573
+ s.add(payout.toBufferWriter().toBuffer())
574
+ s.add(bsv.Opcode.OP_CAT)
575
+ s.add(bsv.Opcode.OP_SWAP)
576
+ s.add(bsv.Opcode.OP_ENDIF)
577
+ s.add(bsv.Opcode.OP_TRUE)
578
+ return s
579
+ }
580
+
581
+ it('rejects a fabricated listing that enforces no payment', function () {
582
+ var fake = fabricatedListing()
583
+ Ord.isOrdLock(fake).should.equal(false)
584
+ ;(Ord.parseOrdLock(fake) === null).should.equal(true)
585
+ })
586
+
587
+ it('proves the fabricated listing really is spendable for free', function () {
588
+ // Without this, the test above only shows we reject *something*.
589
+ var interp = new bsv.Script.Interpreter()
590
+ var unlock = new bsv.Script().add(bsv.Opcode.OP_1)
591
+ var spent = interp.verify(unlock, fabricatedListing(), new bsv.Transaction(), 0, 0)
592
+ spent.should.equal(true)
593
+ })
594
+
595
+ it('rejects a genuine listing with anything appended', function () {
596
+ var real = Ord.buildOrdLock({ seller: owner.toAddress(), price: 50000 })
597
+ var tampered = bsv.Script.fromHex(real.toHex()).add(bsv.Opcode.OP_NOP)
598
+ Ord.isOrdLock(tampered).should.equal(false)
599
+ })
600
+
601
+ it('still accepts every genuine listing shape', function () {
602
+ var simple = Ord.buildOrdLock({ seller: owner.toAddress(), price: 50000 })
603
+ Ord.parseOrdLock(simple).totalPrice.should.equal(50000)
604
+
605
+ var withInsc = Ord.buildOrdLock({
606
+ seller: owner.toAddress(),
607
+ price: 777,
608
+ inscription: { contentType: 'text/plain', content: 'for sale' }
609
+ })
610
+ var parsed = Ord.parseOrdLock(withInsc)
611
+ parsed.totalPrice.should.equal(777)
612
+ parsed.inscription.contentText.should.equal('for sale')
613
+
614
+ var multi = Ord.buildOrdLock({
615
+ seller: owner.toAddress(),
616
+ price: 1000,
617
+ royalties: [{ address: attacker.toAddress(), satoshis: 50 }]
618
+ })
619
+ Ord.parseOrdLock(multi).payOutputs.length.should.equal(2)
620
+ Ord.parseOrdLock(multi).totalPrice.should.equal(1050)
621
+ })
622
+ })
552
623
  })
package/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  'use strict'
2
2
  // GENERATED by scripts/sync-version.js on `npm version` — do not edit.
3
- module.exports = '7.1.0'
3
+ module.exports = '7.3.0'