@dignetwork/chia-block-listener 0.1.6 → 0.1.7

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.
@@ -53,19 +53,20 @@ jobs:
53
53
  settings:
54
54
  - host: macos-latest
55
55
  target: x86_64-apple-darwin
56
- build: npm run build -- --target x86_64-apple-darwin
56
+ build: npm run build -- --target x86_64-apple-darwin && node scripts/post-build.js
57
57
  - host: windows-latest
58
- build: npm run build -- --target x86_64-pc-windows-msvc
58
+ build: npm run build -- --target x86_64-pc-windows-msvc && node scripts/post-build.js
59
59
  target: x86_64-pc-windows-msvc
60
60
  - host: ubuntu-latest
61
61
  target: x86_64-unknown-linux-gnu
62
62
  build: |
63
63
  set -e &&
64
64
  npm run build -- --target x86_64-unknown-linux-gnu &&
65
+ node scripts/post-build.js &&
65
66
  strip *.node
66
67
  - host: macos-latest
67
68
  target: aarch64-apple-darwin
68
- build: npm run build -- --target aarch64-apple-darwin
69
+ build: npm run build -- --target aarch64-apple-darwin && node scripts/post-build.js
69
70
  - host: ubuntu-latest
70
71
  target: aarch64-unknown-linux-gnu
71
72
  setup: |
@@ -74,7 +75,8 @@ jobs:
74
75
  build: |
75
76
  set -e &&
76
77
  export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc &&
77
- npm run build -- --target aarch64-unknown-linux-gnu
78
+ npm run build -- --target aarch64-unknown-linux-gnu &&
79
+ node scripts/post-build.js
78
80
  name: stable - ${{ matrix.settings.target }} - node@22
79
81
  runs-on: ${{ matrix.settings.host }}
80
82
  steps:
package/README.md CHANGED
@@ -1,22 +1,17 @@
1
- # Proof of Work
1
+ # Chia Block Listener
2
2
 
3
- A high-performance Bitcoin-compatible proof of work library for Node.js, built with Rust and NAPI bindings. This library provides efficient mining capabilities using Bitcoin's target-based difficulty system with double SHA-256 hashing.
3
+ A high-performance Chia blockchain listener for Node.js, built with Rust and NAPI bindings. This library provides real-time monitoring of the Chia blockchain with efficient peer connections and block parsing capabilities.
4
4
 
5
5
  ## Features
6
6
 
7
- - **Bitcoin-Compatible**: Uses Bitcoin's target-based difficulty system with double SHA-256 hashing
8
- - **High Performance**: Written in Rust for maximum mining efficiency
9
- - **Asynchronous Mining**: Non-blocking proof of work computation that won't freeze your application
10
- - **Cancellable Operations**: Start mining with ability to cancel anytime using handles
11
- - **Progress Tracking**: Real-time progress monitoring with attempt counts and timing
12
- - **Unlimited Attempts**: Mine until solution is found (unless explicitly limited)
13
- - **Nonce Verification**: Verify that a nonce meets difficulty requirements
14
- - **Standardized Verification**: Consensus-critical verification with algorithm version validation
15
- - **Difficulty Analysis**: Calculate difficulty levels from hash values
16
- - **Security Features**: Tamper-resistant verification with algorithm immutability
17
- - **Cross-platform Support**: Builds for Windows, macOS, and Linux
18
- - **Multiple Architectures**: Supports x64 and ARM64 architectures
19
- - **TypeScript Support**: Full TypeScript definitions included
7
+ - **Real-time Block Monitoring**: Listen for new blocks as they're produced on the Chia network
8
+ - **Peer Management**: Connect to multiple Chia full nodes simultaneously
9
+ - **Efficient Parsing**: Fast extraction of coin spends, additions, and removals from blocks
10
+ - **Event-Driven Architecture**: TypeScript-friendly event system with full type safety
11
+ - **Transaction Analysis**: Parse CLVM puzzles and solutions from coin spends
12
+ - **Historical Block Access**: Retrieve blocks by height or ranges
13
+ - **Cross-platform Support**: Works on Windows, macOS, and Linux (x64 and ARM64)
14
+ - **TypeScript Support**: Complete TypeScript definitions with IntelliSense
20
15
 
21
16
  ## Installation
22
17
 
