1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//! # rust-bitcoinkernel
//!
//! Rust bindings for the `libbitcoinkernel` library, providing safe and idiomatic
//! access to Bitcoin's consensus engine and validation logic.
//!
//! ## Overview
//!
//! This crate enables Rust applications to leverage Bitcoin Core's consensus implementation.
//! It provides type-safe wrappers around the C API exposed by `libbitcoinkernel`.
//!
//! ## Key Features
//!
//! - **Block Processing**: Process and validate blocks and block headers against consensus rules
//! - **Script Verification**: Validate transaction scripts
//! - **Chain Queries**: Traverse the chain and read block data
//! - **Event Notifications**: Subscribe to block validation, tip updates, and error events
//! - **Memory Safety**: FFI interactions are wrapped in safe Rust abstractions
//!
//! ## Architecture
//!
//! The crate is organized into several modules:
//!
//! - [`core`]: Core Bitcoin primitives (blocks, transactions, scripts)
//! - [`state`]: Chain state management (chainstate, context, chain parameters)
//! - [`notifications`]: Event callbacks for validation and synchronization events
//! - [`log`]: Logging integration with Bitcoin Core's logging system
//! - [`prelude`]: Commonly used extension traits for ergonomic API access
//!
//! ## Quick Start
//!
//! ### Basic Block Validation
//!
//! ```no_run
//! use bitcoinkernel::{
//! Block, ContextBuilder, ChainType, ChainstateManager,
//! KernelError, ProcessBlockResult
//! };
//!
//! // Create a context for mainnet
//! let context = ContextBuilder::new()
//! .chain_type(ChainType::Mainnet)
//! .build()?;
//!
//! // Initialize chainstate manager
//! let chainman = ChainstateManager::new(&context, "/path/to/data", "path/to/blocks/")?;
//!
//! // Process a block
//! let block_data = vec![0u8; 100]; // placeholder
//! let block = Block::new(&block_data)?;
//!
//! match chainman.process_block(&block) {
//! ProcessBlockResult::NewBlock => println!("Block validated and written to disk"),
//! ProcessBlockResult::Duplicate => println!("Block already known (valid)"),
//! ProcessBlockResult::Rejected => println!("Block validation failed"),
//! }
//!
//! # Ok::<(), KernelError>(())
//! ```
//!
//! ### Script Verification
//!
//! ```no_run
//! use bitcoinkernel::{prelude::*, PrecomputedTransactionData, Transaction, verify, VERIFY_ALL};
//! let spending_tx_bytes = vec![]; // placeholder
//! let prev_tx_bytes = vec![]; // placeholder
//! let spending_tx = Transaction::new(&spending_tx_bytes).unwrap();
//! let prev_tx = Transaction::new(&prev_tx_bytes).unwrap();
//! let prev_output = prev_tx.output(0).unwrap();
//! let tx_data = PrecomputedTransactionData::new(&spending_tx, &[prev_output]).unwrap();
//!
//! let result = verify(
//! &prev_output.script_pubkey(),
//! Some(prev_output.value()),
//! &spending_tx,
//! 0,
//! Some(VERIFY_ALL),
//! &tx_data,
//! );
//!
//! match result {
//! Ok(()) => println!("Script verification passed"),
//! Err(e) => println!("Script verification failed: {}", e),
//! }
//! ```
//!
//! ### Event Notifications
//!
//! ```no_run
//! use bitcoinkernel::{
//! Block, BlockValidationStateRef, ChainType, ContextBuilder, KernelError,
//! ValidationCallbackRegistry,
//! };
//!
//! let context = ContextBuilder::new()
//! .chain_type(ChainType::Mainnet)
//! .notifications(|registry| {
//! registry.register_progress(|title, percent, _resume| {
//! println!("{}: {}%", title, percent);
//! });
//! registry.register_warning_set(|warning, message| {
//! eprintln!("Warning: {} - {}", warning, message);
//! });
//! registry.register_flush_error(|message| {
//! eprintln!("Flush error: {}", message);
//! // Consider tearing down context and terminating operations
//! });
//! registry.register_fatal_error(|message| {
//! eprintln!("FATAL: {}", message);
//! // Tear down context and terminate all operations
//! std::process::exit(1);
//! });
//! })
//! .validation(|registry| {
//! registry.register_block_checked(|block: Block, _state: BlockValidationStateRef<'_>| {
//! println!("Checked block: {}", block.hash());
//! });
//! })
//! .build()?;
//! # Ok::<(), KernelError>(())
//! ```
//!
//! **Note**: System-level errors are surfaced through [`FatalErrorCallback`] and
//! [`FlushErrorCallback`]. When encountering either error type, it is recommended to
//! tear down the [`Context`] and terminate any running tasks using the [`ChainstateManager`].
//!
//! ### Chain Traversal
//!
//! ```no_run
//! use bitcoinkernel::{ContextBuilder, ChainType, ChainstateManager, KernelError};
//!
//! // Create a context for mainnet
//! let context = ContextBuilder::new()
//! .chain_type(ChainType::Mainnet)
//! .build()?;
//!
//! // Initialize chainstate manager
//! let chainman = ChainstateManager::new(&context, "path/to/data", "path/to/blocks")?;
//!
//! chainman.import_blocks()?;
//!
//! // Get the active chain
//! let chain = chainman.active_chain();
//!
//! // Traverse the chain
//! for entry in chain.iter() {
//! println!("Block hash {} at height {}", entry.block_hash(), entry.height());
//! }
//! # Ok::<(), KernelError>(())
//! ```
//!
//! ## Type System
//!
//! The crate uses owned and borrowed types extensively:
//!
//! - **Owned types** (e.g., `Block`, `Transaction`): Manage C memory lifecycle
//! - **Borrowed types** (e.g., `BlockRef`, `TransactionRef`): Zero-copy views into data
//! - **Extension traits**: Provide ergonomic methods (use `prelude::*` to import)
//!
//! ## Error Handling
//!
//! The crate provides multiple layers of error handling:
//!
//! - **Operation Errors**: Standard [`KernelError`] results for validation failures,
//! serialization errors, and internal library errors
//! - **System Errors**: Critical failures are reported through notification callbacks:
//! - [`FatalErrorCallback`]: Unrecoverable system errors requiring immediate shutdown
//! - [`FlushErrorCallback`]: Disk I/O errors during state persistence
//!
//! When encountering fatal or flush errors through these callbacks, applications should
//! tear down the [`Context`] and terminate any operations using the [`ChainstateManager`].
//!
//! ## Minimum Supported Rust Version (MSRV)
//!
//! This crate requires Rust 1.71.0 or later.
//!
//! ## Examples
//!
//! See the `examples/` directory for complete working examples including:
//!
//! - Silent Payment Scanning
use NulError;
use ;
use crate;
use c_helpers;
/// Serializes data using a C callback function pattern.
///
/// Takes a C function that writes data via a callback and returns the
/// serialized bytes as a `Vec<u8>`.
/// A collection of errors emitted by this library
pub use crate;
pub use crate;
pub use crate;
pub use crate;
pub use crate;