smartledger-bsv 3.3.1 → 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 +5 -3
  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
@@ -1,133 +1 @@
1
- /**
2
- * SmartLedger BSV - SmartContract Interface
3
- *
4
- * Standalone SmartContract interface with debug tools for browser use.
5
- * This module provides the complete SmartContract development framework
6
- * including covenant builders, script debuggers, and testing tools.
7
- *
8
- * Usage:
9
- * <script src="bsv.min.js"></script>
10
- * <script src="bsv-smartcontract.min.js"></script>
11
- * <script>
12
- * // SmartContract interface available under bsv.SmartContract
13
- * const script = bsv.Script.fromASM('OP_1 OP_2 OP_ADD');
14
- * const result = bsv.SmartContract.examineStack(script);
15
- * const metrics = bsv.SmartContract.getScriptMetrics(script);
16
- * </script>
17
- */
18
-
19
- 'use strict'
20
-
21
- // Check if BSV library is available
22
- if (typeof window !== 'undefined' && typeof window.bsv === 'undefined') {
23
- throw new Error('SmartContract interface requires BSV library. Load bsv.min.js first.')
24
- }
25
-
26
- // Get BSV reference (works in both Node.js and browser)
27
- var bsv = (typeof window !== 'undefined') ? window.bsv : require('./index.js')
28
-
29
- if (!bsv) {
30
- throw new Error('BSV library not found. Ensure bsv.min.js is loaded before bsv-smartcontract.min.js')
31
- }
32
-
33
- // Load SmartContract interface
34
- var SmartContract
35
- try {
36
- SmartContract = require('./lib/smart_contract')
37
- } catch (e) {
38
- throw new Error('SmartContract module not found: ' + e.message)
39
- }
40
-
41
- // Attach to BSV library
42
- bsv.SmartContract = SmartContract
43
-
44
- // Make available globally for browser usage
45
- if (typeof window !== 'undefined') {
46
- window.bsvSmartContract = SmartContract
47
-
48
- // Also ensure it's on the global bsv object
49
- if (window.bsv) {
50
- window.bsv.SmartContract = SmartContract
51
- }
52
- }
53
-
54
- // Add debug tools information
55
- if (SmartContract) {
56
- SmartContract.version = bsv.version || '3.2.1'
57
- SmartContract.standalone = true
58
- SmartContract.debugToolsAvailable = {
59
- examineStack: !!SmartContract.examineStack,
60
- interpretScript: !!SmartContract.interpretScript,
61
- getScriptMetrics: !!SmartContract.getScriptMetrics,
62
- optimizeScript: !!SmartContract.optimizeScript
63
- }
64
-
65
- // Convenience method to check if debug tools are working
66
- SmartContract.testDebugTools = function() {
67
- try {
68
- if (!bsv.Script) {
69
- return { success: false, error: 'BSV Script class not available' }
70
- }
71
-
72
- const testScript = bsv.Script.fromASM('OP_1 OP_2 OP_ADD')
73
- const results = {}
74
-
75
- if (SmartContract.examineStack) {
76
- try {
77
- results.examineStack = SmartContract.examineStack(testScript)
78
- results.examineStackWorking = true
79
- } catch (e) {
80
- results.examineStackWorking = false
81
- results.examineStackError = e.message
82
- }
83
- }
84
-
85
- if (SmartContract.interpretScript) {
86
- try {
87
- results.interpretScript = SmartContract.interpretScript(testScript)
88
- results.interpretScriptWorking = true
89
- } catch (e) {
90
- results.interpretScriptWorking = false
91
- results.interpretScriptError = e.message
92
- }
93
- }
94
-
95
- if (SmartContract.getScriptMetrics) {
96
- try {
97
- results.scriptMetrics = SmartContract.getScriptMetrics(testScript)
98
- results.scriptMetricsWorking = true
99
- } catch (e) {
100
- results.scriptMetricsWorking = false
101
- results.scriptMetricsError = e.message
102
- }
103
- }
104
-
105
- if (SmartContract.optimizeScript) {
106
- try {
107
- results.optimizeScript = SmartContract.optimizeScript(testScript)
108
- results.optimizeScriptWorking = true
109
- } catch (e) {
110
- results.optimizeScriptWorking = false
111
- results.optimizeScriptError = e.message
112
- }
113
- }
114
-
115
- return {
116
- success: true,
117
- testScript: 'OP_1 OP_2 OP_ADD',
118
- results: results,
119
- methodCount: Object.keys(SmartContract).length
120
- }
121
- } catch (e) {
122
- return { success: false, error: e.message }
123
- }
124
- }
125
- }
126
-
127
- console.log('SmartContract interface loaded:', !!SmartContract)
128
- if (SmartContract) {
129
- console.log('SmartContract methods available:', Object.keys(SmartContract).length)
130
- console.log('Debug tools available:', SmartContract.debugToolsAvailable)
131
- }
132
-
133
- module.exports = SmartContract
1
+ module.exports = require('./lib/smart_contract');
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Test Transaction VerifySignature Method
5
+ *
6
+ * Tests the transaction's built-in verifySignature method
7
+ */
8
+
9
+ const bsv = require('./index.js');
10
+
11
+ console.log('🔍 Test Transaction VerifySignature Method');
12
+ console.log('==========================================\n');
13
+
14
+ const privateKey = new bsv.PrivateKey('L1aW4aubDFB7yfras2S1mN3bqg9nwySY8nkoLmJebSLD5BWv3ENZ');
15
+ const address = privateKey.toAddress().toString();
16
+
17
+ // Create and sign transaction
18
+ const mockUTXO = {
19
+ txid: '1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
20
+ vout: 0,
21
+ address: address,
22
+ satoshis: 50000,
23
+ script: bsv.Script.buildPublicKeyHashOut(address).toHex()
24
+ };
25
+
26
+ const transaction = new bsv.Transaction()
27
+ .from(mockUTXO)
28
+ .to(address, 100)
29
+ .change(address)
30
+ .feePerKb(10)
31
+ .sign(privateKey);
32
+
33
+ console.log('✅ Transaction created and signed');
34
+ console.log(`Transaction ID: ${transaction.id}`);
35
+ console.log(`Basic verify(): ${transaction.verify()}`);
36
+
37
+ // Extract signature details
38
+ const input = transaction.inputs[0];
39
+ const signature = input.script.chunks[0]?.buf;
40
+ const publicKey = input.script.chunks[1]?.buf;
41
+
42
+ if (signature && publicKey) {
43
+ console.log('\n🧪 Transaction VerifySignature Method Test:');
44
+ console.log('==========================================');
45
+
46
+ const sigWithoutHashtype = signature.slice(0, -1);
47
+ const pubkeyObj = new bsv.PublicKey(publicKey);
48
+ const subscript = input.output.script;
49
+ const satoshisBN = new bsv.crypto.BN(input.output.satoshis);
50
+
51
+ try {
52
+ // Parse the signature first
53
+ const parsedSig = bsv.crypto.Signature.fromDER(sigWithoutHashtype);
54
+ parsedSig.nhashtype = signature[signature.length - 1]; // Set the hashtype
55
+
56
+ console.log(`Parsed signature r: ${parsedSig.r.toString('hex')}`);
57
+ console.log(`Parsed signature s: ${parsedSig.s.toString('hex')}`);
58
+ console.log(`Signature hashtype: 0x${parsedSig.nhashtype.toString(16)}`);
59
+
60
+ // Test transaction's built-in verifySignature method
61
+ const builtinVerify = transaction.verifySignature(parsedSig, pubkeyObj, 0, subscript, satoshisBN);
62
+ console.log(`transaction.verifySignature(): ${builtinVerify ? '✅ VALID' : '❌ INVALID'}`);
63
+
64
+ // Test with default flags
65
+ const builtinVerifyWithFlags = transaction.verifySignature(parsedSig, pubkeyObj, 0, subscript, satoshisBN,
66
+ bsv.Script.Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID);
67
+ console.log(`transaction.verifySignature() with flags: ${builtinVerifyWithFlags ? '✅ VALID' : '❌ INVALID'}`);
68
+
69
+ console.log('\n🔍 Manual Sighash.verify Test:');
70
+ console.log('==============================');
71
+
72
+ // Test the Sighash.verify method directly
73
+ const sighashVerify = bsv.Transaction.Sighash.verify(transaction, parsedSig, pubkeyObj, 0, subscript, satoshisBN);
74
+ console.log(`Sighash.verify(): ${sighashVerify ? '✅ VALID' : '❌ INVALID'}`);
75
+
76
+ const sighashVerifyWithFlags = bsv.Transaction.Sighash.verify(transaction, parsedSig, pubkeyObj, 0, subscript, satoshisBN,
77
+ bsv.Script.Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID);
78
+ console.log(`Sighash.verify() with flags: ${sighashVerifyWithFlags ? '✅ VALID' : '❌ INVALID'}`);
79
+
80
+ console.log('\n🔧 Compare Sighash Calculation:');
81
+ console.log('===============================');
82
+
83
+ // Get the sighash that Sighash.verify would calculate
84
+ const officialSighash = bsv.Transaction.Sighash.sighash(
85
+ transaction,
86
+ parsedSig.nhashtype,
87
+ 0,
88
+ subscript,
89
+ satoshisBN,
90
+ bsv.Script.Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID
91
+ );
92
+
93
+ console.log(`Official Sighash.sighash(): ${officialSighash.toString('hex')}`);
94
+
95
+ // Compare with our transaction.sighash method
96
+ const ourSighash = transaction.sighash(0, parsedSig.nhashtype, subscript, satoshisBN);
97
+ console.log(`Our transaction.sighash(): ${ourSighash.toString('hex')}`);
98
+ console.log(`Sighashes match: ${officialSighash.equals(ourSighash) ? '✅ YES' : '❌ NO'}`);
99
+
100
+ // Test verification with the official sighash
101
+ console.log('\n🎯 Verification with Official Sighash:');
102
+ console.log('=====================================');
103
+
104
+ const ecdsaWithOfficial = bsv.crypto.ECDSA.verify(officialSighash, parsedSig, pubkeyObj);
105
+ console.log(`ECDSA.verify(officialSighash): ${ecdsaWithOfficial ? '✅ VALID' : '❌ INVALID'}`);
106
+
107
+ const smartVerifyWithOfficial = bsv.SmartVerify.smartVerify(officialSighash, parsedSig, pubkeyObj);
108
+ console.log(`SmartVerify(officialSighash): ${smartVerifyWithOfficial ? '✅ VALID' : '❌ INVALID'}`);
109
+
110
+ } catch (error) {
111
+ console.log('❌ Test failed:', error.message);
112
+ console.log('Stack:', error.stack);
113
+ }
114
+
115
+ } else {
116
+ console.log('❌ Could not extract signature or public key');
117
+ }
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Test Script for Debug Tools Integration
4
+ * =======================================
5
+ * Tests the newly integrated StackExaminer and ScriptInterpreter tools
6
+ * in the SmartContract interface
7
+ */
8
+
9
+ const SmartContract = require('./lib/smart_contract/index.js');
10
+
11
+ console.log("🧪 Testing SmartContract Debug Tools Integration");
12
+ console.log("=================================================\n");
13
+
14
+ // Test 1: Check if modules are loaded
15
+ console.log("1. Module Loading Test:");
16
+ console.log(" StackExaminer loaded:", !!SmartContract.StackExaminer);
17
+ console.log(" ScriptInterpreter loaded:", !!SmartContract.ScriptInterpreter);
18
+ console.log(" examineStack method:", typeof SmartContract.examineStack);
19
+ console.log(" debugScriptExecution method:", typeof SmartContract.debugScriptExecution);
20
+ console.log(" parseScript method:", typeof SmartContract.parseScript);
21
+
22
+ // Test 2: Feature flags
23
+ console.log("\n2. Feature Flags Test:");
24
+ console.log(" STACK_EXAMINATION:", SmartContract.features.STACK_EXAMINATION);
25
+ console.log(" SCRIPT_DEBUGGING:", SmartContract.features.SCRIPT_DEBUGGING);
26
+ console.log(" STEP_BY_STEP_EXECUTION:", SmartContract.features.STEP_BY_STEP_EXECUTION);
27
+ console.log(" INTERACTIVE_DEBUGGING:", SmartContract.features.INTERACTIVE_DEBUGGING);
28
+
29
+ // Test 3: Simple script parsing
30
+ console.log("\n3. Script Parsing Test:");
31
+ try {
32
+ const parsedASM = SmartContract.parseScript("OP_DUP OP_HASH160");
33
+ console.log(" ✅ ASM parsing successful");
34
+ console.log(" Script length:", parsedASM.chunks.length);
35
+ } catch (err) {
36
+ console.log(" ❌ ASM parsing failed:", err.message);
37
+ }
38
+
39
+ try {
40
+ const parsedHex = SmartContract.parseScript("76a914");
41
+ console.log(" ✅ HEX parsing successful");
42
+ console.log(" Script length:", parsedHex.chunks.length);
43
+ } catch (err) {
44
+ console.log(" ❌ HEX parsing failed:", err.message);
45
+ }
46
+
47
+ // Test 4: Stack examination (non-interactive)
48
+ console.log("\n4. Stack Examination Test:");
49
+ try {
50
+ // Use simple valid scripts for testing
51
+ const result = SmartContract.examineStack("51", "51"); // OP_1, OP_1
52
+ console.log(" ✅ Stack examination completed, result:", result);
53
+ } catch (err) {
54
+ console.log(" ⚠️ Stack examination had issues:", err.message);
55
+ }
56
+
57
+ console.log("\n=================================================");
58
+ console.log("🎉 Debug Tools Integration Test Complete!");
59
+ console.log("=================================================");
60
+
61
+ // Count total methods in SmartContract
62
+ const methodCount = Object.keys(SmartContract).filter(key =>
63
+ typeof SmartContract[key] === 'function'
64
+ ).length;
65
+
66
+ console.log(`\n📊 SmartContract Interface Summary:`);
67
+ console.log(` Total Methods: ${methodCount}`);
68
+ console.log(` Total Modules: ${Object.keys(SmartContract).filter(key =>
69
+ typeof SmartContract[key] === 'object' && SmartContract[key].constructor.name !== 'Object'
70
+ ).length}`);
71
+ console.log(` Feature Flags: ${Object.keys(SmartContract.features).length}`);
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Test ECDSA.verify with 'little' endianness
5
+ *
6
+ * Tests if adding 'little' parameter fixes ECDSA.verify too
7
+ */
8
+
9
+ const bsv = require('./index.js');
10
+
11
+ console.log('🔍 Test ECDSA.verify with little endianness');
12
+ console.log('============================================\n');
13
+
14
+ // Simple signature test
15
+ const privateKey = new bsv.PrivateKey('L1aW4aubDFB7yfras2S1mN3bqg9nwySY8nkoLmJebSLD5BWv3ENZ');
16
+ const publicKey = privateKey.publicKey;
17
+ const message = Buffer.from('hello world', 'utf8');
18
+ const hash = bsv.crypto.Hash.sha256(message);
19
+
20
+ console.log('Creating signature...');
21
+ const signature = bsv.crypto.ECDSA.sign(hash, privateKey);
22
+ const derSig = signature.toDER();
23
+
24
+ console.log('\n🧪 ECDSA.verify Test Matrix:');
25
+ console.log('============================');
26
+
27
+ // Test without 'little'
28
+ const ecdsaWithoutLittle = bsv.crypto.ECDSA.verify(hash, signature, publicKey);
29
+ console.log(`ECDSA.verify(hash, sig, pubkey): ${ecdsaWithoutLittle ? '✅ VALID' : '❌ INVALID'}`);
30
+
31
+ // Test with 'little'
32
+ const ecdsaWithLittle = bsv.crypto.ECDSA.verify(hash, signature, publicKey, 'little');
33
+ console.log(`ECDSA.verify(hash, sig, pubkey, 'little'): ${ecdsaWithLittle ? '✅ VALID' : '❌ INVALID'}`);
34
+
35
+ // Test with DER buffer without 'little'
36
+ const ecdsaDerWithoutLittle = bsv.crypto.ECDSA.verify(hash, derSig, publicKey);
37
+ console.log(`ECDSA.verify(hash, derSig, pubkey): ${ecdsaDerWithoutLittle ? '✅ VALID' : '❌ INVALID'}`);
38
+
39
+ // Test with DER buffer with 'little'
40
+ const ecdsaDerWithLittle = bsv.crypto.ECDSA.verify(hash, derSig, publicKey, 'little');
41
+ console.log(`ECDSA.verify(hash, derSig, pubkey, 'little'): ${ecdsaDerWithLittle ? '✅ VALID' : '❌ INVALID'}`);
42
+
43
+ console.log('\n🔍 Compare with SmartVerify:');
44
+ console.log('============================');
45
+
46
+ // Test SmartVerify
47
+ const smartVerifyObj = bsv.SmartVerify.smartVerify(hash, signature, publicKey);
48
+ console.log(`SmartVerify(hash, sig, pubkey): ${smartVerifyObj ? '✅ VALID' : '❌ INVALID'}`);
49
+
50
+ const smartVerifyDer = bsv.SmartVerify.smartVerify(hash, derSig, publicKey);
51
+ console.log(`SmartVerify(hash, derSig, pubkey): ${smartVerifyDer ? '✅ VALID' : '❌ INVALID'}`);
52
+
53
+ console.log('\n🔧 Signature Details:');
54
+ console.log('=====================');
55
+ console.log(`Signature r: ${signature.r.toString('hex')}`);
56
+ console.log(`Signature s: ${signature.s.toString('hex')}`);
57
+ console.log(`Is canonical: ${signature.isCanonical()}`);
58
+
59
+ // Check if this is a canonicalization issue
60
+ const canonicalSig = signature.toCanonical();
61
+ console.log(`Canonical r: ${canonicalSig.r.toString('hex')}`);
62
+ console.log(`Canonical s: ${canonicalSig.s.toString('hex')}`);
63
+ console.log(`Same as original: ${signature.r.eq(canonicalSig.r) && signature.s.eq(canonicalSig.s)}`);
64
+
65
+ // Test with canonical signature
66
+ const ecdsaCanonical = bsv.crypto.ECDSA.verify(hash, canonicalSig, publicKey, 'little');
67
+ console.log(`ECDSA.verify(hash, canonicalSig, pubkey, 'little'): ${ecdsaCanonical ? '✅ VALID' : '❌ INVALID'}`);
68
+
69
+ const smartVerifyCanonical = bsv.SmartVerify.smartVerify(hash, canonicalSig, publicKey);
70
+ console.log(`SmartVerify(hash, canonicalSig, pubkey): ${smartVerifyCanonical ? '✅ VALID' : '❌ INVALID'}`);
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Test SmartVerify DER Buffer Handling
5
+ *
6
+ * Tests SmartVerify with different input types to isolate the DER parsing issue
7
+ */
8
+
9
+ const bsv = require('./index.js');
10
+
11
+ console.log('🔍 Test SmartVerify DER Buffer Handling');
12
+ console.log('=======================================\n');
13
+
14
+ // Simple signature test like minimal reproduction
15
+ const privateKey = new bsv.PrivateKey('L1aW4aubDFB7yfras2S1mN3bqg9nwySY8nkoLmJebSLD5BWv3ENZ');
16
+ const publicKey = privateKey.publicKey;
17
+ const message = Buffer.from('hello world', 'utf8');
18
+ const hash = bsv.crypto.Hash.sha256(message);
19
+
20
+ console.log('Creating signature...');
21
+ const signature = bsv.crypto.ECDSA.sign(hash, privateKey);
22
+ const derSig = signature.toDER();
23
+
24
+ console.log(`Original signature r: ${signature.r.toString('hex')}`);
25
+ console.log(`Original signature s: ${signature.s.toString('hex')}`);
26
+ console.log(`DER buffer: ${derSig.toString('hex')}`);
27
+ console.log(`DER length: ${derSig.length}`);
28
+
29
+ console.log('\n🧪 SmartVerify Test Matrix:');
30
+ console.log('===========================');
31
+
32
+ // Test 1: Signature object
33
+ const smartVerifyObj = bsv.SmartVerify.smartVerify(hash, signature, publicKey);
34
+ console.log(`SmartVerify(hash, sigObject, pubkey): ${smartVerifyObj ? '✅ VALID' : '❌ INVALID'}`);
35
+
36
+ // Test 2: DER buffer
37
+ const smartVerifyBuffer = bsv.SmartVerify.smartVerify(hash, derSig, publicKey);
38
+ console.log(`SmartVerify(hash, derBuffer, pubkey): ${smartVerifyBuffer ? '✅ VALID' : '❌ INVALID'}`);
39
+
40
+ // Test 3: Manually parsed DER
41
+ try {
42
+ const parsedFromDER = bsv.crypto.Signature.fromDER(derSig);
43
+ console.log(`Parsed from DER r: ${parsedFromDER.r.toString('hex')}`);
44
+ console.log(`Parsed from DER s: ${parsedFromDER.s.toString('hex')}`);
45
+
46
+ const smartVerifyParsed = bsv.SmartVerify.smartVerify(hash, parsedFromDER, publicKey);
47
+ console.log(`SmartVerify(hash, parsedSig, pubkey): ${smartVerifyParsed ? '✅ VALID' : '❌ INVALID'}`);
48
+
49
+ console.log('\n🔍 Compare r,s values:');
50
+ console.log('======================');
51
+ console.log(`Original r: ${signature.r.toString('hex')}`);
52
+ console.log(`Parsed r : ${parsedFromDER.r.toString('hex')}`);
53
+ console.log(`r matches : ${signature.r.eq(parsedFromDER.r) ? '✅ YES' : '❌ NO'}`);
54
+
55
+ console.log(`Original s: ${signature.s.toString('hex')}`);
56
+ console.log(`Parsed s : ${parsedFromDER.s.toString('hex')}`);
57
+ console.log(`s matches : ${signature.s.eq(parsedFromDER.s) ? '✅ YES' : '❌ NO'}`);
58
+
59
+ } catch (error) {
60
+ console.log(`❌ DER parsing failed: ${error.message}`);
61
+ }
62
+
63
+ console.log('\n🔧 Debug SmartVerify DER Parsing:');
64
+ console.log('==================================');
65
+
66
+ // Let's manually step through what SmartVerify does with DER buffers
67
+ try {
68
+ console.log('Step 1: Input validation...');
69
+ console.log(` Hash is Buffer: ${Buffer.isBuffer(hash)}`);
70
+ console.log(` Hash length: ${hash.length}`);
71
+ console.log(` DER is Buffer: ${Buffer.isBuffer(derSig)}`);
72
+
73
+ console.log('Step 2: DER parsing in SmartVerify...');
74
+
75
+ // This replicates what SmartVerify does internally
76
+ const Signature = bsv.crypto.Signature;
77
+ const testParsed = Signature.fromDER(derSig);
78
+ console.log(` Parsed successfully: ✅`);
79
+ console.log(` Parsed r: ${testParsed.r.toString('hex')}`);
80
+ console.log(` Parsed s: ${testParsed.s.toString('hex')}`);
81
+
82
+ const BN = bsv.crypto.BN;
83
+ const r = BN.isBN(testParsed.r) ? testParsed.r : new BN(testParsed.r);
84
+ const s = BN.isBN(testParsed.s) ? testParsed.s : new BN(testParsed.s);
85
+ console.log(` r as BN: ${r.toString('hex')}`);
86
+ console.log(` s as BN: ${s.toString('hex')}`);
87
+
88
+ // Check canonicalization
89
+ const Point = bsv.crypto.Point;
90
+ const n = Point.getN();
91
+ const nh = n.shrn(1);
92
+ console.log(` s > n/2: ${s.gt(nh)}`);
93
+
94
+ const canonicalS = s.gt(nh) ? n.sub(s) : s;
95
+ console.log(` canonical s: ${canonicalS.toString('hex')}`);
96
+
97
+ // Test final ECDSA call
98
+ const canonicalSig = new Signature({
99
+ r: r,
100
+ s: canonicalS
101
+ });
102
+
103
+ const ECDSA = bsv.crypto.ECDSA;
104
+ const finalResult = ECDSA.verify(hash, canonicalSig, publicKey, 'little');
105
+ console.log(` Final ECDSA result: ${finalResult ? '✅ VALID' : '❌ INVALID'}`);
106
+
107
+ } catch (error) {
108
+ console.log(`❌ Debug failed: ${error.message}`);
109
+ console.log(`Stack: ${error.stack}`);
110
+ }