@@ -27,311 +22,350 @@ npm install @dignetwork/chia-block-listener
27
22
  ## Quick Start
28
23
 
29
24
  ```javascript
30
- const { computeProofOfWorkAsync } = require('@dignetwork/chia-block-listener')
31
-
32
- async function mine() {
33
- const entropySeed = Buffer.from('my_plot_entropy_seed', 'utf-8')
34
- const difficulty = 1.0 // Bitcoin difficulty (1.0 = easiest)
35
-
36
- // Start mining (returns immediately with a handle)
37
- const handle = computeProofOfWorkAsync(entropySeed, difficulty)
38
-
39
- // Set up Ctrl+C handling for cancellation
40
- process.on('SIGINT', () => {
41
- console.log('\nCancelling mining...')
42
- handle.cancel()
43
- process.exit(0)
44
- })
45
-
46
- // Wait for completion
47
- while (!handle.isCompleted() && !handle.hasError()) {
48
- console.log(`Mining... attempts: ${handle.getAttempts()}`)
49
- await new Promise(resolve => setTimeout(resolve, 1000))
25
+ const { ChiaBlockListener, initTracing } = require('@dignetwork/chia-block-listener')
26
+
27
+ // Initialize tracing for debugging (optional)
28
+ initTracing()
29
+
30
+ // Create a new listener instance
31
+ const listener = new ChiaBlockListener()
32
+
33
+ // Listen for block events
34
+ listener.on('blockReceived', (block) => {
35
+ console.log(`New block received: ${block.height}`)
36
+ console.log(`Header hash: ${block.headerHash}`)
37
+ console.log(`Timestamp: ${new Date(block.timestamp * 1000)}`)
38
+ console.log(`Coin additions: ${block.coinAdditions.length}`)
39
+ console.log(`Coin removals: ${block.coinRemovals.length}`)
40
+ console.log(`Coin spends: ${block.coinSpends.length}`)
41
+ })
42
+
43
+ // Listen for peer connection events
44
+ listener.on('peerConnected', (peer) => {
45
+ console.log(`Connected to peer: ${peer.peerId} (${peer.host}:${peer.port})`)
46
+ })
47
+
48
+ listener.on('peerDisconnected', (peer) => {
49
+ console.log(`Disconnected from peer: ${peer.peerId}`)
50
+ if (peer.message) {
51
+ console.log(`Reason: ${peer.message}`)
50
52
  }
51
-
52
- if (handle.hasError()) {
53
- console.log('Mining failed:', handle.getError())
54
- } else {
55
- const result = handle.getResult()
56
- console.log('Solution found!')
57
- console.log('Nonce:', result.nonce)
58
- console.log('Hash:', result.hash)
59
- console.log('Attempts:', result.attempts)
60
- console.log('Time:', result.time_ms, 'ms')
61
- }
62
- }
63
-
64
- mine().catch(console.error)
53
+ })
54
+
55
+ // Connect to a Chia full node
56
+ const peerId = listener.addPeer('localhost', 8444, 'mainnet')
57
+ console.log(`Added peer: ${peerId}`)
58
+
59
+ // Keep the process running
60
+ process.on('SIGINT', () => {
61
+ console.log('Shutting down...')
62
+ listener.disconnectAllPeers()
63
+ process.exit(0)
64
+ })
65
65
  ```
66
66
 
67
67
  ## API Reference
68
68
 
69
- ### Main Functions
69
+ ### ChiaBlockListener Class
70
70
 
71
- #### `computeProofOfWorkAsync(entropySeed, difficulty, maxAttempts?, logAttempts?, doubleSha?): ProofOfWorkHandle`
71
+ #### Constructor
72
72
 
73
- Computes proof of work asynchronously using Bitcoin's target-based difficulty system. Returns immediately with a handle for cancellation and progress tracking.
73
+ ```javascript
74
+ const listener = new ChiaBlockListener()
75
+ ```
74
76
 
75
- **Parameters:**
76
- - `entropySeed` (Buffer): The entropy seed (plotId) to bind the work to
77
- - `difficulty` (number): Bitcoin-style difficulty level (1.0 = easiest, higher = harder)
78
- - `maxAttempts` (number, optional): Maximum attempts before giving up (default: unlimited)
79
- - `logAttempts` (boolean, optional): Whether to log each hash attempt (default: false)
80
- - `doubleSha` (boolean, optional): Whether to use double SHA-256 like Bitcoin (default: true)
77
+ Creates a new Chia block listener instance.
81
78
 
