@smartledger/bsv 9.1.1 → 9.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.
@@ -48,7 +48,7 @@ const tx: Transaction = new Transaction();
48
48
  #### **Core Library Only (937KB)**
49
49
  For basic Bitcoin SV operations:
50
50
  ```html
51
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.min.js"></script>
51
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.min.js"></script>
52
52
  <script>
53
53
  const privateKey = new bsv.PrivateKey();
54
54
  const address = privateKey.toAddress();
@@ -58,7 +58,7 @@ For basic Bitcoin SV operations:
58
58
  #### **Complete Bundle (937KB)**
59
59
  Everything in one file:
60
60
  ```html
61
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.bundle.js"></script>
61
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.bundle.js"></script>
62
62
  <script>
63
63
  // All features available immediately
64
64
  const shares = bsv.splitSecret('secret', 5, 3);
@@ -71,9 +71,9 @@ Everything in one file:
71
71
 
72
72
  #### **Smart Contract Development (~2.7MB total — each bundle is self-contained and re-embeds core BSV)**
73
73
  ```html
74
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.min.js"></script>
75
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-covenant.min.js"></script>
76
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-smartcontract.min.js"></script>
74
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.min.js"></script>
75
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-covenant.min.js"></script>
76
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-smartcontract.min.js"></script>
77
77
  <script>
78
78
  const covenant = bsv.SmartContract.createCovenantBuilder()
79
79
  .extractField('amount').push(50000).greaterThanOrEqual().build();
@@ -82,9 +82,9 @@ Everything in one file:
82
82
 
83
83
  #### **Legal & Identity Development (~3.2MB total — each bundle is self-contained and re-embeds core BSV)**
84
84
  ```html
85
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.min.js"></script>
86
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-ltp.min.js"></script>
87
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-gdaf.min.js"></script>
85
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.min.js"></script>
86
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-ltp.min.js"></script>
87
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-gdaf.min.js"></script>
88
88
  <script>
89
89
  // Legal Token Protocol
