@smartledger/bsv 3.3.2 → 3.3.3

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 (79) hide show
  1. package/CHANGELOG.md +211 -83
  2. package/README.md +266 -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-script-helper.min.js +2 -2
  7. package/bsv-security.min.js +3 -24
  8. package/bsv-shamir.min.js +2 -2
  9. package/bsv-smartcontract.min.js +10 -8
  10. package/bsv.bundle.js +9 -9
  11. package/bsv.min.js +10 -8
  12. package/build/webpack.bundle.config.js +2 -2
  13. package/build/webpack.config.js +2 -2
  14. package/build/webpack.covenant.config.js +2 -2
  15. package/build/webpack.gdaf.config.js +6 -43
  16. package/build/webpack.script-helper.config.js +2 -2
  17. package/build/webpack.security.config.js +2 -2
  18. package/build/webpack.smartcontract.config.js +2 -2
  19. package/bundle-entry.js +1 -341
  20. package/covenant-entry.js +1 -44
  21. package/docs/DOCUMENTATION_REVIEW_REPORT.md +295 -0
  22. package/docs/MODULE_REFERENCE_COMPLETE.md +330 -0
  23. package/docs/README.md +107 -79
  24. package/docs/advanced/LEGAL_TOKEN_PROTOCOL.md +411 -0
  25. package/docs/advanced/SMART_CONTRACT_GUIDE.md +1255 -0
  26. package/docs/advanced/UTXO_MANAGER_GUIDE.md +851 -0
  27. package/docs/api/LTP.md +334 -0
  28. package/docs/getting-started/INSTALLATION.md +410 -0
  29. package/docs/getting-started/QUICK_START.md +180 -0
  30. package/docs/migration/FROM_BSV_1_5_6.md +260 -0
  31. package/docs/technical/GDAF_DEVELOPER_INTERFACE.md +187 -0
  32. package/docs/technical/GDAF_IMPLEMENTATION_COMPLETE.md +190 -0
  33. package/docs/technical/SHAMIR_INTEGRATION_SUMMARY.md +165 -0
  34. package/docs/technical/roadmap.md +1250 -0
  35. package/docs/technical/trust_law.md +142 -0
  36. package/gdaf-entry.js +2 -54
  37. package/index.js +32 -0
  38. package/ltp-entry.js +2 -92
  39. package/package.json +6 -4
  40. package/script-helper-entry.js +1 -49
  41. package/security-entry.js +1 -70
  42. package/shamir-entry.js +1 -173
  43. package/smartcontract-entry.js +1 -133
  44. package/tests/test_builtin_verify.js +117 -0
  45. package/tests/test_debug_integration.js +71 -0
  46. package/tests/test_ecdsa_little.js +70 -0
  47. package/tests/test_smartverify_der.js +110 -0
  48. package/utilities/blockchain-state.js +155 -155
  49. package/utilities/blockchain-state.json +103293 -5244
  50. package/utilities/miner-simulator.js +354 -358
  51. package/utilities/mock-utxo-generator.js +54 -54
  52. package/utilities/raw-tx-examples.js +120 -122
  53. package/utilities/success-demo.js +104 -105
  54. package/utilities/transaction-examples.js +188 -188
  55. package/utilities/utxo-manager.js +91 -91
  56. package/utilities/wallet-setup.js +79 -80
  57. package/utilities/working-signature-demo.js +108 -110
  58. package/SECURITY.md +0 -75
  59. package/architecture_demo.js +0 -247
  60. package/build/bsv-covenant.min.js +0 -10
  61. package/build/bsv-script-helper.min.js +0 -10
  62. package/build/bsv-security.min.js +0 -31
  63. package/build/bsv-smartcontract.min.js +0 -39
  64. package/build/bsv.bundle.js +0 -39
  65. package/build/bsv.min.js +0 -39
  66. package/complete_ltp_demo.js +0 -511
  67. package/shamir_demo.js +0 -121
  68. package/simple_demo.js +0 -204
  69. package/validation_test.js +0 -97
  70. /package/docs/{ADVANCED_COVENANT_DEVELOPMENT.md → advanced/ADVANCED_COVENANT_DEVELOPMENT.md} +0 -0
  71. /package/docs/{CUSTOM_SCRIPT_DEVELOPMENT.md → advanced/CUSTOM_SCRIPT_DEVELOPMENT.md} +0 -0
  72. /package/docs/{block.md → api/BLOCKS.md} +0 -0
  73. /package/docs/{ecies.md → api/ECIES.md} +0 -0
  74. /package/docs/{networks.md → api/NETWORKS.md} +0 -0
  75. /package/docs/{script.md → api/SCRIPTS.md} +0 -0
  76. /package/docs/{transaction.md → api/TRANSACTIONS.md} +0 -0
  77. /package/docs/{unspentoutput.md → api/UTXO.md} +0 -0
  78. /package/{test_shamir.js → tests/test_shamir.js} +0 -0
  79. /package/{test_standalone_shamir.html → tests/test_standalone_shamir.html} +0 -0