82
- **Returns:** `ProofOfWorkHandle` for cancellation and progress tracking
79
+ #### Methods
83
80
 
84
- #### `verifyProofOfWork(entropySeed, nonce, difficulty, doubleSha?): boolean`
81
+ ##### `addPeer(host, port, networkId): string`
85
82
 
86
- Verifies that a nonce produces a hash that meets the Bitcoin difficulty target.
83
+ Connects to a Chia full node and starts listening for blocks.
87
84
 
88
85
  **Parameters:**
89
- - `entropySeed` (Buffer): The entropy seed that was used
90
- - `nonce` (number): The nonce to verify
91
- - `difficulty` (number): The required difficulty level
92
- - `doubleSha` (boolean, optional): Whether to use double SHA-256 (default: true)
86
+ - `host` (string): The hostname or IP address of the Chia node
87
+ - `port` (number): The port number (typically 8444 for mainnet)
88
+ - `networkId` (string): The network identifier ('mainnet', 'testnet', etc.)
93
89
 
94
- **Returns:** `true` if the nonce is valid for the given difficulty
90
+ **Returns:** A unique peer ID string for this connection
95
91
 
96
- #### `verifyProofOfWorkStandardized(entropySeed, nonce, difficulty, expectedVersion?, doubleSha?): boolean`
92
+ ##### `disconnectPeer(peerId): boolean`
97
93
 
98
- **CONSENSUS CRITICAL:** Standardized verification with algorithm validation. This function verifies both the proof of work AND the algorithm compatibility.
94
+ Disconnects from a specific peer.
99
95
 
100
96
  **Parameters:**
101
- - `entropySeed` (Buffer): The entropy seed that was used
102
- - `nonce` (number): The nonce to verify
103
- - `difficulty` (number): The required difficulty level
104
- - `expectedVersion` (number, optional): Expected algorithm version (default: current)
105
- - `doubleSha` (boolean, optional): Whether to use double SHA-256 (default: true)
97
+ - `peerId` (string): The peer ID returned by `addPeer()`
106
98
 
107
- **Returns:** `true` if the nonce is valid AND algorithm is correct
99
+ **Returns:** `true` if the peer was successfully disconnected, `false` otherwise
108
100
 
109
- **Security Note:** Use this function for network consensus validation. It validates algorithm version compatibility and prevents tampering.
101
+ ##### `disconnectAllPeers(): void`
110
102
 
111
- ### Utility Functions
103
+ Disconnects from all connected peers.
112
104
 
113
- #### `difficultyToTargetHex(difficulty): string`
105
+ ##### `getConnectedPeers(): string[]`
114
106
 
115
- Convert a Bitcoin-style difficulty to the corresponding target value as hex.
107
+ Returns an array of currently connected peer IDs.
116
108
 
117
- **Parameters:**
118
- - `difficulty` (number): The difficulty level
109
+ ##### `getBlockByHeight(peerId, height): BlockReceivedEvent`
119
110
 
120
- **Returns:** The target as a hex string
111
+ Retrieves a specific block by its height from a connected peer.
121
112
 
122
- #### `hashToDifficulty(hash): number`
113
+ **Parameters:**
114
+ - `peerId` (string): The peer ID to query
115
+ - `height` (number): The block height to retrieve
123
116
 
124
- Calculate the difficulty that a given hash would satisfy.
117
+ **Returns:** A `BlockReceivedEvent` object containing the block data
125
118
 
126
- **Parameters:**
127
- - `hash` (Buffer): The hash to analyze (32 bytes)
119
+ ##### `getBlocksRange(peerId, startHeight, endHeight): BlockReceivedEvent[]`
128
120
 
129
- **Returns:** The difficulty level this hash would satisfy
121
+ Retrieves a range of blocks from a connected peer.
130
122
 
131
- ### Consensus & Security Functions
123
+ **Parameters:**
124
+ - `peerId` (string): The peer ID to query
125
+ - `startHeight` (number): The starting block height (inclusive)
126
+ - `endHeight` (number): The ending block height (inclusive)
132
127
 
