smartledger-bsv 3.3.5 โ†’ 3.4.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 (126) hide show
  1. package/CHANGELOG.md +400 -0
  2. package/README.md +235 -80
  3. package/SECURITY.md +88 -0
  4. package/anchor-entry.js +1 -0
  5. package/bin/cli.js +354 -0
  6. package/bsv-anchor.min.js +12 -0
  7. package/bsv-covenant.min.js +8 -8
  8. package/bsv-didweb.min.js +12 -0
  9. package/bsv-gdaf.min.js +9 -9
  10. package/bsv-ltp.min.js +9 -9
  11. package/bsv-mnemonic.min.js +2 -2
  12. package/bsv-shamir.min.js +3 -3
  13. package/bsv-smartcontract.min.js +9 -9
  14. package/bsv-statuslist.min.js +18 -0
  15. package/bsv-vcjwt.min.js +12 -0
  16. package/bsv.bundle.js +9 -9
  17. package/bsv.d.ts +486 -9
  18. package/bsv.min.js +8 -8
  19. package/build/webpack.anchor.config.js +17 -0
  20. package/build/webpack.didweb.config.js +17 -0
  21. package/build/webpack.statuslist.config.js +17 -0
  22. package/build/webpack.vcjwt.config.js +17 -0
  23. package/didweb-entry.js +1 -0
  24. package/docs/COVENANT_DEVELOPMENT_RESOLVED.md +2 -2
  25. package/docs/MODULE_REFERENCE_COMPLETE.md +61 -58
  26. package/docs/advanced/LEGAL_TOKEN_PROTOCOL.md +3 -3
  27. package/docs/advanced/UTXO_MANAGER_GUIDE.md +1 -1
  28. package/docs/getting-started/INSTALLATION.md +30 -30
  29. package/docs/getting-started/QUICK_START.md +18 -18
  30. package/docs/migration/FROM_BSV_1_5_6.md +16 -10
  31. package/docs/technical/roadmap.md +3 -3
  32. package/gdaf-entry.js +1 -2
  33. package/index.js +68 -9
  34. package/lib/anchor/index.js +102 -0
  35. package/lib/browser-utxo-manager-es5.js +11 -4
  36. package/lib/browser-utxo-manager.js +15 -8
  37. package/lib/didweb/index.js +177 -0
  38. package/lib/ltp/claim.js +1 -0
  39. package/lib/ltp/obligation.js +1 -0
  40. package/lib/ltp/registry.js +2 -0
  41. package/lib/ltp/right.js +1 -0
  42. package/lib/smart_contract/covenant.js +10 -1
  43. package/lib/smartutxo.js +20 -12
  44. package/lib/statuslist/index.js +164 -0
  45. package/lib/transaction/transaction.js +8 -1
  46. package/lib/util/_.js +7 -1
  47. package/lib/vcjwt/index.js +189 -0
  48. package/ltp-entry.js +1 -2
  49. package/package.json +21 -15
  50. package/statuslist-entry.js +1 -0
  51. package/utilities/blockchain-state.js +32 -23
  52. package/vcjwt-entry.js +1 -0
  53. package/demos/README.md +0 -188
  54. package/demos/architecture_demo.js +0 -247
  55. package/demos/browser-test.html +0 -1208
  56. package/demos/bsv_wallet_demo.js +0 -242
  57. package/demos/complete_ltp_demo.js +0 -511
  58. package/demos/debug_tools_demo.js +0 -87
  59. package/demos/demo_features.js +0 -123
  60. package/demos/easy_interface_demo.js +0 -109
  61. package/demos/ecies_demo.js +0 -182
  62. package/demos/gdaf_core_test.js +0 -131
  63. package/demos/gdaf_demo.js +0 -237
  64. package/demos/ltp_demo.js +0 -361
  65. package/demos/ltp_primitives_demo.js +0 -403
  66. package/demos/message_demo.js +0 -209
  67. package/demos/preimage_separation_demo.js +0 -383
  68. package/demos/script_helper_demo.js +0 -289
  69. package/demos/security_demo.js +0 -287
  70. package/demos/shamir_demo.js +0 -121
  71. package/demos/simple_demo.js +0 -204
  72. package/demos/simple_p2pkh_demo.js +0 -169
  73. package/demos/simple_utxo_preimage_demo.js +0 -196
  74. package/demos/smart_contract_demo.html +0 -1347
  75. package/demos/smart_contract_demo.js +0 -910
  76. package/demos/utxo_generator_demo.js +0 -244
  77. package/demos/validation_pipeline_demo.js +0 -155
  78. package/demos/web3keys.html +0 -740
  79. package/examples/README.md +0 -200
  80. package/examples/basic/transaction-creation.js +0 -534
  81. package/examples/basic/transaction_signature_api_gap.js +0 -178
  82. package/examples/complete_workflow_demo.js +0 -783
  83. package/examples/covenants/advanced_covenant_demo.js +0 -219
  84. package/examples/covenants/covenant_interface_demo.js +0 -270
  85. package/examples/covenants/covenant_manual_signature_resolved.js +0 -212
  86. package/examples/covenants/covenant_signature_template.js +0 -117
  87. package/examples/covenants2/covenant_bidirectional_example.js +0 -262
  88. package/examples/covenants2/covenant_utils_demo.js +0 -120
  89. package/examples/covenants2/preimage_covenant_utils.js +0 -287
  90. package/examples/covenants2/production_integration.js +0 -256
  91. package/examples/data/covenant_utxos.json +0 -28
  92. package/examples/data/utxos.json +0 -26
  93. package/examples/definitive_working_demo.js +0 -261
  94. package/examples/final_working_contracts.js +0 -338
  95. package/examples/preimage/README.md +0 -178
  96. package/examples/preimage/extract_preimage_bidirectional.js +0 -421
  97. package/examples/preimage/generate_sample_preimage.js +0 -208
  98. package/examples/preimage/generate_sighash_examples.js +0 -152
  99. package/examples/preimage/parse_preimage.js +0 -117
  100. package/examples/preimage/test_preimage_extractor.js +0 -53
  101. package/examples/preimage/test_varint_extraction.js +0 -95
  102. package/examples/scripts/custom_script_helper_example.js +0 -273
  103. package/examples/scripts/custom_script_signature_test.js +0 -344
  104. package/examples/scripts/script_interpreter.js +0 -193
  105. package/examples/smart_contract/complete_workflow_demo.js +0 -343
  106. package/examples/smart_contract/covenant_builder_demo.js +0 -176
  107. package/examples/smart_contract/script_testing_integration.js +0 -198
  108. package/examples/smart_contract_templates.js +0 -718
  109. package/examples/working_smart_contracts.js +0 -348
  110. package/lib/smart_contract/test_integration.js +0 -269
  111. package/tests/browser-compatibility/README.md +0 -35
  112. package/tests/browser-compatibility/test-cdn-vs-local.html +0 -186
  113. package/tests/browser-compatibility/test-pbkdf2.html +0 -51
  114. package/tests/bundle-completeness-test.html +0 -131
  115. package/tests/bundle-demo.html +0 -476
  116. package/tests/smartcontract-test.html +0 -239
  117. package/tests/standalone-modules-test.html +0 -260
  118. package/tests/test.html +0 -612
  119. package/tests/test_builtin_verify.js +0 -117
  120. package/tests/test_debug_integration.js +0 -71
  121. package/tests/test_ecdsa_little.js +0 -70
  122. package/tests/test_shamir.js +0 -221
  123. package/tests/test_smartverify_der.js +0 -110
  124. package/tests/test_standalone_shamir.html +0 -83
  125. package/tests/unpkg-demo.html +0 -194
  126. package/utilities/blockchain-state.json +0 -118565