@@ -0,0 +1,1255 @@
1
+ # SmartContract Module Documentation
2
+
3
+ ## Overview
4
+
5
+ The SmartContract module is a production-ready covenant framework for Bitcoin SV (BSV) that provides comprehensive tools for creating, testing, and deploying smart contracts on the BSV blockchain. It implements BIP-143 transaction preimage parsing, covenant operations, and advanced script utilities.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Quick Start](#quick-start)
10
+ - [Core Components](#core-components)
11
+ - [Covenant Development](#covenant-development)
12
+ - [Preimage Operations](#preimage-operations)
13
+ - [Script Building](#script-building)
14
+ - [Testing & Debugging](#testing--debugging)
15
+ - [Advanced Features](#advanced-features)
16
+ - [API Reference](#api-reference)
17
+ - [Examples](#examples)
18
+ - [Best Practices](#best-practices)
19
+
20
+ ## Quick Start
21
+
22
+ ### Installation
23
+
24
+ ```javascript
25
+ const bsv = require('@smartledger/bsv');
26
+ const SmartContract = require('@smartledger/bsv/lib/smart_contract');
27
+ ```
28
+
29
+ ### Basic Usage
30
+
31
+ ```javascript
32
+ // Generate authentic UTXOs for testing
33
+ const utxoGenerator = new SmartContract.UTXOGenerator();
34
+ const utxos = utxoGenerator.createRealUTXOs(2, 100000); // 2 UTXOs, 100k satoshis each
35
+ const keypair = utxos[0].keypair; // Get keypair from first UTXO
36
+
37
+ console.log('Generated UTXO:', utxos[0].txid);
38
+ console.log('Keypair address:', keypair.addressString);
39
+ console.log('Private key (WIF):', keypair.wif);
40
+
41
+ // Create transaction and generate BIP-143 preimage
42
+ const bsv = require('@smartledger/bsv');
43
+ const privateKey = new bsv.PrivateKey(keypair.wif);
44
+ const address = new bsv.Address(keypair.addressString);
45
+
46
+ const tx = new bsv.Transaction()
47
+ .from({
48
+ txId: utxos[0].txid,
49
+ outputIndex: utxos[0].vout,
50
+ script: utxos[0].script,
51
+ satoshis: utxos[0].satoshis
52
+ })
53
+ .to(address, 95000)
54
+ .sign(privateKey);
55
+
56
+ // Generate preimage and extract fields
57
+ const sighashType = bsv.crypto.Signature.SIGHASH_ALL | bsv.crypto.Signature.SIGHASH_FORKID;
58
+ const preimageBuffer = bsv.Transaction.sighash.sighashPreimage(
59
+ tx, sighashType, 0, bsv.Script.buildPublicKeyHashOut(address), new bsv.crypto.BN(utxos[0].satoshis)
60
+ );
61
+
62
+ const preimage = new SmartContract.Preimage(preimageBuffer.toString('hex'));
63
+ const amount = preimage.getField('amount');
64
+ console.log('Extracted amount:', amount.readBigUInt64LE(0).toString(), 'satoshis');
65
+
66
+ // Build a covenant using extracted field
67
+ const builder = SmartContract.createCovenantBuilder();
68
+ const covenant = builder
69
+ .comment('Value lock covenant - requires minimum 50000 satoshis')
70
+ .extractField('amount')
71
+ .push(50000)
72
+ .greaterThanOrEqual()
73
+ .verify()
74
+ .build();
75
+
76
+ console.log('Covenant script:', covenant.asm);
77
+ ```
78
+
79
+ ## Core Components
80
+
81
+ ### 🏗️ **SmartContract Architecture**
82
+
83
+ The module consists of several interconnected components:
84
+
85
+ | Component | Purpose | Key Features |
86
+ |-----------|---------|--------------|
87
+ | **Covenant** | Core covenant logic and workflow management | P2PKH→Covenant→Spending, UTXO tracking |
88
+ | **Preimage** | BIP-143 preimage parsing and field extraction | Bidirectional extraction, SIGHASH detection |
89
+ | **CovenantBuilder** | High-level JavaScript-to-Script translation | Template patterns, conditional logic |
90
+ | **UTXOGenerator** | Authentic UTXO creation for testing | Real BSV keys, covenant-ready UTXOs |
91
+ | **ScriptTester** | Local script execution and verification | No blockchain required, full validation |
92
+ | **SIGHASH** | SIGHASH flag analysis and detection | Zero hash warnings, multi-type support |
93
+
94
+ ### 🎯 **Key Features**
95
+
96
+ - ✅ **BIP-143 Preimage Support** - Complete transaction preimage parsing
97
+ - ✅ **Covenant Workflows** - End-to-end covenant creation and spending
98
+ - ✅ **Script Generation** - JavaScript to Bitcoin Script translation
99
+ - ✅ **Local Testing** - Comprehensive testing without blockchain
100
+ - ✅ **UTXO Management** - Authentic test UTXO generation
101
+ - ✅ **Debug Tools** - Step-by-step script execution analysis
102
+ - ✅ **Production Ready** - Enterprise-grade error handling and validation
103
+
104
+ ## Covenant Development
105
+
106
+ ### Creating Covenants
107
+
108
+ #### Method 1: Using CovenantBuilder (Recommended)
109
+
110
+ ```javascript
111
+ const SmartContract = require('@smartledger/bsv/lib/smart_contract');
112
+
113
+ // Create a value-lock covenant
114
+ const valueLockCovenant = SmartContract.createQuickCovenant('value_lock', {
115
+ value: 100000 // Minimum 100,000 satoshis required
116
+ });
117
+
118
+ console.log('Value Lock Covenant:');
119
+ console.log('ASM:', valueLockCovenant.asm);
120
+ console.log('Hex:', valueLockCovenant.hex);
121
+ console.log('Size:', valueLockCovenant.size, 'bytes');
122
+
123
+ // Create a hash-lock covenant
124
+ const hashLockCovenant = SmartContract.createQuickCovenant('hash_lock', {
125
+ hash: 'abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890'
126
+ });
127
+
128
+ // Create a time-lock covenant
129
+ const timeLockCovenant = SmartContract.createQuickCovenant('time_lock', {
130
+ timestamp: 1640995200 // Unix timestamp
131
+ });
132
+ ```
133
+
134
+ #### Method 2: Manual Covenant Building
135
+
136
+ ```javascript
137
+ const builder = SmartContract.createCovenantBuilder();
138
+
139
+ const customCovenant = builder
140
+ .comment('Multi-condition covenant')
141
+
142
+ // Condition 1: Check minimum value
143
+ .extractField('value')
144
+ .push(50000)
145
+ .greaterThanOrEqual()
146
+ .verify('Value must be >= 50000 sats')
147
+
148
+ // Condition 2: Check output count
149
+ .extractField('outputCount')
150
+ .push(2)
151
+ .equal()
152
+ .verify('Must have exactly 2 outputs')
153
+
154
+ // Condition 3: Signature verification
155
+ .extractField('publicKey')
156
+ .checkSig()
157
+
158
+ .build();
159
+
160
+ console.log('Custom covenant script:', customCovenant.asm);
161
+ ```
162
+
163
+ #### Method 3: Complete Covenant Workflow
164
+
165
+ ```javascript
166
+ const bsv = require('@smartledger/bsv');
167
+
168
+ async function createCovenantWorkflow() {
169
+ // 1. Generate keypair for covenant
170
+ const privateKey = new bsv.PrivateKey();
171
+ const covenant = SmartContract.createCovenant(privateKey);
172
+
173
+ // 2. Create mock P2PKH UTXO for testing
174
+ const mockUtxo = {
175
+ txid: 'mock_' + Date.now(),
176
+ vout: 0,
177
+ satoshis: 100000,
178
+ script: bsv.Script.buildPublicKeyHashOut(privateKey.toAddress()).toString()
179
+ };
180
+
181
+ // 3. Create covenant from P2PKH
182
+ const covenantResult = covenant.createFromP2PKH(mockUtxo);
183
+
184
+ console.log('Covenant Creation Result:');
185
+ console.log('Transaction ID:', covenantResult.transaction.id);
186
+ console.log('Covenant UTXO:', covenantResult.covenantUtxo);
187
+
188
+ return covenantResult;
189
+ }
190
+
191
+ createCovenantWorkflow().catch(console.error);
192
+ ```
193
+
194
+ ## UTXO Generation
195
+
196
+ ### Creating Authentic Test UTXOs
197
+
198
+ The UTXOGenerator creates real, blockchain-valid UTXOs for testing and development:
199
+
200
+ ```javascript
201
+ const SmartContract = require('@smartledger/bsv/lib/smart_contract');
202
+
203
+ function demonstrateUTXOGeneration() {
204
+ // Create UTXOGenerator instance
205
+ const generator = new SmartContract.UTXOGenerator({
206
+ network: 'livenet', // or 'testnet'
207
+ count: 3, // number of UTXOs to generate
208
+ satoshis: 150000 // satoshis per UTXO
209
+ });
210
+
211
+ // Generate authentic UTXOs
212
+ const utxos = generator.createRealUTXOs(3, 150000);
213
+
214
+ console.log(`Generated ${utxos.length} UTXOs:`);
215
+ utxos.forEach((utxo, index) => {
216
+ console.log(`\nUTXO ${index + 1}:`);
217
+ console.log(` TXID: ${utxo.txid}`);
218
+ console.log(` VOUT: ${utxo.vout}`);
219
+ console.log(` Amount: ${utxo.satoshis.toLocaleString()} satoshis`);
220
+ console.log(` Address: ${utxo.address}`);
221
+ console.log(` Script: ${utxo.script}`);
222
+ console.log(` Private Key: ${utxo.keypair.wif}`);
223
+ console.log(` Script Type: ${utxo.scriptType}`);
224
+ });
225
+
226
+ // UTXOs are ready for transactions
227
+ const firstUTXO = utxos[0];
228
+ console.log('\nFirst UTXO ready for spending:');
229
+ console.log(` Can be used in transactions: ${firstUTXO.txid}:${firstUTXO.vout}`);
230
+ console.log(` Signed with key: ${firstUTXO.keypair.wif}`);
231
+
232
+ return utxos;
233
+ }
234
+
235
+ // Generate UTXOs for covenant testing
236
+ function generateCovenantUTXOs() {
237
+ const generator = new SmartContract.UTXOGenerator();
238
+
239
+ // Create multiple UTXOs for complex covenant scenarios
240
+ const smallUTXOs = generator.createRealUTXOs(5, 50000); // 5x 50k sat UTXOs
241
+ const largeUTXOs = generator.createRealUTXOs(2, 200000); // 2x 200k sat UTXOs
242
+
243
+ console.log('Generated covenant test UTXOs:');
244
+ console.log(` Small UTXOs: ${smallUTXOs.length} × 50,000 sat`);
245
+ console.log(` Large UTXOs: ${largeUTXOs.length} × 200,000 sat`);
246
+ console.log(` Total: ${smallUTXOs.length + largeUTXOs.length} UTXOs`);
247
+
248
+ return [...smallUTXOs, ...largeUTXOs];
249
+ }
250
+
251
+ demonstrateUTXOGeneration();
252
+ ```
253
+
254
+ ### UTXOGenerator API Reference
255
+
256
+ ```javascript
257
+ // Constructor options
258
+ const generator = new SmartContract.UTXOGenerator(options);
259
+
260
+ // Main methods
261
+ generator.createRealUTXOs(count, satoshis) // Generate UTXOs
262
+ generator.createTestTransaction(options) // Create test transaction
263
+ generator.createCovenantTest(options) // Covenant-specific test setup
264
+ generator.getUTXOs() // Get generated UTXOs
265
+ generator.reset() // Reset generator state
266
+
267
+ // UTXO Structure
268
+ const utxo = {
269
+ txid: 'string', // Transaction ID
270
+ vout: 0, // Output index
271
+ satoshis: 100000, // Amount in satoshis
272
+ address: 'string', // Base58 address
273
+ script: 'string', // Script hex
274
+ scriptType: 'P2PKH', // Script type
275
+ keypair: { // Associated keypair
276
+ privateKey: PrivateKey,
277
+ publicKey: PublicKey,
278
+ address: Address,
279
+ wif: 'string',
280
+ addressString: 'string'
281
+ },
282
+ created: 'ISO date' // Creation timestamp
283
+ };
284
+ ```
285
+
286
+ ## Preimage Operations
287
+
288
+ ### BIP-143 Preimage Parsing
289
+
290
+ The SmartContract module provides comprehensive BIP-143 preimage parsing capabilities with multiple extraction strategies:
291
+
292
+ ```javascript
293
+ const SmartContract = require('@smartledger/bsv/lib/smart_contract');
294
+ const bsv = require('@smartledger/bsv');
295
+
296
+ function demonstratePreimageExtraction() {
297
+ // Generate authentic UTXO using UTXOGenerator
298
+ const generator = new SmartContract.UTXOGenerator();
299
+ const utxos = generator.createRealUTXOs(1, 100000);
300
+ const utxo = utxos[0];
301
+
302
+ // Create transaction using real UTXO
303
+ const privateKey = new bsv.PrivateKey(utxo.keypair.wif);
304
+ const address = new bsv.Address(utxo.address);
305
+
306
+ const tx = new bsv.Transaction()
307
+ .from({
308
+ txId: utxo.txid,
309
+ outputIndex: utxo.vout,
310
+ script: utxo.script,
311
+ satoshis: utxo.satoshis
312
+ })
313
+ .to(address, 95000)
314
+ .sign(privateKey);
315
+
316
+ // Generate BIP-143 preimage
317
+ const sighashType = bsv.crypto.Signature.SIGHASH_ALL | bsv.crypto.Signature.SIGHASH_FORKID;
318
+ const preimageBuffer = bsv.Transaction.sighash.sighashPreimage(
319
+ tx, sighashType, 0, bsv.Script.buildPublicKeyHashOut(address), new bsv.crypto.BN(utxo.satoshis)
320
+ );
321
+
322
+ // Create preimage parser instance
323
+ const preimage = new SmartContract.Preimage(preimageBuffer.toString('hex'));
324
+
325
+ console.log('Preimage Analysis:');
326
+ console.log('Length:', preimageBuffer.length, 'bytes');
327
+ console.log('Hex:', preimageBuffer.toString('hex'));
328
+
329
+ // Test different extraction strategies
330
+ const strategies = ['LEFT', 'RIGHT', 'DYNAMIC'];
331
+ strategies.forEach(strategy => {
332
+ try {
333
+ const extracted = preimage.extract(strategy);
334
+ console.log(`${strategy} extraction: ${Object.keys(extracted).length} fields`);
335
+ } catch (error) {
336
+ console.log(`${strategy} extraction failed:`, error.message);
337
+ }
338
+ });
339
+
340
+ // Access individual BIP-143 fields
341
+ const fieldNames = ['version', 'hashPrevouts', 'hashSequence', 'outpoint', 'scriptCode',
342
+ 'amount', 'sequence', 'hashOutputs', 'locktime', 'sighash'];
343
+
344
+ fieldNames.forEach(fieldName => {
345
+ try {
346
+ const fieldBuffer = preimage.getField(fieldName);
347
+ console.log(`${fieldName}: ${fieldBuffer.toString('hex')} (${fieldBuffer.length} bytes)`);
348
+
349
+ // Interpret common fields
350
+ if (fieldName === 'amount') {
351
+ const satoshis = fieldBuffer.readBigUInt64LE(0);
352
+ console.log(` → ${satoshis} satoshis`);
353
+ } else if (fieldName === 'version') {
354
+ const version = fieldBuffer.readUInt32LE(0);
355
+ console.log(` → Version ${version}`);
356
+ } else if (fieldName === 'outpoint') {
357
+ const txid = fieldBuffer.slice(0, 32).reverse().toString('hex');
358
+ const vout = fieldBuffer.slice(32).readUInt32LE(0);
359
+ console.log(` → ${txid}:${vout}`);
360
+ }
361
+ } catch (error) {
362
+ console.log(`${fieldName}: extraction failed`);
363
+ }
364
+ });
365
+
366
+ // Get SIGHASH analysis
367
+ const sighashInfo = preimage.getSighashInfo();
368
+ console.log('SIGHASH Analysis:', {
369
+ hasZeroHashes: sighashInfo.hasZeroHashes,
370
+ type: sighashInfo.type,
371
+ isStandard: sighashInfo.isStandard
372
+ });
373
+
374
+ return preimage;
375
+ }
376
+
377
+ demonstratePreimageExtraction();
378
+ ```
379
+
380
+ ### Field Extraction for Covenants
381
+
382
+ ```javascript
383
+ function extractSpecificFields(preimageHex) {
384
+ const preimage = new SmartContract.Preimage(preimageHex);
385
+
386
+ // BIP-143 defines these 10 fields in order
387
+ const fieldNames = [
388
+ 'version', // 4 bytes - nVersion
389
+ 'hashPrevouts', // 32 bytes - hashPrevouts
390
+ 'hashSequence', // 32 bytes - hashSequence
391
+ 'outpoint', // 36 bytes - outpoint (32 byte hash + 4 byte index)
392
+ 'scriptCode', // Variable - scriptCode with length prefix
393
+ 'amount', // 8 bytes - value in satoshis
394
+ 'sequence', // 4 bytes - nSequence
395
+ 'hashOutputs', // 32 bytes - hashOutputs
396
+ 'locktime', // 4 bytes - nLockTime
397
+ 'sighash' // 4 bytes - sighash flags
398
+ ];
399
+
400
+ console.log('🔍 BIP-143 Preimage Field Extraction:');
401
+ console.log('='.repeat(50));
402
+
403
+ const extractedFields = {};
404
+ let offset = 0;
405
+
406
+ fieldNames.forEach((fieldName, index) => {
407
+ try {
408
+ const fieldBuffer = preimage.getField(fieldName);
409
+ extractedFields[fieldName] = fieldBuffer;
410
+
411
+ console.log(`\n${(index + 1).toString().padStart(2)}. ${fieldName.toUpperCase()}:`);
412
+ console.log(` Offset: ${offset}-${offset + fieldBuffer.length - 1} (${fieldBuffer.length} bytes)`);
413
+ console.log(` Hex: ${fieldBuffer.toString('hex')}`);
414
+
415
+ // Interpret field values
416
+ switch (fieldName) {
417
+ case 'version':
418
+ console.log(` Value: Version ${fieldBuffer.readUInt32LE(0)}`);
419
+ break;
420
+ case 'amount':
421
+ const satoshis = fieldBuffer.readBigUInt64LE(0);
422
+ console.log(` Value: ${satoshis} satoshis (${(Number(satoshis) / 100000000).toFixed(8)} BSV)`);
423
+ break;
424
+ case 'outpoint':
425
+ const txid = fieldBuffer.slice(0, 32).reverse().toString('hex');
426
+ const vout = fieldBuffer.slice(32).readUInt32LE(0);
427
+ console.log(` Value: ${txid}:${vout}`);
428
+ break;
429
+ case 'sequence':
430
+ const seq = fieldBuffer.readUInt32LE(0);
431
+ console.log(` Value: ${seq} (0x${seq.toString(16)})`);
432
+ break;
433
+ case 'locktime':
434
+ const locktime = fieldBuffer.readUInt32LE(0);
435
+ console.log(` Value: ${locktime} ${locktime < 500000000 ? '(block height)' : '(timestamp)'}`);
436
+ break;
437
+ case 'sighash':
438
+ const sighash = fieldBuffer.readUInt32LE(0);
439
+ const flags = [];
440
+ if (sighash & 0x01) flags.push('SIGHASH_ALL');
441
+ if (sighash & 0x02) flags.push('SIGHASH_NONE');
442
+ if (sighash & 0x03) flags.push('SIGHASH_SINGLE');
443
+ if (sighash & 0x40) flags.push('SIGHASH_FORKID');
444
+ if (sighash & 0x80) flags.push('SIGHASH_ANYONECANPAY');
445
+ console.log(` Value: 0x${sighash.toString(16)} (${flags.join(' | ')})`);
446
+ break;
447
+ case 'scriptCode':
448
+ console.log(` Value: P2PKH script (${fieldBuffer.length} bytes)`);
449
+ break;
450
+ default:
451
+ console.log(` Value: 32-byte hash`);
452
+ }
453
+
454
+ offset += fieldBuffer.length;
455
+
456
+ } catch (error) {
457
+ console.log(` ERROR: ${error.message}`);
458
+ }
459
+ });
460
+
461
+ // Test extraction strategies
462
+ console.log('\n🧪 Testing Extraction Strategies:');
463
+ ['LEFT', 'RIGHT', 'DYNAMIC'].forEach(strategy => {
464
+ try {
465
+ const result = preimage.extract(strategy);
466
+ console.log(`✅ ${strategy}: ${Object.keys(result).length} fields extracted`);
467
+ } catch (error) {
468
+ console.log(`❌ ${strategy}: ${error.message}`);
469
+ }
470
+ });
471
+
472
+ console.log(`\n📊 Summary: ${Object.keys(extractedFields).length}/10 fields extracted, ${offset} bytes processed`);
473
+
474
+ return extractedFields;
475
+ }
476
+
477
+ // Complete UTXO to Preimage workflow
478
+ function completeUTXOToPreimageWorkflow() {
479
+ console.log('🚀 Complete UTXO → Transaction → Preimage → Field Extraction Workflow\n');
480
+
481
+ // Step 1: Generate UTXO
482
+ const generator = new SmartContract.UTXOGenerator();
483
+ const utxos = generator.createRealUTXOs(1, 100000);
484
+ const utxo = utxos[0];
485
+ console.log(`✅ UTXO Generated: ${utxo.txid}:${utxo.vout} (${utxo.satoshis} sats)`);
486
+
487
+ // Step 2: Create transaction
488
+ const bsv = require('@smartledger/bsv');
489
+ const privateKey = new bsv.PrivateKey(utxo.keypair.wif);
490
+ const address = new bsv.Address(utxo.address);
491
+
492
+ const tx = new bsv.Transaction()
493
+ .from({ txId: utxo.txid, outputIndex: utxo.vout, script: utxo.script, satoshis: utxo.satoshis })
494
+ .to(address, 95000)
495
+ .sign(privateKey);
496
+
497
+ console.log(`✅ Transaction Created: ${tx.id}`);
498
+
499
+ // Step 3: Generate preimage
500
+ const sighashType = bsv.crypto.Signature.SIGHASH_ALL | bsv.crypto.Signature.SIGHASH_FORKID;
501
+ const preimageBuffer = bsv.Transaction.sighash.sighashPreimage(
502
+ tx, sighashType, 0, bsv.Script.buildPublicKeyHashOut(address), new bsv.crypto.BN(utxo.satoshis)
503
+ );
504
+
505
+ console.log(`✅ Preimage Generated: ${preimageBuffer.length} bytes`);
506
+
507
+ // Step 4: Extract fields
508
+ const fields = extractSpecificFields(preimageBuffer.toString('hex'));
509
+
510
+ console.log(`✅ Workflow Complete: UTXO → TX → Preimage → ${Object.keys(fields).length} Fields`);
511
+
512
+ return { utxo, transaction: tx, preimage: preimageBuffer, fields };
513
+ }
514
+ ```
515
+
516
+ ## Script Building
517
+
518
+ ### High-Level Script Construction
519
+
520
+ ```javascript
521
+ const SmartContract = require('@smartledger/bsv/lib/smart_contract');
522
+
523
+ function buildAdvancedCovenants() {
524
+ const builder = SmartContract.createCovenantBuilder();
525
+
526
+ // Example 1: Multi-signature with value constraints
527
+ const multisigValueCovenant = builder
528
+ .comment('2-of-3 multisig with minimum value requirement')
529
+
530
+ // Check minimum value (100,000 satoshis)
531
+ .extractField('amount')
532
+ .push(100000)
533
+ .greaterThanOrEqual()
534
+ .verify()
535
+
536
+ // Multisig verification (simplified)
537
+ .push(2) // Required signatures
538
+ .push('pubkey1_placeholder')
539
+ .push('pubkey2_placeholder')
540
+ .push('pubkey3_placeholder')
541
+ .push(3) // Total keys
542
+ .checkMultisig()
543
+
544
+ .build();
545
+
546
+ // Example 2: Time-locked with hash verification
547
+ const timeHashCovenant = builder
548
+ .comment('Time-locked covenant with secret hash')
549
+
550
+ // Time lock check (must be after timestamp)
551
+ .extractField('locktime')
552
+ .push(1640995200) // Future timestamp
553
+ .greaterThan()
554
+ .verify()
555
+
556
+ // Hash verification
557
+ .push('secret_preimage_placeholder')
558
+ .sha256()
559
+ .push('expected_hash_placeholder')
560
+ .equalVerify()
561
+
562
+ // Signature check
563
+ .push('pubkey_placeholder')
564
+ .checkSig()
565
+
566
+ .build();
567
+
568
+ // Example 3: Conditional spending paths
569
+ const conditionalCovenant = builder
570
+ .comment('Conditional covenant - multiple spending paths')
571
+
572
+ // Path selection (simplified IF/ELSE structure)
573
+ .if()
574
+ // Path 1: Owner spending with signature
575
+ .push('owner_pubkey_placeholder')
576
+ .checkSig()
577
+ .else()
578
+ // Path 2: Anyone after timelock
579
+ .extractField('locktime')
580
+ .push(1641081600) // Later timestamp
581
+ .greaterThan()
582
+ .verify()
583
+ .endif()
584
+
585
+ .build();
586
+
587
+ return {
588
+ multisigValue: multisigValueCovenant,
589
+ timeHash: timeHashCovenant,
590
+ conditional: conditionalCovenant
591
+ };
592
+ }
593
+
594
+ const covenants = buildAdvancedCovenants();
595
+ console.log('Advanced Covenants Created:');
596
+ Object.entries(covenants).forEach(([type, covenant]) => {
597
+ console.log(`${type}: ${covenant.size} bytes`);
598
+ });
599
+ ```
600
+
601
+ ### Script Conversion and Analysis
602
+
603
+ ```javascript
604
+ function scriptUtilities() {
605
+ // Convert between ASM and hex formats
606
+ const asmScript = 'OP_DUP OP_HASH160 0x14 0x1234567890123456789012345678901234567890 OP_EQUALVERIFY OP_CHECKSIG';
607
+
608
+ console.log('Script Conversion:');
609
+ console.log('ASM:', asmScript);
610
+
611
+ const hexScript = SmartContract.asmToHex(asmScript);
612
+ console.log('Hex:', hexScript);
613
+
614
+ const backToASM = SmartContract.hexToASM(hexScript);
615
+ console.log('Back to ASM:', backToASM);
616
+
617
+ // Validate scripts
618
+ const validation = SmartContract.validateASM(asmScript);
619
+ console.log('Validation:', validation);
620
+
621
+ // Get script metrics (if available)
622
+ try {
623
+ const metrics = SmartContract.scriptMetrics(asmScript);
624
+ console.log('Metrics:', metrics);
625
+ } catch (error) {
626
+ console.log('Metrics not available:', error.message);
627
+ }
628
+ }
629
+
630
+ scriptUtilities();
631
+ ```
632
+
633
+ ## Testing & Debugging
634
+
635
+ ### Local Script Testing
636
+
637
+ ```javascript
638
+ function testScriptLocally() {
639
+ console.log('Local Script Testing:');
640
+
641
+ // Test 1: Simple arithmetic script
642
+ const unlockingScript = 'OP_2 OP_3';
643
+ const lockingScript = 'OP_ADD OP_5 OP_EQUAL';
644
+
645
+ try {
646
+ const result = SmartContract.testScript(unlockingScript, lockingScript);
647
+ console.log('Arithmetic test result:');
648
+ console.log(' Valid:', result.valid);
649
+ console.log(' Success:', result.success);
650
+ if (result.stack) {
651
+ console.log(' Final stack:', result.stack.join(', '));
652
+ }
653
+ } catch (error) {
654
+ console.log('Test failed:', error.message);
655
+ }
656
+
657
+ // Test 2: Hash validation script
658
+ const secretPreimage = 'hello world';
659
+ const secretHash = require('crypto').createHash('sha256').update(secretPreimage).digest('hex');
660
+
661
+ const hashUnlocking = secretPreimage; // In hex: Buffer.from(secretPreimage).toString('hex')
662
+ const hashLocking = `OP_SHA256 0x20 0x${secretHash} OP_EQUAL`;
663
+
664
+ try {
665
+ const hashResult = SmartContract.testScript(hashUnlocking, hashLocking);
666
+ console.log('Hash validation test result:');
667
+ console.log(' Success:', hashResult.success);
668
+ } catch (error) {
669
+ console.log('Hash test failed:', error.message);
670
+ }
671
+ }
672
+
673
+ testScriptLocally();
674
+ ```
675
+
676
+ ### Covenant Testing Environment
677
+
678
+ ```javascript
679
+ function createComprehensiveTestEnv() {
680
+ // Create test environment with covenant support
681
+ const testEnv = SmartContract.createTestEnvironment({
682
+ utxoCount: 3,
683
+ satoshis: 150000,
684
+ covenantAmount: 120000
685
+ });
686
+
687
+ console.log('Comprehensive Test Environment:');
688
+ console.log('Generator available:', !!testEnv.generator);
689
+ console.log('Test setup available:', !!testEnv.test);
690
+
691
+ // Get test components
692
+ const keypair = testEnv.getKeypair();
693
+ const preimage = testEnv.getPreimage();
694
+
695
+ console.log('Test Environment Details:');
696
+ console.log(' Keypair address:', keypair.addressString);
697
+ console.log(' Private key (WIF):', keypair.wif);
698
+ console.log(' Preimage length:', preimage.length / 2, 'bytes');
699
+
700
+ // Extract specific fields for testing
701
+ try {
702
+ const extractedValue = testEnv.extractField('amount');
703
+ console.log(' Extracted amount field:', extractedValue);
704
+ } catch (error) {
705
+ console.log(' Field extraction not available:', error.message);
706
+ }
707
+
708
+ return testEnv;
709
+ }
710
+
711
+ const testEnv = createComprehensiveTestEnv();
712
+ ```
713
+
714
+ ### Debug Script Execution
715
+
716
+ ```javascript
717
+ function debugScriptExecution() {
718
+ console.log('Script Debugging:');
719
+
720
+ // Create debug configuration
721
+ const debugConfig = {
722
+ unlockingScript: 'OP_1 OP_2',
723
+ lockingScript: 'OP_ADD OP_3 OP_EQUAL',
724
+ stepByStep: true
725
+ };
726
+
727
+ try {
728
+ const debugResult = SmartContract.debugScriptExecution(
729
+ debugConfig.unlockingScript,
730
+ debugConfig.lockingScript,
731
+ { stepMode: false }
732
+ );
733
+
734
+ console.log('Debug execution result:');
735
+ console.log(' Success:', debugResult.success);
736
+ console.log(' Final result:', debugResult.result);
737
+
738
+ if (debugResult.stack) {
739
+ console.log(' Final stack:', debugResult.stack);
740
+ }
741
+
742
+ } catch (error) {
743
+ console.log('Debug execution failed:', error.message);
744
+ }
745
+ }
746
+
747
+ debugScriptExecution();
748
+ ```
749
+
750
+ ## Advanced Features
751
+
752
+ ### SIGHASH Analysis
753
+
754
+ ```javascript
755
+ function sighashAnalysis() {
756
+ console.log('SIGHASH Analysis:');
757
+
758
+ // Get all available SIGHASH types
759
+ const sighashTypes = SmartContract.getAllSIGHASHTypes();
760
+ console.log('Available SIGHASH types:', Object.keys(sighashTypes).length);
761
+
762
+ // Display first few types
763
+ Object.entries(sighashTypes).slice(0, 5).forEach(([flag, info]) => {
764
+ console.log(` ${flag}: ${info.name} - ${info.description || 'Standard SIGHASH type'}`);
765
+ });
766
+
767
+ // Get educational resources
768
+ const resources = SmartContract.getEducationalResources();
769
+ console.log('Educational resources available:');
770
+ console.log(' Zero hash mystery info:', !!resources.zeroHashMystery);
771
+ console.log(' Example demonstrations:', resources.exampleDemonstrations.length);
772
+
773
+ // Demonstrate SIGHASH analysis
774
+ try {
775
+ const sighashDemo = SmartContract.demonstrateAllSIGHASH();
776
+ console.log('SIGHASH demonstrations generated:', sighashDemo.length);
777
+ } catch (error) {
778
+ console.log('SIGHASH demo generation failed:', error.message);
779
+ }
780
+ }
781
+
782
+ sighashAnalysis();
783
+ ```
784
+
785
+ ### Opcode Mapping and Simulation
786
+
787
+ ```javascript
788
+ function opcodeOperations() {
789
+ console.log('Opcode Operations:');
790
+
791
+ // Get opcode map
792
+ const opcodeMap = SmartContract.getOpcodeMap();
793
+ console.log('Available opcodes:', Object.keys(opcodeMap).length);
794
+
795
+ // Show some common opcodes
796
+ const commonOpcodes = ['OP_DUP', 'OP_HASH160', 'OP_EQUALVERIFY', 'OP_CHECKSIG'];
797
+ commonOpcodes.forEach(opcode => {
798
+ if (opcodeMap[opcode]) {
799
+ console.log(` ${opcode}: 0x${opcodeMap[opcode].toString(16)}`);
800
+ }
801
+ });
802
+
803
+ // Simulate script execution (if available)
804
+ try {
805
+ const operations = ['OP_1', 'OP_2', 'OP_ADD'];
806
+ const simulation = SmartContract.simulateScript(operations, []);
807
+ console.log('Script simulation result:', simulation);
808
+ } catch (error) {
809
+ console.log('Script simulation not available:', error.message);
810
+ }
811
+ }
812
+
813
+ opcodeOperations();
814
+ ```
815
+
816
+ ## API Reference
817
+
818
+ ### Core Classes
819
+
820
+ #### SmartContract.Covenant
821
+
822
+ ```javascript
823
+ const covenant = new SmartContract.Covenant(privateKey, options);
824
+
825
+ // Methods
826
+ covenant.createFromP2PKH(utxo) // Create covenant from P2PKH UTXO
827
+ covenant.spendCovenant(covenantUtxo) // Spend existing covenant
828
+ covenant.completeFlow(utxo, callback) // Complete workflow
829
+ ```
830
+
831
+ #### SmartContract.Preimage
832
+
833
+ ```javascript
834
+ const preimage = new SmartContract.Preimage(preimageHex, options);
835
+
836
+ // Core Methods
837
+ preimage.extract(strategy) // Extract all fields ('LEFT'/'RIGHT'/'DYNAMIC')
838
+ preimage.getField(fieldName) // Get specific BIP-143 field
839
+ preimage.extractField(fieldName) // Alternative field extraction
840
+ preimage.getSighashInfo() // Get SIGHASH analysis and warnings
841
+ preimage.validate() // Validate preimage structure
842
+ preimage.toObject() // Convert to plain object
843
+
844
+ // Static Methods
845
+ SmartContract.Preimage.fromTransaction(tx, inputIndex, sighashType) // Create from transaction
846
+ SmartContract.Preimage.extractFromHex(hex) // Quick extraction
847
+ SmartContract.Preimage.analyzeFromHex(hex) // Analysis without instance
848
+
849
+ // BIP-143 Field Names
850
+ // 'version', 'hashPrevouts', 'hashSequence', 'outpoint', 'scriptCode',
851
+ // 'amount', 'sequence', 'hashOutputs', 'locktime', 'sighash'
852
+ ```
853
+
854
+ #### SmartContract.UTXOGenerator
855
+
856
+ ```javascript
857
+ const generator = new SmartContract.UTXOGenerator(options);
858
+
859
+ // Core Methods
860
+ generator.createRealUTXOs(count, satoshis) // Generate authentic UTXOs
861
+ generator.createTestTransaction(options) // Create test transaction
862
+ generator.createCovenantTest(options) // Covenant-specific setup
863
+ generator.getUTXOs() // Get all generated UTXOs
864
+ generator.getKeypairs() // Get associated keypairs (may return undefined)
865
+ generator.reset() // Reset generator state
866
+
867
+ // Generated UTXO Structure
868
+ {
869
+ txid: 'string', // Transaction ID
870
+ vout: number, // Output index
871
+ satoshis: number, // Amount in satoshis
872
+ address: 'string', // Base58 address
873
+ script: 'string', // Script hex
874
+ scriptType: 'P2PKH', // Script type
875
+ keypair: { // Associated keypair
876
+ privateKey: PrivateKey,
877
+ publicKey: PublicKey,
878
+ address: Address,
879
+ wif: 'string',
880
+ addressString: 'string'
881
+ },
882
+ created: 'ISO string' // Creation timestamp
883
+ }
884
+ ```
885
+
886
+ #### SmartContract.CovenantBuilder
887
+
888
+ ```javascript
889
+ const builder = new SmartContract.CovenantBuilder();
890
+
891
+ // Chainable methods
892
+ builder.comment(text) // Add documentation
893
+ builder.push(value) // Push value to stack
894
+ builder.extractField(fieldName) // Extract preimage field
895
+ builder.add() // Arithmetic operations
896
+ builder.equal() // Comparison operations
897
+ builder.verify() // Validation operations
898
+ builder.if() / builder.else() / builder.endif() // Control flow
899
+ builder.build() // Generate final script
900
+ ```
901
+
902
+ ### Utility Functions
903
+
904
+ ```javascript
905
+ // Quick covenant creation
906
+ SmartContract.createQuickCovenant(type, params)
907
+
908
+ // Test environment setup
909
+ SmartContract.createTestEnvironment(options)
910
+
911
+ // Script testing
912
+ SmartContract.testScript(unlocking, locking, options)
913
+
914
+ // Script conversion
915
+ SmartContract.asmToHex(asmString)
916
+ SmartContract.hexToASM(hexString)
917
+ SmartContract.validateASM(asmString)
918
+
919
+ // Educational resources
920
+ SmartContract.getEducationalResources()
921
+ SmartContract.getAllSIGHASHTypes()
922
+ SmartContract.explainZeroHashes()
923
+ ```
924
+
925
+ ## Examples
926
+
927
+ ### Example 1: Simple Value Lock
928
+
929
+ ```javascript
930
+ // Create a covenant that requires minimum 100,000 satoshis
931
+ const valueLock = SmartContract.createQuickCovenant('value_lock', {
932
+ value: 100000
933
+ });
934
+
935
+ console.log('Value Lock Covenant:');
936
+ console.log('Script:', valueLock.asm);
937
+ console.log('Size:', valueLock.size, 'bytes');
938
+
939
+ // Test the covenant
940
+ const testResult = SmartContract.testCovenant(
941
+ 'mock_preimage_hex',
942
+ { minValue: 100000 },
943
+ { validate: true }
944
+ );
945
+ ```
946
+
947
+ ### Example 2: Multi-Condition Covenant
948
+
949
+ ```javascript
950
+ // Create covenant with multiple conditions
951
+ const multiCovenant = SmartContract.createQuickCovenant('multi_condition', {
952
+ conditions: [
953
+ { type: 'value', value: 50000 },
954
+ { type: 'time', timestamp: 1640995200 },
955
+ { type: 'hash', hash: 'abcdef...' }
956
+ ]
957
+ });
958
+
959
+ console.log('Multi-condition Covenant:', multiCovenant.asm);
960
+ ```
961
+
962
+ ### Example 3: Custom Covenant Logic
963
+
964
+ ```javascript
965
+ const builder = SmartContract.createCovenantBuilder();
966
+
967
+ const escrowCovenant = builder
968
+ .comment('Escrow covenant - 2-of-3 with timeout')
969
+
970
+ // Check if timeout reached
971
+ .extractField('locktime')
972
+ .push(1641081600) // Timeout timestamp
973
+ .greaterThan()
974
+
975
+ .if()
976
+ // After timeout: refund to buyer
977
+ .push('buyer_pubkey')
978
+ .checkSig()
979
+ .else()
980
+ // Before timeout: require 2-of-3 signatures
981
+ .push(2)
982
+ .push('buyer_pubkey')
983
+ .push('seller_pubkey')
984
+ .push('arbiter_pubkey')
985
+ .push(3)
986
+ .checkMultisig()
987
+ .endif()
988
+
989
+ .build();
990
+
991
+ console.log('Escrow Covenant:', escrowCovenant.asm);
992
+ ```
993
+
994
+ ### Example 4: UTXO Generator + Preimage Separation Workflow
995
+
996
+ ```javascript
997
+ async function completeUTXOPreimageWorkflow() {
998
+ console.log('🚀 Complete UTXO Generation + Preimage Separation Workflow');
999
+
1000
+ // 1. Generate authentic UTXOs
1001
+ const generator = new SmartContract.UTXOGenerator();
1002
+ const utxos = generator.createRealUTXOs(1, 100000);
1003
+ const utxo = utxos[0];
1004
+
1005
+ console.log('✅ UTXO Generated:');
1006
+ console.log(` TXID: ${utxo.txid}`);
1007
+ console.log(` Amount: ${utxo.satoshis.toLocaleString()} satoshis`);
1008
+ console.log(` Address: ${utxo.address}`);
1009
+
1010
+ // 2. Create transaction from UTXO
1011
+ const bsv = require('@smartledger/bsv');
1012
+ const privateKey = new bsv.PrivateKey(utxo.keypair.wif);
1013
+ const address = new bsv.Address(utxo.address);
1014
+
1015
+ const tx = new bsv.Transaction()
1016
+ .from({
1017
+ txId: utxo.txid,
1018
+ outputIndex: utxo.vout,
1019
+ script: utxo.script,
1020
+ satoshis: utxo.satoshis
1021
+ })
1022
+ .to(address, 95000)
1023
+ .sign(privateKey);
1024
+
1025
+ console.log('✅ Transaction Created:', tx.id);
1026
+
1027
+ // 3. Generate BIP-143 preimage
1028
+ const sighashType = bsv.crypto.Signature.SIGHASH_ALL | bsv.crypto.Signature.SIGHASH_FORKID;
1029
+ const preimageBuffer = bsv.Transaction.sighash.sighashPreimage(
1030
+ tx, sighashType, 0, bsv.Script.buildPublicKeyHashOut(address), new bsv.crypto.BN(utxo.satoshis)
1031
+ );
1032
+
1033
+ console.log('✅ Preimage Generated:', preimageBuffer.length, 'bytes');
1034
+
1035
+ // 4. Extract and analyze preimage fields
1036
+ const preimage = new SmartContract.Preimage(preimageBuffer.toString('hex'));
1037
+
1038
+ console.log('✅ Preimage Field Analysis:');
1039
+
1040
+ // Extract all 10 BIP-143 fields
1041
+ const fieldNames = ['version', 'hashPrevouts', 'hashSequence', 'outpoint', 'scriptCode',
1042
+ 'amount', 'sequence', 'hashOutputs', 'locktime', 'sighash'];
1043
+
1044
+ fieldNames.forEach(fieldName => {
1045
+ try {
1046
+ const fieldBuffer = preimage.getField(fieldName);
1047
+ console.log(` ${fieldName}: ${fieldBuffer.length} bytes`);
1048
+
1049
+ // Show interpreted values for key fields
1050
+ if (fieldName === 'amount') {
1051
+ const sats = fieldBuffer.readBigUInt64LE(0);
1052
+ console.log(` → ${sats} satoshis`);
1053
+ } else if (fieldName === 'outpoint') {
1054
+ const txid = fieldBuffer.slice(0, 32).reverse().toString('hex');
1055
+ const vout = fieldBuffer.slice(32).readUInt32LE(0);
1056
+ console.log(` → ${txid}:${vout}`);
1057
+ }
1058
+ } catch (error) {
1059
+ console.log(` ${fieldName}: extraction failed`);
1060
+ }
1061
+ });
1062
+
1063
+ // 5. Test extraction strategies
1064
+ console.log('✅ Testing Extraction Strategies:');
1065
+ ['LEFT', 'RIGHT', 'DYNAMIC'].forEach(strategy => {
1066
+ try {
1067
+ const result = preimage.extract(strategy);
1068
+ console.log(` ${strategy}: ${Object.keys(result).length} fields extracted`);
1069
+ } catch (error) {
1070
+ console.log(` ${strategy}: failed (${error.message})`);
1071
+ }
1072
+ });
1073
+
1074
+ // 6. SIGHASH analysis
1075
+ const sighashInfo = preimage.getSighashInfo();
1076
+ console.log('✅ SIGHASH Analysis:', {
1077
+ hasZeroHashes: sighashInfo.hasZeroHashes,
1078
+ isStandard: sighashInfo.isStandard
1079
+ });
1080
+
1081
+ console.log('🎉 Complete workflow successful!');
1082
+ console.log(' • Authentic UTXO generated ✅');
1083
+ console.log(' • Transaction created ✅');
1084
+ console.log(' • BIP-143 preimage extracted ✅');
1085
+ console.log(' • All 10 fields separated ✅');
1086
+ console.log(' • Multiple extraction strategies tested ✅');
1087
+
1088
+ return {
1089
+ utxo: utxo,
1090
+ transaction: tx,
1091
+ preimage: preimageBuffer,
1092
+ fields: fieldNames.length
1093
+ };
1094
+ }
1095
+
1096
+ // Run the workflow
1097
+ completeUTXOPreimageWorkflow()
1098
+ .then(result => {
1099
+ console.log(`\n✨ Workflow completed: ${result.fields} fields extracted from ${result.preimage.length}-byte preimage`);
1100
+ })
1101
+ .catch(error => {
1102
+ console.error('❌ Workflow failed:', error.message);
1103
+ });
1104
+ ```
1105
+
1106
+ ## Best Practices
1107
+
1108
+ ### 🔒 **Security Guidelines**
1109
+
1110
+ 1. **Always Test Locally First**
1111
+ ```javascript
1112
+ // Test script execution before deployment
1113
+ const testResult = SmartContract.testScript(unlockingScript, lockingScript);
1114
+ if (!testResult.success) {
1115
+ throw new Error('Script validation failed');
1116
+ }
1117
+ ```
1118
+
1119
+ 2. **Validate Preimage Fields**
1120
+ ```javascript
1121
+ // Ensure preimage extraction is successful
1122
+ const preimage = SmartContract.extractPreimage(preimageHex);
1123
+ const sighashInfo = preimage.getSighashInfo();
1124
+ if (sighashInfo.hasZeroHashes) {
1125
+ console.warn('⚠️ Zero hashes detected - verify SIGHASH type');
1126
+ }
1127
+ ```
1128
+
1129
+ 3. **Use Testnet for Development**
1130
+ ```javascript
1131
+ // Configure for testnet
1132
+ const testEnv = SmartContract.createTestEnvironment({
1133
+ network: 'testnet',
1134
+ utxoCount: 3,
1135
+ satoshis: 100000
1136
+ });
1137
+ ```
1138
+
1139
+ ### ⚡ **Performance Optimization**
1140
+
1141
+ 1. **Minimize Script Size**
1142
+ ```javascript
1143
+ // Find optimization opportunities
1144
+ const optimizations = SmartContract.findOptimizations(scriptASM);
1145
+ console.log('Potential savings:', optimizations.potentialSavings, 'bytes');
1146
+ ```
1147
+
1148
+ 2. **Efficient Opcode Usage**
1149
+ ```javascript
1150
+ const builder = SmartContract.createCovenantBuilder();
1151
+
1152
+ // Use efficient opcodes
1153
+ const optimizedScript = builder
1154
+ .push(1) // Instead of OP_1, use direct push for larger numbers
1155
+ .dup() // Use OP_DUP instead of redundant operations
1156
+ .verify() // Use OP_VERIFY for boolean checks
1157
+ .build();
1158
+ ```
1159
+
1160
+ ### 📚 **Development Workflow**
1161
+
1162
+ 1. **Design → Test → Deploy**
1163
+ ```javascript
1164
+ // 1. Design covenant logic
1165
+ const covenant = SmartContract.createQuickCovenant('value_lock', { value: 100000 });
1166
+
1167
+ // 2. Test locally
1168
+ const testResult = SmartContract.testScript('test_unlock', covenant.asm);
1169
+
1170
+ // 3. Deploy to testnet first
1171
+ // 4. Deploy to mainnet after thorough testing
1172
+ ```
1173
+
1174
+ 2. **Use Educational Resources**
1175
+ ```javascript
1176
+ // Learn about SIGHASH types
1177
+ const resources = SmartContract.getEducationalResources();
1178
+ console.log('Zero hash mystery:', resources.zeroHashMystery);
1179
+
1180
+ // Understand available SIGHASH types
1181
+ const sighashTypes = SmartContract.getAllSIGHASHTypes();
1182
+ ```
1183
+
1184
+ ### 🛠️ **Debugging Tips**
1185
+
1186
+ 1. **Step-by-Step Execution**
1187
+ ```javascript
1188
+ // Enable detailed debugging
1189
+ const debugResult = SmartContract.debugScriptExecution(
1190
+ unlockingScript,
1191
+ lockingScript,
1192
+ { stepMode: true }
1193
+ );
1194
+ ```
1195
+
1196
+ 2. **Stack Examination**
1197
+ ```javascript
1198
+ // Examine stack state during execution
1199
+ const stackResult = SmartContract.examineStack(lockingHex, unlockingHex);
1200
+ console.log('Stack progression:', stackResult.steps);
1201
+ ```
1202
+
1203
+ 3. **Script Validation**
1204
+ ```javascript
1205
+ // Validate scripts before testing
1206
+ const validation = SmartContract.validateASM(scriptASM);
1207
+ if (!validation.valid) {
1208
+ console.error('Script errors:', validation.errors);
1209
+ }
1210
+ ```
1211
+
1212
+ ## Module Features
1213
+
1214
+ The SmartContract module includes **23 production-ready features**:
1215
+
1216
+ - ✅ BIP143_PREIMAGE - Complete BIP-143 preimage parsing
1217
+ - ✅ COMPACT_SIZE_VARINT - Varint encoding/decoding support
1218
+ - ✅ BIDIRECTIONAL_EXTRACTION - Left/right/dynamic field extraction
1219
+ - ✅ SIGHASH_DETECTION - Automatic SIGHASH flag detection
1220
+ - ✅ ZERO_HASH_WARNINGS - Zero hash detection and warnings
1221
+ - ✅ MULTI_FIELD_VALIDATION - Multi-field preimage validation
1222
+ - ✅ REAL_UTXO_GENERATION - Authentic UTXO generation for testing
1223
+ - ✅ SCRIPT_TESTING - Local script execution and validation
1224
+ - ✅ LOCAL_VERIFICATION - No blockchain required for testing
1225
+ - ✅ JAVASCRIPT_TO_SCRIPT - JavaScript to Bitcoin Script translation
1226
+ - ✅ OPCODE_MAPPING - Comprehensive opcode mapping utilities
1227
+ - ✅ COVENANT_BUILDER - High-level covenant construction
1228
+ - ✅ SCRIPT_ANALYSIS - Script metrics and complexity analysis
1229
+ - ✅ SCRIPT_OPTIMIZATION - Optimization suggestions and improvements
1230
+ - ✅ SCRIPT_CONVERSION - ASM/hex/script format conversion
1231
+ - ✅ BATCH_TESTING - Batch script testing capabilities
1232
+ - ✅ QUICK_COVENANTS - Template-based quick covenant creation
1233
+ - ✅ SCRIPT_EXPLANATIONS - Human-readable script explanations
1234
+ - ✅ STACK_EXAMINATION - Stack state examination and debugging
1235
+ - ✅ SCRIPT_DEBUGGING - Interactive script debugging tools
1236
+ - ✅ STEP_BY_STEP_EXECUTION - Step-by-step execution analysis
1237
+ - ✅ INTERACTIVE_DEBUGGING - Interactive debugging support
1238
+ - ✅ PRODUCTION_READY - Enterprise-grade error handling
1239
+
1240
+ ## Conclusion
1241
+
1242
+ The SmartContract module provides a comprehensive, production-ready framework for Bitcoin SV smart contract development. Whether you're building simple value locks or complex multi-condition covenants, the module offers the tools and utilities needed for secure, efficient smart contract development.
1243
+
1244
+ ### Next Steps
1245
+
1246
+ 1. **Explore Examples** - Review the `/examples/smart_contract/` directory for more detailed examples
1247
+ 2. **Test Locally** - Use the testing utilities to validate your covenant logic
1248
+ 3. **Deploy Safely** - Always test on testnet before mainnet deployment
1249
+ 4. **Join Community** - Contribute to the SmartLedger BSV project on GitHub
1250
+
1251
+ For advanced usage and additional examples, see the [SmartLedger BSV repository](https://github.com/codenlighten/smartledger-bsv).
1252
+
1253
+ ---
1254
+
1255
+ *Documentation for SmartContract Module v1.0.0 - Last updated: October 2025*