pop-fork 0.13.0

Library for forking live Substrate chains.
Documentation
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// SPDX-License-Identifier: GPL-3.0

//! Block structure for forked blockchain state.
//!
//! This module provides the [`Block`] struct which represents a single block
//! in a forked blockchain. Each block contains its metadata (number, hash,
//! parent hash, header, extrinsics) and an associated storage layer for
//! reading and modifying state.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │                           Block                                  │
//! │                                                                   │
//! │   ┌──────────────────────────────────────────────────────────┐   │
//! │   │ Metadata: number, hash, parent_hash, header, extrinsics  │   │
//! │   └──────────────────────────────────────────────────────────┘   │
//! │                              │                                    │
//! │                              ▼                                    │
//! │   ┌──────────────────────────────────────────────────────────┐   │
//! │   │                  LocalStorageLayer                        │   │
//! │   │  (tracks modifications on top of remote chain state)      │   │
//! │   └──────────────────────────────────────────────────────────┘   │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Usage
//!
//! ```ignore
//! use pop_fork::{Block, ForkRpcClient, StorageCache};
//!
//! // Create a fork point from a live chain
//! let rpc = ForkRpcClient::connect(&endpoint).await?;
//! let cache = StorageCache::in_memory().await?;
//! let block_hash = rpc.finalized_head().await?;
//! let fork_block = Block::fork_point(rpc, cache, block_hash).await?;
//!
//! // Access storage
//! let value = fork_block.storage().get(fork_block.number, &key).await?;
//!
//! // Modify storage and commit to create a new block
//! fork_block.storage().set(&key, Some(&new_value))?;
//! ```

use crate::{BlockError, ForkRpcClient, LocalStorageLayer, RemoteStorageLayer, StorageCache};
use std::sync::Arc;
use subxt::{Metadata, config::substrate::H256, ext::codec::Encode};
use url::Url;

/// A block in a forked blockchain.
///
/// Represents a single block with its metadata and associated storage state.
/// Blocks can be created as fork points from live chains or as child blocks
/// extending an existing fork.
///
/// # Storage Model
///
/// Each block has an associated [`LocalStorageLayer`] that tracks storage
/// modifications. The storage layer uses a layered architecture:
///
/// - **Local modifications**: In-memory changes for the current block
/// - **Committed state**: Previously committed blocks stored in SQLite
/// - **Remote state**: Original chain state fetched lazily via RPC + cache for faster relaunches.
///
/// # Cloning
///
/// `Block` is cheap to clone, as `LocalStorageLayer` is cheap to clone.
#[derive(Clone, Debug)]
pub struct Block {
	/// The block number (height).
	pub number: u32,
	/// The block hash.
	pub hash: H256,
	/// The parent block hash.
	pub parent_hash: H256,
	/// The encoded block header.
	pub header: Vec<u8>,
	/// The extrinsics (transactions) in this block.
	pub extrinsics: Vec<Vec<u8>>,
	/// The storage layer for this block.
	///
	/// Also manages runtime metadata versions, enabling dynamic lookup of
	/// pallet and call indices for inherent providers.
	storage: LocalStorageLayer,
	/// The parent block. Keeping blocks in memory is cheap as the `LocalStorageLayer` is shared
	/// between all fork-produced blocks.
	pub parent: Option<Box<Block>>,
}

/// Handy type to allow specifying both number and hash as the fork point.
#[derive(Clone, Copy)]
pub enum BlockForkPoint {
	/// Fork at a specific block number.
	Number(u32),
	/// Fork at a specific block hash.
	Hash(H256),
}

impl From<u32> for BlockForkPoint {
	fn from(number: u32) -> Self {
		Self::Number(number)
	}
}

impl From<H256> for BlockForkPoint {
	fn from(hash: H256) -> Self {
		Self::Hash(hash)
	}
}