133
- #### `getAlgorithmVersion(): number`
128
+ **Returns:** An array of `BlockReceivedEvent` objects
134
129
 
135
- Get the current difficulty algorithm version. This version number is part of the network consensus.
130
+ ### Events
136
131
 
137
- **Returns:** The algorithm version number
132
+ The `ChiaBlockListener` emits the following events:
138
133
 
139
- #### `getAlgorithmSpec(): string`
134
+ #### `blockReceived`
140
135
 
141
- Get the algorithm specification hash. This hash identifies the exact algorithm implementation.
136
+ Fired when a new block is received from any connected peer.
142
137
 
143
- **Returns:** The algorithm specification identifier
138
+ **Callback:** `(event: BlockReceivedEvent) => void`
144
139
 
145
- #### `getAlgorithmParameters(): AlgorithmParameters`
140
+ #### `peerConnected`
146
141
 
147
- Get the standardized difficulty algorithm parameters. These parameters are part of the network consensus.
142
+ Fired when a connection to a peer is established.
148
143
 
149
- **Returns:** Algorithm parameters object containing:
150
- - `version` (number): Algorithm version number
151
- - `specHash` (string): Algorithm specification hash
152
- - `baseZeroBits` (number): Base number of zero bits for difficulty 1.0
153
- - `logMultiplier` (number): Logarithmic multiplier for difficulty scaling
154
- - `maxZeroBits` (number): Maximum allowed zero bits
144
+ **Callback:** `(event: PeerConnectedEvent) => void`
155
145
 
156
- ### ProofOfWorkHandle Methods
146
+ #### `peerDisconnected`
157
147
 
158
- The handle returned by `computeProofOfWorkAsync` provides these methods:
148
+ Fired when a peer connection is lost.
159
149
 
160
- #### `cancel(): void`
161
- Cancels the running proof of work computation.
150
+ **Callback:** `(event: PeerDisconnectedEvent) => void`
162
151
 
163
- #### `isCancelled(): boolean`
164
- Returns `true` if the computation has been cancelled.
152
+ ### Event Data Types
165
153
 
166
- #### `isCompleted(): boolean`
167
- Returns `true` if the computation has found a valid solution.
154
+ #### `BlockReceivedEvent`
168
155
 
169
- #### `hasError(): boolean`
170
- Returns `true` if there was an error (cancelled or max attempts reached).
156
+ ```typescript
157
+ interface BlockReceivedEvent {
158
+ peerId: string // ID of the peer that sent this block
159
+ height: number // Block height
160
+ weight: string // Block weight as string
161
+ headerHash: string // Block header hash (hex)
162
+ timestamp: number // Block timestamp (Unix time)
163
+ coinAdditions: CoinRecord[] // New coins created in this block
164
+ coinRemovals: CoinRecord[] // Coins spent in this block
165
+ coinSpends: CoinSpend[] // Detailed spend information
166
+ coinCreations: CoinRecord[] // Coins created by puzzles
167
+ hasTransactionsGenerator: boolean // Whether block has a generator
168
+ generatorSize: number // Size of the generator bytecode
169
+ }
170
+ ```
171
171
 
172
- #### `getError(): string | null`
173
- Returns the error message if there was an error, or `null` if no error.
172
+ #### `PeerConnectedEvent`
174
173
 
175
- #### `getResult(): ProofOfWorkResult | null`
176
- Returns the result if computation completed successfully, or `null` if not completed.
174
+ ```typescript
175
+ interface PeerConnectedEvent {
176
+ peerId: string // Unique peer identifier
177
+ host: string // Peer hostname/IP
178
+ port: number // Peer port number
179
+ }
180
+ ```
177
181
 
178
- #### `getAttempts(): bigint`
179
- Returns the current number of attempts made (approximate).
182
+ #### `PeerDisconnectedEvent`
180
183
 
181
- #### `getProgress(): ProofOfWorkProgress`
182
- Returns detailed progress information (attempts, elapsed time, etc.).
184
+ ```typescript
185
+ interface PeerDisconnectedEvent {
186
+ peerId: string // Unique peer identifier
187
+ host: string // Peer hostname/IP
188
+ port: number // Peer port number
189
+ message?: string // Optional disconnection reason
190
+ }
191
+ ```
183
192
 
