smartledger-bsv 3.3.2 → 3.3.4

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 (118) hide show
  1. package/CHANGELOG.md +220 -79
  2. package/README.md +283 -71
  3. package/bsv-covenant.min.js +26 -3
  4. package/bsv-gdaf.min.js +11 -9
  5. package/bsv-ltp.min.js +10 -8
  6. package/bsv-mnemonic.min.js +4 -4
  7. package/bsv-script-helper.min.js +2 -2
  8. package/bsv-security.min.js +3 -24
  9. package/bsv-shamir.min.js +2 -2
  10. package/bsv-smartcontract.min.js +10 -8
  11. package/bsv.bundle.js +9 -9
  12. package/bsv.min.js +10 -8
  13. package/build/webpack.bundle.config.js +2 -2
  14. package/build/webpack.config.js +2 -2
  15. package/build/webpack.covenant.config.js +2 -2
  16. package/build/webpack.gdaf.config.js +6 -43
  17. package/build/webpack.script-helper.config.js +2 -2
  18. package/build/webpack.security.config.js +2 -2
  19. package/build/webpack.smartcontract.config.js +2 -2
  20. package/bundle-entry.js +1 -341
  21. package/covenant-entry.js +1 -44
  22. package/demos/README.md +188 -0
  23. package/{architecture_demo.js → demos/architecture_demo.js} +2 -2
  24. package/demos/bsv_wallet_demo.js +242 -0
  25. package/{complete_ltp_demo.js → demos/complete_ltp_demo.js} +1 -1
  26. package/demos/debug_tools_demo.js +87 -0
  27. package/demos/demo_features.js +123 -0
  28. package/demos/easy_interface_demo.js +109 -0
  29. package/demos/ecies_demo.js +182 -0
  30. package/demos/gdaf_core_test.js +131 -0
  31. package/demos/gdaf_demo.js +237 -0
  32. package/demos/ltp_demo.js +361 -0
  33. package/demos/ltp_primitives_demo.js +403 -0
  34. package/demos/message_demo.js +209 -0
  35. package/demos/preimage_separation_demo.js +383 -0
  36. package/demos/script_helper_demo.js +289 -0
  37. package/demos/security_demo.js +287 -0
  38. package/{shamir_demo.js → demos/shamir_demo.js} +1 -1
  39. package/{simple_demo.js → demos/simple_demo.js} +1 -1
  40. package/demos/simple_p2pkh_demo.js +169 -0
  41. package/demos/simple_utxo_preimage_demo.js +196 -0
  42. package/demos/smart_contract_demo.html +1347 -0
  43. package/demos/smart_contract_demo.js +910 -0
  44. package/demos/utxo_generator_demo.js +244 -0
  45. package/demos/validation_pipeline_demo.js +155 -0
  46. package/demos/web3keys.html +740 -0
  47. package/docs/BUNDLE_UPDATE_SUMMARY.md +40 -0
  48. package/docs/DOCUMENTATION_REVIEW_REPORT.md +295 -0
  49. package/docs/FIX_CREATEHMAC_ISSUE.md +91 -0
  50. package/docs/MODULE_REFERENCE_COMPLETE.md +330 -0
  51. package/docs/README.md +107 -79
  52. package/docs/SMARTLEDGER_BSV_USAGE_ANSWERS.md +477 -0
  53. package/docs/SMARTLEDGER_BSV_USAGE_EXAMPLES.js +372 -0
  54. package/docs/SMARTLEDGER_BSV_USAGE_GUIDE.md +555 -0
  55. package/docs/SMART_CONTRACT_DEVELOPMENT_GUIDE.md +1459 -0
  56. package/docs/advanced/LEGAL_TOKEN_PROTOCOL.md +411 -0
  57. package/docs/advanced/SMART_CONTRACT_GUIDE.md +1255 -0
  58. package/docs/advanced/UTXO_MANAGER_GUIDE.md +851 -0
  59. package/docs/api/LTP.md +334 -0
  60. package/docs/getting-started/INSTALLATION.md +410 -0
  61. package/docs/getting-started/QUICK_START.md +180 -0
  62. package/docs/migration/FROM_BSV_1_5_6.md +260 -0
  63. package/docs/technical/GDAF_DEVELOPER_INTERFACE.md +187 -0
  64. package/docs/technical/GDAF_IMPLEMENTATION_COMPLETE.md +190 -0
  65. package/docs/technical/SHAMIR_INTEGRATION_SUMMARY.md +165 -0
  66. package/docs/technical/roadmap.md +1250 -0
  67. package/docs/technical/trust_law.md +142 -0
  68. package/examples/complete_workflow_demo.js +783 -0
  69. package/examples/definitive_working_demo.js +261 -0
  70. package/examples/final_working_contracts.js +338 -0
  71. package/examples/smart_contract_templates.js +718 -0
  72. package/examples/working_smart_contracts.js +348 -0
  73. package/gdaf-entry.js +2 -54
  74. package/index.js +32 -0
  75. package/lib/mnemonic/pbkdf2.browser.js +69 -0
  76. package/lib/mnemonic/pbkdf2.js +2 -68
  77. package/lib/mnemonic/pbkdf2.node.js +68 -0
  78. package/ltp-entry.js +2 -92
  79. package/package.json +21 -8
  80. package/script-helper-entry.js +1 -49
  81. package/security-entry.js +1 -70
  82. package/shamir-entry.js +1 -173
  83. package/smartcontract-entry.js +1 -133
  84. package/tests/browser-compatibility/README.md +35 -0
  85. package/tests/browser-compatibility/test-cdn-vs-local.html +186 -0
  86. package/tests/browser-compatibility/test-pbkdf2.html +51 -0
  87. package/tests/test_builtin_verify.js +117 -0
  88. package/tests/test_debug_integration.js +71 -0
  89. package/tests/test_ecdsa_little.js +70 -0
  90. package/tests/test_smartverify_der.js +110 -0
  91. package/utilities/blockchain-state.js +155 -155
  92. package/utilities/blockchain-state.json +103293 -5244
  93. package/utilities/miner-simulator.js +354 -358
  94. package/utilities/mock-utxo-generator.js +54 -54
  95. package/utilities/raw-tx-examples.js +120 -122
  96. package/utilities/success-demo.js +104 -105
  97. package/utilities/transaction-examples.js +188 -188
  98. package/utilities/utxo-manager.js +91 -91
  99. package/utilities/wallet-setup.js +79 -80
  100. package/utilities/working-signature-demo.js +108 -110
  101. package/SECURITY.md +0 -75
  102. package/build/bsv-covenant.min.js +0 -10
  103. package/build/bsv-script-helper.min.js +0 -10
  104. package/build/bsv-security.min.js +0 -31
  105. package/build/bsv-smartcontract.min.js +0 -39
  106. package/build/bsv.bundle.js +0 -39
  107. package/build/bsv.min.js +0 -39
  108. package/validation_test.js +0 -97
  109. /package/docs/{ADVANCED_COVENANT_DEVELOPMENT.md → advanced/ADVANCED_COVENANT_DEVELOPMENT.md} +0 -0
  110. /package/docs/{CUSTOM_SCRIPT_DEVELOPMENT.md → advanced/CUSTOM_SCRIPT_DEVELOPMENT.md} +0 -0
  111. /package/docs/{block.md → api/BLOCKS.md} +0 -0
  112. /package/docs/{ecies.md → api/ECIES.md} +0 -0
  113. /package/docs/{networks.md → api/NETWORKS.md} +0 -0
  114. /package/docs/{script.md → api/SCRIPTS.md} +0 -0
  115. /package/docs/{transaction.md → api/TRANSACTIONS.md} +0 -0
  116. /package/docs/{unspentoutput.md → api/UTXO.md} +0 -0
  117. /package/{test_shamir.js → tests/test_shamir.js} +0 -0
  118. /package/{test_standalone_shamir.html → tests/test_standalone_shamir.html} +0 -0
