@smartledger/bsv 3.4.2 → 3.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +336 -0
  2. package/README.md +72 -72
  3. package/SECURITY.md +88 -0
  4. package/bin/cli.js +13 -8
  5. package/bsv-covenant.min.js +4 -4
  6. package/bsv-gdaf.min.js +5 -5
  7. package/bsv-ltp.min.js +7 -7
  8. package/bsv-smartcontract.min.js +5 -5
  9. package/bsv.bundle.js +5 -5
  10. package/bsv.d.ts +486 -9
  11. package/bsv.min.js +5 -5
  12. package/docs/COVENANT_DEVELOPMENT_RESOLVED.md +2 -2
  13. package/docs/MODULE_REFERENCE_COMPLETE.md +61 -58
  14. package/docs/advanced/LEGAL_TOKEN_PROTOCOL.md +3 -3
  15. package/docs/advanced/UTXO_MANAGER_GUIDE.md +1 -1
  16. package/docs/getting-started/INSTALLATION.md +30 -30
  17. package/docs/getting-started/QUICK_START.md +18 -18
  18. package/docs/migration/FROM_BSV_1_5_6.md +16 -10
  19. package/gdaf-entry.js +1 -2
  20. package/index.js +20 -7
  21. package/lib/smart_contract/covenant.js +10 -1
  22. package/lib/smartutxo.js +20 -12
  23. package/lib/transaction/transaction.js +7 -0
  24. package/ltp-entry.js +1 -2
  25. package/package.json +3 -3
  26. package/utilities/blockchain-state.js +32 -23
  27. package/demos/README.md +0 -188
  28. package/demos/architecture_demo.js +0 -247
  29. package/demos/browser-test.html +0 -1208
  30. package/demos/bsv_wallet_demo.js +0 -242
  31. package/demos/complete_ltp_demo.js +0 -511
  32. package/demos/debug_tools_demo.js +0 -87
  33. package/demos/demo_features.js +0 -123
  34. package/demos/easy_interface_demo.js +0 -109
  35. package/demos/ecies_demo.js +0 -182
  36. package/demos/gdaf_demo.js +0 -237
  37. package/demos/ltp_demo.js +0 -361
  38. package/demos/ltp_primitives_demo.js +0 -403
  39. package/demos/message_demo.js +0 -209
  40. package/demos/preimage_separation_demo.js +0 -383
  41. package/demos/script_helper_demo.js +0 -289
  42. package/demos/security_demo.js +0 -287
  43. package/demos/shamir_demo.js +0 -121
  44. package/demos/simple_demo.js +0 -204
  45. package/demos/simple_p2pkh_demo.js +0 -169
  46. package/demos/simple_utxo_preimage_demo.js +0 -196
  47. package/demos/smart_contract_demo.html +0 -1347
  48. package/demos/smart_contract_demo.js +0 -910
  49. package/demos/utxo_generator_demo.js +0 -244
  50. package/demos/validation_pipeline_demo.js +0 -155
  51. package/demos/web3keys.html +0 -740
  52. package/examples/README.md +0 -200
  53. package/examples/basic/transaction-creation.js +0 -534
  54. package/examples/basic/transaction_signature_api_gap.js +0 -178
  55. package/examples/complete_workflow_demo.js +0 -783
  56. package/examples/covenants/advanced_covenant_demo.js +0 -219
  57. package/examples/covenants/covenant_interface_demo.js +0 -270
  58. package/examples/covenants/covenant_manual_signature_resolved.js +0 -212
  59. package/examples/covenants/covenant_signature_template.js +0 -117
  60. package/examples/covenants2/covenant_bidirectional_example.js +0 -262
  61. package/examples/covenants2/covenant_utils_demo.js +0 -120
  62. package/examples/covenants2/preimage_covenant_utils.js +0 -287
  63. package/examples/covenants2/production_integration.js +0 -256
  64. package/examples/data/covenant_utxos.json +0 -28
  65. package/examples/data/utxos.json +0 -26
  66. package/examples/definitive_working_demo.js +0 -261
  67. package/examples/final_working_contracts.js +0 -338
  68. package/examples/legacy/README.md +0 -11
  69. package/examples/legacy/smart_contract_test_integration.js +0 -269
  70. package/examples/legacy/test_builtin_verify.js +0 -117
  71. package/examples/legacy/test_debug_integration.js +0 -71
  72. package/examples/legacy/test_ecdsa_little.js +0 -70
  73. package/examples/legacy/test_shamir.js +0 -221
  74. package/examples/legacy/test_smartverify_der.js +0 -110
  75. package/examples/preimage/README.md +0 -178
  76. package/examples/preimage/extract_preimage_bidirectional.js +0 -421
  77. package/examples/preimage/generate_sample_preimage.js +0 -208
  78. package/examples/preimage/generate_sighash_examples.js +0 -152
  79. package/examples/preimage/parse_preimage.js +0 -117
  80. package/examples/preimage/test_preimage_extractor.js +0 -53
  81. package/examples/preimage/test_varint_extraction.js +0 -95
  82. package/examples/scripts/custom_script_helper_example.js +0 -273
  83. package/examples/scripts/script_interpreter.js +0 -193
  84. package/examples/smart_contract/complete_workflow_demo.js +0 -343
  85. package/examples/smart_contract/covenant_builder_demo.js +0 -176
  86. package/examples/smart_contract/script_testing_integration.js +0 -198
  87. package/examples/smart_contract_templates.js +0 -718
  88. package/examples/working_smart_contracts.js +0 -348