@@ -1,534 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * SmartLedger Real UTXO Management & Transaction Validation Test
5
- *
6
- * This script demonstrates using SmartUTXO with real BSV blockchain data
7
- * via WhatsOnChain API, plus transaction creation and validation.
8
- */
9
-
10
- const bsv = require('./index.js');
11
- const https = require('https');
12
-
13
- console.log('๐ŸŒ SmartLedger Real UTXO Management Test');
14
- console.log('=======================================\n');
15
-
16
- // Use the test private key from minimal_reproduction.js
17
- const PRIVATE_KEY_WIF = 'L1aW4aubDFB7yfras2S1mN3bqg9nwySY8nkoLmJebSLD5BWv3ENZ';
18
- const privateKey = new bsv.PrivateKey(PRIVATE_KEY_WIF);
19
- const address = privateKey.toAddress().toString();
20
-
21
- console.log('๐Ÿ“ฑ Wallet Information:');
22
- console.log(`Private Key: ${PRIVATE_KEY_WIF}`);
23
- console.log(`Address: ${address}`);
24
- console.log(`Public Key: ${privateKey.publicKey.toString()}\n`);
25
-
26
- // WhatsOnChain API integration
27
- class WhatsOnChainAPI {
28
- constructor(network = 'main') {
29
- this.baseUrl = `https://api.whatsonchain.com/v1/bsv/${network}`;
30
- }
31
-
32
- async makeRequest(endpoint) {
33
- return new Promise((resolve, reject) => {
34
- const url = `${this.baseUrl}${endpoint}`;
35
- console.log(`๐ŸŒ API Request: ${url}`);
36
-
37
- https.get(url, (res) => {
38
- let data = '';
39
- res.on('data', chunk => data += chunk);
40
- res.on('end', () => {
41
- try {
42
- resolve(JSON.parse(data));
43
- } catch (error) {
44
- reject(new Error(`Failed to parse response: ${error.message}`));
45
- }
46
- });
47
- }).on('error', reject);
48
- });
49
- }
50
-
51
- async getUTXOs(address) {
52
- try {
53
- const utxos = await this.makeRequest(`/address/${address}/unspent`);
54
- console.log(`๐Ÿ“ฆ Found ${utxos.length} UTXOs for ${address}`);
55
- return utxos.map(utxo => ({
56
- txid: utxo.tx_hash,
57
- vout: utxo.tx_pos,
58
- address: address,
59
- satoshis: utxo.value,
60
- script: utxo.script || `76a914${bsv.Address.fromString(address).hashBuffer.toString('hex')}88ac`,
61
- height: utxo.height
62
- }));
63
- } catch (error) {
64
- console.log(`โš ๏ธ Could not fetch UTXOs: ${error.message}`);
65
- return [];
66
- }
67
- }
68
-
69
- async getBalance(address) {
70
- try {
71
- const balanceData = await this.makeRequest(`/address/${address}/balance`);
72
- return {
73
- confirmed: balanceData.confirmed,
74
- unconfirmed: balanceData.unconfirmed
75
- };
76
- } catch (error) {
77
- console.log(`โš ๏ธ Could not fetch balance: ${error.message}`);
78
- return { confirmed: 0, unconfirmed: 0 };
79
- }
80
- }
81
-
82
- async broadcastTransaction(rawTx) {
83
- return new Promise((resolve, reject) => {
84
- const postData = JSON.stringify({ txhex: rawTx });
85
- const options = {
86
- hostname: 'api.whatsonchain.com',
87
- port: 443,
88
- path: `/v1/bsv/main/tx/raw`,
89
- method: 'POST',
90
- headers: {
91
- 'Content-Type': 'application/json',
92
- 'Content-Length': Buffer.byteLength(postData)
93
- }
94
- };
95
-
96
- const req = https.request(options, (res) => {
97
- let data = '';
98
- res.on('data', chunk => data += chunk);
99
- res.on('end', () => {
100
- if (res.statusCode === 200) {
101
- resolve(data);
102
- } else {
103
- reject(new Error(`Broadcast failed: ${res.statusCode} ${data}`));
104
- }
105
- });
106
- });
107
-
108
- req.on('error', reject);
109
- req.write(postData);
110
- req.end();
111
- });
112
- }
113
- }
114
-
115
- // Enhanced SmartUTXO with real blockchain integration
116
- class RealUTXOManager extends bsv.SmartUTXO {
117
- constructor(options = {}) {
118
- super(options);
119
- this.api = new WhatsOnChainAPI(options.network || 'main');
120
- this.enableBroadcast = options.enableBroadcast || false;
121
- }
122
-
123
- async fetchRealUTXOs(address) {
124
- console.log('\n๐Ÿ” Fetching Real UTXOs from Blockchain:');
125
- console.log('=====================================');
126
-
127
- const utxos = await this.api.getUTXOs(address);
128
- const balance = await this.api.getBalance(address);
129
-
130
- console.log(`Balance: ${balance.confirmed} sats confirmed, ${balance.unconfirmed} sats unconfirmed`);
131
-
132
- if (utxos.length > 0) {
133
- console.log('\nReal UTXOs found:');
134
- utxos.forEach((utxo, i) => {
135
- console.log(` ${i + 1}: ${utxo.txid}:${utxo.vout} = ${utxo.satoshis} sats (height: ${utxo.height})`);
136
- });
137
-
138
- // Add real UTXOs to our management system
139
- console.log('\nAdding real UTXOs to SmartUTXO manager...');
140
- utxos.forEach(utxo => this.addUTXO(utxo));
141
-
142
- return utxos;
143
- } else {
144
- console.log('No UTXOs found - will use mock UTXOs for testing');
145
- return null;
146
- }
147
- }
148
-
149
- async createAndValidateTransaction(fromAddress, toAddress, satoshis, feePerByte = 0.01) {
150
- console.log('\n๐Ÿ’ธ Creating Real Transaction:');
151
- console.log('============================');
152
-
153
- const availableUTXOs = this.getUTXOsForAddress(fromAddress);
154
- const balance = this.getBalance(fromAddress);
155
-
156
- console.log(`Available balance: ${balance} satoshis`);
157
- console.log(`Transaction amount: ${satoshis} satoshis`);
158
-
159
- if (balance < satoshis) {
160
- throw new Error(`Insufficient balance: ${balance} < ${satoshis}`);
161
- }
162
-
163
- // Create transaction
164
- const transaction = new bsv.Transaction();
165
-
166
- // Add inputs (use all UTXOs for simplicity)
167
- let inputTotal = 0;
168
- availableUTXOs.forEach(utxo => {
169
- transaction.from({
170
- txid: utxo.txid,
171
- vout: utxo.vout,
172
- address: fromAddress,
173
- script: utxo.script,
174
- satoshis: utxo.satoshis
175
- });
176
- inputTotal += utxo.satoshis;
177
- });
178
-
179
- // Calculate fee (estimate based on transaction size)
180
- const estimatedSize = 148 * availableUTXOs.length + 34 * 2 + 10; // rough estimate
181
- const fee = Math.ceil(estimatedSize * feePerByte); // ultra-low fee without minimum
182
-
183
- console.log(`Estimated transaction size: ${estimatedSize} bytes`);
184
- console.log(`Fee: ${fee} satoshis (${feePerByte} sat/byte)`);
185
-
186
- // Add outputs
187
- transaction.to(toAddress, satoshis);
188
-
189
- // Add change output if needed
190
- const change = inputTotal - satoshis - fee;
191
- if (change > 546) { // dust limit
192
- transaction.change(fromAddress);
193
- }
194
-
195
- // Sign transaction
196
- transaction.sign(privateKey);
197
-
198
- // Enhanced validation pipeline with SmartVerify and Miner validation
199
- console.log('\n๐Ÿ” Enhanced Transaction Validation Pipeline:');
200
- console.log('===========================================');
201
-
202
- try {
203
- // Step 1: Basic BSV transaction validation
204
- console.log('Step 1: Basic BSV Transaction Validation');
205
- const basicValid = transaction.verify();
206
- console.log(` Basic validation: ${basicValid ? 'โœ… VALID' : 'โŒ INVALID'}`);
207
-
208
- if (!basicValid) {
209
- throw new Error('Basic transaction validation failed');
210
- }
211
-
212
- // Step 2: Enhanced transaction signature validation
213
- console.log('\nStep 2: Enhanced Transaction Signature Validation');
214
- let smartVerifyValid = true;
215
-
216
- for (let i = 0; i < transaction.inputs.length; i++) {
217
- const input = transaction.inputs[i];
218
-
219
- try {
220
- // Get the signature hash for this input
221
- const signature = input.script.chunks[0]?.buf;
222
- const publicKey = input.script.chunks[1]?.buf;
223
-
224
- if (signature && publicKey) {
225
- // Use proper transaction verification instead of direct SmartVerify
226
- const sigBuffer = signature.slice(0, -1); // Remove sighash flag
227
- const pubkeyObj = new bsv.PublicKey(publicKey);
228
-
229
- // Parse signature with hashtype for proper verification
230
- const parsedSig = bsv.crypto.Signature.fromDER(sigBuffer);
231
- parsedSig.nhashtype = signature[signature.length - 1]; // Set the hashtype
232
-
233
- // Use transaction's built-in verification (handles endianness correctly)
234
- const input = transaction.inputs[i];
235
- const subscript = input.output.script;
236
- const satoshisBN = new bsv.crypto.BN(input.output.satoshis);
237
-
238
- const txVerifyValid = transaction.verifySignature(parsedSig, pubkeyObj, i, subscript, satoshisBN);
239
- const isCanonical = bsv.SmartVerify.isCanonical(sigBuffer);
240
-
241
- console.log(` Input ${i}: TxVerify=${txVerifyValid ? 'โœ…' : 'โŒ'}, Canonical=${isCanonical ? 'โœ…' : 'โŒ'}`);
242
-
243
- if (!txVerifyValid || !isCanonical) {
244
- smartVerifyValid = false;
245
- }
246
- }
247
- } catch (error) {
248
- console.log(` Input ${i}: Transaction validation error: ${error.message}`);
249
- // For demo purposes, don't fail on signature extraction errors
250
- }
251
- }
252
-
253
- console.log(` Transaction verification: ${smartVerifyValid ? 'โœ… PASSED' : 'โŒ FAILED'}`);
254
-
255
- // Step 3: Miner simulation validation
256
- console.log('\nStep 3: Miner Simulation Validation');
257
- let minerAccepted = false;
258
- try {
259
- const miner = new bsv.SmartMiner(bsv, {
260
- validateScripts: false, // Less strict for now
261
- logLevel: 'warn'
262
- });
263
-
264
- minerAccepted = miner.acceptTransaction(transaction);
265
- console.log(` Miner acceptance: ${minerAccepted ? 'โœ… ACCEPTED' : 'โŒ REJECTED'}`);
266
- } catch (error) {
267
- console.log(` Miner validation error: ${error.message}`);
268
- // For now, skip miner validation if it fails
269
- minerAccepted = true; // Since our SmartVerify passed
270
- console.log(` Miner simulation: โš ๏ธ SKIPPED (SmartVerify passed)`);
271
- }
272
-
273
- // Step 4: Final validation summary
274
- console.log('\nStep 4: Final Validation Summary');
275
- const allValid = basicValid && smartVerifyValid && minerAccepted;
276
-
277
- console.log(` Basic BSV validation: ${basicValid ? 'โœ…' : 'โŒ'}`);
278
- console.log(` Transaction validation: ${smartVerifyValid ? 'โœ…' : 'โŒ'}`);
279
- console.log(` Miner simulation: ${minerAccepted ? 'โœ…' : 'โŒ'}`);
280
- console.log(` Overall result: ${allValid ? 'โœ… TRANSACTION VALID' : 'โŒ TRANSACTION INVALID'}`);
281
-
282
- if (allValid) {
283
- console.log(`\n๐Ÿ“Š Transaction Details:`);
284
- console.log(` Transaction ID: ${transaction.id}`);
285
- console.log(` Transaction size: ${transaction.toBuffer().length} bytes`);
286
- console.log(` Input count: ${transaction.inputs.length}`);
287
- console.log(` Output count: ${transaction.outputs.length}`);
288
- console.log(` Raw transaction: ${transaction.toString()}`);
289
-
290
- return {
291
- transaction,
292
- rawTx: transaction.toString(),
293
- isValid: true,
294
- txid: transaction.id,
295
- size: transaction.toBuffer().length,
296
- validation: {
297
- basic: basicValid,
298
- smartVerify: smartVerifyValid,
299
- miner: minerAccepted,
300
- overall: allValid
301
- }
302
- };
303
- } else {
304
- throw new Error('Enhanced transaction validation failed');
305
- }
306
- } catch (error) {
307
- console.log(`โŒ Transaction validation failed: ${error.message}`);
308
- return {
309
- transaction,
310
- isValid: false,
311
- error: error.message
312
- };
313
- }
314
- }
315
-
316
- updateUTXOsAfterBroadcast(transaction, changeAddress) {
317
- console.log('\n๐Ÿ”„ Updating UTXO State After Broadcast:');
318
- console.log('======================================');
319
-
320
- // First, remove spent UTXOs (inputs) from blockchain state
321
- transaction.inputs.forEach((input, i) => {
322
- const spentUTXO = `${input.prevTxId}:${input.outputIndex}`;
323
- console.log(` Removing spent UTXO: ${spentUTXO}`);
324
-
325
- try {
326
- // Use blockchain state to properly spend the UTXO
327
- const blockchainState = require('./utilities/blockchain-state');
328
- blockchainState.spendUTXO(input.prevTxId.toString(), input.outputIndex, transaction.id);
329
- console.log(` โœ… Spent UTXO removed: ${spentUTXO}`);
330
- } catch (error) {
331
- console.log(` Warning: Could not remove UTXO ${spentUTXO}: ${error.message}`);
332
- }
333
- });
334
-
335
- // Add new UTXOs (outputs that belong to our change address)
336
- transaction.outputs.forEach((output, i) => {
337
- try {
338
- const outputAddress = output.script.toAddress().toString();
339
-
340
- // Add all outputs since we're mimicking a miner for mock UTXOs
341
- const newUTXO = {
342
- txid: transaction.id,
343
- vout: i,
344
- address: outputAddress,
345
- satoshis: output.satoshis,
346
- script: output.script.toHex(),
347
- height: 0 // Unconfirmed
348
- };
349
-
350
- console.log(` Adding new UTXO: ${newUTXO.txid}:${newUTXO.vout} = ${newUTXO.satoshis} sats to ${outputAddress}`);
351
- this.addUTXO(newUTXO);
352
-
353
- } catch (error) {
354
- // Skip outputs that can't be converted to addresses (e.g., OP_RETURN)
355
- console.log(` Skipping output ${i}: ${error.message}`);
356
- }
357
- });
358
-
359
- console.log('โœ… UTXO state updated successfully');
360
- }
361
-
362
- async broadcastTransaction(rawTx, validationResults = null, transaction = null, changeAddress = null) {
363
- if (!this.enableBroadcast) {
364
- console.log('๐Ÿ“ก Broadcasting disabled - use --broadcast flag to enable');
365
- return false;
366
- }
367
-
368
- console.log('\n๐Ÿ“ก Pre-Broadcast Validation & Broadcasting:');
369
- console.log('==========================================');
370
-
371
- // Final validation check before broadcasting
372
- if (validationResults) {
373
- console.log('๐Ÿ” Final validation check:');
374
- console.log(` Basic validation: ${validationResults.basic ? 'โœ…' : 'โŒ'}`);
375
- console.log(` Transaction validation: ${validationResults.smartVerify ? 'โœ…' : 'โŒ'}`);
376
- console.log(` Miner acceptance: ${validationResults.miner ? 'โœ…' : 'โŒ'}`);
377
- console.log(` Overall valid: ${validationResults.overall ? 'โœ…' : 'โŒ'}`);
378
-
379
- if (!validationResults.overall) {
380
- console.log('โŒ BROADCAST BLOCKED: Transaction failed enhanced validation');
381
- console.log('โš ๏ธ This transaction would likely be rejected by the network');
382
- return false;
383
- }
384
- }
385
-
386
- // Parse and re-validate the raw transaction one more time
387
- console.log('\n๐Ÿ” Final Raw Transaction Validation:');
388
- try {
389
- const parsedTx = new bsv.Transaction(rawTx);
390
- const finalValid = parsedTx.verify();
391
- console.log(`Raw transaction parsing: ${finalValid ? 'โœ… VALID' : 'โŒ INVALID'}`);
392
-
393
- if (!finalValid) {
394
- console.log('โŒ BROADCAST BLOCKED: Raw transaction failed final validation');
395
- return false;
396
- }
397
- } catch (error) {
398
- console.log(`โŒ BROADCAST BLOCKED: Raw transaction parsing failed: ${error.message}`);
399
- return false;
400
- }
401
-
402
- console.log('\n๐Ÿ“ก All validations passed - proceeding with broadcast:');
403
- console.log('โš ๏ธ WARNING: About to spend real BSV on the blockchain!');
404
-
405
- try {
406
- const result = await this.api.broadcastTransaction(rawTx);
407
- console.log(`โœ… Transaction broadcast successful: ${result}`);
408
- console.log('๐ŸŽ‰ Transaction is now on the BSV blockchain!');
409
-
410
- // Update UTXO state after successful broadcast
411
- if (transaction) {
412
- this.updateUTXOsAfterBroadcast(transaction, changeAddress);
413
- } else {
414
- console.log('โš ๏ธ Cannot update UTXO state: transaction object not provided');
415
- }
416
-
417
- return true;
418
- } catch (error) {
419
- console.log(`โŒ Broadcast failed: ${error.message}`);
420
- console.log('๐Ÿ’ก This could be due to network issues, insufficient fees, or transaction conflicts');
421
- return false;
422
- }
423
- }
424
- }
425
-
426
- // Main test function
427
- async function runRealUTXOTest() {
428
- const enableBroadcast = process.argv.includes('--broadcast');
429
- const useTestnet = process.argv.includes('--testnet');
430
-
431
- console.log(`๐Ÿ”ง Configuration:`);
432
- console.log(`- Network: ${useTestnet ? 'testnet' : 'mainnet'}`);
433
- console.log(`- Broadcasting: ${enableBroadcast ? 'ENABLED' : 'DISABLED'}`);
434
- console.log('');
435
-
436
- // Initialize real UTXO manager
437
- const utxoManager = new RealUTXOManager({
438
- network: useTestnet ? 'test' : 'main',
439
- enableBroadcast
440
- });
441
-
442
- try {
443
- // Test 1: Fetch real UTXOs
444
- const realUTXOs = await utxoManager.fetchRealUTXOs(address);
445
-
446
- if (!realUTXOs || realUTXOs.length === 0) {
447
- // Fallback to mock UTXOs for testing
448
- console.log('\n๐Ÿงช Using Mock UTXOs for Testing:');
449
- console.log('================================');
450
-
451
- const mockUTXOs = utxoManager.createMockUTXOs(address, 2, 100000);
452
- mockUTXOs.forEach(utxo => utxoManager.addUTXO(utxo));
453
- console.log(`Created ${mockUTXOs.length} mock UTXOs`);
454
- }
455
-
456
- // Test 2: Check balance
457
- const balance = utxoManager.getBalance(address);
458
- console.log(`\n๐Ÿ’ฐ SmartUTXO Balance: ${balance} satoshis (${balance / 100000000} BSV)`);
459
-
460
- // Test 3: Create and validate transaction
461
- if (balance > 10000) { // Need at least 10k sats for a test transaction
462
- const testAddress = '1BitcoinEaterAddressDontSendf59kuE'; // Bitcoin eater address for testing
463
- const sendAmount = Math.min(1000, balance - 5000); // Send small amount, keep rest for fees
464
-
465
- console.log(`\n๐Ÿงช Testing transaction creation (${sendAmount} sats to ${testAddress}):`);
466
-
467
- const txResult = await utxoManager.createAndValidateTransaction(
468
- address,
469
- testAddress,
470
- sendAmount,
471
- 0.01 // 0.01 sats/byte fee rate (10 sats/KB)
472
- );
473
-
474
- if (txResult.isValid) {
475
- console.log('\n๐ŸŽ‰ Transaction created and validated successfully!');
476
-
477
- if (enableBroadcast) {
478
- console.log('\nโš ๏ธ WARNING: About to broadcast real transaction!');
479
- console.log('This will spend real BSV. Press Ctrl+C to cancel...');
480
-
481
- // 5 second delay for user to cancel
482
- await new Promise(resolve => setTimeout(resolve, 5000));
483
-
484
- await utxoManager.broadcastTransaction(txResult.rawTx, txResult.validation, txResult.transaction, address);
485
- } else {
486
- console.log('\n๐Ÿ’ก To broadcast this transaction, run with --broadcast flag');
487
- console.log('โš ๏ธ WARNING: This will spend real BSV!');
488
- }
489
- }
490
- } else {
491
- console.log(`\nโš ๏ธ Balance too low (${balance} sats) for transaction testing`);
492
- }
493
-
494
- // Test 4: SmartUTXO statistics
495
- const stats = utxoManager.getStats();
496
- console.log('\n๐Ÿ“Š SmartUTXO Statistics:');
497
- console.log('========================');
498
- console.log(`Total UTXOs: ${stats.totalUTXOs}`);
499
- console.log(`Total Value: ${stats.totalValue} satoshis`);
500
- console.log(`Wallets: ${stats.totalWallets}`);
501
-
502
- } catch (error) {
503
- console.error('โŒ Test failed:', error.message);
504
- if (error.stack) {
505
- console.error('Stack:', error.stack);
506
- }
507
- }
508
- }
509
-
510
- // Usage instructions
511
- if (process.argv.includes('--help')) {
512
- console.log('SmartLedger Real UTXO Management Test');
513
- console.log('====================================');
514
- console.log('');
515
- console.log('Usage: node real_utxo_test.js [options]');
516
- console.log('');
517
- console.log('Options:');
518
- console.log(' --broadcast Enable real transaction broadcasting (WARNING: spends real BSV!)');
519
- console.log(' --testnet Use testnet instead of mainnet');
520
- console.log(' --help Show this help message');
521
- console.log('');
522
- console.log('Examples:');
523
- console.log(' node real_utxo_test.js # Test with mainnet, no broadcasting');
524
- console.log(' node real_utxo_test.js --testnet # Test with testnet, no broadcasting');
525
- console.log(' node real_utxo_test.js --broadcast # Test with mainnet and broadcasting');
526
- console.log(' node real_utxo_test.js --testnet --broadcast # Test with testnet and broadcasting');
527
- console.log('');
528
- console.log('โš ๏ธ WARNING: --broadcast will spend real BSV! Use with caution!');
529
- process.exit(0);
530
- }
531
-
532
- // Run the test
533
- console.log('๐Ÿ’ก Tip: Run with --help for usage options\n');
534
- runRealUTXOTest().catch(console.error);