184
- #### `getDifficulty(): number`
185
- Returns the difficulty level for this computation.
193
+ #### `CoinRecord`
186
194
 
187
- ### Result Types
195
+ ```typescript
196
+ interface CoinRecord {
197
+ parentCoinInfo: string // Parent coin ID (hex)
198
+ puzzleHash: string // Puzzle hash (hex)
199
+ amount: string // Coin amount as string
200
+ }
201
+ ```
188
202
 
189
- #### `ProofOfWorkResult`
190
- - `nonce` (bigint): The nonce that was found
191
- - `hash` (string): The resulting hash as hex string
192
- - `attempts` (bigint): Number of attempts made
193
- - `time_ms` (number): Time taken in milliseconds
194
- - `difficulty` (number): The difficulty that was satisfied
195
- - `target` (string): The target that was used (as hex string)
203
+ #### `CoinSpend`
196
204
 
197
- #### `ProofOfWorkProgress`
198
- - `attempts` (bigint): Current number of attempts
199
- - `nonce` (bigint): Current nonce being tested
200
- - `elapsed_ms` (number): Time elapsed in milliseconds
201
- - `attempts_per_second` (number): Estimated attempts per second
205
+ ```typescript
206
+ interface CoinSpend {
207
+ coin: CoinRecord // The coin being spent
208
+ puzzleReveal: string // CLVM puzzle bytecode (hex)
209
+ solution: string // CLVM solution bytecode (hex)
210
+ realData: boolean // Whether this is real spend data
211
+ parsingMethod: string // Method used to parse the spend
212
+ offset: number // Offset in the generator bytecode
213
+ }
214
+ ```
202
215
 
203
216
  ## TypeScript Usage
204
217
 
205
218
  ```typescript
206
219
  import {
207
- computeProofOfWorkAsync,
208
- verifyProofOfWork,
209
- verifyProofOfWorkStandardized,
210
- getAlgorithmVersion,
211
- getAlgorithmParameters,
212
- hashToDifficulty,
213
- ProofOfWorkResult,
214
- ProofOfWorkHandle,
215
- AlgorithmParameters
220
+ ChiaBlockListener,
221
+ BlockReceivedEvent,
222
+ PeerConnectedEvent,
223
+ PeerDisconnectedEvent,
224
+ CoinRecord,
225
+ CoinSpend,
226
+ initTracing,
227
+ getEventTypes
216
228
  } from '@dignetwork/chia-block-listener'
217
229
 
218
- async function mineWithTypes(): Promise<void> {
219
- const entropySeed = Buffer.from('my_plot_entropy_seed', 'utf-8')
220
- const difficulty = 2.0
230
+ // Initialize tracing for debugging
231
+ initTracing()
232
+
233
+ // Create listener with proper typing
234
+ const listener = new ChiaBlockListener()
235
+
236
+ // Type-safe event handlers
237
+ listener.on('blockReceived', (block: BlockReceivedEvent) => {
238
+ console.log(`Block ${block.height} from peer ${block.peerId}`)
221
239
 
222
- const handle: ProofOfWorkHandle = computeProofOfWorkAsync(entropySeed, difficulty)
240
+ // Process coin additions
241
+ block.coinAdditions.forEach((coin: CoinRecord) => {
242
+ console.log(`New coin: ${coin.amount} mojos`)
243
+ })
223
244
 
224
- // Wait for completion with proper typing
225
- const waitForCompletion = async (handle: ProofOfWorkHandle): Promise<ProofOfWorkResult> => {
226
- while (!handle.isCompleted() && !handle.hasError()) {
227
- await new Promise(resolve => setTimeout(resolve, 100))
228
- }
229
-
230
- if (handle.hasError()) {
231
- throw new Error(handle.getError() || 'Unknown error')
232
- }
233
-
234
- const result = handle.getResult()
235
- if (!result) {
236
- throw new Error('No result available')
237
- }
245
+ // Process coin spends
246
+ block.coinSpends.forEach((spend: CoinSpend) => {
247
+ console.log(`Spend: ${spend.coin.amount} mojos`)
248
+ console.log(`Puzzle: ${spend.puzzleReveal}`)
249
+ console.log(`Solution: ${spend.solution}`)
250
+ })
251
+ })
252
+
253
+ listener.on('peerConnected', (peer: PeerConnectedEvent) => {
254
+ console.log(`Connected: ${peer.peerId} at ${peer.host}:${peer.port}`)
255
+ })
256
+
257
+ listener.on('peerDisconnected', (peer: PeerDisconnectedEvent) => {
258
+ console.log(`Disconnected: ${peer.peerId}`)
259
+ if (peer.message) {
260
+ console.log(`Reason: ${peer.message}`)
261
+ }
262
+ })
263
+
264
+ // Connect to peers
265
+ const mainnetPeer = listener.addPeer('localhost', 8444, 'mainnet')
266
+ const testnetPeer = listener.addPeer('testnet-node.chia.net', 58444, 'testnet')
267
+
268
+ // Get historical blocks
269
+ async function getHistoricalBlocks() {
270
+ try {
271
+ const block = listener.getBlockByHeight(mainnetPeer, 1000000)
272
+ console.log(`Block 1000000 hash: ${block.headerHash}`)
238
273
 
239
- return result
274
+ const blocks = listener.getBlocksRange(mainnetPeer, 1000000, 1000010)
275
+ console.log(`Retrieved ${blocks.length} blocks`)
276
+ } catch (error) {
277
+ console.error('Error getting blocks:', error)
240
278
  }
241
-
242
- const result: ProofOfWorkResult = await waitForCompletion(handle)
243
-
244
- // Standard verification
245
- const isValid: boolean = verifyProofOfWork(
246
- entropySeed,
247
- Number(result.nonce),
248
- difficulty
249
- )
250
-
251
- // Standardized verification (recommended for networks)
252
- const isStandardValid: boolean = verifyProofOfWorkStandardized(
253
- entropySeed,
254
- Number(result.nonce),
255
- difficulty
256
- )
257
-
258
- // Check algorithm parameters
259
- const params: AlgorithmParameters = getAlgorithmParameters()
260
- console.log(`Algorithm version: ${params.version}`)
261
- console.log(`Algorithm spec: ${params.specHash}`)
262
-
263
- console.log('Mining completed, valid:', isValid)
264
- console.log('Consensus valid:', isStandardValid)
265
279
  }
266
- ```
267
280
 