impl Block {
	/// Create a new block at a fork point from a live chain.
	///
	/// This is the entry point for creating a forked chain. It fetches the block
	/// header from the remote chain and sets up a [`LocalStorageLayer`] for tracking
	/// subsequent modifications.
	///
	/// # Arguments
	///
	/// * `endpoint` - RPC client url.
	/// * `cache` - Storage cache for persisting fetched and modified values
	/// * `block_fork_point` - Hash or number of the block to fork from
	///
	/// # Returns
	///
	/// A new `Block` representing the fork point, with an empty extrinsics list
	/// (since we're forking from existing chain state, not producing new blocks).
	pub async fn fork_point(
		endpoint: &Url,
		cache: StorageCache,
		block_fork_point: BlockForkPoint,
	) -> Result<Self, BlockError> {
		// Fetch header from remote chain
		let rpc = ForkRpcClient::connect(endpoint).await?;
		let (block_hash, header) = match block_fork_point {
			BlockForkPoint::Number(block_number) => {
				let (block_hash, block) =
					if let Some(block_by_number) = rpc.block_by_number(block_number).await? {
						block_by_number
					} else {
						return Err(BlockError::BlockNumberNotFound(block_number));
					};
				(block_hash, block.header)
			},
			BlockForkPoint::Hash(block_hash) => (
				block_hash,
				rpc.header(block_hash)
					.await
					.map_err(|_| BlockError::BlockHashNotFound(block_hash))?,
			),
		};
		let block_number = header.number;
		let parent_hash = header.parent_hash;

		// Fetch full block to get extrinsics (needed for parachain inherents)
		let extrinsics = rpc
			.block_by_hash(block_hash)
			.await?
			.map(|block| block.extrinsics.into_iter().map(|ext| ext.0.to_vec()).collect::<Vec<_>>())
			.unwrap_or_default();

		// Fetch and decode runtime metadata
		let metadata = rpc.metadata(block_hash).await?;

		// Create storage layers (metadata is stored in LocalStorageLayer)
		let remote = RemoteStorageLayer::new(rpc, cache);
		let storage = LocalStorageLayer::new(remote, block_number, block_hash, metadata);

		// Encode header for storage
		let header_encoded = header.encode();

		Ok(Self {
			number: block_number,
			hash: block_hash,
			parent_hash,
			header: header_encoded,
			extrinsics, // Extrinsics from the forked block (needed for parachain inherents)
			storage,
			parent: None,
		})
	}

	/// Create a new child block with the given hash, header, and extrinsics.
	///
	/// This commits the parent's storage modifications and creates a new block
	/// that shares the same storage layer (including metadata versions).
	///
	/// # Arguments
	///
	/// * `hash` - The block hash
	/// * `header` - The encoded block header
	/// * `extrinsics` - The extrinsics (transactions) in this block
	///
	/// # Note
	///
	/// The child block shares the same storage layer as the parent, including
	/// metadata versions. If a runtime upgrade occurred (`:code` storage changed),
	/// the new metadata should be registered via `storage.register_metadata_version()`.
	pub async fn child(
		&mut self,
		hash: H256,
		header: Vec<u8>,
		extrinsics: Vec<Vec<u8>>,
	) -> Result<Self, BlockError> {
		self.storage.commit().await?;
		Ok(Self {
			number: self.number + 1,
			hash,
			parent_hash: self.hash,
			header,
			extrinsics,
			storage: self.storage.clone(),
			parent: Some(Box::new(self.clone())),
		})
	}

	/// Create a mocked Block for executing runtime calls on historical blocks.
	///
	/// This block uses the real block hash and number (for correct storage queries)
	/// but placeholder values for other fields since the executor only needs storage access.
	/// The storage layer delegates to remote for historical data.
	///
	/// # Arguments
	///
	/// * `hash` - The real block hash being queried
	/// * `number` - The actual block number (needed for correct storage queries)
	/// * `storage` - Storage layer that delegates to remote for historical data
	pub fn mocked_for_call(hash: H256, number: u32, storage: LocalStorageLayer) -> Self {
		Self {
			number,
			hash,
			parent_hash: H256::zero(),
			header: vec![],
			extrinsics: vec![],
			storage,
			parent: None,
		}
	}

	/// Get a reference to the storage layer.
	///
	/// Use this to read storage values at this block's height.
	///
	/// # Example
	///
	/// ```ignore
	/// let value = block.storage().get(block.number, &key).await?;
	/// ```
	pub fn storage(&self) -> &LocalStorageLayer {
		&self.storage
	}