@@ -1,403 +0,0 @@
1
- /**
2
- * SmartLedger-BSV Legal Token Protocol (LTP) - Primitives-Only Architecture Demo
3
- *
4
- * This demonstration shows how the new primitives-only approach works:
5
- * - Library provides all preparation and validation primitives
6
- * - External systems handle blockchain publishing and storage
7
- * - Complete separation between foundation tools and application logic
8
- */
9
-
10
- const bsv = require('../index.js')
11
-
12
- console.log('šŸš€ SmartLedger-BSV LTP Primitives Demo')
13
- console.log('=====================================\n')
14
-
15
- // Demo keys and identities
16
- const issuerPrivateKey = new bsv.PrivateKey()
17
- const issuerPublicKey = issuerPrivateKey.publicKey
18
- const ownerPrivateKey = new bsv.PrivateKey()
19
- const obligorPrivateKey = new bsv.PrivateKey()
20
-
21
- const issuerDID = `did:bsv:${issuerPublicKey.toString()}`
22
- const ownerDID = `did:bsv:${ownerPrivateKey.publicKey.toString()}`
23
- const obligorDID = `did:bsv:${obligorPrivateKey.publicKey.toString()}`
24
-
25
- console.log('šŸ“‹ Demo Participants:')
26
- console.log(`Issuer DID: ${issuerDID}`)
27
- console.log(`Owner DID: ${ownerDID}`)
28
- console.log(`Obligor DID: ${obligorDID}\n`)
29
-
30
- /**
31
- * STEP 1: LEGAL CLAIM PREPARATION
32
- * Prepare and validate legal claims using standardized schemas
33
- */
34
- console.log('šŸ“ STEP 1: Legal Claim Preparation')
35
- console.log('----------------------------------')
36
-
37
- // Prepare property ownership claim
38
- const propertyClaimData = {
39
- type: 'PropertyOwnership',
40
- property: {
41
- address: '123 Blockchain Street, Crypto City, CC 12345',
42
- parcel_id: 'BLK-2024-001-DEMO',
43
- property_type: 'residential',
44
- square_footage: 2500,
45
- estimated_value: 750000
46
- },
47
- owner: ownerDID,
48
- acquisition_date: '2024-01-15',
49
- deed_reference: 'DEED-2024-CC-001-DEMO'
50
- }
51
-
52
- // Validate claim against schema
53
- const claimValidation = bsv.prepareClaimValidation(propertyClaimData, 'PropertyOwnership')
54
- console.log('āœ… Property claim validation result:', claimValidation.isValid ? 'VALID' : 'INVALID')
55
- if (!claimValidation.isValid) {
56
- console.log('āŒ Validation errors:', claimValidation.errors || ['Schema validation pending'])
57
- }
58
-
59
- // Prepare claim for attestation
60
- // Use working LTP primitives
61
- const claimHash = bsv.hashClaim(propertyClaimData)
62
- const canonicalClaim = bsv.canonicalizeClaim(propertyClaimData)
63
-
64
- const claimAttestation = {
65
- claimHash: claimHash,
66
- attestor: { role: 'property_registrar', did: issuerDID }
67
- }
68
-
69
- console.log('šŸ“‹ Claim attestation prepared for external processing')
70
- console.log(' Claim Hash:', claimAttestation.claimHash)
71
- console.log(' Attestor:', claimAttestation.attestor.role)
72
- console.log('')
73
-
74
- /**
75
- * STEP 2: RIGHT TOKEN PREPARATION
76
- * Create legal rights tokens based on validated claims
77
- */
78
- console.log('šŸ›ļø STEP 2: Right Token Preparation')
79
- console.log('----------------------------------')
80
-
81
- // Prepare property ownership right token
82
- const rightTokenPreparation = bsv.prepareRightToken(
83
- 'PropertyTitle',
84
- issuerDID,
85
- ownerDID,
86
- propertyClaimData,
87
- issuerPrivateKey,
88
- {
89
- jurisdiction: 'crypto_city',
90
- validUntil: '2034-01-15',
91
- transferable: true,
92
- divisible: false
93
- }
94
- )
95
-
96
- console.log('šŸ  Property ownership right token prepared:')
97
- console.log(' Token ID:', rightTokenPreparation.rightToken ? rightTokenPreparation.rightToken.id : 'Generated')
98
- console.log(' Right Type:', rightTokenPreparation.metadata ? rightTokenPreparation.metadata.type : 'PropertyTitle')
99
- console.log(' Subject:', rightTokenPreparation.metadata ? rightTokenPreparation.metadata.subject : ownerDID)
100
- console.log(' Transferable:', rightTokenPreparation.metadata ? rightTokenPreparation.metadata.transferable : true)
101
- console.log(' Valid Until:', rightTokenPreparation.rightToken ? rightTokenPreparation.rightToken.credentialSubject.validUntil : '2034-01-15')
102
-
103
- // Prepare verification data for the right token
104
- const rightVerification = bsv.prepareRightTokenVerification(rightTokenPreparation.token)
105
- console.log('āœ… Right token verification prepared:', rightVerification.isValid ? 'VALID' : 'INVALID')
106
- console.log('')
107
-
108
- /**
109
- * STEP 3: OBLIGATION TOKEN PREPARATION
110
- * Create legal obligations tied to rights
111
- */
112
- console.log('āš–ļø STEP 3: Obligation Token Preparation')
113
- console.log('-------------------------------------')
114
-
115
- // Prepare mortgage obligation
116
- const mortgageObligationData = {
117
- type: 'mortgage_payment',
118
- principal_amount: 600000,
119
- interest_rate: 0.065,
120
- payment_schedule: 'monthly',
121
- payment_amount: 3582.17,
122
- payments_remaining: 348,
123
- next_payment_date: '2024-11-15',
124
- collateral_reference: rightTokenPreparation.tokenId
125
- }
126
-
127
- const obligationTokenPreparation = bsv.prepareObligationToken(
128
- 'PaymentObligation',
129
- issuerDID,
130
- obligorDID,
131
- mortgageObligationData,
132
- issuerPrivateKey,
133
- {
134
- priority: 'HIGH',
135
- jurisdiction: 'crypto_city',
136
- enforcement_mechanism: 'collateral_seizure',
137
- grace_period_days: 30
138
- }
139
- )
140
-
141
- console.log('šŸ’° Mortgage obligation token prepared:')
142
- console.log(' Obligation ID:', obligationTokenPreparation.obligationToken ? obligationTokenPreparation.obligationToken.id : 'Generated')
143
- console.log(' Obligor:', obligationTokenPreparation.metadata ? obligationTokenPreparation.metadata.obligor : obligorDID)
144
- console.log(' Type:', obligationTokenPreparation.metadata ? obligationTokenPreparation.metadata.type : 'PaymentObligation')
145
- console.log(' Principal Amount:', `$${mortgageObligationData.principal_amount.toLocaleString()}`)
146
- console.log(' Monthly Payment:', `$${mortgageObligationData.payment_amount.toLocaleString()}`)
147
- console.log(' Priority Level:', obligationTokenPreparation.metadata ? obligationTokenPreparation.metadata.priority : 'HIGH')
148
- console.log('')
149
-
150
- /**
151
- * STEP 4: CRYPTOGRAPHIC PROOF PREPARATION
152
- * Generate proofs for privacy and legal validity
153
- */
154
- console.log('šŸ” STEP 4: Cryptographic Proof Preparation')
155
- console.log('-----------------------------------------')
156
-
157
- // Prepare selective disclosure proof (hide sensitive financial data)
158
- const disclosureFields = ['type', 'payment_schedule', 'next_payment_date'] // Hide amounts
159
- // Create a mock token object for demonstration
160
- const mockToken = {
161
- id: 'demo-token-' + Date.now(),
162
- type: ['VerifiableCredential', 'LegalObligationToken'],
163
- credentialSubject: {
164
- id: obligorDID,
165
- type: 'PaymentObligation',
166
- payment_schedule: 'monthly',
167
- next_payment_date: '2024-11-15',
168
- principal_amount: 600000,
169
- interest_rate: 0.067,
170
- payment_amount: 3582.17
171
- }
172
- }
173
-
174
- const selectiveDisclosure = bsv.prepareSelectiveDisclosure(
175
- mockToken,
176
- disclosureFields,
177
- 'demo_nonce_2024'
178
- )
179
-
180
- console.log('šŸŽ­ Selective disclosure proof prepared:')
181
- console.log(' Revealed Fields:', disclosureFields.join(', '))
182
- console.log(' Hidden Fields: principal_amount, interest_rate, payment_amount')
183
- console.log(' Proof Hash:', selectiveDisclosure.proof ? (selectiveDisclosure.proof.merkleRoot || 'Generated Proof Hash') : 'Generated Proof Hash')
184
- console.log(' Revealed Count:', selectiveDisclosure.revealedFieldCount || disclosureFields.length)
185
- console.log(' Hidden Count:', selectiveDisclosure.hiddenFieldCount || 3)
186
-
187
- // Prepare legal validity proof
188
- const mockRightToken = {
189
- id: 'demo-right-token-' + Date.now(),
190
- type: ['VerifiableCredential', 'LegalRightToken'],
191
- credentialSubject: {
192
- id: ownerDID,
193
- rightType: 'PropertyTitle',
194
- jurisdiction: 'crypto_city',
195
- claim: propertyClaimData
196
- }
197
- }
198
-
199
- const legalValidityProof = bsv.prepareLegalValidityProof(
200
- mockRightToken,
201
- {
202
- code: 'crypto_city',
203
- name: 'Crypto City',
204
- requirements: [
205
- { type: 'field_present', field: 'jurisdiction' },
206
- { type: 'field_present', field: 'rightType' },
207
- { type: 'temporal_validity' }
208
- ]
209
- },
210
- 'legal_validity_nonce_2024'
211
- )
212
-
213
- console.log('āš–ļø Legal validity proof prepared:')
214
- console.log(' Jurisdiction:', legalValidityProof.proof ? legalValidityProof.proof.jurisdiction : 'crypto_city')
215
- console.log(' Validity:', legalValidityProof.valid ? 'VALID' : 'PENDING_REVIEW')
216
- console.log(' Compliance Hash:', legalValidityProof.proof ? legalValidityProof.proof.complianceHash : 'Generated')
217
- console.log(' Checks Performed:', legalValidityProof.proof ? legalValidityProof.proof.checks.length : 3)
218
- console.log('')
219
-
220
- /**
221
- * STEP 5: REGISTRY PREPARATION
222
- * Prepare tokens for external registry systems
223
- */
224
- console.log('šŸ“š STEP 5: Registry Management Preparation')
225
- console.log('-----------------------------------------')
226
-
227
- // Prepare registry configuration
228
- const registryConfig = bsv.prepareRegistry({
229
- name: 'Crypto City Property Registry',
230
- jurisdiction: 'crypto_city',
231
- authority: issuerDID,
232
- compliance_framework: 'GDAF_W3C',
233
- storage_type: 'distributed_ledger'
234
- })
235
-
236
- console.log('šŸ›ļø Registry configuration prepared:')
237
- console.log(' Registry Name:', registryConfig.registry ? registryConfig.registry.name : 'Crypto City Property Registry')
238
- console.log(' Authority:', registryConfig.registry ? registryConfig.registry.authority : issuerDID)
239
- console.log(' Jurisdiction:', registryConfig.registry ? registryConfig.registry.jurisdiction : 'crypto_city')
240
- console.log(' Registry ID:', registryConfig.registry ? registryConfig.registry.id : 'Generated')
241
-
242
- // Prepare token registration
243
- const tokenRegistration = bsv.prepareTokenRegistration(
244
- mockRightToken,
245
- registryConfig,
246
- {
247
- category: 'property_rights',
248
- public_visibility: false,
249
- audit_level: 'full'
250
- }
251
- )
252
-
253
- console.log('šŸ“‹ Token registration prepared for external processing:')
254
- console.log(' Registration ID:', tokenRegistration.registrationId || 'Generated')
255
- console.log(' Category:', 'property_rights')
256
- console.log(' Audit Level:', 'full')
257
- console.log('')
258
-
259
- /**
260
- * STEP 6: BLOCKCHAIN ANCHORING PREPARATION
261
- * Prepare tokens for blockchain commitment
262
- */
263
- console.log('ā›“ļø STEP 6: Blockchain Anchoring Preparation')
264
- console.log('------------------------------------------')
265
-
266
- // Prepare individual token commitment
267
- const tokenCommitment = bsv.prepareTokenCommitment(mockRightToken, {
268
- include_metadata: true,
269
- merkle_proof: true,
270
- commitment_type: 'sha256'
271
- })
272
-
273
- console.log('šŸ”— Token commitment prepared for blockchain:')
274
- console.log(' Commitment Hash:', tokenCommitment.commitmentHash || 'Generated SHA256 Hash')
275
- console.log(' Merkle Root:', tokenCommitment.merkleRoot || 'Generated Merkle Root')
276
- console.log(' Commitment Type:', 'sha256')
277
-
278
- // Prepare batch commitment for multiple tokens
279
- const tokenBatch = [mockRightToken, mockToken]
280
- const batchCommitment = bsv.prepareBatchCommitment(tokenBatch, {
281
- batch_size: 2,
282
- include_individual_proofs: true,
283
- optimization: 'gas_efficient'
284
- })
285
-
286
- console.log('šŸ“¦ Batch commitment prepared:')
287
- console.log(' Batch Size:', 2)
288
- console.log(' Batch Root:', batchCommitment.batchRoot || 'Generated Batch Root')
289
- console.log(' Individual Proofs:', 'YES')
290
- console.log('')
291
-
292
- /**
293
- * STEP 7: OBLIGATION LIFECYCLE MANAGEMENT
294
- * Demonstrate obligation fulfillment and monitoring
295
- */
296
- console.log('šŸ“Š STEP 7: Obligation Lifecycle Management')
297
- console.log('-----------------------------------------')
298
-
299
- // Prepare payment fulfillment
300
- const paymentFulfillment = {
301
- payment_amount: 3582.17,
302
- payment_date: '2024-10-15',
303
- payment_method: 'bank_transfer',
304
- transaction_reference: 'TXN-2024-OCT-001',
305
- remaining_balance: 596417.83
306
- }
307
-
308
- const fulfillmentPreparation = bsv.prepareObligationFulfillment(
309
- mockToken,
310
- paymentFulfillment,
311
- obligorPrivateKey,
312
- {
313
- update_schedule: true,
314
- generate_receipt: true,
315
- notify_creditor: true
316
- }
317
- )
318
-
319
- console.log('šŸ’³ Payment fulfillment prepared:')
320
- console.log(' Payment Amount:', `$${paymentFulfillment.payment_amount.toLocaleString()}`)
321
- console.log(' Payment Date:', paymentFulfillment.payment_date)
322
- console.log(' Remaining Balance:', `$${paymentFulfillment.remaining_balance.toLocaleString()}`)
323
- console.log(' Receipt Generated:', fulfillmentPreparation.receiptGenerated ? 'YES' : 'NO')
324
-
325
- // Prepare monitoring report
326
- const monitoringReport = bsv.prepareObligationMonitoringReport(
327
- [obligationTokenPreparation.token],
328
- {
329
- period: '2024-Q3',
330
- include_performance_metrics: true,
331
- risk_assessment: true
332
- }
333
- )
334
-
335
- console.log('šŸ“ˆ Obligation monitoring report prepared:')
336
- console.log(' Monitoring Period:', '2024-Q3')
337
- console.log(' Performance Status:', 'ON_TRACK')
338
- console.log(' Risk Level:', 'LOW')
339
- console.log('')
340
-
341
- /**
342
- * STEP 8: TRANSFER PREPARATION
343
- * Prepare right token transfer to new owner
344
- */
345
- console.log('šŸ”„ STEP 8: Right Token Transfer Preparation')
346
- console.log('------------------------------------------')
347
-
348
- const newOwnerPrivateKey = new bsv.PrivateKey()
349
- const newOwnerDID = `did:bsv:${newOwnerPrivateKey.publicKey.toString()}`
350
-
351
- const transferPreparation = bsv.prepareRightTokenTransfer(
352
- mockRightToken,
353
- newOwnerDID,
354
- ownerPrivateKey,
355
- {
356
- transfer_type: 'sale',
357
- consideration: 750000,
358
- effective_date: '2024-12-01',
359
- include_obligations: true,
360
- clear_title: true
361
- }
362
- )
363
-
364
- console.log('šŸ” Property transfer prepared:')
365
- console.log(' Current Owner:', ownerDID.substring(0, 40) + '...')
366
- console.log(' New Owner:', newOwnerDID.substring(0, 40) + '...')
367
- console.log(' Transfer Type:', 'sale')
368
- console.log(' Consideration:', transferPreparation.consideration ? `$${transferPreparation.consideration.toLocaleString()}` : '$750,000')
369
- console.log(' Effective Date:', transferPreparation.effectiveDate || '2024-12-01')
370
- console.log(' Clear Title:', transferPreparation.clearTitle ? 'YES' : 'NO')
371
- console.log('')
372
-
373
- /**
374
- * SUMMARY: PRIMITIVES-ONLY ARCHITECTURE BENEFITS
375
- */
376
- console.log('šŸŽÆ PRIMITIVES-ONLY ARCHITECTURE SUMMARY')
377
- console.log('=======================================')
378
- console.log('')
379
- console.log('āœ… WHAT THE LIBRARY PROVIDES:')
380
- console.log(' • Complete validation and preparation primitives')
381
- console.log(' • Cryptographic proof generation')
382
- console.log(' • Legal claim schema validation')
383
- console.log(' • Token structure preparation')
384
- console.log(' • Registry data formatting')
385
- console.log(' • Blockchain commitment preparation')
386
- console.log('')
387
- console.log('šŸ”— WHAT EXTERNAL SYSTEMS HANDLE:')
388
- console.log(' • Actual blockchain publishing')
389
- console.log(' • Registry storage and queries')
390
- console.log(' • Network communication')
391
- console.log(' • User interface and workflows')
392
- console.log(' • Application-specific business logic')
393
- console.log('')
394
- console.log('šŸ—ļø ARCHITECTURE BENEFITS:')
395
- console.log(' • Clean separation of concerns')
396
- console.log(' • Maximum flexibility for integrators')
397
- console.log(' • No vendor lock-in to specific platforms')
398
- console.log(' • Comprehensive foundation for any LTP application')
399
- console.log(' • Focus on cryptographic and legal correctness')
400
- console.log('')
401
- console.log('šŸš€ This demonstration shows how SmartLedger-BSV now provides')
402
- console.log(' complete Legal Token Protocol primitives while maintaining')
403
- console.log(' architectural flexibility for diverse implementation needs.')
@@ -1,209 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Message Signing and Verification Demo
5
- * =====================================
6
- *
7
- * Demonstrates BSV message signing and verification capabilities
8
- * using SmartLedger-BSV's message module.
9
- *
10
- * Features demonstrated:
11
- * - Message signing with private keys
12
- * - Signature verification with addresses
13
- * - Bitcoin message format compliance
14
- * - Multi-signature validation
15
- * - Error handling and edge cases
16
- */
17
-
18
- const bsv = require('../index.js');
19
-
20
- console.log('āœļø SmartLedger-BSV Message Signing Demo');
21
- console.log('========================================\n');
22
-
23
- // Demonstrate message signing and verification
24
- async function demonstrateMessageSigning() {
25
- try {
26
- // Generate keypairs for demonstration
27
- console.log('šŸ”‘ Generating keypairs...');
28
- const privateKey = bsv.PrivateKey.fromRandom();
29
- const publicKey = privateKey.publicKey;
30
- const address = privateKey.toAddress();
31
-
32
- console.log('šŸ‘¤ Address:', address.toString());
33
- console.log('šŸ”‘ Private Key (WIF):', privateKey.toWIF());
34
- console.log('šŸ” Public Key:', publicKey.toString());
35
- console.log('');
36
-
37
- // Test 1: Basic message signing
38
- console.log('šŸ“ Test 1: Basic Message Signing');
39
- console.log('--------------------------------');
40
-
41
- const message = 'Hello BSV! This message was signed with SmartLedger-BSV.';
42
- console.log('šŸ“„ Message:', message);
43
-
44
- // Sign the message
45
- const signature = bsv.Message(message).sign(privateKey);
46
- console.log('āœ… Message signed successfully');
47
- console.log('āœļø Signature:', signature);
48
- console.log('šŸ“ Signature length:', signature.length, 'characters');
49
- console.log('');
50
-
51
- // Verify the signature
52
- console.log('šŸ” Verifying signature...');
53
- const isValid = bsv.Message(message).verify(address, signature);
54
- console.log('šŸŽÆ Verification result:', isValid ? 'āœ… VALID' : 'āŒ INVALID');
55
- console.log('');
56
-
57
- // Test 2: Different message types
58
- console.log('šŸ“Š Test 2: Different Message Types');
59
- console.log('---------------------------------');
60
-
61
- const testMessages = [
62
- 'Short message',
63
- 'This is a much longer message that contains multiple words and punctuation marks! Does it still work?',
64
- '{"type":"json","data":{"amount":12345,"address":"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"}}',
65
- 'šŸš€ Unicode message with emojis! šŸ’Ž BSV rocks! šŸ”',
66
- '0123456789abcdef' // Hex-like data
67
- ];
68
-
69
- testMessages.forEach((msg, index) => {
70
- console.log(`šŸ“ Message ${index + 1}:`, msg.substring(0, 50) + (msg.length > 50 ? '...' : ''));
71
-
72
- const sig = bsv.Message(msg).sign(privateKey);
73
- const valid = bsv.Message(msg).verify(address, sig);
74
-
75
- console.log(` āœļø Signature: ${sig.substring(0, 20)}...`);
76
- console.log(` šŸŽÆ Valid: ${valid ? 'āœ…' : 'āŒ'}`);
77
- console.log('');
78
- });
79
-
80
- // Test 3: Multiple addresses verification
81
- console.log('šŸ‘„ Test 3: Multiple Addresses');
82
- console.log('-----------------------------');
83
-
84
- const addresses = [];
85
- const signatures = [];
86
- const testMessage = 'Multi-signature test message for SmartLedger-BSV';
87
-
88
- // Create 3 different keypairs and sign the same message
89
- for (let i = 0; i < 3; i++) {
90
- const key = bsv.PrivateKey.fromRandom();
91
- const addr = key.toAddress();
92
- const sig = bsv.Message(testMessage).sign(key);
93
-
94
- addresses.push(addr);
95
- signatures.push(sig);
96
-
97
- console.log(`šŸ‘¤ Address ${i + 1}: ${addr.toString()}`);
98
- console.log(` āœļø Signature: ${sig.substring(0, 30)}...`);
99
-
100
- // Verify each signature
101
- const valid = bsv.Message(testMessage).verify(addr, sig);
102
- console.log(` šŸŽÆ Valid: ${valid ? 'āœ…' : 'āŒ'}`);
103
- }
104
- console.log('');
105
-
106
- // Test 4: Cross-verification (should fail)
107
- console.log('šŸ”„ Test 4: Cross-Verification (Should Fail)');
108
- console.log('-------------------------------------------');
109
-
110
- // Try to verify signature from address 1 with address 2
111
- const crossValid = bsv.Message(testMessage).verify(addresses[1], signatures[0]);
112
- console.log('šŸŽÆ Cross-verification result:', crossValid ? 'āŒ UNEXPECTED SUCCESS' : 'āœ… CORRECTLY FAILED');
113
- console.log('');
114
-
115
- // Test 5: Modified message verification (should fail)
116
- console.log('šŸ”§ Test 5: Modified Message Verification');
117
- console.log('---------------------------------------');
118
-
119
- const originalMsg = 'Original message for modification test';
120
- const modifiedMsg = 'Modified message for modification test';
121
-
122
- const originalSig = bsv.Message(originalMsg).sign(privateKey);
123
- console.log('šŸ“ Original message:', originalMsg);
124
- console.log('šŸ“ Modified message:', modifiedMsg);
125
-
126
- const originalValid = bsv.Message(originalMsg).verify(address, originalSig);
127
- const modifiedValid = bsv.Message(modifiedMsg).verify(address, originalSig);
128
-
129
- console.log('šŸŽÆ Original verification:', originalValid ? 'āœ… VALID' : 'āŒ INVALID');
130
- console.log('šŸŽÆ Modified verification:', modifiedValid ? 'āŒ UNEXPECTED SUCCESS' : 'āœ… CORRECTLY FAILED');
131
- console.log('');
132
-
133
- // Test 6: Performance benchmarking
134
- console.log('šŸ“Š Test 6: Performance Benchmarking');
135
- console.log('-----------------------------------');
136
-
137
- const iterations = 100;
138
- const benchMessage = 'Performance benchmark message for BSV message signing';
139
-
140
- // Signing benchmark
141
- const signStart = Date.now();
142
- for (let i = 0; i < iterations; i++) {
143
- bsv.Message(benchMessage).sign(privateKey);
144
- }
145
- const signEnd = Date.now();
146
- const signTime = signEnd - signStart;
147
-
148
- // Verification benchmark
149
- const benchSig = bsv.Message(benchMessage).sign(privateKey);
150
- const verifyStart = Date.now();
151
- for (let i = 0; i < iterations; i++) {
152
- bsv.Message(benchMessage).verify(address, benchSig);
153
- }
154
- const verifyEnd = Date.now();
155
- const verifyTime = verifyEnd - verifyStart;
156
-
157
- console.log(`ā±ļø ${iterations} signatures: ${signTime}ms (${(signTime/iterations).toFixed(2)}ms avg)`);
158
- console.log(`šŸš€ Signing rate: ${(iterations*1000/signTime).toFixed(0)} signatures/second`);
159
- console.log(`ā±ļø ${iterations} verifications: ${verifyTime}ms (${(verifyTime/iterations).toFixed(2)}ms avg)`);
160
- console.log(`šŸš€ Verification rate: ${(iterations*1000/verifyTime).toFixed(0)} verifications/second`);
161
- console.log('');
162
-
163
- // Test 7: Message format analysis
164
- console.log('šŸ” Test 7: Message Format Analysis');
165
- console.log('---------------------------------');
166
-
167
- const analysisMsg = 'Format analysis test';
168
- const analysisSig = bsv.Message(analysisMsg).sign(privateKey);
169
-
170
- console.log('šŸ“„ Message:', analysisMsg);
171
- console.log('šŸ“ Message length:', analysisMsg.length, 'characters');
172
- console.log('āœļø Signature:', analysisSig);
173
- console.log('šŸ“ Signature length:', analysisSig.length, 'characters');
174
- console.log('šŸ” Signature format: Base64-encoded Bitcoin message signature');
175
-
176
- // Demonstrate signature components
177
- try {
178
- const sigBuffer = Buffer.from(analysisSig, 'base64');
179
- console.log('šŸ”¢ Signature bytes:', sigBuffer.length);
180
- console.log('šŸŽÆ Recovery flag:', sigBuffer[0]);
181
- console.log('šŸ“Š Signature data:', sigBuffer.slice(1).toString('hex').substring(0, 20) + '...');
182
- } catch (e) {
183
- console.log('ā„¹ļø Signature analysis requires additional parsing');
184
- }
185
-
186
- } catch (error) {
187
- console.error('āŒ Demo error:', error.message);
188
- console.error('šŸ“‹ Stack:', error.stack);
189
- }
190
- }
191
-
192
- // Run the demo
193
- demonstrateMessageSigning().then(() => {
194
- console.log('\nšŸŽ‰ Message Signing Demo completed!');
195
- console.log('');
196
- console.log('šŸ’” Use Cases:');
197
- console.log(' • Identity verification with BSV addresses');
198
- console.log(' • Proof of ownership for digital assets');
199
- console.log(' • Secure authentication without passwords');
200
- console.log(' • Smart contract authorization');
201
- console.log(' • Timestamped message attestation');
202
- console.log(' • Multi-party agreement signatures');
203
- console.log('');
204
- console.log('šŸ”§ Integration Tips:');
205
- console.log(' • Store signatures with messages for later verification');
206
- console.log(' • Use message signing for API authentication');
207
- console.log(' • Combine with timestamps for audit trails');
208
- console.log(' • Integrate with web apps for wallet-based login');
209
- });