smartledger-bsv 3.2.1 → 3.3.1

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 (70) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +289 -55
  3. package/architecture_demo.js +247 -0
  4. package/bsv-covenant.min.js +10 -0
  5. package/bsv-gdaf.min.js +37 -0
  6. package/bsv-ltp.min.js +37 -0
  7. package/bsv-script-helper.min.js +10 -0
  8. package/bsv-security.min.js +31 -0
  9. package/bsv-shamir.min.js +12 -0
  10. package/bsv-smartcontract.min.js +37 -0
  11. package/bsv.bundle.js +9 -9
  12. package/bsv.min.js +3 -3
  13. package/build/bsv-covenant.min.js +10 -0
  14. package/build/bsv-script-helper.min.js +10 -0
  15. package/build/bsv-security.min.js +31 -0
  16. package/build/bsv-smartcontract.min.js +39 -0
  17. package/build/bsv.bundle.js +39 -0
  18. package/build/bsv.min.js +39 -0
  19. package/build/webpack.bundle.config.js +22 -0
  20. package/build/webpack.config.js +18 -0
  21. package/build/webpack.covenant.config.js +27 -0
  22. package/build/webpack.gdaf.config.js +54 -0
  23. package/build/webpack.ltp.config.js +17 -0
  24. package/build/webpack.script-helper.config.js +27 -0
  25. package/build/webpack.security.config.js +23 -0
  26. package/build/webpack.smartcontract.config.js +25 -0
  27. package/build/webpack.subproject.config.js +6 -0
  28. package/bundle-entry.js +341 -0
  29. package/complete_ltp_demo.js +511 -0
  30. package/covenant-entry.js +44 -0
  31. package/docs/pushtx-key-insights.md +106 -0
  32. package/gdaf-entry.js +54 -0
  33. package/index.js +272 -5
  34. package/lib/crypto/shamir.js +360 -0
  35. package/lib/gdaf/attestation-signer.js +461 -0
  36. package/lib/gdaf/attestation-verifier.js +600 -0
  37. package/lib/gdaf/did-resolver.js +382 -0
  38. package/lib/gdaf/index.js +471 -0
  39. package/lib/gdaf/schema-validator.js +682 -0
  40. package/lib/gdaf/smartledger-anchor.js +486 -0
  41. package/lib/gdaf/zk-prover.js +507 -0
  42. package/lib/ltp/anchor.js +438 -0
  43. package/lib/ltp/claim.js +1026 -0
  44. package/lib/ltp/index.js +470 -0
  45. package/lib/ltp/obligation.js +945 -0
  46. package/lib/ltp/proof.js +828 -0
  47. package/lib/ltp/registry.js +702 -0
  48. package/lib/ltp/right.js +765 -0
  49. package/lib/smart_contract/API_REFERENCE.md +1 -1
  50. package/lib/smart_contract/EXAMPLES.md +2 -2
  51. package/lib/smart_contract/QUICK_START.md +2 -2
  52. package/lib/smart_contract/README.md +1 -1
  53. package/lib/smart_contract/index.js +4 -0
  54. package/ltp-entry.js +92 -0
  55. package/package.json +91 -20
  56. package/script-helper-entry.js +49 -0
  57. package/security-entry.js +70 -0
  58. package/shamir-entry.js +173 -0
  59. package/shamir_demo.js +121 -0
  60. package/simple_demo.js +204 -0
  61. package/smartcontract-entry.js +133 -0
  62. package/test_shamir.js +221 -0
  63. package/test_standalone_shamir.html +83 -0
  64. package/tests/bundle-completeness-test.html +131 -0
  65. package/tests/bundle-demo.html +476 -0
  66. package/tests/smartcontract-test.html +239 -0
  67. package/tests/standalone-modules-test.html +260 -0
  68. package/tests/test.html +612 -0
  69. package/tests/unpkg-demo.html +194 -0
  70. package/docs/nchain.md +0 -958