	/// Get a mutable reference to the storage layer.
	///
	/// Use this to modify storage values. Modifications are tracked locally
	/// and can be committed using [`LocalStorageLayer::commit`].
	///
	/// # Example
	///
	/// ```ignore
	/// block.storage_mut().set(&key, Some(&value))?;
	/// block.storage_mut().commit().await?;
	/// ```
	pub fn storage_mut(&mut self) -> &mut LocalStorageLayer {
		&mut self.storage
	}

	/// Get the runtime metadata for this block.
	///
	/// This provides access to pallet and call indices for dynamic extrinsic
	/// encoding. Use this in inherent providers to look up pallet indices
	/// instead of relying on hardcoded values.
	///
	/// Returns an `Arc<Metadata>` which can be used like a reference (via `Deref`).
	/// The metadata is shared across all blocks that use the same runtime version,
	/// avoiding unnecessary cloning.
	///
	/// # Example
	///
	/// ```ignore
	/// let metadata = block.metadata().await?;
	/// let pallet = metadata.pallet_by_name("Timestamp")?;
	/// let pallet_index = pallet.index();
	/// let call_variant = pallet.call_variant_by_name("set")?;
	/// let call_index = call_variant.index;
	/// ```
	pub async fn metadata(&self) -> Result<Arc<Metadata>, BlockError> {
		Ok(self.storage.metadata_at(self.number).await?)
	}