268
- ## Difficulty System
281
+ // Get event type constants
282
+ const eventTypes = getEventTypes()
283
+ console.log('Available events:', eventTypes)
284
+ ```
269
285
 
270
- This library uses Bitcoin's target-based difficulty system:
286
+ ## Advanced Usage
271
287
 
272
- - **Difficulty 1.0**: Easiest level, requires 8 leading zero bits in hash
273
- - **Difficulty 2.0**: Requires 12 leading zero bits
274
- - **Difficulty 4.0**: Requires 16 leading zero bits (2 zero bytes)
275
- - **Higher difficulties**: Exponentially more difficult
288
+ ### Monitoring Specific Transactions
276
289
 
277
- The difficulty directly corresponds to how computationally expensive it is to find a valid nonce.
290
+ ```javascript
291
+ // Monitor all coin spends for a specific puzzle hash
292
+ listener.on('blockReceived', (block) => {
293
+ const targetPuzzleHash = '0x1234...' // Your puzzle hash
294
+
295
+ block.coinSpends.forEach((spend) => {
296
+ if (spend.coin.puzzleHash === targetPuzzleHash) {
297
+ console.log('Found spend for our puzzle!')
298
+ console.log('Amount:', spend.coin.amount)
299
+ console.log('Solution:', spend.solution)
300
+ }
301
+ })
302
+ })
303
+ ```
278
304
 
279
- ## Security & Consensus
305
+ ### Multiple Network Monitoring
280
306
 
281
- This library implements a **consensus-critical verification system** to prevent tampering and ensure network compatibility.
307
+ ```javascript
308
+ // Monitor both mainnet and testnet
309
+ const mainnetPeer = listener.addPeer('localhost', 8444, 'mainnet')
310
+ const testnetPeer = listener.addPeer('localhost', 58444, 'testnet')
311
+
312
+ listener.on('blockReceived', (block) => {
313
+ if (block.peerId === mainnetPeer) {
314
+ console.log(`Mainnet block ${block.height}`)
315
+ } else if (block.peerId === testnetPeer) {
316
+ console.log(`Testnet block ${block.height}`)
317
+ }
318
+ })
319
+ ```
282
320
 
283
- ### Algorithm Standardization
321
+ ### Connection Management
284
322
 
285
- - **Version 1 Specification**: `DIG_POW_V1_SMOOTH_LOG_DIFFICULTY_2024`
286
- - **Formula**: `zero_bits = 8 + log2(difficulty) * 2`
287
- - **Immutable Parameters**: All difficulty calculation parameters are locked constants
288
- - **Version Validation**: Algorithm version must match across all network participants
323
+ ```javascript
324
+ // Automatic reconnection
325
+ listener.on('peerDisconnected', (peer) => {
326
+ console.log(`Lost connection to ${peer.peerId}, reconnecting...`)
327
+
328
+ // Reconnect after 5 seconds
329
+ setTimeout(() => {
330
+ try {
331
+ listener.addPeer(peer.host, peer.port, 'mainnet')
332
+ console.log('Reconnected successfully')
333
+ } catch (error) {
334
+ console.error('Reconnection failed:', error)
335
+ }
336
+ }, 5000)
337
+ })
338
+ ```
289
339
 
290
- ### Security Guarantees
340
+ ## Utility Functions
291
341
 
292
- 1. **Tamper Detection**: Algorithm spec hash prevents silent modifications
293
- 2. **Version Enforcement**: Mismatched versions are rejected automatically
294
- 3. **Consensus Compliance**: All parameters are immutable constants
295
- 4. **Network Compatibility**: Ensures identical verification across nodes
296
- 5. **Upgrade Safety**: Algorithm changes require coordinated hard forks
342
+ ### `initTracing(): void`
297
343
 
298
- ### Usage for Network Consensus
344
+ Initializes the Rust tracing system for debugging purposes. Call this before creating any `ChiaBlockListener` instances if you want to see debug output.
299
345
 
300
- ```javascript
301
- // For production networks: Always use standardized verification
302
- const isValid = verifyProofOfWorkStandardized(entropySeed, nonce, difficulty)
346
+ ### `getEventTypes(): EventTypes`
303
347
 