package/shamir_demo.js ADDED
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * BSV Shamir Secret Sharing Demo
5
+ *
6
+ * This demonstrates how to use Shamir Secret Sharing for secure secret distribution
7
+ * Perfect for backup keys, passwords, or any sensitive data that needs to be distributed
8
+ * across multiple parties with threshold security.
9
+ */
10
+
11
+ 'use strict'
12
+
13
+ var bsv = require('./index.js')
14
+
15
+ console.log('🔐 BSV Shamir Secret Sharing Demo')
16
+ console.log('=====================================\n')
17
+
18
+ // Example 1: Basic secret sharing
19
+ console.log('📝 Example 1: Basic Secret Sharing')
20
+ console.log('----------------------------------')
21
+
22
+ var secret = 'my-super-secret-bitcoin-private-key'
23
+ var threshold = 3 // Need at least 3 shares to reconstruct
24
+ var totalShares = 5 // Create 5 total shares
25
+
26
+ console.log('Secret to protect:', secret)
27
+ console.log('Security policy: ' + threshold + ' of ' + totalShares + ' shares required\n')
28
+
29
+ // Split the secret
30
+ var shares = bsv.Shamir.split(secret, threshold, totalShares)
31
+ console.log('✅ Secret split into', shares.length, 'shares')
32
+
33
+ // Display share information (truncated for security)
34
+ shares.forEach(function(share, index) {
35
+ console.log(' Share ' + (index + 1) + ': ID=' + share.id + ', bytes=' + share.length)
36
+ })
37
+
38
+ // Reconstruct with minimum shares (3 of 5)
39
+ console.log('\n🔓 Reconstructing with shares 1, 3, and 5...')
40
+ var selectedShares = [shares[0], shares[2], shares[4]] // shares 1, 3, 5
41
+ var reconstructed = bsv.Shamir.combine(selectedShares)
42
+ var reconstructedSecret = reconstructed.toString('utf8')
43
+
44
+ console.log('Reconstructed secret:', reconstructedSecret)
45
+ console.log('Match original:', reconstructedSecret === secret ? '✅ YES' : '❌ NO')
46
+
47
+ // Example 2: Bitcoin wallet backup scenario
48
+ console.log('\n\n💰 Example 2: Bitcoin Wallet Backup Scenario')
49
+ console.log('---------------------------------------------')
50
+
51
+ var walletMnemonic = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'
52
+ var backupPolicy = { threshold: 2, shares: 3 } // 2-of-3 backup
53
+
54
+ console.log('Wallet mnemonic (12 words):', walletMnemonic.split(' ').slice(0, 3).join(' ') + '...')
55
+ console.log('Backup policy: ' + backupPolicy.threshold + ' of ' + backupPolicy.shares + ' shares needed\n')
56
+
57
+ var walletShares = bsv.Shamir.split(walletMnemonic, backupPolicy.threshold, backupPolicy.shares)
58
+
59
+ console.log('📋 Backup shares created:')
60
+ walletShares.forEach(function(share, index) {
61
+ var label = ['👤 Family Member', '🏦 Bank Safe', '☁️ Cloud Storage'][index]
62
+ console.log(' Share ' + (index + 1) + ': ' + label + ' (ID: ' + share.id + ')')
63
+ })
64
+
65
+ // Simulate recovery with 2 shares
66
+ console.log('\n🔧 Simulating wallet recovery with shares from Family Member + Bank Safe...')
67
+ var recoveryShares = [walletShares[0], walletShares[1]] // First 2 shares
68
+ var recoveredMnemonic = bsv.Shamir.combine(recoveryShares).toString('utf8')
69
+
70
+ console.log('Recovered mnemonic:', recoveredMnemonic === walletMnemonic ? '✅ SUCCESS' : '❌ FAILED')
71
+
72
+ // Example 3: Binary data (keys, certificates, etc.)
73
+ console.log('\n\n🔑 Example 3: Binary Data Protection')
74
+ console.log('-----------------------------------')
75
+
76
+ var binarySecret = Buffer.from([0x04, 0x8f, 0xab, 0x23, 0xc1, 0x9e, 0x77, 0x44]) // Example key bytes
77
+ console.log('Binary secret (hex):', binarySecret.toString('hex'))
78
+ console.log('Binary secret length:', binarySecret.length, 'bytes\n')
79
+
80
+ var binaryShares = bsv.Shamir.split(binarySecret, 2, 4)
81
+ console.log('✅ Binary data split into', binaryShares.length, 'shares')
82
+
83
+ var recoveredBinary = bsv.Shamir.combine(binaryShares.slice(0, 2))
84
+ console.log('Recovered binary (hex):', recoveredBinary.toString('hex'))
85
+ console.log('Binary match:', Buffer.compare(binarySecret, recoveredBinary) === 0 ? '✅ YES' : '❌ NO')
86
+
87
+ // Example 4: Share verification
88
+ console.log('\n\n🔍 Example 4: Share Verification')
89
+ console.log('--------------------------------')
90
+
91
+ var testShares = bsv.Shamir.split('verification-test', 2, 3)
92
+ console.log('Testing share integrity...')
93
+
94
+ testShares.forEach(function(share, index) {
95
+ var isValid = bsv.Shamir.verifyShare(share)
96
+ console.log(' Share ' + (index + 1) + ':', isValid ? '✅ Valid' : '❌ Invalid')
97
+ })
98
+
99
+ // Test with corrupted share
100
+ var corruptedShare = JSON.parse(JSON.stringify(testShares[0]))
101
+ corruptedShare.bytes[0].y = 'invalid-hex' // Corrupt the data
102
+ console.log(' Corrupted share:', bsv.Shamir.verifyShare(corruptedShare) ? '❌ Invalid test failed' : '✅ Correctly rejected')
103
+
104
+ console.log('\n🎯 Use Cases for Shamir Secret Sharing:')
105
+ console.log('--------------------------------------')
106
+ console.log('• 🔐 Bitcoin wallet backup (split mnemonic across family/friends)')
107
+ console.log('• 🏢 Corporate key management (distribute signing keys)')
108
+ console.log('• 🛡️ Multi-party authentication (API keys, passwords)')
109
+ console.log('• 💾 Secure data backup (encrypt once, distribute shares)')
110
+ console.log('• 🤝 Trustless escrow (require multiple parties to unlock)')
111
+ console.log('• 🏦 Bank vault security (multiple keyholders required)')
112
+
113
+ console.log('\n📦 Integration Options:')
114
+ console.log('----------------------')
115
+ console.log('• Main library: bsv.Shamir or bsv.crypto.Shamir')
116
+ console.log('• Standalone: bsv-shamir.min.js (433 KB)')
117
+ console.log('• CDN ready: Use in browser with <script> tag')
118
+ console.log('• Node.js: require("smartledger-bsv").Shamir')
119
+
120
+ console.log('\n✨ Demo completed successfully!')
121
+ console.log('Visit: https://github.com/codenlighten/smartledger-bsv for more examples')
package/simple_demo.js ADDED
@@ -0,0 +1,204 @@
1
+ /**
2
+ * SmartLedger-BSV Legal Token Protocol (LTP) - Primitives-Only Architecture Demo
3
+ *
4
+ * This demonstrates the architectural transformation from application framework
5
+ * to foundation library with primitives-only approach.
6
+ */
7
+
8
+ const bsv = require('./index.js')
9
+
10
+ console.log('🚀 SmartLedger-BSV LTP: Primitives-Only Architecture')
11
+ console.log('==================================================\n')
12
+
13
+ console.log('🔄 ARCHITECTURAL TRANSFORMATION COMPARISON')
14
+ console.log('------------------------------------------\n')
15
+
16
+ /**
17
+ * BEFORE vs AFTER: Key Differences
18
+ */
19
+ console.log('📋 BEFORE (Application Framework Approach):')
20
+ console.log('--------------------------------------------')
21
+ console.log('❌ bsv.createRightToken() → Created AND published to blockchain')
22
+ console.log('❌ bsv.validateLegalClaim() → Validated AND stored in database')
23
+ console.log('❌ bsv.anchorTokenBatch() → Created batch AND sent transaction')
24
+ console.log('❌ bsv.createLegalRegistry() → Created registry AND managed storage')
25
+ console.log('❌ bsv.transferRight() → Prepared transfer AND published')
26
+ console.log('')
27
+ console.log(' Problems with this approach:')
28
+ console.log(' • Library had too many responsibilities')
29
+ console.log(' • Developers locked into specific platforms')
30
+ console.log(' • Hard to integrate with existing systems')
31
+ console.log(' • Mixed crypto logic with application logic')
32
+ console.log('')
33
+
34
+ console.log('📋 AFTER (Primitives-Only Approach):')
35
+ console.log('-------------------------------------')
36
+ console.log('✅ bsv.prepareRightToken() → Prepares token structure only')
37
+ console.log('✅ bsv.prepareClaimValidation() → Validates structure only')
38
+ console.log('✅ bsv.prepareBatchCommitment() → Prepares commitment only')
39
+ console.log('✅ bsv.prepareRegistry() → Prepares registry data only')
40
+ console.log('✅ bsv.prepareRightTokenTransfer() → Prepares transfer data only')
41
+ console.log('')
42
+ console.log(' Benefits of this approach:')
43
+ console.log(' • Clear separation of concerns')
44
+ console.log(' • Maximum developer flexibility')
45
+ console.log(' • Easy integration with any system')
46
+ console.log(' • Focus on cryptographic correctness')
47
+ console.log('')
48
+
49
+ /**
50
+ * DEMONSTRATE THE NEW INTERFACE
51
+ */
52
+ console.log('🛠️ NEW PRIMITIVES INTERFACE AVAILABLE:')
53
+ console.log('======================================\n')
54
+
55
+ console.log('🏛️ RIGHT TOKEN PRIMITIVES:')
56
+ console.log(' • bsv.prepareRightToken()')
57
+ console.log(' • bsv.prepareRightTokenVerification()')
58
+ console.log(' • bsv.prepareRightTokenTransfer()')
59
+ console.log(' • bsv.prepareRightTypeValidation()')
60
+ console.log('')
61
+
62
+ console.log('⚖️ OBLIGATION TOKEN PRIMITIVES:')
63
+ console.log(' • bsv.prepareObligationToken()')
64
+ console.log(' • bsv.prepareObligationVerification()')
65
+ console.log(' • bsv.prepareObligationFulfillment()')
66
+ console.log(' • bsv.prepareObligationBreachAssessment()')
67
+ console.log(' • bsv.prepareObligationMonitoringReport()')
68
+ console.log('')
69
+
70
+ console.log('📝 CLAIM VALIDATION PRIMITIVES:')
71
+ console.log(' • bsv.prepareClaimValidation()')
72
+ console.log(' • bsv.prepareClaimAttestation()')
73
+ console.log(' • bsv.prepareClaimDispute()')
74
+ console.log(' • bsv.prepareBulkClaimValidation()')
75
+ console.log(' • bsv.prepareClaimTemplate()')
76
+ console.log('')
77
+
78
+ console.log('🔐 PROOF GENERATION PRIMITIVES:')
79
+ console.log(' • bsv.prepareSignatureProof()')
80
+ console.log(' • bsv.prepareSelectiveDisclosure()')
81
+ console.log(' • bsv.prepareLegalValidityProof()')
82
+ console.log(' • bsv.prepareZeroKnowledgeProof()')
83
+ console.log('')
84
+
85
+ console.log('📚 REGISTRY MANAGEMENT PRIMITIVES:')
86
+ console.log(' • bsv.prepareRegistry()')
87
+ console.log(' • bsv.prepareTokenRegistration()')
88
+ console.log(' • bsv.prepareTokenApproval()')
89
+ console.log(' • bsv.prepareTokenRevocation()')
90
+ console.log(' • bsv.prepareTokenStatusQuery()')
91
+ console.log(' • bsv.prepareTokenSearch()')
92
+ console.log('')
93
+
94
+ console.log('⛓️ BLOCKCHAIN ANCHORING PRIMITIVES:')
95
+ console.log(' • bsv.prepareTokenCommitment()')
96
+ console.log(' • bsv.prepareBatchCommitment()')
97
+ console.log(' • bsv.verifyTokenAnchor()')
98
+ console.log(' • bsv.formatRevocation()')
99
+ console.log('')
100
+
101
+ /**
102
+ * SHOW UTILITY FUNCTIONS (UNCHANGED)
103
+ */
104
+ console.log('🔧 UTILITY FUNCTIONS (Unchanged):')
105
+ console.log(' • bsv.getRightTypes() → Static data access')
106
+ console.log(' • bsv.getObligationTypes() → Static data access')
107
+ console.log(' • bsv.getClaimSchemas() → Static data access')
108
+ console.log(' • bsv.canonicalizeClaim() → Data transformation')
109
+ console.log(' • bsv.hashClaim() → Hash generation')
110
+ console.log('')
111
+
112
+ /**
113
+ * EXAMPLE USAGE PATTERN
114
+ */
115
+ console.log('💡 EXAMPLE: How Applications Use The New Primitives')
116
+ console.log('===================================================\n')
117
+
118
+ console.log('// STEP 1: Use SmartLedger-BSV to prepare legal structures')
119
+ console.log('const rightTokenPrep = bsv.prepareRightToken(')
120
+ console.log(' "PROPERTY_OWNERSHIP", issuerDID, ownerDID, claimData, privateKey')
121
+ console.log(')')
122
+ console.log('')
123
+
124
+ console.log('// STEP 2: Use external system to publish to blockchain')
125
+ console.log('const blockchainResult = await MyBlockchain.publish({')
126
+ console.log(' commitment: rightTokenPrep.commitment,')
127
+ console.log(' signature: rightTokenPrep.signature')
128
+ console.log('})')
129
+ console.log('')
130
+
131
+ console.log('// STEP 3: Use external system to store in registry')
132
+ console.log('const registryResult = await MyRegistry.store({')
133
+ console.log(' token: rightTokenPrep.token,')
134
+ console.log(' metadata: rightTokenPrep.metadata')
135
+ console.log('})')
136
+ console.log('')
137
+
138
+ console.log('// STEP 4: Use SmartLedger-BSV to verify the results')
139
+ console.log('const verification = bsv.verifyTokenAnchor(')
140
+ console.log(' rightTokenPrep.token, blockchainResult.txid')
141
+ console.log(')')
142
+ console.log('')
143
+
144
+ /**
145
+ * BENEFITS SUMMARY
146
+ */
147
+ console.log('🎯 PRIMITIVES-ONLY ARCHITECTURE BENEFITS')
148
+ console.log('========================================\n')
149
+
150
+ console.log('👨‍💻 FOR DEVELOPERS:')
151
+ console.log(' ✅ Choose your own blockchain (BSV, Bitcoin, Ethereum, etc.)')
152
+ console.log(' ✅ Choose your own storage (SQL, NoSQL, IPFS, etc.)')
153
+ console.log(' ✅ Choose your own UI framework (React, Vue, Angular, etc.)')
154
+ console.log(' ✅ Integrate with existing business systems')
155
+ console.log(' ✅ Maintain full control over user experience')
156
+ console.log('')
157
+
158
+ console.log('🏢 FOR ENTERPRISES:')
159
+ console.log(' ✅ No vendor lock-in to specific platforms')
160
+ console.log(' ✅ Compliance with existing IT policies')
161
+ console.log(' ✅ Integration with legacy systems')
162
+ console.log(' ✅ Scalable architecture patterns')
163
+ console.log(' ✅ Audit-friendly separation of concerns')
164
+ console.log('')
165
+
166
+ console.log('🔒 FOR SECURITY:')
167
+ console.log(' ✅ Cryptographic operations isolated and testable')
168
+ console.log(' ✅ No network dependencies in core library')
169
+ console.log(' ✅ Predictable, deterministic behavior')
170
+ console.log(' ✅ Smaller attack surface')
171
+ console.log(' ✅ Clear boundaries for security reviews')
172
+ console.log('')
173
+
174
+ console.log('⚖️ FOR LEGAL COMPLIANCE:')
175
+ console.log(' ✅ Standardized legal token structures')
176
+ console.log(' ✅ Cryptographic proof generation')
177
+ console.log(' ✅ Audit trail preparation')
178
+ console.log(' ✅ Jurisdiction-specific adaptability')
179
+ console.log(' ✅ Regulatory compliance primitives')
180
+ console.log('')
181
+
182
+ console.log('🚀 CONCLUSION')
183
+ console.log('=============')
184
+ console.log('')
185
+ console.log('SmartLedger-BSV is now a pure foundation library that provides')
186
+ console.log('everything needed to build Legal Token Protocol applications')
187
+ console.log('while giving developers complete architectural freedom.')
188
+ console.log('')
189
+ console.log('The library focuses on what it does best:')
190
+ console.log('• Cryptographic correctness')
191
+ console.log('• Legal structure validation')
192
+ console.log('• Standardized data formats')
193
+ console.log('• Compliance primitives')
194
+ console.log('')
195
+ console.log('External systems handle:')
196
+ console.log('• Blockchain publishing')
197
+ console.log('• Data storage')
198
+ console.log('• User interfaces')
199
+ console.log('• Business workflows')
200
+ console.log('')
201
+ console.log('This creates the perfect foundation for any Legal Token')
202
+ console.log('Protocol application while maintaining maximum flexibility!')
203
+ console.log('')
204
+ console.log('🎉 Primitives-only transformation: COMPLETE! 🎉')
@@ -0,0 +1,133 @@
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
package/test_shamir.js ADDED
@@ -0,0 +1,221 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * BSV Shamir Secret Sharing Test
5
+ * Comprehensive test of the Shamir Secret Sharing implementation
6
+ */
7
+
8
+ 'use strict'
9
+
10
+ console.log('=== BSV Shamir Secret Sharing Test ===\n')
11
+
12
+ // Load the BSV library with Shamir support
13
+ var bsv
14
+ try {
15
+ bsv = require('./index.js')
16
+ console.log('✓ Loaded BSV library with Shamir support')
17
+ } catch (e) {
18
+ console.error('✗ Failed to load BSV library:', e.message)
19
+ process.exit(1)
20
+ }
21
+
22
+ // Test 1: Basic functionality test
23
+ console.log('\n--- Test 1: Basic Secret Sharing ---')
24
+ try {
25
+ var secret = 'Hello, Bitcoin SV!'
26
+ var threshold = 3
27
+ var shares = 5
28
+
29
+ console.log('Original secret:', secret)
30
+ console.log('Threshold:', threshold, '/ Total shares:', shares)
31
+
32
+ // Split the secret
33
+ var splitShares = bsv.Shamir.split(secret, threshold, shares)
34
+ console.log('✓ Successfully split secret into', splitShares.length, 'shares')
35
+
36
+ // Reconstruct with minimum shares
37
+ var reconstructed = bsv.Shamir.combine(splitShares.slice(0, threshold))
38
+ var reconstructedSecret = reconstructed.toString('utf8')
39
+
40
+ console.log('Reconstructed:', reconstructedSecret)
41
+
42
+ if (reconstructedSecret === secret) {
43
+ console.log('✓ Test 1 PASSED: Secret correctly reconstructed')
44
+ } else {
45
+ console.log('✗ Test 1 FAILED: Secret reconstruction failed')
46
+ }
47
+ } catch (e) {
48
+ console.log('✗ Test 1 ERROR:', e.message)
49
+ }
50
+
51
+ // Test 2: Larger secret test
52
+ console.log('\n--- Test 2: Large Secret Test ---')
53
+ try {
54
+ var largeSecret = 'This is a much longer secret that will test the chunking functionality of the Shamir Secret Sharing implementation. It should handle secrets of arbitrary length by breaking them into manageable chunks and processing each chunk separately.'
55
+ var threshold2 = 4
56
+ var shares2 = 7
57
+
58
+ console.log('Large secret length:', largeSecret.length, 'characters')
59
+
60
+ var splitShares2 = bsv.Shamir.split(largeSecret, threshold2, shares2)
61
+ console.log('✓ Successfully split large secret')
62
+
63
+ var reconstructed2 = bsv.Shamir.combine(splitShares2.slice(0, threshold2))
64
+ var reconstructedSecret2 = reconstructed2.toString('utf8')
65
+
66
+ if (reconstructedSecret2 === largeSecret) {
67
+ console.log('✓ Test 2 PASSED: Large secret correctly reconstructed')
68
+ } else {
69
+ console.log('✗ Test 2 FAILED: Large secret reconstruction failed')
70
+ console.log('Expected length:', largeSecret.length)
71
+ console.log('Actual length:', reconstructedSecret2.length)
72
+ console.log('First 50 chars expected:', largeSecret.substring(0, 50))
73
+ console.log('First 50 chars actual :', reconstructedSecret2.substring(0, 50))
74
+ console.log('Match:', largeSecret === reconstructedSecret2)
75
+ }
76
+ } catch (e) {
77
+ console.log('✗ Test 2 ERROR:', e.message)
78
+ }
79
+
80
+ // Test 3: Different share combinations
81
+ console.log('\n--- Test 3: Share Combination Test ---')
82
+ try {
83
+ var secret3 = 'Testing different combinations'
84
+ var splitShares3 = bsv.Shamir.split(secret3, 3, 6)
85
+
86
+ // Test different combinations of 3 shares
87
+ var combinations = [
88
+ [0, 1, 2], // First three
89
+ [1, 3, 5], // Every other
90
+ [2, 4, 5] // Last three + one
91
+ ]
92
+
93
+ var allPassed = true
94
+ for (var i = 0; i < combinations.length; i++) {
95
+ var combo = combinations[i]
96
+ var testShares = combo.map(function(idx) { return splitShares3[idx] })
97
+ var reconstructed3 = bsv.Shamir.combine(testShares)
98
+ var result = reconstructed3.toString('utf8')
99
+
100
+ if (result === secret3) {
101
+ console.log('✓ Combination', combo, 'successful')
102
+ } else {
103
+ console.log('✗ Combination', combo, 'failed')
104
+ allPassed = false
105
+ }
106
+ }
107
+
108
+ if (allPassed) {
109
+ console.log('✓ Test 3 PASSED: All share combinations work')
110
+ } else {
111
+ console.log('✗ Test 3 FAILED: Some combinations failed')
112
+ }
113
+ } catch (e) {
114
+ console.log('✗ Test 3 ERROR:', e.message)
115
+ }
116
+
117
+ // Test 4: Share verification
118
+ console.log('\n--- Test 4: Share Verification Test ---')
119
+ try {
120
+ var secret4 = 'Verification test'
121
+ var splitShares4 = bsv.Shamir.split(secret4, 2, 4)
122
+
123
+ var validCount = 0
124
+ for (var j = 0; j < splitShares4.length; j++) {
125
+ if (bsv.Shamir.verifyShare(splitShares4[j])) {
126
+ validCount++
127
+ }
128
+ }
129
+
130
+ if (validCount === splitShares4.length) {
131
+ console.log('✓ Test 4 PASSED: All shares verified as valid')
132
+ } else {
133
+ console.log('✗ Test 4 FAILED: Only', validCount, 'of', splitShares4.length, 'shares valid')
134
+ }
135
+
136
+ // Test invalid share
137
+ var invalidShare = { invalid: 'data' }
138
+ if (!bsv.Shamir.verifyShare(invalidShare)) {
139
+ console.log('✓ Invalid share correctly rejected')
140
+ } else {
141
+ console.log('✗ Invalid share incorrectly accepted')
142
+ }
143
+ } catch (e) {
144
+ console.log('✗ Test 4 ERROR:', e.message)
145
+ }
146
+
147
+ // Test 5: Error handling
148
+ console.log('\n--- Test 5: Error Handling Test ---')
149
+ try {
150
+ var errorTests = [
151
+ function() { bsv.Shamir.split('', 2, 3) }, // Empty secret
152
+ function() { bsv.Shamir.split('secret', 1, 3) }, // Threshold too low
153
+ function() { bsv.Shamir.split('secret', 3, 2) }, // More threshold than shares
154
+ function() { bsv.Shamir.combine([]) }, // Empty shares array
155
+ function() { bsv.Shamir.combine([{id: 1, threshold: 2, shares: 3, length: 1, bytes: []}]) } // Insufficient shares
156
+ ]
157
+
158
+ var errorsPassed = 0
159
+ for (var k = 0; k < errorTests.length; k++) {
160
+ try {
161
+ errorTests[k]()
162
+ console.log('✗ Error test', k + 1, 'should have thrown an error')
163
+ } catch (e) {
164
+ console.log('✓ Error test', k + 1, 'correctly threw:', e.message)
165
+ errorsPassed++
166
+ }
167
+ }
168
+
169
+ if (errorsPassed === errorTests.length) {
170
+ console.log('✓ Test 5 PASSED: All error conditions handled correctly')
171
+ } else {
172
+ console.log('✗ Test 5 FAILED: Some error conditions not handled')
173
+ }
174
+ } catch (e) {
175
+ console.log('✗ Test 5 ERROR:', e.message)
176
+ }
177
+
178
+ // Test 6: Binary data test
179
+ console.log('\n--- Test 6: Binary Data Test ---')
180
+ try {
181
+ var binaryData = Buffer.from([0x00, 0x01, 0x02, 0xFF, 0xFE, 0xFD, 0x80, 0x7F])
182
+ var splitBinary = bsv.Shamir.split(binaryData, 2, 3)
183
+ var reconstructedBinary = bsv.Shamir.combine(splitBinary.slice(0, 2))
184
+
185
+ if (Buffer.compare(binaryData, reconstructedBinary) === 0) {
186
+ console.log('✓ Test 6 PASSED: Binary data correctly handled')
187
+ } else {
188
+ console.log('✗ Test 6 FAILED: Binary data reconstruction failed')
189
+ console.log('Original:', Array.from(binaryData))
190
+ console.log('Reconstructed:', Array.from(reconstructedBinary))
191
+ }
192
+ } catch (e) {
193
+ console.log('✗ Test 6 ERROR:', e.message)
194
+ }
195
+
196
+ // Test 7: Generate test vectors
197
+ console.log('\n--- Test 7: Test Vectors Generation ---')
198
+ try {
199
+ var testVectors = bsv.Shamir.generateTestVectors()
200
+
201
+ console.log('Test vectors generated:')
202
+ console.log('- Secret:', testVectors.secret)
203
+ console.log('- Threshold:', testVectors.threshold)
204
+ console.log('- Total shares:', testVectors.totalShares)
205
+ console.log('- Shares generated:', testVectors.shares.length)
206
+ console.log('- Reconstruction successful:', testVectors.valid)
207
+
208
+ if (testVectors.valid) {
209
+ console.log('✓ Test 7 PASSED: Test vectors generated and validated')
210
+ } else {
211
+ console.log('✗ Test 7 FAILED: Test vectors validation failed')
212
+ }
213
+ } catch (e) {
214
+ console.log('✗ Test 7 ERROR:', e.message)
215
+ }
216
+
217
+ console.log('\n=== Shamir Secret Sharing Tests Complete ===')
218
+ console.log('💡 Integration successful! Shamir Secret Sharing is now available in:')
219
+ console.log(' • Main library: bsv.Shamir or bsv.crypto.Shamir')
220
+ console.log(' • Standalone: bsv-shamir.min.js (after build)')
221
+ console.log(' • CDN ready: Use npm run build-shamir to generate minified version')