@@ -0,0 +1,188 @@
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.3
186
+ **Last Updated:** October 30, 2025
187
+
188
+ *Both demos provide identical functionality - choose the interface that works best for your workflow!* 🎉
@@ -6,7 +6,7 @@
6
6
  * AFTER: Library provides preparation primitives, external systems handle publishing
7
7
  */
8
8
 
9
- const bsv = require('./index.js')
9
+ const bsv = require('../index.js')
10
10
 
11
11
  console.log('🚀 SmartLedger-BSV LTP: Primitives-Only Architecture')
12
12
  console.log('==================================================\n')
@@ -47,7 +47,7 @@ console.log('📚 Available claim schemas:', availableSchemas.join(', '))
47
47
  // Create claim template (utility function)
48
48
  const claimTemplate = bsv.createClaimTemplate('PropertyTitle')
49
49
  console.log('📋 Claim template structure:')
50
- console.log(' Required fields:', Object.keys(claimTemplate.properties).slice(0, 3).join(', '), '...')
50
+ console.log(' Required fields:', Object.keys(claimTemplate).slice(0, 3).join(', '), '...')
51
51
 
52
52
  console.log('\n🔧 PRIMITIVES-ONLY APPROACH:')
53
53
  console.log(' ✅ Library validates claim structure')
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * SmartLedger Real BSV Wallet Demo
5
+ *
6
+ * This script demonstrates how to use SmartLedger-BSV with real BSV addresses
7
+ * for UTXO management, transaction creation, and validation.
8
+ *
9
+ * Usage Examples:
10
+ * - Check real BSV address balance and UTXOs
11
+ * - Create and validate real BSV transactions
12
+ * - Test signature verification with real data
13
+ * - Optionally broadcast transactions to BSV network
14
+ */
15
+
16
+ const bsv = require('../index.js');
17
+
18
+ // Demo configuration - replace with your own for real use
19
+ const DEMO_CONFIG = {
20
+ // Test private key (has 0 balance) - replace with your own for real testing
21
+ privateKey: 'L1aW4aubDFB7yfras2S1mN3bqg9nwySY8nkoLmJebSLD5BWv3ENZ',
22
+
23
+ // Demo addresses for testing
24
+ testAddresses: {
25
+ bitcoinEater: '1BitcoinEaterAddressDontSendf59kuE', // Provably unspendable
26
+ satoshiGenesis: '12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX' // Genesis block address
27
+ }
28
+ };
29
+
30
+ console.log('🚀 SmartLedger Real BSV Wallet Demo');
31
+ console.log('===================================\n');
32
+
33
+ console.log('💡 This demo shows how to:');
34
+ console.log(' • Use real BSV private keys and addresses');
35
+ console.log(' • Fetch real UTXOs from the BSV blockchain');
36
+ console.log(' • Create and validate real BSV transactions');
37
+ console.log(' • Test signature verification with real data');
38
+ console.log(' • Optionally broadcast to the BSV network\n');
39
+
40
+ console.log('⚠️ IMPORTANT SAFETY NOTES:');
41
+ console.log(' • This demo uses a test key with 0 balance');
42
+ console.log(' • Replace DEMO_CONFIG.privateKey with your own for real use');
43
+ console.log(' • Always test on testnet first (use --testnet flag)');
44
+ console.log(' • Broadcasting requires --broadcast flag for safety\n');
45
+
46
+ // Initialize wallet
47
+ const privateKey = new bsv.PrivateKey(DEMO_CONFIG.privateKey);
48
+ const address = privateKey.toAddress().toString();
49
+
50
+ console.log('📱 Demo Wallet:');
51
+ console.log(`Private Key: ${DEMO_CONFIG.privateKey}`);
52
+ console.log(`Address: ${address}`);
53
+ console.log(`Public Key: ${privateKey.publicKey.toString()}\n`);
54
+
55
+ // Real BSV integration example
56
+ async function demonstrateRealBSV() {
57
+ console.log('🌍 Real BSV Blockchain Integration:');
58
+ console.log('==================================');
59
+ console.log('');
60
+ console.log('📚 Real BSV integration available via separate modules');
61
+
62
+ console.log('1. ✅ SmartLedger signature verification works');
63
+ console.log('2. ✅ Real UTXO fetching via WhatsOnChain API');
64
+ console.log('3. ✅ Transaction creation and validation');
65
+ console.log('4. ✅ Broadcasting capability (when enabled)');
66
+ console.log('5. ✅ Mock UTXO fallback for testing\n');
67
+ }
68
+
69
+ // Signature verification demo with real keys
70
+ function demonstrateSignatureVerification() {
71
+ console.log('🔐 Signature Verification with Real Keys:');
72
+ console.log('=========================================');
73
+
74
+ // Create a message to sign
75
+ const message = `SmartLedger-BSV Demo - ${new Date().toISOString()}`;
76
+ const messageBuffer = Buffer.from(message, 'utf8');
77
+ const hash = bsv.crypto.Hash.sha256(messageBuffer);
78
+
79
+ console.log(`Message: "${message}"`);
80
+ console.log(`Hash: ${hash.toString('hex')}`);
81
+
82
+ // Create signature
83
+ const signature = bsv.crypto.ECDSA.sign(hash, privateKey);
84
+ const derSig = signature.toDER();
85
+
86
+ console.log(`Signature: ${derSig.toString('hex')}`);
87
+ console.log(`Is canonical: ${signature.isCanonical()}`);
88
+
89
+ // Verify signature - this was broken in v3.0.1, fixed in v3.0.2!
90
+ const verified1 = bsv.crypto.ECDSA.verify(hash, derSig, privateKey.publicKey);
91
+ const verified2 = bsv.SmartVerify.smartVerify(hash, derSig, privateKey.publicKey);
92
+ const isCanonical = bsv.SmartVerify.isCanonical(derSig);
93
+
94
+ console.log('\n📊 Verification Results:');
95
+ console.log(`ECDSA.verify(): ${verified1 ? '✅ VALID' : '❌ INVALID'}`);
96
+ console.log(`SmartVerify.smartVerify(): ${verified2 ? '✅ VALID' : '❌ INVALID'}`);
97
+ console.log(`SmartVerify.isCanonical(): ${isCanonical ? '✅ CANONICAL' : '❌ NON-CANONICAL'}`);
98
+
99
+ if (verified1 && verified2 && isCanonical) {
100
+ console.log('\n🎉 All signature verification methods working correctly!');
101
+ } else {
102
+ console.log('\n❌ Signature verification failed - this indicates a bug');
103
+ }
104
+ }
105
+
106
+ // Transaction creation demo
107
+ function demonstrateTransactionCreation() {
108
+ console.log('\n💸 Transaction Creation Demo:');
109
+ console.log('============================');
110
+
111
+ // Create a mock UTXO for demonstration
112
+ const mockUTXO = {
113
+ txid: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
114
+ vout: 0,
115
+ address: address,
116
+ satoshis: 100000, // 1000 bits
117
+ script: '76a914' + bsv.Address.fromString(address).hashBuffer.toString('hex') + '88ac'
118
+ };
119
+
120
+ console.log('Mock UTXO for demo:');
121
+ console.log(` TXID: ${mockUTXO.txid}`);
122
+ console.log(` Vout: ${mockUTXO.vout}`);
123
+ console.log(` Address: ${mockUTXO.address}`);
124
+ console.log(` Satoshis: ${mockUTXO.satoshis}`);
125
+
126
+ try {
127
+ // Create transaction
128
+ const transaction = new bsv.Transaction()
129
+ .from(mockUTXO)
130
+ .to(DEMO_CONFIG.testAddresses.bitcoinEater, 1000)
131
+ .change(address)
132
+ .sign(privateKey);
133
+
134
+ console.log('\n🏗️ Transaction Created:');
135
+ console.log(` Transaction ID: ${transaction.id}`);
136
+ console.log(` Inputs: ${transaction.inputs.length}`);
137
+ console.log(` Outputs: ${transaction.outputs.length}`);
138
+ console.log(` Size: ${transaction.toBuffer().length} bytes`);
139
+
140
+ // Validate transaction
141
+ const isValid = transaction.verify();
142
+ console.log(` Validation: ${isValid ? '✅ VALID' : '❌ INVALID'}`);
143
+
144
+ if (isValid) {
145
+ console.log(` Raw TX: ${transaction.toString()}`);
146
+ console.log('\n✅ Transaction created and validated successfully!');
147
+ console.log('💡 This transaction could be broadcast with real UTXOs');
148
+ } else {
149
+ console.log('\n❌ Transaction validation failed');
150
+ }
151
+ } catch (error) {
152
+ console.log(`\n❌ Transaction creation failed: ${error.message}`);
153
+ }
154
+ }
155
+
156
+ // UTXO management demo
157
+ function demonstrateUTXOManagement() {
158
+ console.log('\n💰 UTXO Management Demo:');
159
+ console.log('========================');
160
+
161
+ // Create SmartUTXO manager
162
+ const utxoManager = new bsv.SmartUTXO();
163
+
164
+ // Create some mock UTXOs
165
+ const mockUTXOs = utxoManager.createMockUTXOs(address, 3, 50000);
166
+
167
+ console.log('Adding mock UTXOs to management system:');
168
+ mockUTXOs.forEach((utxo, i) => {
169
+ utxoManager.addUTXO(utxo);
170
+ console.log(` ${i + 1}: ${utxo.txid.substring(0, 16)}...${utxo.txid.substring(48)}:${utxo.vout} = ${utxo.satoshis} sats`);
171
+ });
172
+
173
+ // Check balance and UTXOs
174
+ const balance = utxoManager.getBalance(address);
175
+ const utxos = utxoManager.getUTXOsForAddress(address);
176
+ const stats = utxoManager.getStats();
177
+
178
+ console.log('\n📊 Wallet Status:');
179
+ console.log(` Balance: ${balance} satoshis (${balance / 100000000} BSV)`);
180
+ console.log(` Available UTXOs: ${utxos.length}`);
181
+ console.log(` Total blockchain UTXOs: ${stats.totalUTXOs}`);
182
+ console.log(` Total blockchain value: ${stats.totalValue} satoshis`);
183
+
184
+ // Demonstrate spending
185
+ if (utxos.length > 0) {
186
+ const utxoToSpend = utxos[0];
187
+ console.log(`\n💸 Spending UTXO: ${utxoToSpend.txid.substring(0, 16)}...${utxoToSpend.txid.substring(48)}:${utxoToSpend.vout}`);
188
+
189
+ utxoManager.spendUTXOs([{ txid: utxoToSpend.txid, vout: utxoToSpend.vout }]);
190
+
191
+ const newBalance = utxoManager.getBalance(address);
192
+ console.log(` New balance: ${newBalance} satoshis (reduced by ${balance - newBalance})`);
193
+ }
194
+
195
+ console.log('\n✅ UTXO management working correctly!');
196
+ }
197
+
198
+ // Production usage guide
199
+ function showProductionGuide() {
200
+ console.log('\n📚 Production Usage Guide:');
201
+ console.log('=========================');
202
+
203
+ console.log('For real BSV applications:');
204
+ console.log('');
205
+ console.log('1. 🔑 Replace DEMO_CONFIG.privateKey with your private key');
206
+ console.log(' const privateKey = new bsv.PrivateKey("YOUR_PRIVATE_KEY_WIF");');
207
+ console.log('');
208
+ console.log('2. 🌍 Fetch real UTXOs using the RealUTXOManager:');
209
+ console.log(' const utxoManager = new RealUTXOManager({ network: "main" });');
210
+ console.log(' const realUTXOs = await utxoManager.fetchRealUTXOs(address);');
211
+ console.log('');
212
+ console.log('3. 💸 Create real transactions:');
213
+ console.log(' const txResult = await utxoManager.createAndValidateTransaction(');
214
+ console.log(' fromAddress, toAddress, satoshis, feePerByte');
215
+ console.log(' );');
216
+ console.log('');
217
+ console.log('4. 📡 Broadcast to network (BE CAREFUL!):');
218
+ console.log(' if (txResult.isValid) {');
219
+ console.log(' await utxoManager.broadcastTransaction(txResult.rawTx);');
220
+ console.log(' }');
221
+ console.log('');
222
+ console.log('💡 Always test on testnet first: node real_utxo_test.js --testnet');
223
+ console.log('⚠️ Use --broadcast flag only when ready to spend real BSV!');
224
+ }
225
+
226
+ // Run all demos
227
+ console.log('🚀 Running SmartLedger-BSV Demos...\n');
228
+
229
+ demonstrateSignatureVerification();
230
+ demonstrateTransactionCreation();
231
+ demonstrateUTXOManagement();
232
+ demonstrateRealBSV();
233
+ showProductionGuide();
234
+
235
+ console.log('\n🎉 Demo completed successfully!');
236
+ console.log('✅ SmartLedger-BSV v3.0.2 is ready for real BSV development!');
237
+ console.log('');
238
+ console.log('📖 Next steps:');
239
+ console.log(' • Run: node real_utxo_test.js --help');
240
+ console.log(' • Test with testnet: node real_utxo_test.js --testnet');
241
+ console.log(' • Check documentation: README.md and CHANGELOG.md');
242
+ console.log(' • Report issues: https://github.com/codenlighten/smartledger-bsv/issues');
@@ -8,7 +8,7 @@
8
8
  * - Complete end-to-end LTP workflow
