@smartledger/bsv 3.4.3 → 3.4.5

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.
Files changed (89) hide show
  1. package/CHANGELOG.md +367 -0
  2. package/README.md +72 -72
  3. package/SECURITY.md +88 -0
  4. package/bin/cli.js +13 -8
  5. package/bsv-covenant.min.js +4 -4
  6. package/bsv-gdaf.min.js +5 -5
  7. package/bsv-ltp.min.js +7 -7
  8. package/bsv-smartcontract.min.js +5 -5
  9. package/bsv.bundle.js +5 -5
  10. package/bsv.d.ts +486 -9
  11. package/bsv.min.js +5 -5
  12. package/docs/COVENANT_DEVELOPMENT_RESOLVED.md +2 -2
  13. package/docs/MODULE_REFERENCE_COMPLETE.md +60 -57
  14. package/docs/advanced/UTXO_MANAGER_GUIDE.md +1 -1
  15. package/docs/getting-started/INSTALLATION.md +30 -30
  16. package/docs/getting-started/QUICK_START.md +14 -14
  17. package/docs/migration/FROM_BSV_1_5_6.md +5 -5
  18. package/gdaf-entry.js +1 -2
  19. package/index.js +20 -7
  20. package/lib/script/script.js +19 -0
  21. package/lib/smart_contract/covenant.js +10 -1
  22. package/lib/smartutxo.js +20 -12
  23. package/lib/transaction/input/publickeyhash.js +6 -1
  24. package/lib/transaction/transaction.js +12 -1
  25. package/ltp-entry.js +1 -2
  26. package/package.json +3 -3
  27. package/utilities/blockchain-state.js +32 -23
  28. package/demos/README.md +0 -188
  29. package/demos/architecture_demo.js +0 -247
  30. package/demos/browser-test.html +0 -1208
  31. package/demos/bsv_wallet_demo.js +0 -242
  32. package/demos/complete_ltp_demo.js +0 -511
  33. package/demos/debug_tools_demo.js +0 -87
  34. package/demos/demo_features.js +0 -123
  35. package/demos/easy_interface_demo.js +0 -109
  36. package/demos/ecies_demo.js +0 -182
  37. package/demos/gdaf_demo.js +0 -237
  38. package/demos/ltp_demo.js +0 -361
  39. package/demos/ltp_primitives_demo.js +0 -403
  40. package/demos/message_demo.js +0 -209
  41. package/demos/preimage_separation_demo.js +0 -383
  42. package/demos/script_helper_demo.js +0 -289
  43. package/demos/security_demo.js +0 -287
  44. package/demos/shamir_demo.js +0 -121
  45. package/demos/simple_demo.js +0 -204
  46. package/demos/simple_p2pkh_demo.js +0 -169
  47. package/demos/simple_utxo_preimage_demo.js +0 -196
  48. package/demos/smart_contract_demo.html +0 -1347
  49. package/demos/smart_contract_demo.js +0 -910
  50. package/demos/utxo_generator_demo.js +0 -244
  51. package/demos/validation_pipeline_demo.js +0 -155
  52. package/demos/web3keys.html +0 -740
  53. package/examples/README.md +0 -200
  54. package/examples/basic/transaction-creation.js +0 -534
  55. package/examples/basic/transaction_signature_api_gap.js +0 -178
  56. package/examples/complete_workflow_demo.js +0 -783
  57. package/examples/covenants/advanced_covenant_demo.js +0 -219
  58. package/examples/covenants/covenant_interface_demo.js +0 -270
  59. package/examples/covenants/covenant_manual_signature_resolved.js +0 -212
  60. package/examples/covenants/covenant_signature_template.js +0 -117
  61. package/examples/covenants2/covenant_bidirectional_example.js +0 -262
  62. package/examples/covenants2/covenant_utils_demo.js +0 -120
  63. package/examples/covenants2/preimage_covenant_utils.js +0 -287
  64. package/examples/covenants2/production_integration.js +0 -256
  65. package/examples/data/covenant_utxos.json +0 -28
  66. package/examples/data/utxos.json +0 -26
  67. package/examples/definitive_working_demo.js +0 -261
  68. package/examples/final_working_contracts.js +0 -338
  69. package/examples/legacy/README.md +0 -11
  70. package/examples/legacy/smart_contract_test_integration.js +0 -269
  71. package/examples/legacy/test_builtin_verify.js +0 -117
  72. package/examples/legacy/test_debug_integration.js +0 -71
  73. package/examples/legacy/test_ecdsa_little.js +0 -70
  74. package/examples/legacy/test_shamir.js +0 -221
  75. package/examples/legacy/test_smartverify_der.js +0 -110
  76. package/examples/preimage/README.md +0 -178
  77. package/examples/preimage/extract_preimage_bidirectional.js +0 -421
  78. package/examples/preimage/generate_sample_preimage.js +0 -208
  79. package/examples/preimage/generate_sighash_examples.js +0 -152
  80. package/examples/preimage/parse_preimage.js +0 -117
  81. package/examples/preimage/test_preimage_extractor.js +0 -53
  82. package/examples/preimage/test_varint_extraction.js +0 -95
  83. package/examples/scripts/custom_script_helper_example.js +0 -273
  84. package/examples/scripts/script_interpreter.js +0 -193
  85. package/examples/smart_contract/complete_workflow_demo.js +0 -343
  86. package/examples/smart_contract/covenant_builder_demo.js +0 -176
  87. package/examples/smart_contract/script_testing_integration.js +0 -198
  88. package/examples/smart_contract_templates.js +0 -718
  89. package/examples/working_smart_contracts.js +0 -348