304
- // Check algorithm compatibility
305
- const version = getAlgorithmVersion() // Returns: 1
306
- const spec = getAlgorithmSpec() // Returns: "DIG_POW_V1_SMOOTH_LOG_DIFFICULTY_2024"
348
+ Returns an object containing the event type constants:
307
349
 
308
- // Validate all proofs with version checking
309
- function validateNetworkProof(entropySeed, nonce, difficulty) {
310
- return verifyProofOfWorkStandardized(entropySeed, nonce, difficulty, 1)
311
- }
350
+ ```javascript
351
+ const eventTypes = getEventTypes()
352
+ console.log(eventTypes)
353
+ // Output: { blockReceived: "blockReceived", peerConnected: "peerConnected", peerDisconnected: "peerDisconnected" }
312
354
  ```
313
355
 
314
- ### Network Upgrade Process
315
-
316
- To change the difficulty algorithm:
317
- 1. Define new algorithm version (e.g., version 2)
318
- 2. Update consensus parameters and spec hash
319
- 3. Coordinate hard fork across all network participants
320
- 4. Validate version compatibility on peer connections
321
-
322
356
  ## Performance Tips
323
357
 
324
- 1. **Use appropriate difficulty levels**: Start with 1.0-4.0 for testing
325
- 2. **Monitor progress**: Use the handle to track mining progress
326
- 3. **Set reasonable limits**: Use `maxAttempts` for time-critical applications
327
- 4. **Handle cancellation**: Always provide a way to cancel long-running operations
358
+ 1. **Use specific event handlers**: Only listen for the events you need
359
+ 2. **Process blocks efficiently**: Avoid heavy computation in event handlers
360
+ 3. **Manage connections**: Don't create too many peer connections simultaneously
361
+ 4. **Handle errors gracefully**: Always wrap peer operations in try-catch blocks
328
362
 
329
363
  ## Development
330
364
 
331
365
  ### Prerequisites
332
366
 
