@smartledger/bsv 3.1.0 → 3.2.0
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.
- package/CHANGELOG.md +123 -1
- package/README.md +233 -277
- package/bsv.bundle.js +39 -0
- package/bsv.min.js +8 -8
- package/docs/ADVANCED_COVENANT_DEVELOPMENT.md +533 -0
- package/docs/COVENANT_DEVELOPMENT_RESOLVED.md +169 -0
- package/docs/CUSTOM_SCRIPT_DEVELOPMENT.md +320 -0
- package/docs/README.md +201 -0
- package/docs/block.md +46 -0
- package/docs/ecies.md +102 -0
- package/docs/index.md +104 -0
- package/docs/nchain.md +958 -0
- package/docs/networks.md +55 -0
- package/docs/preimage.md +126 -0
- package/docs/script.md +139 -0
- package/docs/transaction.md +174 -0
- package/docs/unspentoutput.md +32 -0
- package/examples/README.md +200 -0
- package/examples/basic/transaction-creation.js +534 -0
- package/examples/basic/transaction_signature_api_gap.js +178 -0
- package/examples/covenants/advanced_covenant_demo.js +219 -0
- package/examples/covenants/covenant_interface_demo.js +270 -0
- package/examples/covenants/covenant_manual_signature_resolved.js +212 -0
- package/examples/covenants/covenant_signature_template.js +117 -0
- package/examples/covenants2/covenant_bidirectional_example.js +262 -0
- package/examples/covenants2/covenant_utils_demo.js +120 -0
- package/examples/covenants2/preimage_covenant_utils.js +287 -0
- package/examples/covenants2/production_integration.js +256 -0
- package/examples/data/covenant_utxos.json +28 -0
- package/examples/data/utxos.json +26 -0
- package/examples/preimage/README.md +178 -0
- package/examples/preimage/extract_preimage_bidirectional.js +421 -0
- package/examples/preimage/generate_sample_preimage.js +208 -0
- package/examples/preimage/generate_sighash_examples.js +152 -0
- package/examples/preimage/parse_preimage.js +117 -0
- package/examples/preimage/test_preimage_extractor.js +53 -0
- package/examples/preimage/test_varint_extraction.js +95 -0
- package/examples/scripts/custom_script_helper_example.js +273 -0
- package/examples/scripts/custom_script_signature_test.js +344 -0
- package/examples/scripts/script_interpreter.js +193 -0
- package/examples/smart_contract/complete_workflow_demo.js +343 -0
- package/examples/smart_contract/covenant_builder_demo.js +176 -0
- package/examples/smart_contract/script_testing_integration.js +198 -0
- package/index.js +3 -0
- package/lib/covenant-interface.js +713 -0
- package/lib/opcode.js +14 -7
- package/lib/smart_contract/API_REFERENCE.md +754 -0
- package/lib/smart_contract/DOCUMENTATION_SUMMARY.md +201 -0
- package/lib/smart_contract/EXAMPLES.md +751 -0
- package/lib/smart_contract/QUICK_START.md +549 -0
- package/lib/smart_contract/README.md +395 -0
- package/lib/smart_contract/builder.js +452 -0
- package/lib/smart_contract/covenant.js +336 -0
- package/lib/smart_contract/covenant_builder.js +512 -0
- package/lib/smart_contract/index.js +311 -0
- package/lib/smart_contract/opcode_list.js +30 -0
- package/lib/smart_contract/opcode_map.js +1174 -0
- package/lib/smart_contract/opcodes.md +1173 -0
- package/lib/smart_contract/preimage.js +903 -0
- package/lib/smart_contract/script_tester.js +487 -0
- package/lib/smart_contract/script_utils.js +609 -0
- package/lib/smart_contract/sighash.js +310 -0
- package/lib/smart_contract/smartledger-opcode_review.md +70 -0
- package/lib/smart_contract/test_integration.js +269 -0
- package/lib/smart_contract/utxo_generator.js +367 -0
- package/package.json +43 -10
- package/utilities/blockchain-state.json +20478 -3
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
# SmartContract Module Documentation
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
The SmartContract module provides enterprise-grade covenant functionality for Bitcoin SV, integrating enhanced BIP-143 preimage parsing, SIGHASH flag detection, and production-ready covenant workflows.
|
|
6
|
+
|
|
7
|
+
## Installation & Usage
|
|
8
|
+
|
|
9
|
+
```javascript
|
|
10
|
+
const bsv = require('bsv-elliptic-fix')
|
|
11
|
+
|
|
12
|
+
// Access SmartContract module
|
|
13
|
+
const SmartContract = bsv.SmartContract
|
|
14
|
+
|
|
15
|
+
// Quick covenant creation
|
|
16
|
+
const privateKey = bsv.PrivateKey.fromRandom()
|
|
17
|
+
const covenant = SmartContract.createCovenant(privateKey)
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Core Classes
|
|
21
|
+
|
|
22
|
+
### 1. SmartContract.Covenant
|
|
23
|
+
|
|
24
|
+
Production-ready covenant management with complete P2PKH → Covenant → Spending workflow.
|
|
25
|
+
|
|
26
|
+
**Features:**
|
|
27
|
+
- Local UTXO storage and portfolio management
|
|
28
|
+
- WhatsOnChain API integration ready
|
|
29
|
+
- BIP-143 preimage validation
|
|
30
|
+
- Script.Interpreter compliance
|
|
31
|
+
|
|
32
|
+
**Basic Usage:**
|
|
33
|
+
```javascript
|
|
34
|
+
const covenant = new SmartContract.Covenant(privateKey, {
|
|
35
|
+
storageDir: './my-covenants'
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
// Create covenant from P2PKH UTXO
|
|
39
|
+
const result = covenant.createFromP2PKH({
|
|
40
|
+
txid: 'abc123...',
|
|
41
|
+
vout: 0,
|
|
42
|
+
satoshis: 100000,
|
|
43
|
+
script: 'p2pkh_script_hex'
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
// Save covenant UTXO
|
|
47
|
+
covenant.save(result.covenantUtxo)
|
|
48
|
+
|
|
49
|
+
// Create spending transaction
|
|
50
|
+
const spendingTx = covenant.createSpendingTx(result.covenantUtxo)
|
|
51
|
+
|
|
52
|
+
// Validate spending
|
|
53
|
+
const validation = covenant.validate(spendingTx, result.covenantUtxo)
|
|
54
|
+
console.log('Valid:', validation.valid)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Complete Workflow:**
|
|
58
|
+
```javascript
|
|
59
|
+
// One-shot covenant flow
|
|
60
|
+
const flow = covenant.completeFlow(p2pkhUtxo, function(tx, phase) {
|
|
61
|
+
console.log(`${phase} transaction:`, tx.toString())
|
|
62
|
+
// Optional: broadcast transaction
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
console.log('Flow success:', flow.success)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 2. SmartContract.Preimage
|
|
69
|
+
|
|
70
|
+
Enhanced BIP-143 preimage utilities with CompactSize varint support and bidirectional extraction.
|
|
71
|
+
|
|
72
|
+
**Features:**
|
|
73
|
+
- Complete CompactSize varint support (1-3 bytes)
|
|
74
|
+
- SIGHASH flag detection and zero hash warnings
|
|
75
|
+
- Bidirectional field extraction (LEFT/RIGHT/DYNAMIC)
|
|
76
|
+
- Multi-input transaction handling
|
|
77
|
+
|
|
78
|
+
**Basic Usage:**
|
|
79
|
+
```javascript
|
|
80
|
+
const preimage = new SmartContract.Preimage(preimageHex, {
|
|
81
|
+
strategy: 'DYNAMIC' // AUTO-DETECT best extraction method
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
const fields = preimage.extract()
|
|
85
|
+
console.log('Script code:', fields.scriptCode.toString('hex'))
|
|
86
|
+
console.log('Amount:', fields.amount.toString('hex'))
|
|
87
|
+
|
|
88
|
+
// Get SIGHASH analysis
|
|
89
|
+
const sighashInfo = preimage.getSighashInfo()
|
|
90
|
+
if (sighashInfo.hasZeroHashes) {
|
|
91
|
+
console.log('Zero hash warnings:', sighashInfo.warnings)
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
**The "Zero Hash Mystery" Explained:**
|
|
96
|
+
```javascript
|
|
97
|
+
// Why do I see zero hashes in my preimage?
|
|
98
|
+
const explanation = SmartContract.explainZeroHashes()
|
|
99
|
+
console.log(explanation.title)
|
|
100
|
+
console.log('Reality:', explanation.reality)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
**CompactSize Varint Decoding:**
|
|
104
|
+
```javascript
|
|
105
|
+
// Decode script length varint (handles 1-3 bytes)
|
|
106
|
+
const result = SmartContract.Preimage.decodeCompactSize(buffer, offset)
|
|
107
|
+
console.log('Script length:', result.value)
|
|
108
|
+
console.log('Next offset:', result.nextOffset)
|
|
109
|
+
console.log('Varint bytes used:', result.bytes)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### 3. SmartContract.SIGHASH
|
|
113
|
+
|
|
114
|
+
SIGHASH flag utilities with comprehensive flag analysis and zero hash behavior explanation.
|
|
115
|
+
|
|
116
|
+
**Features:**
|
|
117
|
+
- Complete flag analysis and detection
|
|
118
|
+
- Zero hash behavior explanation
|
|
119
|
+
- Multi-input transaction examples
|
|
120
|
+
- BIP-143 compliance verification
|
|
121
|
+
|
|
122
|
+
**Basic Usage:**
|
|
123
|
+
```javascript
|
|
124
|
+
const sighash = new SmartContract.SIGHASH(0x41) // SIGHASH_ALL | FORKID
|
|
125
|
+
const analysis = sighash.analyze()
|
|
126
|
+
console.log('Flag name:', analysis.flagName)
|
|
127
|
+
console.log('Has ANYONECANPAY:', analysis.anyoneCanPay)
|
|
128
|
+
|
|
129
|
+
// Understand zero hash behavior
|
|
130
|
+
const behavior = sighash.getZeroHashBehavior()
|
|
131
|
+
console.log('Will hashPrevouts be zero?', behavior.hashPrevouts)
|
|
132
|
+
console.log('Explanation:', behavior.explanation)
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
**Generate Educational Examples:**
|
|
136
|
+
```javascript
|
|
137
|
+
// Create example demonstrating SIGHASH behavior
|
|
138
|
+
const example = sighash.generateExample()
|
|
139
|
+
console.log('Transaction:', example.transaction.toString())
|
|
140
|
+
console.log('Preimage fields:', example.fields)
|
|
141
|
+
console.log('Zero hash behavior:', example.zeroHashBehavior)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
**All SIGHASH Types:**
|
|
145
|
+
```javascript
|
|
146
|
+
const allTypes = SmartContract.getAllSIGHASHTypes()
|
|
147
|
+
allTypes.forEach(type => {
|
|
148
|
+
console.log(`${type.name}: 0x${type.value.toString(16)}`)
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
// Generate demonstrations for all types
|
|
152
|
+
const demonstrations = SmartContract.demonstrateAllSIGHASH()
|
|
153
|
+
demonstrations.forEach(demo => {
|
|
154
|
+
console.log(`${demo.typeName}:`, demo.demonstration.observations)
|
|
155
|
+
})
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### 4. SmartContract.Builder
|
|
159
|
+
|
|
160
|
+
Advanced covenant builder with multi-field validation and dynamic script construction.
|
|
161
|
+
|
|
162
|
+
**Features:**
|
|
163
|
+
- Multi-field preimage validation
|
|
164
|
+
- Dynamic script construction
|
|
165
|
+
- Template-based covenant creation
|
|
166
|
+
- Complex condition chaining
|
|
167
|
+
|
|
168
|
+
**Basic Usage:**
|
|
169
|
+
```javascript
|
|
170
|
+
const builder = new SmartContract.Builder(privateKey)
|
|
171
|
+
|
|
172
|
+
// Add field validation rules
|
|
173
|
+
builder
|
|
174
|
+
.validateField('hashPrevouts', 'ORIGINAL_hashPrevouts', {
|
|
175
|
+
operator: 'EQUAL',
|
|
176
|
+
description: 'Ensure same input set'
|
|
177
|
+
})
|
|
178
|
+
.validateField('amount', minimumAmount, {
|
|
179
|
+
operator: 'NOT_EQUAL',
|
|
180
|
+
description: 'Prevent amount reduction'
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
// Create covenant
|
|
184
|
+
const result = builder.createCovenant(p2pkhUtxo)
|
|
185
|
+
console.log('Covenant created:', result.covenantUtxo.txid)
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
**Template-Based Creation:**
|
|
189
|
+
```javascript
|
|
190
|
+
// Hash-lock covenant
|
|
191
|
+
const hashLock = SmartContract.createHashLockCovenant(
|
|
192
|
+
privateKey,
|
|
193
|
+
expectedPreimageHash
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
// Multi-field validation covenant
|
|
197
|
+
const multiField = SmartContract.createMultiFieldCovenant(privateKey, [
|
|
198
|
+
{ field: 'hashPrevouts', expectedValue: 'ORIGINAL_hashPrevouts' },
|
|
199
|
+
{ field: 'amount', expectedValue: minimumAmount, operator: 'NOT_EQUAL' }
|
|
200
|
+
])
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## Convenience Methods
|
|
204
|
+
|
|
205
|
+
### Quick Access Functions
|
|
206
|
+
|
|
207
|
+
```javascript
|
|
208
|
+
// Create covenant instance
|
|
209
|
+
const covenant = SmartContract.createCovenant(privateKey, options)
|
|
210
|
+
|
|
211
|
+
// Extract preimage fields
|
|
212
|
+
const preimage = SmartContract.extractPreimage(preimageHex)
|
|
213
|
+
|
|
214
|
+
// Analyze SIGHASH flags
|
|
215
|
+
const analysis = SmartContract.analyzeSIGHASH(sighashType)
|
|
216
|
+
|
|
217
|
+
// Build advanced covenant
|
|
218
|
+
const builder = SmartContract.buildCovenant(privateKey, options)
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### Educational Resources
|
|
222
|
+
|
|
223
|
+
```javascript
|
|
224
|
+
// Get all educational materials
|
|
225
|
+
const resources = SmartContract.getEducationalResources()
|
|
226
|
+
console.log('Zero hash mystery:', resources.zeroHashMystery)
|
|
227
|
+
console.log('All SIGHASH types:', resources.sighashTypes)
|
|
228
|
+
console.log('Example demonstrations:', resources.exampleDemonstrations)
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
## Production Integration
|
|
232
|
+
|
|
233
|
+
### Complete Covenant Workflow
|
|
234
|
+
|
|
235
|
+
```javascript
|
|
236
|
+
// Production-ready covenant flow with broadcasting
|
|
237
|
+
const result = SmartContract.completeCovenantFlow(
|
|
238
|
+
privateKey,
|
|
239
|
+
p2pkhUtxo,
|
|
240
|
+
function(transaction, phase) {
|
|
241
|
+
console.log(`Broadcasting ${phase} transaction...`)
|
|
242
|
+
|
|
243
|
+
// Your broadcast logic here
|
|
244
|
+
// return broadcastTransaction(transaction)
|
|
245
|
+
}
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
if (result.success) {
|
|
249
|
+
console.log('Covenant flow completed successfully')
|
|
250
|
+
console.log('Creation TX:', result.creationTx.id)
|
|
251
|
+
console.log('Spending TX:', result.spendingTx.id)
|
|
252
|
+
} else {
|
|
253
|
+
console.log('Validation errors:', result.validation.errors)
|
|
254
|
+
}
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
### Portfolio Management
|
|
258
|
+
|
|
259
|
+
```javascript
|
|
260
|
+
const covenant = new SmartContract.Covenant(privateKey)
|
|
261
|
+
|
|
262
|
+
// Get portfolio overview
|
|
263
|
+
const portfolio = covenant.getPortfolio()
|
|
264
|
+
console.log('Total covenants:', portfolio.total)
|
|
265
|
+
console.log('Total value:', portfolio.totalValue, 'satoshis')
|
|
266
|
+
console.log('By status:', portfolio.byStatus)
|
|
267
|
+
console.log('Recent:', portfolio.recent)
|
|
268
|
+
|
|
269
|
+
// List all stored covenants
|
|
270
|
+
const allCovenants = covenant.list()
|
|
271
|
+
allCovenants.forEach(cov => {
|
|
272
|
+
console.log(`${cov.txid}: ${cov.satoshis} sats (${cov.status})`)
|
|
273
|
+
})
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
## Error Handling & Validation
|
|
277
|
+
|
|
278
|
+
### Preimage Validation
|
|
279
|
+
|
|
280
|
+
```javascript
|
|
281
|
+
const preimage = new SmartContract.Preimage(preimageHex)
|
|
282
|
+
const validation = preimage.validate()
|
|
283
|
+
|
|
284
|
+
if (!validation.valid) {
|
|
285
|
+
console.log('Preimage errors:', validation.errors)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (validation.warnings.length > 0) {
|
|
289
|
+
console.log('Preimage warnings:', validation.warnings)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
console.log('SIGHASH info:', validation.sighashInfo)
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
### Covenant Validation
|
|
296
|
+
|
|
297
|
+
```javascript
|
|
298
|
+
const validation = covenant.validate(spendingTx, covenantUtxo)
|
|
299
|
+
|
|
300
|
+
if (!validation.valid) {
|
|
301
|
+
console.log('Validation failed:', validation.error)
|
|
302
|
+
} else {
|
|
303
|
+
console.log('Covenant spending is valid!')
|
|
304
|
+
}
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
### Builder Validation
|
|
308
|
+
|
|
309
|
+
```javascript
|
|
310
|
+
const builder = new SmartContract.Builder(privateKey)
|
|
311
|
+
// ... configure builder ...
|
|
312
|
+
|
|
313
|
+
const spendingValidation = builder.validateSpending(spendingTx, covenantUtxo)
|
|
314
|
+
|
|
315
|
+
console.log('Spending valid:', spendingValidation.valid)
|
|
316
|
+
console.log('Field validations:', spendingValidation.fieldValidations)
|
|
317
|
+
console.log('Errors:', spendingValidation.errors)
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
## Advanced Features
|
|
321
|
+
|
|
322
|
+
### Bidirectional Preimage Extraction
|
|
323
|
+
|
|
324
|
+
```javascript
|
|
325
|
+
// Try different extraction strategies
|
|
326
|
+
const preimage = new SmartContract.Preimage(preimageHex)
|
|
327
|
+
|
|
328
|
+
// LEFT-to-RIGHT (standard)
|
|
329
|
+
const leftFields = preimage.extract('LEFT')
|
|
330
|
+
|
|
331
|
+
// RIGHT-to-LEFT (fallback for malformed preimages)
|
|
332
|
+
const rightFields = preimage.extract('RIGHT')
|
|
333
|
+
|
|
334
|
+
// DYNAMIC (auto-detect best strategy)
|
|
335
|
+
const dynamicFields = preimage.extract('DYNAMIC')
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
### Custom Validation Rules
|
|
339
|
+
|
|
340
|
+
```javascript
|
|
341
|
+
const builder = new SmartContract.Builder(privateKey)
|
|
342
|
+
|
|
343
|
+
// Add custom validation logic
|
|
344
|
+
builder.addCondition(function(spendingTx, covenantUtxo) {
|
|
345
|
+
// Custom validation logic
|
|
346
|
+
const outputSum = spendingTx.outputs.reduce((sum, out) => sum + out.satoshis, 0)
|
|
347
|
+
return outputSum >= covenantUtxo.satoshis * 0.9 // Allow max 10% fee
|
|
348
|
+
}, {
|
|
349
|
+
description: 'Ensure reasonable fee limits'
|
|
350
|
+
})
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
### SIGHASH Compliance Checking
|
|
354
|
+
|
|
355
|
+
```javascript
|
|
356
|
+
const sighash = new SmartContract.SIGHASH(sighashType)
|
|
357
|
+
const compliance = sighash.checkCompliance(preimage)
|
|
358
|
+
|
|
359
|
+
if (!compliance.compliant) {
|
|
360
|
+
console.log('BIP-143 compliance issues:', compliance.issues)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (compliance.unexpectedZeros.length > 0) {
|
|
364
|
+
console.log('Unexpected zero hashes:', compliance.unexpectedZeros)
|
|
365
|
+
}
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
## Module Features
|
|
369
|
+
|
|
370
|
+
- **BIP-143 Preimage Parsing**: Complete support with CompactSize varint handling
|
|
371
|
+
- **SIGHASH Detection**: Automatic flag analysis and zero hash warnings
|
|
372
|
+
- **Bidirectional Extraction**: Multiple strategies for robust field parsing
|
|
373
|
+
- **Production Ready**: Enterprise-grade covenant infrastructure
|
|
374
|
+
- **Educational Tools**: Comprehensive explanations of Bitcoin protocol details
|
|
375
|
+
- **Zero Hash Warnings**: Explains the "extra zero mystery" that confuses developers
|
|
376
|
+
- **Multi-Field Validation**: Advanced covenant condition checking
|
|
377
|
+
|
|
378
|
+
## Compatibility
|
|
379
|
+
|
|
380
|
+
- **Node.js**: Full functionality including file system storage
|
|
381
|
+
- **Browser**: Core functionality (storage features require adaptation)
|
|
382
|
+
- **Bitcoin SV**: Full BIP-143 compliance with FORKID support
|
|
383
|
+
- **Network Ready**: WhatsOnChain API integration prepared
|
|
384
|
+
|
|
385
|
+
## Version Information
|
|
386
|
+
|
|
387
|
+
```javascript
|
|
388
|
+
console.log('SmartContract version:', SmartContract.version)
|
|
389
|
+
console.log('Description:', SmartContract.description)
|
|
390
|
+
console.log('Features:', SmartContract.features)
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
## Support
|
|
394
|
+
|
|
395
|
+
The SmartContract module is based on extensive research and production testing in the SmartLedger-BSV ecosystem. It addresses real-world Bitcoin protocol edge cases and provides enterprise-grade tooling for advanced Bitcoin SV applications.
|