@@ -34,7 +34,12 @@ PublicKeyHashInput.prototype.getSignatures = function (transaction, privateKey,
34
34
  hashData = hashData || Hash.sha256ripemd160(privateKey.publicKey.toBuffer())
35
35
  sigtype = sigtype || (Signature.SIGHASH_ALL | Signature.SIGHASH_FORKID)
36
36
 
37
- if (hashData.equals(this.output.script.getPublicKeyHash())) {
37
+ // The dispatcher (Transaction._fromNonP2SH) may have routed a "P2PKH +
38
+ // trailing data" script here via isPublicKeyHashOutPrefix() — in which
39
+ // case the strict getPublicKeyHash() would throw. Read the 20-byte hash
40
+ // directly from chunks[2] (validated by the prefix check at dispatch).
41
+ var scriptPkh = this.output.script.chunks[2] && this.output.script.chunks[2].buf
42
+ if (scriptPkh && hashData.equals(scriptPkh)) {
38
43
  return [new TransactionSignature({
39
44
  publicKey: privateKey.publicKey,
40
45
  prevTxId: this.prevTxId,
@@ -549,7 +549,11 @@ Transaction.prototype.from = function (utxo, pubkeys, threshold) {
549
549
  Transaction.prototype._fromNonP2SH = function (utxo) {
550
550
  var Clazz
551
551
  utxo = new UnspentOutput(utxo)
552
- if (utxo.script.isPublicKeyHashOut()) {
552
+ // Use the loose P2PKH check so 1Sat Ordinal outputs (P2PKH + inscription
553
+ // envelope) and other "P2PKH + trailing data" patterns dispatch to the
554
+ // signing-capable subclass instead of falling through to the abstract
555
+ // base Input. See Script.prototype.isPublicKeyHashOutPrefix.
556
+ if (utxo.script.isPublicKeyHashOutPrefix()) {
553
557
  Clazz = PublicKeyHashInput
554
558
  } else if (utxo.script.isPublicKeyOut()) {
555
559
  Clazz = PublicKeyInput
@@ -911,6 +915,13 @@ Transaction.prototype._getUnspentValue = function () {
911
915
 
912
916
  Transaction.prototype._clearSignatures = function () {
913
917
  _.each(this.inputs, function (input) {
918
+ // Custom-script inputs (bare Input base class — e.g. covenant or other
919
+ // non-standard locking scripts) have no library-managed signatures to
920
+ // clear; the caller owns input.script. Mirror the guard pattern used by
921
+ // Transaction.prototype.isFullySigned / isValidSignature below.
922
+ if (input.clearSignatures === Input.prototype.clearSignatures) {
923
+ return
924
+ }
914
925
  input.clearSignatures()
915
926
  })
916
927
  }
package/ltp-entry.js CHANGED
@@ -1,2 +1 @@
1
- // LTP module placeholder - will be implemented in future release
2
- module.exports = require('./lib/smart_contract');
1
+ module.exports = require('./lib/ltp')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smartledger/bsv",
3
- "version": "3.4.3",
3
+ "version": "3.4.5",
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",
@@ -8,12 +8,14 @@
8
8
  "url": "https://github.com/codenlighten/smartledger-bsv/issues"
9
9
  },
10
10
  "main": "index.js",
11
+ "types": "bsv.d.ts",
11
12
  "bin": {
12
13
  "smartledger-bsv": "./bin/cli.js"
13
14
  },
14
15
  "scripts": {
15
16
  "lint": "standard",
16
17
  "test": "mocha",
18
+ "test:cli": "mocha test/cli/smoke.js --timeout 25000",
17
19
  "test:ltp": "node complete_ltp_demo.js",
18
20
  "test:ltp-primitives": "node simple_demo.js",
19
21
  "test:architecture": "node architecture_demo.js",
@@ -96,8 +98,6 @@
96
98
  "bsv-anchor.min.js",
97
99
  "bsv.d.ts",
98
100
  "docs/",
99
- "demos/",
100
- "examples/",
101
101
  "LICENSE",
102
102
  "README.md",
103
103
  "SECURITY.md",
@@ -5,6 +5,15 @@
5
5
  * Acts as the "blockchain database" for our miner simulator.
6
6
  */
7
7
 
8
+ // Set BSV_DEBUG=1 (Node) or window.BSV_DEBUG = true (browser) to surface
9
+ // info/warning narration from this module. Matches the gating pattern
10
+ // used by lib/browser-utxo-manager-es5.js since v3.4.1.
11
+ const debug = function () {
12
+ const enabled = (typeof process !== 'undefined' && process.env && process.env.BSV_DEBUG) ||
13
+ (typeof window !== 'undefined' && window.BSV_DEBUG)
14
+ if (enabled) console.log.apply(console, arguments)
15
+ }
16
+
8
17
  // Browser-compatible imports
9
18
  let bsv, fs, path, BLOCKCHAIN_STATE_PATH
10
19
 
@@ -16,7 +25,7 @@ if (typeof window === 'undefined' && typeof require === 'function') {
16
25
  path = require('path')
17
26
  BLOCKCHAIN_STATE_PATH = path.join(__dirname, 'blockchain-state.json')
18
27
  } catch (e) {
19
- console.warn('BlockchainState: Running in browser mode - persistence disabled')
28
+ debug('BlockchainState: Running in browser mode - persistence disabled')
20
29
  }
21
30
  } else {
22
31
  // In browser, try to get bsv from global scope or fallback
@@ -54,14 +63,14 @@ function loadBlockchainState () {
54
63
  }
55
64
 
56
65
  if (!fs.existsSync(BLOCKCHAIN_STATE_PATH)) {
57
- console.log('🆕 Creating new blockchain state...')
66
+ debug('🆕 Creating new blockchain state...')
58
67
  const initialState = initializeBlockchainState()
59
68
  saveBlockchainState(initialState)
60
69
  return initialState
61
70
  }
62
71
 
63
72
  const state = JSON.parse(fs.readFileSync(BLOCKCHAIN_STATE_PATH, 'utf8'))
64
- console.log('📖 Loaded existing blockchain state')
73
+ debug('📖 Loaded existing blockchain state')
65
74
  return state
66
75
  } catch (error) {
67
76
  console.error('❌ Error loading blockchain state:', error.message)
@@ -79,7 +88,7 @@ function saveBlockchainState (state) {
79
88
  // Only save to file in Node.js environment
80
89
  if (fs && BLOCKCHAIN_STATE_PATH) {
81
90
  fs.writeFileSync(BLOCKCHAIN_STATE_PATH, JSON.stringify(state, null, 2))
82
- console.log('💾 Blockchain state saved')
91
+ debug('💾 Blockchain state saved')
83
92
  }
84
93
  } catch (error) {
85
94
  console.error('❌ Error saving blockchain state:', error.message)
@@ -90,12 +99,12 @@ function saveBlockchainState (state) {
90
99
  * Register a new wallet in the blockchain state
91
100
  */
92
101
  function registerWallet (walletAddress, walletData) {
93
- console.log(`📝 Registering wallet: ${walletAddress}`)
102
+ debug(`📝 Registering wallet: ${walletAddress}`)
94
103
 
95
104
  const state = loadBlockchainState()
96
105
 
97
106
  if (state.wallets[walletAddress]) {
98
- console.log('ℹ️ Wallet already exists, updating...')
107
+ debug('ℹ️ Wallet already exists, updating...')
99
108
  }
100
109
 
101
110
  state.wallets[walletAddress] = {
@@ -122,7 +131,7 @@ function registerWallet (walletAddress, walletData) {
122
131
 
123
132
  saveBlockchainState(state)
124
133
 
125
- console.log(`✅ Wallet registered: ${walletAddress}`)
134
+ debug(`✅ Wallet registered: ${walletAddress}`)
126
135
  return state
127
136
  }
128
137
 
@@ -185,7 +194,7 @@ function spendUTXO (txid, vout, spentInTx) {
185
194
 
186
195
  updateBlockchainMetadata(state)
187
196
  saveBlockchainState(state)
188
- console.log(`❌ UTXO spent: ${utxoKey} in tx ${spentInTx}`)
197
+ debug(`❌ UTXO spent: ${utxoKey} in tx ${spentInTx}`)
189
198
  }
190
199
 
191
200
  /**
@@ -197,7 +206,7 @@ function addUTXO (utxo, ownerAddress) {
197
206
 
198
207
  // Check if UTXO already exists
199
208
  if (state.globalUTXOSet[utxoKey]) {
200
- console.log(`⚠️ UTXO ${utxoKey} already exists, skipping`)
209
+ debug(`⚠️ UTXO ${utxoKey} already exists, skipping`)
201
210
  return
202
211
  }
203
212
 
@@ -229,7 +238,7 @@ function addUTXO (utxo, ownerAddress) {
229
238
  updateBlockchainMetadata(state)
230
239
  saveBlockchainState(state)
231
240
 
232
- console.log(`✅ UTXO added: ${utxoKey} for ${ownerAddress}`)
241
+ debug(`✅ UTXO added: ${utxoKey} for ${ownerAddress}`)
233
242
  }
234
243
 
235
244
  /**
@@ -255,18 +264,18 @@ function updateBlockchainMetadata (state) {
255
264
  function getBlockchainStats () {
256
265
  const state = loadBlockchainState()
257
266
 
258
- console.log('🌐 Blockchain State Statistics:')
259
- console.log('═══════════════════════════════════════════')
260
- console.log(`📊 Total Wallets: ${state.metadata.totalWallets}`)
261
- console.log(`💰 Total UTXOs: ${state.metadata.totalUTXOs}`)
262
- console.log(`💎 Total Value: ${state.metadata.totalValue} satoshis`)
263
- console.log(`🏗️ Block Height: ${state.metadata.blockHeight}`)
264
- console.log(`🕐 Last Updated: ${state.metadata.lastUpdated}\n`)
267
+ debug('🌐 Blockchain State Statistics:')
268
+ debug('═══════════════════════════════════════════')
269
+ debug(`📊 Total Wallets: ${state.metadata.totalWallets}`)
270
+ debug(`💰 Total UTXOs: ${state.metadata.totalUTXOs}`)
271
+ debug(`💎 Total Value: ${state.metadata.totalValue} satoshis`)
272
+ debug(`🏗️ Block Height: ${state.metadata.blockHeight}`)
273
+ debug(`🕐 Last Updated: ${state.metadata.lastUpdated}\n`)
265
274
 
266
275
  if (Object.keys(state.wallets).length > 0) {
267
- console.log('👛 Registered Wallets:')
276
+ debug('👛 Registered Wallets:')
268
277
  Object.entries(state.wallets).forEach(([address, wallet]) => {
269
- console.log(` ${address}: ${wallet.utxos.length} UTXOs, ${wallet.totalValue} sats`)
278
+ debug(` ${address}: ${wallet.utxos.length} UTXOs, ${wallet.totalValue} sats`)
270
279
  })
271
280
  }
272
281
 
@@ -280,14 +289,14 @@ function importWalletFromFile () {
280
289
  const walletPath = path.join(__dirname, 'wallet.json')
281
290
 
282
291
  if (!fs.existsSync(walletPath)) {
283
- console.log('❌ No wallet.json found to import')
292
+ debug('❌ No wallet.json found to import')
284
293
  return false
285
294
  }
286
295
 
287
296
  try {
288
297
  const walletData = JSON.parse(fs.readFileSync(walletPath, 'utf8'))
289
298
 
290
- console.log('📥 Importing wallet from wallet.json...')
299
+ debug('📥 Importing wallet from wallet.json...')
291
300
 
292
301
  const walletInfo = {
293
302
  registeredAt: new Date().toISOString(),
@@ -296,7 +305,7 @@ function importWalletFromFile () {
296
305
 
297
306
  registerWallet(walletData.wallet.address, walletInfo)
298
307
 
299
- console.log('✅ Wallet imported successfully')
308
+ debug('✅ Wallet imported successfully')
300
309
  return true
301
310
  } catch (error) {
302
311
  console.error('❌ Error importing wallet:', error.message)
@@ -313,7 +322,7 @@ if (require.main === module) {
313
322
  } else if (args[0] === 'init') {
314
323
  const state = initializeBlockchainState()
315
324
  saveBlockchainState(state)
316
- console.log('🆕 Initialized new blockchain state')
325
+ debug('🆕 Initialized new blockchain state')
317
326
  }
318
327
 
319
328
  getBlockchainStats()
package/demos/README.md DELETED
@@ -1,188 +0,0 @@
1
- # 🚀 SmartLedger-BSV Demo Collection
2
-
3
- This directory contains interactive demonstrations of the SmartLedger-BSV smart contract framework capabilities.
4
-
5
- ## 📋 Available Demos
6
-
7
- ### 1. 🌐 **HTML Interactive Demo** (`smart_contract_demo.html`)
8
- **Web-based interactive demonstration with visual interface**
9
-
10
- - **Purpose:** Browser-based exploration of smart contract features
11
- - **Interface:** Modern web UI with tabs, buttons, and real-time output
12
- - **Best for:** Visual learners, presentations, and quick exploration
13
-
14
- **Features:**
15
- - 📚 **Basics Tab** - Library loading and feature overview
16
- - 🔒 **Covenant Builder** - Interactive covenant creation with multiple types
17
- - 🧾 **Preimage Parser** - BIP-143 transaction field extraction
18
- - 💎 **UTXO Generator** - Mock UTXO creation and management
19
- - 🛠️ **Script Tools** - Bitcoin Script building and analysis
20
-
21
- **Usage:**
22
- ```bash
23
- # Serve locally (requires http-server or similar)
24
- npx http-server demos/
25
- # Then open http://localhost:8080/smart_contract_demo.html
26
-
27
- # Or open directly in browser
28
- open demos/smart_contract_demo.html
29
- ```
30
-
31
- ---
32
-
33
- ### 2. 💻 **Node.js CLI Demo** (`smart_contract_demo.js`)
34
- **Command-line interactive demonstration for developers**
35
-
36
- - **Purpose:** Terminal-based smart contract development workflow
37
- - **Interface:** Interactive CLI with colored output and structured commands
38
- - **Best for:** Developers, automation, CI/CD integration
39
-
40
- **Features:**
41
- - 🎯 **Interactive Mode** - Full CLI experience with command history
42
- - ⚡ **Direct Commands** - Run specific features without interaction
43
- - 🎨 **Colored Output** - Enhanced readability with chalk (optional)
44
- - 📊 **Structured Logging** - Timestamped output with status indicators
45
- - 🔧 **Developer-Friendly** - Perfect for scripting and automation
46
-
47
- **Usage:**
48
-
49
- ```bash
50
- # Interactive mode
51
- node demos/smart_contract_demo.js
52
-
53
- # Show help
54
- node demos/smart_contract_demo.js --help
55
-
56
- # Run specific features
57
- node demos/smart_contract_demo.js --feature basics
58
- node demos/smart_contract_demo.js --feature covenant
59
- node demos/smart_contract_demo.js --feature preimage
60
- node demos/smart_contract_demo.js --feature utxo
61
- node demos/smart_contract_demo.js --feature scripts
62
- ```
63
-
64
- **Interactive Commands:**
65
- ```
66
- smartledger-bsv> basics # Load library and run tests
67
- smartledger-bsv> covenant generate simple # Generate simple covenant
68
- smartledger-bsv> covenant test # Test current covenant
69
- smartledger-bsv> preimage sample # Generate sample transaction
70
- smartledger-bsv> utxo generate 50000 # Generate 50k sat UTXO
71
- smartledger-bsv> scripts build # Build sample script
72
- smartledger-bsv> examples # Show real-world use cases
73
- smartledger-bsv> help # Show all commands
74
- smartledger-bsv> exit # Exit demo
75
- ```
76
-
77
- ---
78
-
79
- ## 🎯 **Feature Comparison**
80
-
81
- | Feature | HTML Demo | Node.js Demo |
82
- |---------|-----------|--------------|
83
- | **Interface** | Visual web UI | Command-line interface |
84
- | **Interactivity** | Click-based | Type-based commands |
85
- | **Real-time Output** | Browser console + UI | Terminal with colors |
86
- | **Covenant Builder** | Form inputs + dropdowns | Command parameters |
87
- | **Script Analysis** | Visual results panel | Structured text output |
88
- | **UTXO Management** | Interactive forms | Command-driven |
89
- | **Automation** | Manual only | Scriptable commands |
90
- | **Dependencies** | Modern browser | Node.js (chalk optional) |
91
- | **Best Use Case** | Learning & exploration | Development & testing |
92
-
93
- ---
94
-
95
- ## 🔧 **Common Features Demonstrated**
96
-
97
- Both demos showcase the complete SmartLedger-BSV functionality:
98
-
99
- ### **Core Capabilities**
100
- - ✅ **Private Key & Address Generation** - Create BSV wallets
101
- - ✅ **Transaction Building** - Construct valid BSV transactions
102
- - ✅ **Script Creation** - Build custom Bitcoin Scripts
103
- - ✅ **UTXO Management** - Generate and spend test UTXOs
104
- - ✅ **Preimage Parsing** - Extract BIP-143 transaction fields
105
- - ✅ **Covenant Logic** - Create smart contract spending conditions
106
-
107
- ### **Smart Contract Types**
108
- 1. **Simple Covenants** - Basic spending restrictions
109
- 2. **Timelock Covenants** - Time-based spending conditions using preimage validation
110
- 3. **Multisig Covenants** - Multi-signature requirements
111
- 4. **Conditional Covenants** - IF/ELSE spending paths
112
-
113
- ### **Advanced Features**
114
- - 🧾 **BIP-143 Preimage Extraction** - Parse transaction preimages
115
- - 📊 **SIGHASH Analysis** - Understand signature hash types
116
- - 🔍 **Script Debugging** - Step-through script execution
117
- - ⚡ **Script Optimization** - Minimize script size and cost
118
- - 🧪 **Local Testing** - Verify scripts without blockchain access
119
-
120
- ---
121
-
122
- ## 🚀 **Quick Start Guide**
123
-
124
- ### **For Visual Learners (HTML Demo)**
125
- 1. Open `smart_contract_demo.html` in your browser
126
- 2. Click "Load BSV Smart Contract Library"
127
- 3. Explore each tab (Basics → Covenant → Preimage → UTXO → Scripts)
128
- 4. Try the real-world use case examples
129
-
130
- ### **For Developers (Node.js Demo)**
131
- 1. Run `node demos/smart_contract_demo.js`
132
- 2. Type `basics` to load and test the library
133
- 3. Try `covenant generate simple` to create your first covenant
134
- 4. Use `help` to see all available commands
135
- 5. Explore with `utxo generate`, `preimage sample`, etc.
136
-
137
- ---
138
-
139
- ## 📚 **Learning Path**
140
-
141
- **Recommended progression through the demos:**
142
-
143
- 1. **🎯 Start Here:** `basics` - Understand core BSV functionality
144
- 2. **🏗️ Build:** `covenant generate` - Create your first smart contract
145
- 3. **🔍 Analyze:** `preimage sample` - Understand transaction structure
146
- 4. **💎 Manage:** `utxo generate` - Handle UTXOs and spending
147
- 5. **🛠️ Script:** `scripts build` - Custom Bitcoin Script development
148
- 6. **🎓 Advanced:** `examples` - Real-world smart contract patterns
149
-
150
- ---
151
-
152
- ## 🔗 **Related Documentation**
153
-
154
- - **[Usage Guide](../docs/SMARTLEDGER_BSV_USAGE_GUIDE.md)** - Complete API reference
155
- - **[Usage Answers](../docs/SMARTLEDGER_BSV_USAGE_ANSWERS.md)** - FAQ and troubleshooting
156
- - **[Smart Contract Guide](../docs/advanced/SMART_CONTRACT_GUIDE.md)** - Advanced development
157
- - **[Examples Directory](../examples/)** - Additional code samples
158
- - **[GitHub Repository](https://github.com/codenlighten/smartledger-bsv)** - Source code
159
-
160
- ---
161
-
162
- ## 🆘 **Support & Troubleshooting**
163
-
164
- ### **Common Issues**
165
-
166
- **HTML Demo:**
167
- - **Bundle not found:** Ensure `../bsv.bundle.js` exists (run `npm run build`)
168
- - **CORS issues:** Serve via HTTP server, don't open file:// directly
169
- - **Console errors:** Check browser developer tools for detailed errors
170
-
171
- **Node.js Demo:**
172
- - **Module errors:** Run `npm install` to ensure dependencies
173
- - **Chalk missing:** Demo works without chalk (fallback to plain text)
174
- - **Permission denied:** Use `chmod +x demos/smart_contract_demo.js`
175
-
176
- ### **Getting Help**
177
-
178
- - **Issues:** [GitHub Issues](https://github.com/codenlighten/smartledger-bsv/issues)
179
- - **Documentation:** Check the `docs/` directory for detailed guides
180
- - **Examples:** Browse `examples/` for working code samples
181
-
182
- ---
183
-
184
- **Created by:** SmartLedger-BSV Development Team
185
- **Version:** v3.3.4
186
- **Last Updated:** October 30, 2025
187
-
188
- *Both demos provide identical functionality - choose the interface that works best for your workflow!* 🎉
@@ -1,247 +0,0 @@
1
- /**
2
- * SmartLedger-BSV Legal Token Protocol (LTP) - Primitives-Only Architecture Demo
3
- *
4
- * This demonstrates the key architectural difference:
5
- * BEFORE: Library did blockchain publishing and storage
6
- * AFTER: Library provides preparation primitives, external systems handle publishing
7
- */
8
-
9
- const bsv = require('../index.js')
10
-
11
- console.log('🚀 SmartLedger-BSV LTP: Primitives-Only Architecture')
12
- console.log('==================================================\n')
13
-
14
- console.log('🔄 ARCHITECTURAL TRANSFORMATION DEMO')
15
- console.log('------------------------------------\n')
16
-
17
- // Demo keys and identities
18
- const issuerPrivateKey = new bsv.PrivateKey()
19
- const ownerDID = `did:bsv:${new bsv.PrivateKey().publicKey.toString()}`
20
- const obligorDID = `did:bsv:${new bsv.PrivateKey().publicKey.toString()}`
21
-
22
- console.log('📋 Participants:')
23
- console.log(` Issuer DID: ${issuerPrivateKey.publicKey.toString()}`)
24
- console.log(` Owner DID: ${ownerDID}`)
25
- console.log(` Obligor DID: ${obligorDID}\n`)
26
-
27
- /**
28
- * DEMONSTRATE CLAIM VALIDATION PRIMITIVES
29
- */
30
- console.log('1️⃣ CLAIM VALIDATION - Primitives Only')
31
- console.log('=====================================')
32
-
33
- const propertyClaimData = {
34
- type: 'PropertyTitle',
35
- property: {
36
- address: '123 Blockchain Street',
37
- parcel_id: 'BLK-2024-001',
38
- property_type: 'residential'
39
- },
40
- owner: ownerDID
41
- }
42
-
43
- // Get available schemas (unchanged utility)
44
- const availableSchemas = bsv.getClaimSchemaNames()
45
- console.log('📚 Available claim schemas:', availableSchemas.join(', '))
46
-
47
- // Create claim template (utility function)
48
- const claimTemplate = bsv.createClaimTemplate('PropertyTitle')
49
- console.log('📋 Claim template structure:')
50
- console.log(' Required fields:', Object.keys(claimTemplate).slice(0, 3).join(', '), '...')
51
-
52
- console.log('\n🔧 PRIMITIVES-ONLY APPROACH:')
53
- console.log(' ✅ Library validates claim structure')
54
- console.log(' ✅ Library provides canonicalization')
55
- console.log(' ✅ Library generates claim hash')
56
- console.log(' ❌ Library does NOT store claims')
57
- console.log(' ❌ Library does NOT publish to blockchain')
58
-
59
- // Demonstrate claim processing primitives
60
- const claimHash = bsv.hashClaim(propertyClaimData)
61
- const canonicalClaim = bsv.canonicalizeClaim(propertyClaimData)
62
-
63
- console.log('📊 Claim processing results:')
64
- console.log(` Claim Hash: ${claimHash}`)
65
- console.log(` Canonical Form: ${canonicalClaim.length} bytes`)
66
- console.log('')
67
-
68
- /**
69
- * DEMONSTRATE RIGHT TOKEN PRIMITIVES
70
- */
71
- console.log('2️⃣ RIGHT TOKEN - Preparation Primitives')
72
- console.log('=======================================')
73
-
74
- console.log('🔧 PRIMITIVES-ONLY APPROACH:')
75
-
76
- // Get available right types
77
- const rightTypes = bsv.getRightTypes()
78
- console.log('⚖️ Available right types:', Object.keys(rightTypes).slice(0, 4).join(', '), '...')
79
-
80
- // Prepare right token (doesn't create, just prepares structure)
81
- try {
82
- const rightTokenPrep = bsv.prepareRightToken(
83
- 'PROPERTY_OWNERSHIP',
84
- `did:bsv:${issuerPrivateKey.publicKey.toString()}`,
85
- ownerDID,
86
- propertyClaimData,
87
- issuerPrivateKey,
88
- {
89
- jurisdiction: 'demo_jurisdiction',
90
- validUntil: '2034-01-15'
91
- }
92
- )
93
-
94
- console.log('🏠 Right token prepared:')
95
- console.log(` Token ID: ${rightTokenPrep.tokenId}`)
96
- console.log(` Right Type: ${rightTokenPrep.rightType}`)
97
- console.log(` Valid Until: ${rightTokenPrep.validUntil}`)
98
- console.log(` Jurisdiction: ${rightTokenPrep.jurisdiction}`)
99
-
100
- // Prepare verification data
101
- const verificationPrep = bsv.prepareRightTokenVerification(rightTokenPrep.token)
102
- console.log(` Verification Ready: ${verificationPrep.isValid ? 'YES' : 'NO'}`)
103
-
104
- console.log('\n ✅ Library prepares token structure')
105
- console.log(' ✅ Library validates token format')
106
- console.log(' ✅ Library signs token data')
107
- console.log(' ❌ Library does NOT publish to blockchain')
108
- console.log(' ❌ Library does NOT store in registry')
109
-
110
- } catch (error) {
111
- console.log('⚠️ Right token preparation demo skipped (module loading)')
112
- console.log(' Expected: Token preparation without blockchain publishing')
113
- }
114
-
115
- console.log('')
116
-
117
- /**
118
- * DEMONSTRATE OBLIGATION PRIMITIVES
119
- */
120
- console.log('3️⃣ OBLIGATION TOKEN - Management Primitives')
121
- console.log('===========================================')
122
-
123
- console.log('🔧 PRIMITIVES-ONLY APPROACH:')
124
-
125
- // Get obligation types and statuses
126
- try {
127
- const obligationTypes = bsv.getObligationTypes()
128
- const obligationStatuses = bsv.getObligationStatus()
129
-
130
- console.log('📊 Obligation framework:')
131
- console.log(` Types available: ${Object.keys(obligationTypes).length}`)
132
- console.log(` Status options: ${Object.keys(obligationStatuses).length}`)
133
- console.log(` Priority levels: ${Object.keys(bsv.getObligationPriority()).length}`)
134
-
135
- console.log('\n ✅ Library prepares obligation tokens')
136
- console.log(' ✅ Library validates fulfillment data')
137
- console.log(' ✅ Library tracks obligation status')
138
- console.log(' ❌ Library does NOT execute payments')
139
- console.log(' ❌ Library does NOT enforce obligations')
140
-
141
- } catch (error) {
142
- console.log('⚠️ Obligation demo skipped (module loading)')
143
- console.log(' Expected: Obligation management without execution')
144
- }
145
-
146
- console.log('')
147
-
148
- /**
149
- * DEMONSTRATE REGISTRY PRIMITIVES
150
- */
151
- console.log('4️⃣ REGISTRY MANAGEMENT - Preparation Primitives')
152
- console.log('===============================================')
153
-
154
- console.log('🔧 PRIMITIVES-ONLY APPROACH:')
155
- console.log(' ✅ Library prepares registry data structures')
156
- console.log(' ✅ Library formats token registration data')
157
- console.log(' ✅ Library validates registry queries')
158
- console.log(' ❌ Library does NOT store registry data')
159
- console.log(' ❌ Library does NOT manage database connections')
160
-
161
- // Simulate registry preparation
162
- console.log('📝 Registry operations prepared:')
163
- console.log(' • Token registration data formatted')
164
- console.log(' • Search query structure validated')
165
- console.log(' • Audit log format prepared')
166
- console.log(' • Statistics query template ready')
167
- console.log('')
168
-
169
- /**
170
- * DEMONSTRATE BLOCKCHAIN ANCHORING PRIMITIVES
171
- */
172
- console.log('5️⃣ BLOCKCHAIN ANCHORING - Commitment Primitives')
173
- console.log('===============================================')
174
-
175
- console.log('🔧 PRIMITIVES-ONLY APPROACH:')
176
- console.log(' ✅ Library prepares commitment hashes')
177
- console.log(' ✅ Library creates merkle tree structures')
178
- console.log(' ✅ Library validates anchor proofs')
179
- console.log(' ❌ Library does NOT publish transactions')
180
- console.log(' ❌ Library does NOT manage wallet keys')
181
-
182
- // Simulate anchor preparation
183
- console.log('⛓️ Blockchain operations prepared:')
184
- console.log(' • Token commitment hash: ready for transaction')
185
- console.log(' • Batch merkle root: ready for efficient anchoring')
186
- console.log(' • Verification proof: ready for anchor validation')
187
- console.log(' • Revocation format: ready for token cancellation')
188
- console.log('')
189
-
190
- /**
191
- * SUMMARY OF ARCHITECTURAL BENEFITS
192
- */
193
- console.log('🎯 PRIMITIVES-ONLY ARCHITECTURE BENEFITS')
194
- console.log('========================================')
195
- console.log('')
196
- console.log('🏗️ SEPARATION OF CONCERNS:')
197
- console.log(' 📚 SmartLedger-BSV: Foundation library with crypto primitives')
198
- console.log(' 🔧 External Apps: Handle UI, storage, and blockchain publishing')
199
- console.log(' ⚖️ Legal Framework: Validated structure and compliance tools')
200
- console.log('')
201
- console.log('💪 DEVELOPER BENEFITS:')
202
- console.log(' • Maximum flexibility in implementation choices')
203
- console.log(' • No vendor lock-in to specific platforms or blockchains')
204
- console.log(' • Clean separation between crypto/legal logic and app logic')
205
- console.log(' • Easy integration with existing systems and workflows')
206
- console.log('')
207
- console.log('⚡ LIBRARY ADVANTAGES:')
208
- console.log(' • Focused on what it does best: cryptography and validation')
209
- console.log(' • Smaller footprint and fewer dependencies')
210
- console.log(' • More predictable behavior and easier testing')
211
- console.log(' • Clear API boundaries and responsibilities')
212
- console.log('')
213
- console.log('🔗 INTEGRATION PATTERN:')
214
- console.log(' 1. Use SmartLedger-BSV to prepare and validate legal tokens')
215
- console.log(' 2. Use external systems for blockchain publishing')
216
- console.log(' 3. Use external systems for storage and registries')
217
- console.log(' 4. Use external systems for user interfaces and workflows')
218
- console.log('')
219
- console.log('🚀 RESULT: Complete foundation for any Legal Token Protocol')
220
- console.log(' application while maintaining architectural flexibility!')
221
-
222
- /**
223
- * SHOW EXAMPLE EXTERNAL SYSTEM INTEGRATION
224
- */
225
- console.log('')
226
- console.log('📋 EXAMPLE: How External Systems Would Use These Primitives')
227
- console.log('=========================================================')
228
- console.log('')
229
- console.log('// External Application Code Example:')
230
- console.log('const bsv = require("smartledger-bsv")')
231
- console.log('const MyBlockchainAPI = require("my-blockchain-service")')
232
- console.log('const MyStorage = require("my-database-service")')
233
- console.log('')
234
- console.log('// 1. Use SmartLedger-BSV to prepare legal token')
235
- console.log('const tokenPrep = bsv.prepareRightToken(...)')
236
- console.log('')
237
- console.log('// 2. Use external service to publish to blockchain')
238
- console.log('const txResult = await MyBlockchainAPI.publish(tokenPrep.commitment)')
239
- console.log('')
240
- console.log('// 3. Use external service to store token data')
241
- console.log('const storeResult = await MyStorage.save(tokenPrep.token)')
242
- console.log('')
243
- console.log('// 4. Use SmartLedger-BSV to verify results')
244
- console.log('const verification = bsv.verifyTokenAnchor(token, txResult.txid)')
245
- console.log('')
246
- console.log('This pattern gives developers complete control while ensuring')
247
- console.log('cryptographic and legal correctness through SmartLedger-BSV!')