	/// Get the runtime code (`:code`) for this block.
	///
	/// Retrieves the WASM runtime code from the storage layer, which handles
	/// the layered lookup (local modifications → cache → remote).
	///
	/// # Returns
	///
	/// The runtime WASM code as bytes.
	///
	/// # Errors
	///
	/// Returns [`BlockError::RuntimeCodeNotFound`] if the `:code` key is not
	/// found in storage.
	///
	/// # Example
	///
	/// ```ignore
	/// let runtime_code = block.runtime_code().await?;
	/// let executor = RuntimeExecutor::new(runtime_code)?;
	/// ```
	pub async fn runtime_code(&self) -> Result<Vec<u8>, BlockError> {
		let code_key = sp_core::storage::well_known_keys::CODE;
		self.storage()
			.get(self.number, code_key)
			.await?
			.and_then(|v| v.value.clone())
			.ok_or(BlockError::RuntimeCodeNotFound)
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn from_u32_creates_number_variant() {
		let fork_point: BlockForkPoint = 42u32.into();
		assert!(matches!(fork_point, BlockForkPoint::Number(42)));
	}

	#[test]
	fn from_h256_creates_hash_variant() {
		let hash = H256::from([0xab; 32]);
		let fork_point: BlockForkPoint = hash.into();
		assert!(matches!(fork_point, BlockForkPoint::Hash(h) if h == hash));
	}

	/// Tests that spawn local test nodes.
	///
	/// These tests are run sequentially via nextest configuration to avoid
	/// concurrent node downloads causing race conditions.
	mod sequential {
		use super::*;
		use crate::testing::TestContext;

		#[tokio::test(flavor = "multi_thread")]
		async fn fork_point_with_hash_creates_block_with_correct_metadata() {
			let ctx = TestContext::for_storage().await;

			let expected_parent_hash =
				ctx.rpc().header(ctx.block_hash()).await.unwrap().parent_hash;

			let block =
				Block::fork_point(&ctx.endpoint, ctx.cache().clone(), ctx.block_hash().into())
					.await
					.unwrap();

			assert_eq!(block.number, ctx.block_number());
			assert_eq!(block.hash, ctx.block_hash());
			assert_eq!(block.parent_hash, expected_parent_hash);
			assert!(!block.header.is_empty());
			// Note: extrinsics may or may not be empty depending on the block
			assert!(block.parent.is_none());
		}

		#[tokio::test(flavor = "multi_thread")]
		async fn fork_point_with_non_existent_hash_returns_error() {
			let ctx = TestContext::for_storage().await;
			let non_existent_hash = H256::from([0xde; 32]);

			let result =
				Block::fork_point(&ctx.endpoint, ctx.cache().clone(), non_existent_hash.into())
					.await;

			assert!(
				matches!(result, Err(BlockError::BlockHashNotFound(h)) if h == non_existent_hash)
			);
		}

		#[tokio::test(flavor = "multi_thread")]
		async fn fork_point_with_number_creates_block_with_correct_metadata() {
			let ctx = TestContext::for_storage().await;
			let expected_parent_hash =
				ctx.rpc().header(ctx.block_hash()).await.unwrap().parent_hash;

			let block =
				Block::fork_point(&ctx.endpoint, ctx.cache().clone(), ctx.block_number().into())
					.await
					.unwrap();

			assert_eq!(block.number, ctx.block_number());
			assert_eq!(block.hash, ctx.block_hash());
			assert_eq!(block.parent_hash, expected_parent_hash);
			assert!(!block.header.is_empty());
			// Note: extrinsics may or may not be empty depending on the block
			assert!(block.parent.is_none());
		}

		#[tokio::test(flavor = "multi_thread")]
		async fn fork_point_with_non_existent_number_returns_error() {
			let ctx = TestContext::for_storage().await;
			let non_existent_number = u32::MAX;

			let result =
				Block::fork_point(&ctx.endpoint, ctx.cache().clone(), non_existent_number.into())
					.await;

			assert!(
				matches!(result, Err(BlockError::BlockNumberNotFound(n)) if n == non_existent_number)
			);
		}

		#[tokio::test(flavor = "multi_thread")]
		async fn child_creates_block_with_correct_metadata() {
			let ctx = TestContext::for_storage().await;
			let mut parent =
				Block::fork_point(&ctx.endpoint, ctx.cache().clone(), ctx.block_hash().into())
					.await
					.unwrap();

			let child_hash = H256::from([0x42; 32]);
			let child_header = vec![1, 2, 3, 4];
			let child_extrinsics = vec![vec![5, 6, 7]];

			let child = parent
				.child(child_hash, child_header.clone(), child_extrinsics.clone())
				.await
				.unwrap();

			assert_eq!(child.number, parent.number + 1);
			assert_eq!(child.hash, child_hash);
			assert_eq!(child.parent_hash, parent.hash);
			assert_eq!(child.header, child_header);
			assert_eq!(child.extrinsics, child_extrinsics);
			assert_eq!(child.parent.unwrap().number, parent.number);
		}

		async fn get_storage_value(block: Block, number: u32, key: &[u8]) -> Vec<u8> {
			block
				.storage()
				.get(number, key)
				.await
				.unwrap()
				.as_deref()
				.unwrap()
				.value
				.clone()
				.unwrap()
		}

		#[tokio::test(flavor = "multi_thread")]
		async fn child_commits_parent_storage() {
			let ctx = TestContext::for_storage().await;
			let mut parent =
				Block::fork_point(&ctx.endpoint, ctx.cache().clone(), ctx.block_hash().into())
					.await
					.unwrap();

			let key = b"committed_key";
			let value = b"committed_value";

			// Set value on parent
			parent.storage_mut().set(key, Some(value)).unwrap();

			// Create child (this commits parent storage)
			let mut child = parent.child(H256::from([0x42; 32]), vec![], vec![]).await.unwrap();

			let value2 = b"committed_value2";

			child.storage_mut().set(key, Some(value2)).unwrap();

			// child.number is the latest committed block, but these changes aren't committed yet,
			// they're happening in the block we're building
			assert_eq!(get_storage_value(child.clone(), child.number + 1, key).await, value2);
			// child.number is the latest committed block
			assert_eq!(get_storage_value(child.clone(), child.number, key).await, value);
		}

		#[tokio::test(flavor = "multi_thread")]
		async fn child_storage_inherits_parent_modifications() {
			let ctx = TestContext::for_storage().await;
			let mut parent =
				Block::fork_point(&ctx.endpoint, ctx.cache().clone(), ctx.block_hash().into())
					.await
					.unwrap();

			let key = b"inherited_key";
			let value = b"inherited_value";

			parent.storage_mut().set(key, Some(value)).unwrap();

			let child = parent.child(H256::from([0x42; 32]), vec![], vec![]).await.unwrap();

			// Child should see the value at its block number
			assert_eq!(get_storage_value(child.clone(), child.number, key).await, value);
		}
	}
}