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,851 @@
1
+ # UTXO Manager and Mock UTXO Generation Guide
2
+
3
+ ## Overview
4
+
5
+ The SmartLedger BSV library provides powerful utilities for managing UTXOs (Unspent Transaction Outputs) and generating mock UTXOs for development and testing purposes. This guide covers the complete workflow from UTXO generation to spending transactions.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Quick Start](#quick-start)
10
+ - [UTXO Manager Features](#utxo-manager-features)
11
+ - [Mock UTXO Generator](#mock-utxo-generator)
12
+ - [Command Line Usage](#command-line-usage)
13
+ - [Programmatic Usage](#programmatic-usage)
14
+ - [Real-World Examples](#real-world-examples)
15
+ - [Best Practices](#best-practices)
16
+ - [Troubleshooting](#troubleshooting)
17
+
18
+ ## Quick Start
19
+
20
+ ### Installation
21
+
22
+ ```bash
23
+ npm install @smartledger/bsv
24
+ ```
25
+
26
+ ### Basic Usage
27
+
28
+ ```javascript
29
+ const bsv = require('@smartledger/bsv');
30
+
31
+ // Method 1: Using SmartUTXOManager (recommended)
32
+ const SmartUTXOManager = require('@smartledger/bsv/lib/smartutxo');
33
+ const utxoManager = new SmartUTXOManager();
34
+
35
+ // Create mock UTXOs for testing
36
+ const testAddress = '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa';
37
+ const mockUTXOs = utxoManager.createMockUTXOs(testAddress, 3, 100000);
38
+ console.log('Created', mockUTXOs.length, 'mock UTXOs');
39
+
40
+ // Method 2: Using Smart Contract UTXOGenerator
41
+ const UTXOGenerator = require('@smartledger/bsv/lib/smart_contract/utxo_generator');
42
+ const generator = new UTXOGenerator();
43
+
44
+ // Generate real BSV keypair and UTXOs
45
+ const keypair = generator.generateKeypair('my-test-wallet');
46
+ const realUTXOs = generator.createRealUTXOs({
47
+ count: 2,
48
+ satoshis: 50000,
49
+ keypair: keypair
50
+ });
51
+
52
+ // Create spending transaction
53
+ const tx = new bsv.Transaction()
54
+ .from({
55
+ txId: realUTXOs[0].txid,
56
+ outputIndex: realUTXOs[0].vout,
57
+ script: realUTXOs[0].script,
58
+ satoshis: realUTXOs[0].satoshis
59
+ })
60
+ .to('1BitcoinEaterAddressDontSendf59kuE', 40000)
61
+ .sign(keypair.privateKey);
62
+
63
+ console.log('Transaction created:', tx.id);
64
+ ```
65
+
66
+ ## UTXO Manager Features
67
+
68
+ ### 🎯 Core Capabilities
69
+
70
+ - **Mock UTXO Generation** - Create realistic test UTXOs for development
71
+ - **Multi-Network Support** - Works with mainnet, testnet, and regtest
72
+ - **Flexible Value Management** - Support for any satoshi amount (minimum 546 sats)
73
+ - **Key Management** - Generate new keys or use existing WIF private keys
74
+ - **Script Flexibility** - Support for P2PKH, P2SH, and custom scripts
75
+ - **Transaction Building** - Seamless integration with BSV transaction creation
76
+
77
+ ### 🔧 Supported UTXO Types
78
+
79
+ | Type | Description | Use Case |
80
+ |------|-------------|----------|
81
+ | **P2PKH** | Pay-to-Public-Key-Hash | Standard Bitcoin addresses |
82
+ | **P2SH** | Pay-to-Script-Hash | Multi-signature and smart contracts |
83
+ | **Covenant** | Smart contract UTXOs | Advanced covenant spending conditions |
84
+ | **Custom** | User-defined scripts | Experimental and specialized use cases |
85
+
86
+ ## Mock UTXO Generator
87
+
88
+ ### Command Line Tool
89
+
90
+ The library includes a command-line utility for generating mock UTXOs:
91
+
92
+ ```bash
93
+ # Basic usage - generates random UTXO with random private key
94
+ node utilities/mock-utxo-generator.js
95
+
96
+ # Specify satoshi amount (generates random key)
97
+ node utilities/mock-utxo-generator.js "" 50000
98
+
99
+ # Create spending transaction to recipient
100
+ node utilities/mock-utxo-generator.js "" 50000 1BitcoinEaterAddressDontSendf59kuE
101
+
102
+ # Use specific private key (WIF format)
103
+ node utilities/mock-utxo-generator.js L1aW4aubDFB7yfras2S1mMEW7bZ1aW4aubD 100000
104
+
105
+ # Complete example with all parameters
106
+ node utilities/mock-utxo-generator.js L1aW4aubDFB7yfras2S1mMEW7bZ1aW4aubD 75000 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa
107
+ ```
108
+
109
+ ### Parameters
110
+
111
+ | Parameter | Description | Default | Required |
112
+ |-----------|-------------|---------|----------|
113
+ | `WIF` | Private key in Wallet Import Format | Random generation | No |
114
+ | `satoshis` | UTXO value in satoshis | 100000 | No |
115
+ | `recipient` | Target address for spending | Random generation | No |
116
+
117
+ ### Output Format
118
+
119
+ The generator produces a detailed UTXO report:
120
+
121
+ ```
122
+ === MOCK UTXO ===
123
+ {
124
+ "privateKeyWIF": "KxNqRDCi7sKJQw6uPQrEkUhht6AMzRwqEBP9PAcE9b9WKufAsEhv",
125
+ "privateKeyHex": "KxNqRDCi7sKJQw6uPQrEkUhht6AMzRwqEBP9PAcE9b9WKufAsEhv",
126
+ "address": "13hR1jbcgZovT9tRyswMXbyjuEZJGpGseN",
127
+ "utxo": {
128
+ "txid": "efc80a6881d8d7ecb0fb1393a7efdea3bc9b5cf7307bc3f983a532f3356c335a",
129
+ "vout": 0,
130
+ "scriptPubKey": "76a9141d94ef4f13cd354e2fce2ff9ce03303077b75ade88ac",
131
+ "satoshis": 100000
132
+ }
133
+ }
134
+ =================
135
+
136
+ === SIGNED SPEND TX === (when recipient provided)
137
+ TX HEX: 01000000014acc275ecd667d311a7bc3980efd3bac23e2ec2304a4bb95070c80d5eb1844ef...
138
+ TX ID (hash): 249088722ea20f2d7483bdf90d6e43761c31b3b739122bc3750b827c634ea860
139
+ fee (mock): 500
140
+ sendAmount: 49500
141
+ ========================
142
+ ```
143
+
144
+ ## Programmatic Usage
145
+
146
+ ### Basic UTXO Creation
147
+
148
+ ```javascript
149
+ const bsv = require('@smartledger/bsv');
150
+
151
+ // Method 1: Using SmartUTXOManager for simple mock UTXOs
152
+ const SmartUTXOManager = require('@smartledger/bsv/lib/smartutxo');
153
+
154
+ function createMockUTXOs(address, count = 3, satoshis = 100000) {
155
+ const utxoManager = new SmartUTXOManager();
156
+ return utxoManager.createMockUTXOs(address, count, satoshis);
157
+ }
158
+
159
+ // Method 2: Using UTXOGenerator for real BSV keys and UTXOs
160
+ const UTXOGenerator = require('@smartledger/bsv/lib/smart_contract/utxo_generator');
161
+
162
+ function createRealUTXOs(config = {}) {
163
+ const generator = new UTXOGenerator();
164
+
165
+ // Generate keypair if not provided
166
+ const keypair = config.keypair || generator.generateKeypair('utxo_owner');
167
+
168
+ // Create real UTXOs with authentic BSV transactions
169
+ const utxos = generator.createRealUTXOs({
170
+ count: config.count || 3,
171
+ satoshis: config.satoshis || 100000,
172
+ keypair: keypair,
173
+ scriptType: config.scriptType || 'P2PKH'
174
+ });
175
+
176
+ return { keypair, utxos };
177
+ }
178
+
179
+ // Usage examples
180
+ const testAddress = '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa';
181
+ const mockUTXOs = createMockUTXOs(testAddress, 2, 50000);
182
+
183
+ const { keypair, utxos } = createRealUTXOs({
184
+ count: 3,
185
+ satoshis: 75000,
186
+ scriptType: 'P2PKH'
187
+ });
188
+
189
+ console.log('Mock UTXOs:', mockUTXOs.length);
190
+ console.log('Real UTXOs:', utxos.length);
191
+ console.log('Keypair address:', keypair.addressString);
192
+ ```
193
+
194
+ ### Advanced UTXO Management
195
+
196
+ ```javascript
197
+ class UTXOManager {
198
+ constructor() {
199
+ this.utxos = new Map();
200
+ }
201
+
202
+ // Generate multiple UTXOs
203
+ generateBatch(count, minValue = 10000, maxValue = 100000) {
204
+ const batch = [];
205
+ for (let i = 0; i < count; i++) {
206
+ const satoshis = Math.floor(Math.random() * (maxValue - minValue)) + minValue;
207
+ const utxo = createRandomUTXO(satoshis);
208
+ batch.push(utxo);
209
+ this.utxos.set(utxo.txId + ':' + utxo.outputIndex, utxo);
210
+ }
211
+ return batch;
212
+ }
213
+
214
+ // Find UTXOs by criteria
215
+ findByAmount(minAmount, maxAmount = Infinity) {
216
+ return Array.from(this.utxos.values()).filter(utxo =>
217
+ utxo.satoshis >= minAmount && utxo.satoshis <= maxAmount
218
+ );
219
+ }
220
+
221
+ // Create spending transaction
222
+ createSpendingTx(utxo, recipient, amount) {
223
+ const tx = new bsv.Transaction()
224
+ .from(utxo)
225
+ .to(recipient, amount)
226
+ .change(utxo.address)
227
+ .sign(utxo.privateKey);
228
+
229
+ // Mark UTXO as spent
230
+ this.utxos.delete(utxo.txId + ':' + utxo.outputIndex);
231
+
232
+ return tx;
233
+ }
234
+
235
+ // Get total balance
236
+ getTotalBalance() {
237
+ return Array.from(this.utxos.values())
238
+ .reduce((sum, utxo) => sum + utxo.satoshis, 0);
239
+ }
240
+ }
241
+
242
+ // Usage
243
+ const manager = new UTXOManager();
244
+ const utxos = manager.generateBatch(10, 10000, 50000);
245
+ console.log('Generated', utxos.length, 'UTXOs');
246
+ console.log('Total balance:', manager.getTotalBalance(), 'satoshis');
247
+ ```
248
+
249
+ ## Real-World Examples
250
+
251
+ ### Example 1: Development Testing
252
+
253
+ ```javascript
254
+ const bsv = require('@smartledger/bsv');
255
+ const UTXOGenerator = require('@smartledger/bsv/lib/smart_contract/utxo_generator');
256
+
257
+ async function testTransactionFlow() {
258
+ console.log('🧪 Testing Transaction Flow');
259
+
260
+ // 1. Create test environment with real UTXOs
261
+ const generator = new UTXOGenerator();
262
+ const wallet1 = generator.generateKeypair('wallet1');
263
+ const wallet2 = generator.generateKeypair('wallet2');
264
+
265
+ const utxos1 = generator.createRealUTXOs({ count: 1, satoshis: 100000, keypair: wallet1 });
266
+ const utxos2 = generator.createRealUTXOs({ count: 1, satoshis: 50000, keypair: wallet2 });
267
+
268
+ console.log('📦 Created UTXOs:');
269
+ console.log(` UTXO 1: ${utxos1[0].satoshis} sats`);
270
+ console.log(` UTXO 2: ${utxos2[0].satoshis} sats`);
271
+
272
+ // 2. Create multi-input transaction
273
+ const recipientKey = new bsv.PrivateKey();
274
+ const recipientAddress = recipientKey.toAddress();
275
+
276
+ const tx = new bsv.Transaction()
277
+ .from([
278
+ {
279
+ txId: utxos1[0].txid,
280
+ outputIndex: utxos1[0].vout,
281
+ script: utxos1[0].script,
282
+ satoshis: utxos1[0].satoshis
283
+ },
284
+ {
285
+ txId: utxos2[0].txid,
286
+ outputIndex: utxos2[0].vout,
287
+ script: utxos2[0].script,
288
+ satoshis: utxos2[0].satoshis
289
+ }
290
+ ])
291
+ .to(recipientAddress, 120000)
292
+ .change(wallet1.addressString)
293
+ .fee(1000)
294
+ .sign([wallet1.privateKey, wallet2.privateKey]);
295
+
296
+ console.log('✅ Transaction created:');
297
+ console.log(` ID: ${tx.id}`);
298
+ console.log(` Size: ${tx.toString().length / 2} bytes`);
299
+ console.log(` Fee: ${tx.getFee()} satoshis`);
300
+
301
+ return tx;
302
+ }
303
+
304
+ testTransactionFlow().catch(console.error);
305
+ ```
306
+
307
+ ### Example 2: Smart Contract Testing
308
+
309
+ ```javascript
310
+ const UTXOGenerator = require('@smartledger/bsv/lib/smart_contract/utxo_generator');
311
+
312
+ async function testCovenantUTXO() {
313
+ console.log('🔒 Testing Covenant UTXO');
314
+
315
+ // Create covenant test environment
316
+ const generator = new UTXOGenerator();
317
+ const covenantTest = generator.createCovenantTest({
318
+ utxoCount: 2,
319
+ satoshis: 100000,
320
+ covenantAmount: 80000
321
+ });
322
+
323
+ console.log('📜 Covenant test created:');
324
+ console.log(` Keypair address: ${covenantTest.keypair.addressString}`);
325
+ console.log(` UTXO count: ${covenantTest.utxos.length}`);
326
+ console.log(` Total value: ${covenantTest.utxos.reduce((sum, utxo) => sum + utxo.satoshis, 0)} sats`);
327
+ console.log(` Preimage length: ${covenantTest.preimage.length} bytes`);
328
+
329
+ // Generate preimage for covenant validation
330
+ const preimageHex = covenantTest.preimage.hex;
331
+ console.log(` Preimage: ${preimageHex.substring(0, 64)}...`);
332
+
333
+ // Test covenant validation
334
+ const validation = covenantTest.validateCovenant({
335
+ type: 'timelock',
336
+ lockTime: 144
337
+ });
338
+
339
+ console.log('✅ Covenant validation:', validation.testPassed ? 'PASSED' : 'FAILED');
340
+
341
+ return covenantTest;
342
+ }
343
+
344
+ testCovenantUTXO().catch(console.error);
345
+ ```
346
+
347
+ ### Example 3: Batch Processing
348
+
349
+ ```javascript
350
+ async function processBatchPayments() {
351
+ console.log('💰 Processing Batch Payments');
352
+
353
+ // Create funding UTXO
354
+ const fundingUTXO = createRandomUTXO(1000000); // 1M sats
355
+
356
+ // Define recipients
357
+ const recipients = [
358
+ { address: new bsv.PrivateKey().toAddress(), amount: 100000 },
359
+ { address: new bsv.PrivateKey().toAddress(), amount: 150000 },
360
+ { address: new bsv.PrivateKey().toAddress(), amount: 200000 }
361
+ ];
362
+
363
+ // Create batch payment transaction
364
+ let tx = new bsv.Transaction().from(fundingUTXO);
365
+
366
+ recipients.forEach(recipient => {
367
+ tx = tx.to(recipient.address, recipient.amount);
368
+ });
369
+
370
+ tx = tx.change(fundingUTXO.address)
371
+ .fee(1000)
372
+ .sign(fundingUTXO.privateKey);
373
+
374
+ console.log('📤 Batch payment created:');
375
+ console.log(` Recipients: ${recipients.length}`);
376
+ console.log(` Total sent: ${recipients.reduce((sum, r) => sum + r.amount, 0)} sats`);
377
+ console.log(` Change: ${tx.getChangeOutput() ? tx.getChangeOutput().satoshis : 0} sats`);
378
+
379
+ return tx;
380
+ }
381
+ ```
382
+
383
+ ## Network Configuration
384
+
385
+ ### Mainnet Usage
386
+
387
+ ```javascript
388
+ // Mainnet UTXOs (use with caution - real money!)
389
+ const mainnetUTXO = createRandomUTXO(100000, 'livenet');
390
+ ```
391
+
392
+ ### Testnet Usage
393
+
394
+ ```javascript
395
+ // Testnet UTXOs (safe for testing)
396
+ const testnetUTXO = createRandomUTXO(100000, 'testnet');
397
+ ```
398
+
399
+ ### Regtest Usage
400
+
401
+ ```javascript
402
+ // Regtest UTXOs (local development)
403
+ const regtestUTXO = createRandomUTXO(100000, 'regtest');
404
+ ```
405
+
406
+ ## Best Practices
407
+
408
+ ### 🎯 Development Guidelines
409
+
410
+ 1. **Always use testnet or regtest** for development and testing
411
+ 2. **Validate UTXO values** - minimum 546 satoshis required
412
+ 3. **Handle private keys securely** - never log or expose in production
413
+ 4. **Use proper fee estimation** - 1 sat/byte minimum
414
+ 5. **Test edge cases** - empty UTXOs, large values, network mismatches
415
+
416
+ ### 🔒 Security Considerations
417
+
418
+ ```javascript
419
+ // ❌ BAD - Exposing private keys
420
+ console.log('Private key:', privateKey.toString());
421
+
422
+ // ✅ GOOD - Secure key handling
423
+ const maskedKey = privateKey.toString().substr(0, 8) + '...';
424
+ console.log('Private key (masked):', maskedKey);
425
+
426
+ // ✅ GOOD - Environment-based configuration
427
+ const network = process.env.NODE_ENV === 'production' ? 'livenet' : 'testnet';
428
+ ```
429
+
430
+ ### 📊 Performance Optimization
431
+
432
+ ```javascript
433
+ // Efficient UTXO batch processing
434
+ class OptimizedUTXOManager extends UTXOManager {
435
+ // Cache frequently accessed data
436
+ constructor() {
437
+ super();
438
+ this.balanceCache = 0;
439
+ this.sortedUTXOs = [];
440
+ }
441
+
442
+ addUTXO(utxo) {
443
+ this.utxos.set(utxo.txId + ':' + utxo.outputIndex, utxo);
444
+ this.balanceCache += utxo.satoshis;
445
+ this.invalidateSortCache();
446
+ }
447
+
448
+ removeUTXO(utxoId) {
449
+ const utxo = this.utxos.get(utxoId);
450
+ if (utxo) {
451
+ this.balanceCache -= utxo.satoshis;
452
+ this.utxos.delete(utxoId);
453
+ this.invalidateSortCache();
454
+ }
455
+ }
456
+
457
+ getTotalBalance() {
458
+ return this.balanceCache; // O(1) instead of O(n)
459
+ }
460
+
461
+ invalidateSortCache() {
462
+ this.sortedUTXOs = [];
463
+ }
464
+ }
465
+ ```
466
+
467
+ ## Common Use Cases
468
+
469
+ ### 1. Unit Testing
470
+
471
+ ```javascript
472
+ describe('Transaction Tests', () => {
473
+ it('should create valid transaction', () => {
474
+ const utxo = createRandomUTXO(100000);
475
+ const tx = new bsv.Transaction()
476
+ .from(utxo)
477
+ .to('1BitcoinEaterAddressDontSendf59kuE', 50000)
478
+ .sign(utxo.privateKey);
479
+
480
+ expect(tx.isValidSignature(0)).toBe(true);
481
+ expect(tx.outputs[0].satoshis).toBe(50000);
482
+ });
483
+ });
484
+ ```
485
+
486
+ ### 2. Integration Testing
487
+
488
+ ```javascript
489
+ async function testWalletIntegration() {
490
+ const wallet = new MockWallet();
491
+
492
+ // Add test UTXOs
493
+ const utxos = [
494
+ createRandomUTXO(100000),
495
+ createRandomUTXO(200000),
496
+ createRandomUTXO(50000)
497
+ ];
498
+
499
+ utxos.forEach(utxo => wallet.addUTXO(utxo));
500
+
501
+ // Test wallet operations
502
+ const balance = wallet.getBalance();
503
+ const tx = wallet.send('recipient-address', 150000);
504
+
505
+ assert(balance === 350000);
506
+ assert(tx.outputs[0].satoshis === 150000);
507
+ }
508
+ ```
509
+
510
+ ### 3. Load Testing
511
+
512
+ ```javascript
513
+ async function loadTest() {
514
+ console.log('🚀 Starting load test...');
515
+
516
+ const startTime = Date.now();
517
+ const utxoCount = 1000;
518
+ const utxos = [];
519
+
520
+ // Generate UTXOs
521
+ for (let i = 0; i < utxoCount; i++) {
522
+ utxos.push(createRandomUTXO(Math.random() * 100000 + 10000));
523
+ }
524
+
525
+ // Process transactions
526
+ const transactions = [];
527
+ for (let i = 0; i < utxos.length; i += 10) {
528
+ const batch = utxos.slice(i, i + 10);
529
+ const tx = new bsv.Transaction();
530
+
531
+ batch.forEach(utxo => tx.from(utxo));
532
+ tx.to('1BitcoinEaterAddressDontSendf59kuE', batch.reduce((sum, utxo) => sum + utxo.satoshis, 0) - 10000);
533
+
534
+ batch.forEach(utxo => tx.sign(utxo.privateKey));
535
+ transactions.push(tx);
536
+ }
537
+
538
+ const endTime = Date.now();
539
+ console.log(`✅ Processed ${utxoCount} UTXOs in ${endTime - startTime}ms`);
540
+ console.log(`📊 Average: ${((endTime - startTime) / utxoCount).toFixed(2)}ms per UTXO`);
541
+ }
542
+ ```
543
+
544
+ ## Troubleshooting
545
+
546
+ ### Common Issues
547
+
548
+ #### 1. "Insufficient funds" Error
549
+
550
+ ```javascript
551
+ // Problem: UTXO value too small for desired output + fee
552
+ const utxo = createRandomUTXO(1000); // Too small!
553
+
554
+ // Solution: Check available balance
555
+ function createSafeTransaction(utxo, recipient, amount) {
556
+ const fee = 1000; // Minimum fee
557
+ const totalNeeded = amount + fee;
558
+
559
+ if (utxo.satoshis < totalNeeded) {
560
+ throw new Error(`Insufficient funds: need ${totalNeeded}, have ${utxo.satoshis}`);
561
+ }
562
+
563
+ return new bsv.Transaction()
564
+ .from(utxo)
565
+ .to(recipient, amount)
566
+ .fee(fee)
567
+ .sign(utxo.privateKey);
568
+ }
569
+ ```
570
+
571
+ #### 2. "Invalid signature" Error
572
+
573
+ ```javascript
574
+ // Problem: Wrong private key or UTXO mismatch
575
+ const utxo1 = createRandomUTXO(100000);
576
+ const utxo2 = createRandomUTXO(100000);
577
+
578
+ // ❌ Wrong key for UTXO
579
+ const badTx = new bsv.Transaction()
580
+ .from(utxo1)
581
+ .to('recipient', 50000)
582
+ .sign(utxo2.privateKey); // Wrong key!
583
+
584
+ // ✅ Correct key matching
585
+ const goodTx = new bsv.Transaction()
586
+ .from(utxo1)
587
+ .to('recipient', 50000)
588
+ .sign(utxo1.privateKey); // Correct key
589
+ ```
590
+
591
+ #### 3. Network Mismatch
592
+
593
+ ```javascript
594
+ // Problem: Mixing networks
595
+ const mainnetKey = new bsv.PrivateKey(undefined, 'livenet');
596
+ const testnetAddress = mainnetKey.toAddress('testnet'); // Mismatch!
597
+
598
+ // Solution: Consistent network usage
599
+ function createNetworkConsistentUTXO(network = 'testnet') {
600
+ const privateKey = new bsv.PrivateKey(undefined, network);
601
+ const address = privateKey.toAddress(network);
602
+
603
+ return {
604
+ txId: 'mock_' + Date.now(),
605
+ outputIndex: 0,
606
+ address: address.toString(),
607
+ script: bsv.Script.buildPublicKeyHashOut(address).toString(),
608
+ satoshis: 100000,
609
+ privateKey: privateKey,
610
+ network: network
611
+ };
612
+ }
613
+ ```
614
+
615
+ ### Debug Utilities
616
+
617
+ ```javascript
618
+ // UTXO validation helper
619
+ function validateUTXO(utxo) {
620
+ const errors = [];
621
+
622
+ if (!utxo.txId) errors.push('Missing txId');
623
+ if (utxo.outputIndex === undefined) errors.push('Missing outputIndex');
624
+ if (!utxo.script) errors.push('Missing script');
625
+ if (!utxo.satoshis || utxo.satoshis < 546) errors.push('Invalid satoshi amount');
626
+
627
+ if (utxo.privateKey) {
628
+ const derivedAddress = utxo.privateKey.toAddress().toString();
629
+ if (derivedAddress !== utxo.address) {
630
+ errors.push('Address/privateKey mismatch');
631
+ }
632
+ }
633
+
634
+ return errors.length === 0 ? null : errors;
635
+ }
636
+
637
+ // Transaction validation helper
638
+ function validateTransaction(tx) {
639
+ const validation = {
640
+ valid: true,
641
+ errors: [],
642
+ warnings: []
643
+ };
644
+
645
+ if (tx.inputs.length === 0) {
646
+ validation.valid = false;
647
+ validation.errors.push('No inputs');
648
+ }
649
+
650
+ if (tx.outputs.length === 0) {
651
+ validation.valid = false;
652
+ validation.errors.push('No outputs');
653
+ }
654
+
655
+ const fee = tx.getFee();
656
+ if (fee < 1) {
657
+ validation.warnings.push('Fee too low');
658
+ }
659
+
660
+ if (fee > 10000) {
661
+ validation.warnings.push('Fee unusually high');
662
+ }
663
+
664
+ return validation;
665
+ }
666
+ ```
667
+
668
+ ## API Reference
669
+
670
+ ### SmartUTXOManager Class
671
+
672
+ | Method | Parameters | Returns | Description |
673
+ |--------|------------|---------|-------------|
674
+ | `constructor` | `(options)` | `SmartUTXOManager` | Initialize UTXO manager |
675
+ | `createMockUTXOs` | `(address, count, satoshis)` | `Array` | Generate mock UTXOs for testing |
676
+ | `getUTXOsForAddress` | `(address)` | `Array` | Get all UTXOs for address |
677
+ | `addUTXO` | `(utxo)` | `void` | Add UTXO to system |
678
+ | `spendUTXOs` | `(inputs, spentInTx)` | `void` | Mark UTXOs as spent |
679
+ | `getBalance` | `(address)` | `number` | Get total balance for address |
680
+ | `getStats` | `()` | `Object` | Get blockchain statistics |
681
+ | `reset` | `()` | `void` | Reset blockchain state |
682
+
683
+ ### UTXOGenerator Class
684
+
685
+ | Method | Parameters | Returns | Description |
686
+ |--------|------------|---------|-------------|
687
+ | `constructor` | `(options)` | `UTXOGenerator` | Initialize generator |
688
+ | `generateKeypair` | `(label)` | `Object` | Generate BSV keypair |
689
+ | `createRealUTXOs` | `(config)` | `Array` | Create authentic UTXOs |
690
+ | `createTestTransaction` | `(config)` | `Object` | Create test transaction |
691
+ | `createCovenantTest` | `(config)` | `Object` | Create covenant test environment |
692
+ | `getKeypairs` | `()` | `Object` | Get all generated keypairs |
693
+ | `getUTXOs` | `()` | `Array` | Get all generated UTXOs |
694
+ | `reset` | `()` | `void` | Clear all generated data |
695
+
696
+ ### Static Functions
697
+
698
+ | Function | Parameters | Returns | Description |
699
+ |----------|------------|---------|-------------|
700
+ | `UTXOGenerator.createTestEnvironment` | `(options)` | `Object` | Create complete test environment |
701
+
702
+ ### UTXO Object Structure
703
+
704
+ ```typescript
705
+ interface UTXO {
706
+ txId: string; // Transaction ID
707
+ outputIndex: number; // Output index (usually 0)
708
+ address: string; // Bitcoin address
709
+ script: string; // Locking script (hex)
710
+ satoshis: number; // Value in satoshis
711
+ privateKey?: PrivateKey; // Private key (for spending)
712
+ network?: string; // Network (livenet/testnet/regtest)
713
+ }
714
+ ```
715
+
716
+ ## Integration Examples
717
+
718
+ ### Web Application Integration
719
+
720
+ ```html
721
+ <!DOCTYPE html>
722
+ <html>
723
+ <head>
724
+ <title>UTXO Manager Demo</title>
725
+ <script src="https://cdn.jsdelivr.net/npm/@smartledger/bsv@3.3.3/bsv.min.js"></script>
726
+ </head>
727
+ <body>
728
+ <script>
729
+ // Generate UTXO in browser
730
+ function generateWebUTXO() {
731
+ const privateKey = new bsv.PrivateKey();
732
+ const address = privateKey.toAddress();
733
+
734
+ const utxo = {
735
+ txId: 'web_' + Date.now(),
736
+ outputIndex: 0,
737
+ address: address.toString(),
738
+ script: bsv.Script.buildPublicKeyHashOut(address).toString(),
739
+ satoshis: 100000,
740
+ privateKey: privateKey
741
+ };
742
+
743
+ console.log('Generated web UTXO:', utxo);
744
+ return utxo;
745
+ }
746
+
747
+ generateWebUTXO();
748
+ </script>
749
+ </body>
750
+ </html>
751
+ ```
752
+
753
+ ### Node.js Service Integration
754
+
755
+ ```javascript
756
+ const express = require('express');
757
+ const bsv = require('@smartledger/bsv');
758
+
759
+ const app = express();
760
+ app.use(express.json());
761
+
762
+ // UTXO generation endpoint
763
+ app.post('/api/utxos/generate', (req, res) => {
764
+ try {
765
+ const { satoshis = 100000, network = 'testnet' } = req.body;
766
+
767
+ const utxo = createRandomUTXO(satoshis, network);
768
+
769
+ // Remove private key from response for security
770
+ const safeUTXO = { ...utxo };
771
+ delete safeUTXO.privateKey;
772
+
773
+ res.json({
774
+ success: true,
775
+ utxo: safeUTXO,
776
+ wif: utxo.privateKey.toWIF() // Return WIF separately
777
+ });
778
+ } catch (error) {
779
+ res.status(400).json({
780
+ success: false,
781
+ error: error.message
782
+ });
783
+ }
784
+ });
785
+
786
+ app.listen(3000, () => {
787
+ console.log('UTXO service running on port 3000');
788
+ });
789
+ ```
790
+
791
+ ## Quick Reference
792
+
793
+ ### Command Line Usage
794
+ ```bash
795
+ # Generate random UTXO
796
+ node utilities/mock-utxo-generator.js
797
+
798
+ # Generate with specific amount and create spending tx
799
+ node utilities/mock-utxo-generator.js "" 50000 1BitcoinEaterAddressDontSendf59kuE
800
+
801
+ # Use specific private key
802
+ node utilities/mock-utxo-generator.js KxNqRDCi7sKJQw6uPQrEkUhht6AMzRwqEBP9PAcE9b9WKufAsEhv 25000
803
+ ```
804
+
805
+ ### Library Usage
806
+ ```javascript
807
+ // SmartUTXOManager - Simple mock UTXOs
808
+ const SmartUTXOManager = require('@smartledger/bsv/lib/smartutxo');
809
+ const utxoManager = new SmartUTXOManager();
810
+ const mockUTXOs = utxoManager.createMockUTXOs(address, 3, 100000);
811
+
812
+ // UTXOGenerator - Real BSV UTXOs with authentic keys
813
+ const UTXOGenerator = require('@smartledger/bsv/lib/smart_contract/utxo_generator');
814
+ const generator = new UTXOGenerator();
815
+ const keypair = generator.generateKeypair('test-wallet');
816
+ const realUTXOs = generator.createRealUTXOs({ count: 2, satoshis: 50000, keypair });
817
+
818
+ // Covenant Testing
819
+ const covenantTest = generator.createCovenantTest({
820
+ utxoCount: 2,
821
+ satoshis: 100000,
822
+ covenantAmount: 80000
823
+ });
824
+ ```
825
+
826
+ ## Conclusion
827
+
828
+ The SmartLedger BSV UTXO Manager provides a comprehensive solution for Bitcoin SV development and testing. Whether you're building wallets, smart contracts, or payment processors, these utilities enable rapid development with realistic test data.
829
+
830
+ ### Key Benefits:
831
+ - **🎯 Authentic Testing** - Real BSV keypairs and transaction structures
832
+ - **🚀 Rapid Development** - Quick UTXO generation for any scenario
833
+ - **🔒 Smart Contract Ready** - Covenant testing with preimage generation
834
+ - **📦 Multiple Interfaces** - Command-line tools and programmatic APIs
835
+ - **🌐 Network Flexible** - Support for mainnet, testnet, and regtest
836
+
837
+ ### Tested Examples:
838
+ All examples in this guide have been tested and verified to work with SmartLedger BSV v3.3.3. The documentation reflects the actual API and behavior of the library modules.
839
+
840
+ For more examples and advanced usage, see the `/examples` directory in the repository.
841
+
842
+ ## Additional Resources
843
+
844
+ - [SmartLedger BSV Documentation](https://github.com/codenlighten/smartledger-bsv)
845
+ - [Bitcoin SV Documentation](https://wiki.bitcoinsv.io/)
846
+ - [BSV Transaction Format](https://wiki.bitcoinsv.io/index.php/Bitcoin_Transactions)
847
+ - [Script Reference](https://wiki.bitcoinsv.io/index.php/Script)
848
+
849
+ ---
850
+
851
+ *Last updated: October 2025*