333
367
  - [Rust](https://rustup.rs/) (latest stable)
334
- - [Node.js](https://nodejs.org/) (16 or later)
368
+ - [Node.js](https://nodejs.org/) (20 or later)
335
369
  - [npm](https://www.npmjs.com/)
336
370
 
337
371
  ### Setup
@@ -353,15 +387,20 @@ npm test
353
387
 
354
388
  ```
355
389
  chia-block-listener/
356
- ├── src/
357
- └── lib.rs # Rust implementation with NAPI bindings
358
- ├── __test__/
359
- └── index.spec.mjs # Test suite
360
- ├── npm/ # Platform-specific native binaries
361
- ├── .github/workflows/ # CI/CD pipeline
362
- ├── Cargo.toml # Rust configuration
363
- ├── package.json # Node.js configuration
364
- └── index.d.ts # TypeScript definitions
390
+ ├── src/ # Rust source code
391
+ ├── lib.rs # Main NAPI bindings
392
+ ├── peer.rs # Peer connection management
393
+ ├── protocol.rs # Chia protocol implementation
394
+ ├── event_emitter.rs # Event system
395
+ │ └── tls.rs # TLS connection handling
396
+ ├── crate/ # Additional Rust crates
397
+ │ └── chia-generator-parser/ # CLVM parser
398
+ ├── __test__/ # Test suite
399
+ ├── npm/ # Platform-specific binaries
400
+ ├── .github/workflows/ # CI/CD pipeline
401
+ ├── Cargo.toml # Rust configuration
402
+ ├── package.json # Node.js configuration
403
+ └── index.d.ts # TypeScript definitions
365
404
  ```
366
405
 
367
406
  ## CI/CD & Publishing
@@ -369,8 +408,8 @@ chia-block-listener/
369
408
  This project uses GitHub Actions for:
370
409
  - Cross-platform builds (Windows, macOS, Linux)
371
410
  - Multiple architectures (x64, ARM64)
372
- - Automated testing
373
- - npm publishing based on commit messages
411
+ - Automated testing on all platforms
412
+ - npm publishing based on git tags
374
413
 
375
414
  ## License
376
415
 
@@ -385,3 +424,10 @@ MIT
385
424
  5. Commit your changes (`git commit -m 'Add some amazing feature'`)
386
425
  6. Push to the branch (`git push origin feature/amazing-feature`)
387
426
  7. Open a Pull Request
427
+
428
+ ## Support
429
+
430
+ For issues and questions:
431
+ - GitHub Issues: [Report bugs or request features](https://github.com/DIG-Network/chia-block-listener/issues)
432
+ - Documentation: Check the TypeScript definitions in `index.d.ts`
433
+ - Examples: See the `examples/` directory for more usage examples
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dignetwork/chia-block-listener-darwin-arm64",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/DIG-Network/chia-block-listener"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dignetwork/chia-block-listener-darwin-x64",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/DIG-Network/chia-block-listener"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dignetwork/chia-block-listener-linux-arm64-gnu",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/DIG-Network/chia-block-listener"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dignetwork/chia-block-listener-linux-x64-gnu",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/DIG-Network/chia-block-listener"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dignetwork/chia-block-listener-win32-x64-msvc",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/DIG-Network/chia-block-listener"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dignetwork/chia-block-listener",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "main": "index.js",
5
5
  "types": "index.d.ts",
6
6
  "repository": {
@@ -58,10 +58,10 @@
58
58
  },
59
59
  "packageManager": "yarn@1.22.22",
60
60
  "optionalDependencies": {
61
- "@dignetwork/chia-block-listener-win32-x64-msvc": "0.1.6",
62
- "@dignetwork/chia-block-listener-darwin-x64": "0.1.6",
63
- "@dignetwork/chia-block-listener-linux-x64-gnu": "0.1.6",
64
- "@dignetwork/chia-block-listener-darwin-arm64": "0.1.6",
65
- "@dignetwork/chia-block-listener-linux-arm64-gnu": "0.1.6"
61
+ "@dignetwork/chia-block-listener-win32-x64-msvc": "0.1.7",
62
+ "@dignetwork/chia-block-listener-darwin-x64": "0.1.7",
63
+ "@dignetwork/chia-block-listener-linux-x64-gnu": "0.1.7",
64
+ "@dignetwork/chia-block-listener-darwin-arm64": "0.1.7",
65
+ "@dignetwork/chia-block-listener-linux-arm64-gnu": "0.1.7"
66
66
  }
67
67
  }