90
90
  const propertyToken = bsv.createPropertyToken({
@@ -98,9 +98,9 @@ Everything in one file:
98
98
 
99
99
  #### **Security & Cryptography (~1.4MB total — each bundle is self-contained and re-embeds core BSV)**
100
100
  ```html
101
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.min.js"></script>
102
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-security.min.js"></script>
103
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-shamir.min.js"></script>
101
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.min.js"></script>
102
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-security.min.js"></script>
103
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-shamir.min.js"></script>
104
104
  <script>
105
105
  // Threshold Cryptography
106
106
  const shares = bsv.splitSecret('my_secret_key', 5, 3);
@@ -114,18 +114,18 @@ Everything in one file:
114
114
 
115
115
  | Module | Size | Purpose | CDN Link |
116
116
  |--------|------|---------|----------|
117
- | **bsv.min.js** | 937KB | Core BSV + SmartContract | `unpkg.com/@smartledger/bsv@9.1.1/bsv.min.js` |
118
- | **bsv.bundle.js** | 937KB | Everything in one file | `unpkg.com/@smartledger/bsv@9.1.1/bsv.bundle.js` |
119
- | **bsv-smartcontract.min.js** | 937KB | Complete covenant framework | `unpkg.com/@smartledger/bsv@9.1.1/bsv-smartcontract.min.js` |
120
- | **bsv-ltp.min.js** | 1184KB | **Legal Token Protocol** | `unpkg.com/@smartledger/bsv@9.1.1/bsv-ltp.min.js` |
121
- | **bsv-gdaf.min.js** | 1184KB | **Digital Identity & Attestation** | `unpkg.com/@smartledger/bsv@9.1.1/bsv-gdaf.min.js` |
122
- | **bsv-shamir.min.js** | 432KB | **Threshold Cryptography** | `unpkg.com/@smartledger/bsv@9.1.1/bsv-shamir.min.js` |
123
- | **bsv-security.min.js** | 26KB | Security enhancements (opt-in helpers — see README › Security) | `unpkg.com/@smartledger/bsv@9.1.1/bsv-security.min.js` |
124
- | **bsv-mnemonic.min.js** | 681KB | HD wallets | `unpkg.com/@smartledger/bsv@9.1.1/bsv-mnemonic.min.js` |
125
- | **bsv-ecies.min.js** | 71KB | Encryption | `unpkg.com/@smartledger/bsv@9.1.1/bsv-ecies.min.js` |
126
- | **bsv-covenant.min.js** | 913KB | Covenant operations | `unpkg.com/@smartledger/bsv@9.1.1/bsv-covenant.min.js` |
127
- | **bsv-script-helper.min.js** | 26KB | Custom script tools | `unpkg.com/@smartledger/bsv@9.1.1/bsv-script-helper.min.js` |
128
- | **bsv-message.min.js** | 26KB | Message signing | `unpkg.com/@smartledger/bsv@9.1.1/bsv-message.min.js` |
117
+ | **bsv.min.js** | 937KB | Core BSV + SmartContract | `unpkg.com/@smartledger/bsv@9.3.0/bsv.min.js` |
118
+ | **bsv.bundle.js** | 937KB | Everything in one file | `unpkg.com/@smartledger/bsv@9.3.0/bsv.bundle.js` |
119
+ | **bsv-smartcontract.min.js** | 937KB | Complete covenant framework | `unpkg.com/@smartledger/bsv@9.3.0/bsv-smartcontract.min.js` |
120
+ | **bsv-ltp.min.js** | 1184KB | **Legal Token Protocol** | `unpkg.com/@smartledger/bsv@9.3.0/bsv-ltp.min.js` |
121
+ | **bsv-gdaf.min.js** | 1184KB | **Digital Identity & Attestation** | `unpkg.com/@smartledger/bsv@9.3.0/bsv-gdaf.min.js` |
122
+ | **bsv-shamir.min.js** | 432KB | **Threshold Cryptography** | `unpkg.com/@smartledger/bsv@9.3.0/bsv-shamir.min.js` |
123
+ | **bsv-security.min.js** | 26KB | Security enhancements (opt-in helpers — see README › Security) | `unpkg.com/@smartledger/bsv@9.3.0/bsv-security.min.js` |
124
+ | **bsv-mnemonic.min.js** | 681KB | HD wallets | `unpkg.com/@smartledger/bsv@9.3.0/bsv-mnemonic.min.js` |
125
+ | **bsv-ecies.min.js** | 71KB | Encryption | `unpkg.com/@smartledger/bsv@9.3.0/bsv-ecies.min.js` |
126
+ | **bsv-covenant.min.js** | 913KB | Covenant operations | `unpkg.com/@smartledger/bsv@9.3.0/bsv-covenant.min.js` |
127
+ | **bsv-script-helper.min.js** | 26KB | Custom script tools | `unpkg.com/@smartledger/bsv@9.3.0/bsv-script-helper.min.js` |
128
+ | **bsv-message.min.js** | 26KB | Message signing | `unpkg.com/@smartledger/bsv@9.3.0/bsv-message.min.js` |
129
129
 
130
130
  ## ⚙️ **Development Environment Setup**
131
131
 
@@ -14,10 +14,10 @@ npm install @smartledger/bsv
14
14
  ### Browser CDN (Instant)
15
15
  ```html
16
16
  <!-- Core library (937KB) -->
17
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.min.js"></script>
17
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.min.js"></script>
18
18
 
19
19
  <!-- Everything included (937KB) -->
20
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.bundle.js"></script>
20
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.bundle.js"></script>
21
21
  ```
22
22
 
23
23
  ## 💰 **Your First Transaction (60 seconds)**
@@ -127,19 +127,19 @@ SmartLedger-BSV offers 12 different loading options - use only what you need:
127
127
 
128
128
  ```html
129
129
  <!-- Core BSV only (937KB) -->
130
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.min.js"></script>
130
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.min.js"></script>
131
131
 
132
132
  <!-- Smart contracts (937KB) -->
133
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-smartcontract.min.js"></script>
133
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-smartcontract.min.js"></script>
134
134
 
135
135
  <!-- Legal tokens (1.16MB) -->
136
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-ltp.min.js"></script>
136
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-ltp.min.js"></script>
137
137
 
138
138
  <!-- Digital identity (1.16MB) -->
139
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-gdaf.min.js"></script>
139
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-gdaf.min.js"></script>
140
140
 
141
141
  <!-- Everything (937KB) -->
142
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.bundle.js"></script>
142
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.bundle.js"></script>
143
143
  ```
144
144
 
145
145
  ## ⚡ **Key Advantages**
@@ -159,17 +159,17 @@ const recovered = bsv.reconstructSecret([shares[0], shares[2], shares[4]]);
159
159
  ### **New Modular Options**
160
160
  ```html
161
161
  <!-- Core compatibility (same size as bsv@1.5.6) -->
162
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.min.js"></script>
162
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.min.js"></script>
163
163
 
164
164
  <!-- Add smart contracts when ready -->
165
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-smartcontract.min.js"></script>
165
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-smartcontract.min.js"></script>
166
166
 
167
167
  <!-- Add advanced features as needed -->
168
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-ltp.min.js"></script>
169
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv-gdaf.min.js"></script>
168
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-ltp.min.js"></script>
169
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv-gdaf.min.js"></script>
170
170
 
171
171
  <!-- Everything in one file -->
172
- <script src="https://unpkg.com/@smartledger/bsv@9.1.1/bsv.bundle.js"></script>
172
+ <script src="https://unpkg.com/@smartledger/bsv@9.3.0/bsv.bundle.js"></script>
173
173
  ```
174
174
 
175
175
  ## 🔍 **Testing Your Migration**
@@ -0,0 +1,7 @@
1
+ /**
2
+ * GDAF — governed data anchoring.
3
+ *
4
+ * Same class as `require("@smartledger/bsv").GDAF`.
5
+ */
6
+ import { GDAF } from '@smartledger/bsv';
7
+ export = GDAF;
package/index.js CHANGED
@@ -307,6 +307,7 @@ bsv.createCredentialTemplate = function(credentialType) {
307
307
 
308
308
  // Legal Token Protocol (LTP) - Primitives-Only Interface
309
309
  bsv.LTP = require('./lib/ltp')
310
+ bsv.JCS = require('./lib/util/jcs')
310
311
 
311
312
  // LTP Right Token Primitives
312
313
  bsv.prepareRightToken = function(type, issuerDID, subjectDID, claim, issuerPrivateKey, options) {
@@ -508,12 +509,12 @@ bsv.createClaimTemplate = function(schemaName) {
508
509
  }
509
510
 
510
511
  // LTP Utility Functions
511
- bsv.canonicalizeClaim = function(claim) {
512
- return bsv.LTP.Claim.canonicalize(claim)
512
+ bsv.canonicalizeClaim = function(claim, canonicalization) {
513
+ return bsv.LTP.Claim.canonicalize(claim, canonicalization)
513
514
  }
514
515
 
515
- bsv.hashClaim = function(claim) {
516
- return bsv.LTP.Claim.hash(claim)
516
+ bsv.hashClaim = function(claim, canonicalization) {
517
+ return bsv.LTP.Claim.hash(claim, canonicalization)
517
518
  }
518
519
 
519
520
  bsv.addCustomClaimSchema = function(name, schema) {
package/index.mjs CHANGED
@@ -18,6 +18,7 @@ export const {
18
18
  HDPrivateKey,
19
19
  HDPublicKey,
20
20
  Input,
21
+ JCS,
21
22
  LTP,
22
23
  MerkleBlock,
23
24
  Message,
package/jcs-entry.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * RFC 8785 (JSON Canonicalization Scheme).
3
+ *
4
+ * Object keys sort by UTF-16 code unit, applied during serialization rather than by
5
+ * rebuilding an object — rebuilding lets V8 reorder integer-like keys ahead of the
6
+ * sort, producing `{"2":…,"10":…}` where the RFC requires `{"10":…,"2":…}`.
7
+ *
8
+ * Throws on non-finite numbers, bigint, circular structures, and values with no JSON
9
+ * representation, rather than coercing them: a canonicalizer that silently serializes
10
+ * a different document than the one supplied defeats its own purpose.
11
+ */
12
+ export declare function stringify(value: any): string;
package/jcs-entry.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./lib/util/jcs')
package/lib/ltp/claim.js CHANGED
@@ -3,6 +3,8 @@
3
3
  var Hash = require('../crypto/hash')
4
4
  var $ = require('../util/preconditions')
5
5
  var Id = require('../util/id')
6
+ var JCS = require('../util/jcs')
7
+ var deprecate = require('../util/deprecate')
6
8
 
7
9
  /**
8
10
  * Legal Token Protocol - Claim Preparation Primitives
@@ -282,8 +284,14 @@ var ClaimValidator = {
282
284
  errors: errors,
283
285
  warnings: warnings,
284
286
  schema: schemaName,
285
- claimHash: this.hash(claim),
286
- canonical: this.canonicalize(claim)
287
+ // Both pinned to LEGACY, not inheriting the deprecated default: these are
288
+ // stored as identifiers by callers who cannot pass an argument here, and a
289
+ // warning naming a function they did not call is noise. 10.0.0 moves them to
290
+ // JCS as one documented change rather than a silent one.
291
+ claimHash: Hash.sha256(Buffer.from(
292
+ this._canonicalizeWith(claim, this.CANONICALIZATION.LEGACY)
293
+ )).toString('hex'),
294
+ canonical: this._canonicalizeWith(claim, this.CANONICALIZATION.LEGACY)
287
295
  }
288
296
 
289
297
  return {
@@ -360,7 +368,10 @@ var ClaimValidator = {
360
368
  }
361
369
 
362
370
  // Create attestation hash
363
- var attestationHash = Hash.sha256(Buffer.from(this.canonicalize(attestation))).toString('hex')
371
+ // Pinned to LEGACY — see the note on validateClaim's canonical field.
372
+ var attestationHash = Hash.sha256(Buffer.from(
373
+ this._canonicalizeWith(attestation, this.CANONICALIZATION.LEGACY)
374
+ )).toString('hex')
364
375
  attestation.attestationHash = attestationHash
365
376
 
366
377
  return {
@@ -426,7 +437,10 @@ var ClaimValidator = {
426
437
  }
427
438
 
428
439
  // Create dispute hash
429
- var disputeHash = Hash.sha256(Buffer.from(this.canonicalize(disputeRecord))).toString('hex')
440
+ // Pinned to LEGACY — see the note on validateClaim's canonical field.
441
+ var disputeHash = Hash.sha256(Buffer.from(
442
+ this._canonicalizeWith(disputeRecord, this.CANONICALIZATION.LEGACY)
443
+ )).toString('hex')
430
444
  disputeRecord.disputeHash = disputeHash
431
445
 
432
446
  return {
@@ -541,29 +555,106 @@ var ClaimValidator = {
541
555
  }
542
556
  },
543
557
 
558
+ /**
559
+ * Canonicalization forms understood when hashing a claim.
560
+ *
561
+ * JCS is RFC 8785 and is what a claim hash should be computed with: two independent
562
+ * implementations produce identical bytes, which is the only property that makes a
563
+ * hash meaningful to anyone but us.
564
+ *
565
+ * LEGACY is the sorted-key form this module has always used. It sorts keys and then
566
+ * REBUILDS an object, which loses the sort — V8 orders integer-like own properties
567
+ * numerically ahead of string keys whatever order they were inserted in:
568
+ *
569
+ * LEGACY {"2":"two","10":"ten"}
570
+ * JCS {"10":"ten","2":"two"} (RFC 8785, UTF-16 code unit order)
571
+ *
572
+ * Deterministic, so nothing already hashed is wrong or forgeable. Not interoperable,
573
+ * so an RFC 8785 verifier in any other language computes a different claim hash.
574
+ */
575
+ CANONICALIZATION: {
576
+ JCS: 'jcs',
577
+ LEGACY: 'legacy'
578
+ },
579
+
544
580
  /**
545
581
  * Canonicalize claim for hashing
582
+ *
546
583
  * @param {Object} claim - Claim to canonicalize
584
+ * @param {String} [canonicalization] - CANONICALIZATION.JCS or .LEGACY. Omitting it
585
+ * selects LEGACY and emits a deprecation notice; the default becomes JCS in
586
+ * 10.0.0. Pass one explicitly to pin the behaviour across that change.
547
587
  * @returns {String} Canonical JSON string
548
588
  */
549
- canonicalize: function(claim) {
589
+ canonicalize: function(claim, canonicalization) {
590
+ return this._canonicalizeWith(
591
+ claim,
592
+ this._resolveCanonicalization(canonicalization, 'LTP.Claim.canonicalize')
593
+ )
594
+ },
595
+
596
+ /**
597
+ * Hash claim
598
+ *
599
+ * @param {Object} claim - Claim to hash
600
+ * @param {String} [canonicalization] - see canonicalize()
601
+ * @returns {String} SHA256 hash
602
+ */
603
+ hash: function(claim, canonicalization) {
604
+ var canonical = this._canonicalizeWith(
605
+ claim,
606
+ this._resolveCanonicalization(canonicalization, 'LTP.Claim.hash')
607
+ )
608
+ return Hash.sha256(Buffer.from(canonical)).toString('hex')
609
+ },
610
+
611
+ /**
612
+ * Canonicalize with the form already decided. No deprecation notice: the caller has
613
+ * chosen, either explicitly or on its behalf by _resolveCanonicalization.
614
+ */
615
+ _canonicalizeWith: function(claim, canonicalization) {
550
616
  $.checkArgument(claim && typeof claim === 'object', 'Invalid claim')
551
-
617
+
618
+ if (canonicalization === this.CANONICALIZATION.JCS) {
619
+ return JCS.stringify(claim)
620
+ }
621
+
552
622
  // Sort keys recursively
553
623
  var canonical = this._sortObjectKeys(claim)
554
-
624
+
555
625
  // Return deterministic JSON
556
626
  return JSON.stringify(canonical)
557
627
  },
558
-
628
+
559
629
  /**
560
- * Hash claim
561
- * @param {Object} claim - Claim to hash
562
- * @returns {String} SHA256 hash
630
+ * Resolve an optional canonicalization argument to a concrete form.
631
+ *
632
+ * An unrecognised value throws rather than falling back. A silent fallback would
633
+ * turn a typo such as `'JCS'` into a differently-hashed claim that still looks
634
+ * successful, which is the failure mode this whole change exists to remove.
563
635
  */
564
- hash: function(claim) {
565
- var canonical = this.canonicalize(claim)
566
- return Hash.sha256(Buffer.from(canonical)).toString('hex')
636
+ _resolveCanonicalization: function(canonicalization, caller) {
637
+ if (canonicalization === undefined) {
638
+ // Per STABILITY.md: mark it in a minor, flip it in a major. 9.x does not break
639
+ // callers, so the default stays LEGACY and the notice carries the migration.
640
+ deprecate({
641
+ what: caller + '() without a canonicalization argument',
642
+ since: '9.2.0',
643
+ removeIn: '10.0.0',
644
+ use: caller + '(claim, bsv.LTP.Claim.CANONICALIZATION.JCS)',
645
+ why: 'the default sorted-key form is not RFC 8785, so other implementations compute a different claim hash'
646
+ })
647
+ return this.CANONICALIZATION.LEGACY
648
+ }
649
+
650
+ $.checkArgument(
651
+ canonicalization === this.CANONICALIZATION.JCS ||
652
+ canonicalization === this.CANONICALIZATION.LEGACY,
653
+ 'Unknown canonicalization: ' + canonicalization +
654
+ ". Expected 'jcs' or 'legacy' (bsv.LTP.Claim.CANONICALIZATION)"
655
+ )
656
+
657
+ return canonicalization
567
658
  },
568
659
 
569
660
  /**
@@ -89,6 +89,103 @@ function resolveLock (params) {
89
89
  throw new Error('buildInscription requires an address or a lock script')
90
90
  }
91
91
 
92
+ // Tags the Ordinals spec names. Everything else is "unrecognized", and the spec
93
+ // treats unrecognized tags by parity — see assertTagIsSafe.
94
+ var KNOWN_TAGS = [0, 1, 2, 3, 5, 7, 9, 11]
95
+
96
+ var BODY_TAG = 0
97
+ var CONTENT_TYPE_TAG = 1
98
+
99
+ /**
100
+ * Push a field tag the way a parser expects to read it back.
101
+ *
102
+ * Tags are script numbers. 1..16 have dedicated opcodes; anything larger has no
103
+ * opcode form at all, because OP_16 is the largest numeric opcode — so tag 21
104
+ * must be a data push. Indexers read the resulting STACK ELEMENT, so `OP_5` and
105
+ * a one-byte push of `0x05` are the same tag; the opcode form is used wherever
106
+ * it exists because the data-push form of a small number is non-minimal, and
107
+ * non-minimal pushes are non-standard.
108
+ */
109
+ function addTag (script, tag) {
110
+ if (tag >= 1 && tag <= 16) return script.add(Opcode.OP_1 - 1 + tag)
111
+
112
+ var le = []
113
+ var n = tag
114
+ while (n > 0) { le.push(n & 0xff); n = Math.floor(n / 256) }
115
+ // A script number carries its sign in the high bit of its last byte, so a
116
+ // value ending >= 0x80 needs a zero pad or it reads back negative.
117
+ if (le[le.length - 1] & 0x80) le.push(0x00)
118
+ return script.add(Buffer.from(le))
119
+ }
120
+
121
+ /**
122
+ * Refuse a tag that would produce a permanently broken inscription.
123
+ *
124
+ * The parity rule is the one that costs money. From the spec: "inscriptions with
125
+ * unrecognized even fields must be displayed as unbound, that is, without a
126
+ * location". An unknown ODD tag is simply ignored by an indexer that does not
127
+ * know it; an unknown EVEN tag costs the inscription its location, everywhere,
128
+ * permanently, on an output already paid for — and nothing local reports it,
129
+ * because a builder and its own parser agreeing proves only that they agree.
130
+ *
131
+ * This refuses rather than warns, but it is deliberately not a hard wall. The
132
+ * set of named tags grows as the protocol does, so a library that can never be
133
+ * overridden would eventually be wrong AND unbypassable, and the workaround —
134
+ * hand-assembling envelope bytes — is far more dangerous than the thing being
135
+ * prevented. Hence `allowUnknownEvenFields`, which exists to be reached for
136
+ * knowingly and named so it cannot be passed by accident.
137
+ */
138
+ function assertTagIsSafe (tag, allowUnknownEven) {
139
+ if (!Number.isSafeInteger(tag) || tag < 0) {
140
+ throw new Error('field tag must be a non-negative integer, got ' + JSON.stringify(tag))
141
+ }
142
+ if (tag === BODY_TAG) {
143
+ throw new Error('field tag 0 opens the inscription body and cannot carry a field: ' +
144
+ 'anything pushed after it becomes part of the content')
145
+ }
146
+ if (tag === CONTENT_TYPE_TAG) {
147
+ throw new Error('field tag 1 is the content type; pass `contentType` instead of ' +
148
+ 'a field, or the inscription declares it twice')
149
+ }
150
+ if (tag % 2 === 0 && KNOWN_TAGS.indexOf(tag) === -1 && !allowUnknownEven) {
151
+ throw new Error('field tag ' + tag + ' is an unrecognized even tag. The Ordinals ' +
152
+ 'spec requires such an inscription to be treated as unbound — it would be ' +
153
+ 'indexed without a location, permanently, and nothing local would report it. ' +
154
+ 'Use an odd tag, or pass { allowUnknownEvenFields: true } if you have ' +
155
+ 'established that every indexer you care about recognises ' + tag + '.')
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Normalise `params.fields` into ordered [tag, value] pairs.
161
+ *
162
+ * Emitted in ascending tag order rather than in whatever order the object was
163
+ * written, so the same fields always produce the same bytes. Field order is not
164
+ * significant to a parser before the body opens, but reproducibility is worth
165
+ * more than honouring insertion order nobody specified.
166
+ */
167
+ function resolveFields (params) {
168
+ var fields = params.fields
169
+ if (fields == null) return []
170
+ if (typeof fields !== 'object' || Array.isArray(fields) || Buffer.isBuffer(fields)) {
171
+ throw new Error('fields must be an object of tag numbers to values, e.g. { 5: metadata }')
172
+ }
173
+
174
+ return Object.keys(fields)
175
+ .filter(function (k) { return fields[k] != null })
176
+ .map(function (k) {
177
+ var tag = Number(k)
178
+ assertTagIsSafe(tag, params.allowUnknownEvenFields)
179
+ var value = toBuf(fields[k], 'field ' + tag)
180
+ if (!value.length) {
181
+ throw new Error('field ' + tag + ' has an empty value; omit the field instead ' +
182
+ 'of inscribing a zero-length one permanently')
183
+ }
184
+ return [tag, value]
185
+ })
186
+ .sort(function (a, b) { return a[0] - b[0] })
187
+ }
188
+
92
189
  /**
93
190
  * Build a 1Sat Ordinals inscription locking script: a base lock followed by the
94
191
  * inert `OP_FALSE OP_IF ... OP_ENDIF` envelope carrying the content.
@@ -106,6 +203,12 @@ function resolveLock (params) {
106
203
  * with `address`)
107
204
  * @param {Address|string} [params.address] P2PKH owner (mutually exclusive with `lock`)
108
205
  * @param {boolean} [params.allowEmptyLock] permit an empty base lock; see resolveLock
206
+ * @param {object} [params.fields] additional envelope fields as tag numbers
207
+ * to values, e.g. `{ 5: manifest, 21: thumbnail }`. Tag 5 is `metadata`, the spec's
208
+ * own home for an object's own record. Emitted in ascending tag order, between the
209
+ * content type and the body. Unrecognized EVEN tags are refused — see assertTagIsSafe.
210
+ * @param {boolean} [params.allowUnknownEvenFields] permit an unrecognized even tag.
211
+ * Costs the inscription its location in conformant indexers, permanently.
109
212
  * @returns {Script} the full inscription locking script
110
213
  */
111
214
  function buildInscription (params) {
@@ -135,12 +238,21 @@ function buildInscription (params) {
135
238
  }
136
239
 
137
240
  // Clone the base lock so we never mutate the caller's Script.
241
+ var fields = resolveFields(params)
242
+
138
243
  var s = Script.fromBuffer(lock.toBuffer())
139
244
  s.add(Opcode.OP_FALSE)
140
245
  s.add(Opcode.OP_IF)
141
246
  s.add(ORD)
142
247
  s.add(Opcode.OP_1)
143
248
  s.add(contentType)
249
+ // Every field goes here, between the content type and the body. Tag 0 opens
250
+ // the body and everything after it IS the body, so a field emitted late does
251
+ // not fail — it silently becomes part of the file.
252
+ fields.forEach(function (f) {
253
+ addTag(s, f[0])
254
+ s.add(f[1])
255
+ })
144
256
  s.add(Opcode.OP_0)
145
257
  s.add(content)
146
258
  s.add(Opcode.OP_ENDIF)
package/lib/util/jcs.js CHANGED
@@ -35,6 +35,21 @@ var JCS = {}
35
35
  * @returns {String}
36
36
  */
37
37
  JCS.stringify = function (value) {
38
+ return serialize(value, [])
39
+ }
40
+
41
+ /**
42
+ * `stack` carries the containers currently being serialized, so a cycle throws a
43
+ * typed error instead of recursing until the call stack is exhausted. That matters
44
+ * now the function is public API reachable from a verifier: verification input is by
45
+ * definition untrusted, and a RangeError raised at an arbitrary depth is a worse
46
+ * failure than a deliberate one. A linear scan beats a Set here because these
47
+ * structures are shallow and the array avoids the allocation entirely for the common
48
+ * acyclic case.
49
+ *
50
+ * No acyclic input changes behaviour, so nothing already signed is affected.
51
+ */
52
+ function serialize (value, stack) {
38
53
  if (value === null) return 'null'
39
54
 
40
55
  var type = typeof value
@@ -50,23 +65,38 @@ JCS.stringify = function (value) {
50
65
 
51
66
  if (type === 'string') return JSON.stringify(value)
52
67
 
53
- if (Array.isArray(value)) {
54
- // Arrays are order-significant. `undefined` has no JSON form and becomes null in an
55
- // array, matching JSON.stringify.
56
- return '[' + value.map(function (item) {
57
- return item === undefined ? 'null' : JCS.stringify(item)
58
- }).join(',') + ']'
68
+ if (type === 'bigint') {
69
+ // JSON has no bigint form and coercing one would silently canonicalize a
70
+ // different document than the caller supplied. Carry it as a string.
71
+ throw new Error('Cannot canonicalize bigint; represent it as a string')
59
72
  }
60
73
 
61
- if (type === 'object') {
62
- // Absent and explicitly-undefined are indistinguishable in JSON, so both are dropped.
63
- var keys = Object.keys(value).filter(function (key) {
64
- return value[key] !== undefined && typeof value[key] !== 'function'
65
- }).sort()
74
+ if (Array.isArray(value) || type === 'object') {
75
+ if (stack.indexOf(value) !== -1) {
76
+ throw new Error('Cannot canonicalize a circular structure')
77
+ }
78
+ stack.push(value)
79
+
80
+ var out
81
+ if (Array.isArray(value)) {
82
+ // Arrays are order-significant. `undefined` has no JSON form and becomes null in an
83
+ // array, matching JSON.stringify.
84
+ out = '[' + value.map(function (item) {
85
+ return item === undefined ? 'null' : serialize(item, stack)
86
+ }).join(',') + ']'
87
+ } else {
88
+ // Absent and explicitly-undefined are indistinguishable in JSON, so both are dropped.
89
+ var keys = Object.keys(value).filter(function (key) {
90
+ return value[key] !== undefined && typeof value[key] !== 'function'
91
+ }).sort()
92
+
93
+ out = '{' + keys.map(function (key) {
94
+ return JSON.stringify(key) + ':' + serialize(value[key], stack)
95
+ }).join(',') + '}'
96
+ }
66
97
 
67
- return '{' + keys.map(function (key) {
68
- return JSON.stringify(key) + ':' + JCS.stringify(value[key])
69
- }).join(',') + '}'
98
+ stack.pop()
99
+ return out
70
100
  }
71
101
 
72
102
  throw new Error('Cannot canonicalize value of type: ' + type)
package/ltp-entry.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Legal Token Protocol — rights, claims, obligations, and their registry.
3
+ *
4
+ * Same class as `require("@smartledger/bsv").LTP`, including its statics.
5
+ */
6
+ import { LTP } from '@smartledger/bsv';
7
+ export = LTP;