9
9
  */
10
10
 
11
- const bsv = require('./index.js')
11
+ const bsv = require('../index.js')
12
12
  const crypto = require('crypto')
13
13
 
14
14
  console.log('🚀 SmartLedger-BSV LTP: Complete Working Example')
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Debug Tools Integration Demo
4
+ * ============================
5
+ * Demonstrates the newly integrated debugging tools in SmartContract interface
6
+ */
7
+
8
+ const bsv = require('../bsv.min.js');
9
+ const SmartContract = bsv.SmartContract;
10
+
11
+ console.log("🎯 SmartContract Debug Tools Demo");
12
+ console.log("==================================\n");
13
+
14
+ // Demo 1: Script Parsing
15
+ console.log("1. 📝 Script Parsing:");
16
+ const asmScript = SmartContract.parseScript("OP_1 OP_DUP OP_ADD");
17
+ const hexScript = SmartContract.parseScript("5176935393");
18
+
19
+ console.log(" ASM -> Chunks:", asmScript.chunks.length);
20
+ console.log(" HEX -> Chunks:", hexScript.chunks.length);
21
+ console.log(" ASM Script:", asmScript.toASM());
22
+ console.log(" HEX Script:", hexScript.toASM());
23
+
24
+ // Demo 2: Stack Analysis Tools
25
+ console.log("\n2. 🔍 Stack Analysis:");
26
+ const testStacks = [
27
+ [Buffer.from('01', 'hex')],
28
+ [Buffer.from('01', 'hex'), Buffer.from('02', 'hex')],
29
+ [Buffer.from('ff', 'hex')]
30
+ ];
31
+
32
+ testStacks.forEach((stack, i) => {
33
+ console.log(` Stack ${i + 1}:`);
34
+ SmartContract.printStack(stack);
35
+ });
36
+
37
+ // Demo 3: Script Utilities Integration
38
+ console.log("\n3. 🛠️ Script Utilities:");
39
+ const testScript = SmartContract.parseScript("OP_DUP OP_HASH160");
40
+
41
+ console.log(" Script to ASM:", SmartContract.scriptToASM(testScript.toBuffer()));
42
+ console.log(" Script to HEX:", SmartContract.scriptToHex(testScript));
43
+ console.log(" Script size:", SmartContract.estimateScriptSize(testScript), "bytes");
44
+
45
+ const validation = SmartContract.validateScript(testScript);
46
+ console.log(" Validation:", validation.valid ? "✅ Valid" : "❌ Invalid");
47
+
48
+ // Demo 4: Feature Flags
49
+ console.log("\n4. 🏳️ Debug Feature Flags:");
50
+ const debugFeatures = [
51
+ 'STACK_EXAMINATION',
52
+ 'SCRIPT_DEBUGGING',
53
+ 'STEP_BY_STEP_EXECUTION',
54
+ 'INTERACTIVE_DEBUGGING',
55
+ 'SCRIPT_ANALYSIS',
56
+ 'SCRIPT_OPTIMIZATION'
57
+ ];
58
+
59
+ debugFeatures.forEach(feature => {
60
+ const status = SmartContract.features[feature] ? '✅' : '❌';
61
+ console.log(` ${status} ${feature}`);
62
+ });
63
+
64
+ // Demo 5: Simple Script Analysis
65
+ console.log("\n5. 🧠 Script Analysis:");
66
+ const complexScript = SmartContract.parseScript("OP_DUP OP_DUP OP_DROP OP_HASH160 OP_SWAP OP_DROP");
67
+
68
+ try {
69
+ const explanation = SmartContract.explainScript(complexScript);
70
+ console.log(" Script explanation:", explanation);
71
+
72
+ const metrics = SmartContract.scriptMetrics(complexScript);
73
+ console.log(" Script metrics:");
74
+ console.log(" - Length:", metrics.length);
75
+ console.log(" - Opcodes:", metrics.opcodeCount);
76
+ console.log(" - Complexity:", metrics.complexity);
77
+ } catch (err) {
78
+ console.log(" ⚠️ Analysis error:", err.message);
79
+ }
80
+
81
+ console.log("\n==================================");
82
+ console.log("🎉 Debug Tools Demo Complete!");
83
+ console.log("==================================");
84
+
85
+ console.log(`\n📊 SmartContract now has ${Object.keys(SmartContract).filter(k =>
86
+ typeof SmartContract[k] === 'function'
87
+ ).length} total methods with advanced debugging capabilities!`);
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * SmartLedger-BSV v3.0.2 New Features Demo
5
+ *
6
+ * This script demonstrates the new UTXO management and miner simulation features
7
+ */
8
+
9
+ const bsv = require('../index.js');
10
+
11
+ console.log('🚀 SmartLedger-BSV v3.0.2 New Features Demo');
12
+ console.log('============================================\n');
13
+
14
+ // Create test wallet
15
+ const privateKey = new bsv.PrivateKey();
16
+ const address = privateKey.toAddress().toString();
17
+
18
+ console.log('📱 Demo Wallet:');
19
+ console.log(`Address: ${address}`);
20
+ console.log(`Private Key: ${privateKey.toString()}\n`);
21
+
22
+ // 1. UTXO Management Demo
23
+ console.log('💰 SmartUTXO Management System:');
24
+ console.log('===============================');
25
+
26
+ const utxoManager = new bsv.SmartUTXO();
27
+
28
+ // Create mock UTXOs for testing
29
+ const mockUTXOs = utxoManager.createMockUTXOs(address, 3, 50000);
30
+ console.log(`Created ${mockUTXOs.length} mock UTXOs for testing`);
31
+
32
+ // Add UTXOs to the system
33
+ mockUTXOs.forEach(utxo => utxoManager.addUTXO(utxo));
34
+ console.log('UTXOs added to blockchain state');
35
+
36
+ // Check balance
37
+ const balance = utxoManager.getBalance(address);
38
+ console.log(`Total balance: ${balance} satoshis (${balance / 100000000} BSV)`);
39
+
40
+ // Get UTXOs for the address
41
+ const utxos = utxoManager.getUTXOsForAddress(address);
42
+ console.log(`Available UTXOs: ${utxos.length}`);
43
+
44
+ // Get blockchain stats
45
+ const stats = utxoManager.getStats();
46
+ console.log(`Blockchain stats: ${stats.totalUTXOs} UTXOs, ${stats.totalValue} satoshis\n`);
47
+
48
+ // 2. Miner Simulation Demo
49
+ console.log('⛏️ SmartMiner Blockchain Simulation:');
50
+ console.log('====================================');
51
+
52
+ const miner = new bsv.SmartMiner(bsv, {
53
+ logLevel: 'info',
54
+ validateScripts: true
55
+ });
56
+
57
+ // Create a simple transaction
58
+ try {
59
+ const transaction = new bsv.Transaction()
60
+ .from({
61
+ txid: mockUTXOs[0].txid,
62
+ vout: mockUTXOs[0].vout,
63
+ address: address,
64
+ script: mockUTXOs[0].script,
65
+ satoshis: mockUTXOs[0].satoshis
66
+ })
67
+ .to(address, 25000) // Send to self
68
+ .change(address) // Change back to self
69
+ .sign(privateKey);
70
+
71
+ console.log(`Transaction created: ${transaction.id}`);
72
+
73
+ // Submit to miner
74
+ const accepted = miner.acceptTransaction(transaction);
75
+ console.log(`Transaction accepted: ${accepted}`);
76
+
77
+ // Check mempool
78
+ const mempoolStats = miner.getMempoolStats();
79
+ console.log(`Mempool: ${mempoolStats.transactionCount} transactions`);
80
+
81
+ // Mine a block
82
+ const block = miner.mineBlock();
83
+ console.log(`Mined block ${block.height} with ${block.transactionCount} transactions`);
84
+ console.log(`Block hash: ${block.hash}`);
85
+
86
+ // Get blockchain status
87
+ const blockchainStats = miner.getBlockchainStats();
88
+ console.log(`Blockchain height: ${blockchainStats.currentHeight}`);
89
+
90
+ } catch (error) {
91
+ console.log(`Transaction error (expected for demo): ${error.message}`);
92
+ console.log('Note: This is normal for mock UTXOs without proper scripts');
93
+ }
94
+
95
+ console.log('\n3. Signature Verification Demo:');
96
+ console.log('===============================');
97
+
98
+ // Test the fixed signature verification
99
+ const message = Buffer.from('SmartLedger-BSV v3.0.2 Demo', 'utf8');
100
+ const hash = bsv.crypto.Hash.sha256(message);
101
+ const signature = bsv.crypto.ECDSA.sign(hash, privateKey);
102
+ const derSig = signature.toDER();
103
+
104
+ // Test all verification methods
105
+ console.log('Message:', message.toString());
106
+ console.log('Signature verification tests:');
107
+
108
+ const ecdsaResult = bsv.crypto.ECDSA.verify(hash, derSig, privateKey.publicKey);
109
+ console.log(`✅ ECDSA.verify(): ${ecdsaResult}`);
110
+
111
+ const smartResult = bsv.SmartVerify.smartVerify(hash, derSig, privateKey.publicKey);
112
+ console.log(`✅ SmartVerify.smartVerify(): ${smartResult}`);
113
+
114
+ const canonicalResult = bsv.SmartVerify.isCanonical(derSig);
115
+ console.log(`✅ SmartVerify.isCanonical(): ${canonicalResult}`);
116
+
117
+ console.log('\n🎉 Demo completed successfully!');
118
+ console.log('📚 All signature verification methods are now working correctly.');
119
+ console.log('🔧 New UTXO management and miner tools are ready for development!');
120
+
121
+ // Save state for future use
122
+ utxoManager.saveState();
123
+ console.log('\n💾 Blockchain state saved for future sessions.');