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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
// SPDX-License-Identifier: GPL-3.0

//! New archive_v1_* RPC methods.
//!
//! These methods follow the new Substrate JSON-RPC specification for archive nodes.

use crate::{
	Blockchain,
	rpc_server::{
		RpcServerError, parse_block_hash, parse_hex_bytes,
		types::{
			ArchiveCallResult, ArchiveStorageDiffResult, ArchiveStorageItem, ArchiveStorageResult,
			HexString, StorageDiffItem, StorageDiffQueryItem, StorageDiffType, StorageQueryItem,
			StorageQueryType,
		},
	},
};
use jsonrpsee::{core::RpcResult, proc_macros::rpc, tracing};
use std::sync::Arc;

/// New archive RPC methods (v1 spec).
#[rpc(server, namespace = "archive")]
pub trait ArchiveApi {
	/// Get the current finalized block height.
	#[method(name = "v1_finalizedHeight")]
	async fn finalized_height(&self) -> RpcResult<u32>;

	/// Get block hash by height.
	///
	/// Returns an array of hashes (returns an `Option<Vec>` to comply with the spec but, in
	/// practice, this Vec always contains a single element, as blocks are produced on-demand one
	/// by one).
	#[method(name = "v1_hashByHeight")]
	async fn hash_by_height(&self, height: u32) -> RpcResult<Option<Vec<String>>>;

	/// Get block header by hash.
	///
	/// Returns hex-encoded SCALE-encoded header.
	#[method(name = "v1_header")]
	async fn header(&self, hash: String) -> RpcResult<Option<String>>;

	/// Get block body by hash.
	///
	/// Returns array of hex-encoded extrinsics.
	#[method(name = "v1_body")]
	async fn body(&self, hash: String) -> RpcResult<Option<Vec<String>>>;

	/// Execute a runtime call at a block.
	///
	/// Returns `null` if the block is not found.
	#[method(name = "v1_call")]
	async fn call(
		&self,
		hash: String,
		function: String,
		call_parameters: String,
	) -> RpcResult<Option<ArchiveCallResult>>;

	/// Query storage at a finalized block.
	#[method(name = "v1_storage")]
	async fn storage(
		&self,
		hash: String,
		items: Vec<StorageQueryItem>,
		child_trie: Option<String>,
	) -> RpcResult<ArchiveStorageResult>;

	/// Get the genesis hash.
	#[method(name = "v1_genesisHash")]
	async fn genesis_hash(&self) -> RpcResult<String>;

	/// Query storage differences between two blocks for specific keys.
	///
	/// This is a simplified implementation for fork nodes that does NOT support:
	/// - Iterating all keys (items parameter is required)
	/// - Child trie queries
	///
	/// Only keys that have changed between the two blocks are returned.
	///
	/// If `previous_hash` is not provided, compares against the parent block.
	#[method(name = "v1_storageDiff")]
	async fn storage_diff(
		&self,
		hash: String,
		items: Vec<StorageDiffQueryItem>,
		previous_hash: Option<String>,
	) -> RpcResult<ArchiveStorageDiffResult>;
}

/// Implementation of archive RPC methods.
pub struct ArchiveApi {
	blockchain: Arc<Blockchain>,
}

impl ArchiveApi {
	/// Create a new ArchiveApi instance.
	pub fn new(blockchain: Arc<Blockchain>) -> Self {
		Self { blockchain }
	}
}

#[async_trait::async_trait]
impl ArchiveApiServer for ArchiveApi {
	async fn finalized_height(&self) -> RpcResult<u32> {
		Ok(self.blockchain.head_number().await)
	}

	async fn hash_by_height(&self, height: u32) -> RpcResult<Option<Vec<String>>> {
		// Fetch block hash (checks local blocks first, then remote)
		match self.blockchain.block_hash_at(height).await {
			Ok(Some(hash)) => Ok(Some(vec![HexString::from_bytes(hash.as_bytes()).into()])),
			Ok(None) => Ok(None),
			Err(e) =>
				Err(RpcServerError::Internal(format!("Failed to fetch block hash: {e}")).into()),
		}
	}

	async fn header(&self, hash: String) -> RpcResult<Option<String>> {
		let block_hash = parse_block_hash(&hash)?;

		// Fetch block header (checks local blocks first, then remote)
		match self.blockchain.block_header(block_hash).await {
			Ok(Some(header)) => Ok(Some(HexString::from_bytes(&header).into())),
			Ok(None) => Ok(None),
			Err(e) =>
				Err(RpcServerError::Internal(format!("Failed to fetch block header: {e}")).into()),
		}
	}

	async fn body(&self, hash: String) -> RpcResult<Option<Vec<String>>> {
		let block_hash = parse_block_hash(&hash)?;

		// Fetch block body (checks local blocks first, then remote)
		match self.blockchain.block_body(block_hash).await {
			Ok(Some(extrinsics)) => {
				let hex_extrinsics: Vec<String> =
					extrinsics.iter().map(|ext| HexString::from_bytes(ext).into()).collect();
				Ok(Some(hex_extrinsics))
			},
			Ok(None) => Ok(None),
			Err(e) =>
				Err(RpcServerError::Internal(format!("Failed to fetch block body: {e}")).into()),
		}
	}

	async fn call(
		&self,
		hash: String,
		function: String,
		call_parameters: String,
	) -> RpcResult<Option<ArchiveCallResult>> {
		let block_hash = parse_block_hash(&hash)?;
		let params = parse_hex_bytes(&call_parameters, "parameters")?;

		// Execute the call at the specified block
		match self.blockchain.call_at_block(block_hash, &function, &params).await {
			Ok(Some(result)) =>
				Ok(Some(ArchiveCallResult::ok(HexString::from_bytes(&result).into()))),
			Ok(None) => Ok(None), // Block not found
			Err(e) => Ok(Some(ArchiveCallResult::err(e.to_string()))),
		}
	}

	async fn storage(
		&self,
		hash: String,
		items: Vec<StorageQueryItem>,
		_child_trie: Option<String>,
	) -> RpcResult<ArchiveStorageResult> {
		let block_hash = parse_block_hash(&hash)?;

		// Get block number from hash
		let block_number = match self.blockchain.block_number_by_hash(block_hash).await {
			Ok(Some(num)) => num,
			Ok(None) =>
				return Ok(ArchiveStorageResult::Err { error: "Block not found".to_string() }),
			Err(e) =>
				return Err(RpcServerError::Internal(format!("Failed to resolve block: {e}")).into()),
		};

		// Query storage for each item at the specific block
		let mut results = Vec::new();
		for item in items {
			let key_bytes = parse_hex_bytes(&item.key, "key")?;

			match item.query_type {
				StorageQueryType::ClosestDescendantMerkleValue => {
					// Merkle proofs not supported in fork - return empty result
					results.push(ArchiveStorageItem { key: item.key, value: None, hash: None });
					continue;
				},
				StorageQueryType::DescendantsValues => {
					tracing::debug!(
						prefix = %item.key,
						"archive_v1_storage: DescendantsValues query"
					);
					match self.blockchain.storage_keys_by_prefix(&key_bytes, block_hash).await {
						Ok(keys) => {
							tracing::debug!(
								prefix = %item.key,
								keys_found = keys.len(),
								"archive_v1_storage: DescendantsValues fetching values in parallel"
							);
							let futs: Vec<_> = keys
								.iter()
								.map(|k| self.blockchain.storage_at(block_number, k))
								.collect();
							let values = futures::future::join_all(futs).await;
							for (k, v) in keys.into_iter().zip(values) {
								let value = match v {
									Ok(Some(val)) => Some(HexString::from_bytes(&val).into()),
									_ => None,
								};
								results.push(ArchiveStorageItem {
									key: HexString::from_bytes(&k).into(),
									value,
									hash: None,
								});
							}
						},
						Err(e) => {
							tracing::debug!(
								prefix = %item.key,
								error = %e,
								"archive_v1_storage: DescendantsValues prefix lookup failed"
							);
						},
					}
					continue;
				},
				StorageQueryType::DescendantsHashes => {
					tracing::debug!(
						prefix = %item.key,
						"archive_v1_storage: DescendantsHashes query"
					);
					match self.blockchain.storage_keys_by_prefix(&key_bytes, block_hash).await {
						Ok(keys) => {
							tracing::debug!(
								prefix = %item.key,
								keys_found = keys.len(),
								"archive_v1_storage: DescendantsHashes fetching values in parallel"
							);
							let futs: Vec<_> = keys
								.iter()
								.map(|k| self.blockchain.storage_at(block_number, k))
								.collect();
							let values = futures::future::join_all(futs).await;
							for (k, v) in keys.into_iter().zip(values) {
								let hash = match v {
									Ok(Some(val)) => Some(
										HexString::from_bytes(&sp_core::blake2_256(&val)).into(),
									),
									_ => None,
								};
								results.push(ArchiveStorageItem {
									key: HexString::from_bytes(&k).into(),
									value: None,
									hash,
								});
							}
						},
						Err(e) => {
							tracing::debug!(
								prefix = %item.key,
								error = %e,
								"archive_v1_storage: DescendantsHashes prefix lookup failed"
							);
						},
					}
					continue;
				},
				_ => {},
			}

			match self.blockchain.storage_at(block_number, &key_bytes).await {
				Ok(Some(value)) => match item.query_type {
					StorageQueryType::Value => {
						results.push(ArchiveStorageItem {
							key: item.key,
							value: Some(HexString::from_bytes(&value).into()),
							hash: None,
						});
					},
					StorageQueryType::Hash => {
						let hash = sp_core::blake2_256(&value);
						results.push(ArchiveStorageItem {
							key: item.key,
							value: None,
							hash: Some(HexString::from_bytes(&hash).into()),
						});
					},
					// Already handled above
					StorageQueryType::ClosestDescendantMerkleValue |
					StorageQueryType::DescendantsValues |
					StorageQueryType::DescendantsHashes => unreachable!(),
				},
				Ok(None) => {
					// Key doesn't exist - include in results with null value
					results.push(ArchiveStorageItem { key: item.key, value: None, hash: None });
				},
				Err(e) => {
					return Err(RpcServerError::Storage(e.to_string()).into());
				},
			}
		}
		Ok(ArchiveStorageResult::Ok { items: results })
	}

	async fn genesis_hash(&self) -> RpcResult<String> {
		self.blockchain.genesis_hash().await.map_err(|e| {
			RpcServerError::Internal(format!("Failed to fetch genesis hash: {e}")).into()
		})
	}

	async fn storage_diff(
		&self,
		hash: String,
		items: Vec<StorageDiffQueryItem>,
		previous_hash: Option<String>,
	) -> RpcResult<ArchiveStorageDiffResult> {
		let block_hash = parse_block_hash(&hash)?;

		// Get block number for the target block
		let block_number = match self.blockchain.block_number_by_hash(block_hash).await {
			Ok(Some(num)) => num,
			Ok(None) =>
				return Ok(ArchiveStorageDiffResult::Err { error: "Block not found".to_string() }),
			Err(e) =>
				return Err(RpcServerError::Internal(format!("Failed to resolve block: {e}")).into()),
		};

		// Determine the previous block hash
		let prev_block_hash = match previous_hash {
			Some(prev_hash_str) => parse_block_hash(&prev_hash_str)?,
			None => {
				// Get parent hash from the block
				match self.blockchain.block_parent_hash(block_hash).await {
					Ok(Some(parent_hash)) => parent_hash,
					Ok(None) =>
						return Ok(ArchiveStorageDiffResult::Err {
							error: "Block not found".to_string(),
						}),
					Err(e) =>
						return Err(RpcServerError::Internal(format!(
							"Failed to get parent hash: {e}"
						))
						.into()),
				}
			},
		};

		// Get block number for the previous block
		let prev_block_number = match self.blockchain.block_number_by_hash(prev_block_hash).await {
			Ok(Some(num)) => num,
			Ok(None) =>
				return Ok(ArchiveStorageDiffResult::Err {
					error: "Previous block not found".to_string(),
				}),
			Err(e) =>
				return Err(RpcServerError::Internal(format!(
					"Failed to resolve previous block: {e}"
				))
				.into()),
		};

		// Query storage for each item at both blocks and compute differences
		let mut results = Vec::new();
		for item in items {
			let key_bytes = parse_hex_bytes(&item.key, "key")?;

			// Get value at current block
			let current_value = match self.blockchain.storage_at(block_number, &key_bytes).await {
				Ok(v) => v,
				Err(e) => {
					return Err(RpcServerError::Storage(e.to_string()).into());
				},
			};

			// Get value at previous block
			let previous_value =
				match self.blockchain.storage_at(prev_block_number, &key_bytes).await {
					Ok(v) => v,
					Err(e) => {
						return Err(RpcServerError::Storage(e.to_string()).into());
					},
				};

			// Determine diff type and build result
			let diff_item = match (&current_value, &previous_value) {
				// Both None - no change, skip
				(None, None) => continue,

				// Added: exists in current but not in previous
				(Some(value), None) => {
					let (value_field, hash_field) = match item.return_type {
						StorageQueryType::Value =>
							(Some(HexString::from_bytes(value).into()), None),
						StorageQueryType::Hash =>
							(None, Some(HexString::from_bytes(&sp_core::blake2_256(value)).into())),
						// Merkle/descendants types not applicable to diff - treat as value
						StorageQueryType::ClosestDescendantMerkleValue |
						StorageQueryType::DescendantsValues |
						StorageQueryType::DescendantsHashes => (Some(HexString::from_bytes(value).into()), None),
					};
					StorageDiffItem {
						key: item.key,
						value: value_field,
						hash: hash_field,
						diff_type: StorageDiffType::Added,
					}
				},

				// Deleted: exists in previous but not in current
				(None, Some(_)) => {
					// For deleted items, we don't return value/hash (the key no longer exists)
					StorageDiffItem {
						key: item.key,
						value: None,
						hash: None,
						diff_type: StorageDiffType::Deleted,
					}
				},

				// Both exist - check if modified
				(Some(curr), Some(prev)) => {
					if curr == prev {
						// No change, skip
						continue;
					}
					// Modified
					let (value_field, hash_field) = match item.return_type {
						StorageQueryType::Value => (Some(HexString::from_bytes(curr).into()), None),
						StorageQueryType::Hash =>
							(None, Some(HexString::from_bytes(&sp_core::blake2_256(curr)).into())),
						// Merkle/descendants types not applicable to diff - treat as value
						StorageQueryType::ClosestDescendantMerkleValue |
						StorageQueryType::DescendantsValues |
						StorageQueryType::DescendantsHashes => (Some(HexString::from_bytes(curr).into()), None),
					};
					StorageDiffItem {
						key: item.key,
						value: value_field,
						hash: hash_field,
						diff_type: StorageDiffType::Modified,
					}
				},
			};

			results.push(diff_item);
		}

		Ok(ArchiveStorageDiffResult::Ok { items: results })
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::{
		rpc_server::types::{ArchiveCallResult, ArchiveStorageResult},
		strings::rpc_server::storage,
		testing::TestContext,
	};
	use jsonrpsee::{core::client::ClientT, rpc_params, ws_client::WsClientBuilder};

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_finalized_height_returns_correct_value() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let expected_block_height = ctx.blockchain().head_number().await;

		let height: u32 = client
			.request("archive_v1_finalizedHeight", rpc_params![])
			.await
			.expect("RPC call failed");

		// Height should match the blockchain head number
		assert_eq!(height, expected_block_height);

		// Create a new block
		ctx.blockchain().build_empty_block().await.unwrap();

		let height: u32 = client
			.request("archive_v1_finalizedHeight", rpc_params![])
			.await
			.expect("RPC call failed");

		assert_eq!(height, expected_block_height + 1);
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_genesis_hash_returns_valid_hash() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let hash: String = client
			.request("archive_v1_genesisHash", rpc_params![])
			.await
			.expect("RPC call failed");

		// Hash should be properly formatted
		assert!(hash.starts_with("0x"), "Hash should start with 0x");
		assert_eq!(hash.len(), 66, "Hash should be 0x + 64 hex chars");

		// Hash should match the actual genesis hash (block 0)
		let expected_hash = ctx
			.blockchain()
			.block_hash_at(0)
			.await
			.expect("Failed to get genesis hash")
			.expect("Genesis block should exist");
		let expected = format!("0x{}", hex::encode(expected_hash.as_bytes()));
		assert_eq!(hash, expected);
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_hash_by_height_returns_hash_at_different_heights() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let block_1 = ctx.blockchain().build_empty_block().await.unwrap();
		let block_2 = ctx.blockchain().build_empty_block().await.unwrap();

		let fork_height = ctx.blockchain().fork_point_number();

		// Get hash at fork point height
		let result: Option<Vec<String>> = client
			.request("archive_v1_hashByHeight", rpc_params![fork_height])
			.await
			.expect("RPC call failed");

		let result = result.unwrap();
		assert_eq!(result.len(), 1, "Should return exactly one hash");
		assert!(result[0].starts_with("0x"), "Hash should start with 0x");

		// Hash should match fork point
		let expected = format!("0x{}", hex::encode(ctx.blockchain().fork_point().as_bytes()));
		assert_eq!(result[0], expected);

		// Get hash at further heights
		let result: Option<Vec<String>> = client
			.request("archive_v1_hashByHeight", rpc_params![block_1.number])
			.await
			.expect("RPC call failed");

		let result = result.unwrap();
		assert_eq!(result.len(), 1, "Should return exactly one hash");
		assert!(result[0].starts_with("0x"), "Hash should start with 0x");

		// Hash should match fork point
		let expected = format!("0x{}", hex::encode(block_1.hash.as_bytes()));
		assert_eq!(result[0], expected);

		let result: Option<Vec<String>> = client
			.request("archive_v1_hashByHeight", rpc_params![block_2.number])
			.await
			.expect("RPC call failed");

		let result = result.unwrap();
		assert_eq!(result.len(), 1, "Should return exactly one hash");
		assert!(result[0].starts_with("0x"), "Hash should start with 0x");

		// Hash should match fork point
		let expected = format!("0x{}", hex::encode(block_2.hash.as_bytes()));
		assert_eq!(result[0], expected);

		// Get historical hash (if fork_point isn't 0)
		if fork_height > 0 {
			let result: Option<Vec<String>> = client
				.request("archive_v1_hashByHeight", rpc_params![fork_height - 1])
				.await
				.expect("RPC call failed");

			let result = result.unwrap();
			assert_eq!(result.len(), 1, "Should return exactly one hash");
			assert!(result[0].starts_with("0x"), "Hash should start with 0x");
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_hash_by_height_returns_none_for_unknown_height() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Query a height that doesn't exist (very high number)
		let result: Option<Vec<String>> = client
			.request("archive_v1_hashByHeight", rpc_params![999999999u64])
			.await
			.expect("RPC call failed");

		assert!(result.is_none(), "Should return none array for unknown height");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_header_returns_header_for_head_hash() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Build a block so we have a locally-built header
		ctx.blockchain().build_empty_block().await.unwrap();

		let head_hash = format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		let header: Option<String> = client
			.request("archive_v1_header", rpc_params![head_hash])
			.await
			.expect("RPC call failed");

		assert!(header.is_some(), "Should return header for head hash");
		let header_hex = header.unwrap();
		assert!(header_hex.starts_with("0x"), "Header should be hex-encoded");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_header_returns_none_for_unknown_hash() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Use a made-up hash
		let unknown_hash = "0x0000000000000000000000000000000000000000000000000000000000000001";

		let header: Option<String> = client
			.request("archive_v1_header", rpc_params![unknown_hash])
			.await
			.expect("RPC call failed");

		assert!(header.is_none(), "Should return None for unknown hash");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_header_returns_header_for_fork_point() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let fork_point_hash = format!("0x{}", hex::encode(ctx.blockchain().fork_point().0));

		let header: Option<String> = client
			.request("archive_v1_header", rpc_params![fork_point_hash])
			.await
			.expect("RPC call failed");

		assert!(header.is_some(), "Should return header for fork point");
		let header_hex = header.unwrap();
		assert!(header_hex.starts_with("0x"), "Header should be hex-encoded");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_header_returns_header_for_parent_block() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Build two blocks
		let block1 = ctx.blockchain().build_empty_block().await.unwrap();
		let _block2 = ctx.blockchain().build_empty_block().await.unwrap();

		let block1_hash = format!("0x{}", hex::encode(block1.hash.as_bytes()));

		let header: Option<String> = client
			.request("archive_v1_header", rpc_params![block1_hash])
			.await
			.expect("RPC call failed");

		assert!(header.is_some(), "Should return header for parent block");
		let header_hex = header.unwrap();
		assert!(header_hex.starts_with("0x"), "Header should be hex-encoded");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_header_is_idempotent_over_finalized_blocks() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Build a few blocks
		ctx.blockchain().build_empty_block().await.unwrap();
		ctx.blockchain().build_empty_block().await.unwrap();
		ctx.blockchain().build_empty_block().await.unwrap();

		let height: u32 = client
			.request("archive_v1_finalizedHeight", rpc_params![])
			.await
			.expect("RPC call failed");

		let hash: Option<Vec<String>> = client
			.request("archive_v1_hashByHeight", rpc_params![height])
			.await
			.expect("RPC call failed");

		let hash = hash.unwrap().pop();

		let header_1: Option<String> = client
			.request("archive_v1_header", rpc_params![hash.clone()])
			.await
			.expect("RPC call failed");

		let header_2: Option<String> = client
			.request("archive_v1_header", rpc_params![hash])
			.await
			.expect("RPC call failed");

		assert_eq!(header_1, header_2, "Header should be idempotent");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_body_returns_extrinsics_for_valid_hashes() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let fork_point_hash = format!("0x{}", hex::encode(ctx.blockchain().fork_point().0));

		let fork_point_body: Option<Vec<String>> = client
			.request("archive_v1_body", rpc_params![fork_point_hash])
			.await
			.expect("RPC call failed");

		// Build a few blocks
		ctx.blockchain().build_empty_block().await.unwrap();
		ctx.blockchain().build_empty_block().await.unwrap();
		ctx.blockchain().build_empty_block().await.unwrap();

		let head_hash = format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		let body: Option<Vec<String>> = client
			.request("archive_v1_body", rpc_params![head_hash])
			.await
			.expect("RPC call failed");

		// The latest body is just the mocked timestamp, so should be different from the fork point
		// body
		assert_ne!(fork_point_body.unwrap(), body.unwrap());
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_body_is_idempotent_over_finalized_blocks() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Build a few blocks
		ctx.blockchain().build_empty_block().await.unwrap();
		ctx.blockchain().build_empty_block().await.unwrap();
		ctx.blockchain().build_empty_block().await.unwrap();

		let height: u32 = client
			.request("archive_v1_finalizedHeight", rpc_params![])
			.await
			.expect("RPC call failed");

		let hash: Option<Vec<String>> = client
			.request("archive_v1_hashByHeight", rpc_params![height])
			.await
			.expect("RPC call failed");

		let hash = hash.unwrap().pop();

		let body_1: Option<Vec<String>> = client
			.request("archive_v1_body", rpc_params![hash.clone()])
			.await
			.expect("RPC call failed");

		let body_2: Option<Vec<String>> = client
			.request("archive_v1_body", rpc_params![hash])
			.await
			.expect("RPC call failed");

		assert_eq!(body_1, body_2);
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_body_returns_none_for_unknown_hash() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let unknown_hash = "0x0000000000000000000000000000000000000000000000000000000000000001";

		let body: Option<Vec<String>> = client
			.request("archive_v1_body", rpc_params![unknown_hash])
			.await
			.expect("RPC call failed");

		assert!(body.is_none(), "Should return None for unknown hash");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_call_executes_runtime_api() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.request_timeout(std::time::Duration::from_secs(120))
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let head_hash = format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		// Call Core_version with empty parameters
		let result: Option<serde_json::Value> = client
			.request("archive_v1_call", rpc_params![head_hash, "Core_version", "0x"])
			.await
			.expect("RPC call failed");

		// Result should be Some (block found)
		let result = result.expect("Should return result for valid block hash");

		// Result should have "success": true with value
		assert_eq!(result.get("success").and_then(|v| v.as_bool()), Some(true));
		let value = result.get("value").and_then(|v| v.as_str());
		assert!(value.is_some(), "Should have value field");
		assert!(value.unwrap().starts_with("0x"), "Value should be hex-encoded");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_call_returns_error_for_invalid_function() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.request_timeout(std::time::Duration::from_secs(120))
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let head_hash = format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		// Call a non-existent function
		let result: Option<serde_json::Value> = client
			.request("archive_v1_call", rpc_params![head_hash, "NonExistent_function", "0x"])
			.await
			.expect("RPC call failed");

		// Result should be Some (block found, but call failed)
		let result = result.expect("Should return result for valid block hash");

		// Result should have "success": false with error message
		assert_eq!(result.get("success").and_then(|v| v.as_bool()), Some(false));
		assert!(result.get("error").is_some(), "Should have error field");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_call_returns_null_for_unknown_block() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Use a made-up hash that doesn't exist
		let unknown_hash = "0x0000000000000000000000000000000000000000000000000000000000000001";

		let result: Option<serde_json::Value> = client
			.request("archive_v1_call", rpc_params![unknown_hash, "Core_version", "0x"])
			.await
			.expect("RPC call failed");

		// Result should be None (block not found)
		assert!(result.is_none(), "Should return null for unknown block hash");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_call_executes_at_specific_block() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.request_timeout(std::time::Duration::from_secs(120))
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Get fork point hash
		let fork_hash = format!("0x{}", hex::encode(ctx.blockchain().fork_point().as_bytes()));

		// Build a new block so we have multiple blocks
		ctx.blockchain().build_empty_block().await.unwrap();

		let head_hash = format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		// Both calls should succeed since both blocks exist
		let result_at_fork: Option<serde_json::Value> = client
			.request("archive_v1_call", rpc_params![fork_hash.clone(), "Core_version", "0x"])
			.await
			.expect("RPC call at fork point failed");

		let result_at_head: Option<serde_json::Value> = client
			.request("archive_v1_call", rpc_params![head_hash, "Core_version", "0x"])
			.await
			.expect("RPC call at head failed");

		// Both should return successful results
		assert!(result_at_fork.is_some(), "Should find fork point block");
		assert!(result_at_head.is_some(), "Should find head block");

		let fork_result = result_at_fork.unwrap();
		let head_result = result_at_head.unwrap();

		assert_eq!(fork_result.get("success").and_then(|v| v.as_bool()), Some(true));
		assert_eq!(head_result.get("success").and_then(|v| v.as_bool()), Some(true));
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_call_rejects_invalid_hex_hash() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Pass invalid hex for hash - this should return a JSON-RPC error
		let result: Result<Option<serde_json::Value>, _> = client
			.request("archive_v1_call", rpc_params!["not_valid_hex", "Core_version", "0x"])
			.await;

		assert!(result.is_err(), "Should reject invalid hex hash");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_returns_value_for_existing_key() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let head_hash = format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		// Query System::Number storage key
		let mut key = Vec::new();
		key.extend(sp_core::twox_128(storage::SYSTEM_PALLET));
		key.extend(sp_core::twox_128(storage::NUMBER_STORAGE));
		let key_hex = format!("0x{}", hex::encode(&key));

		let items = vec![serde_json::json!({
			"key": key_hex,
			"type": "value"
		})];

		let result: ArchiveStorageResult = client
			.request("archive_v1_storage", rpc_params![head_hash, items, Option::<String>::None])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageResult::Ok { items } => {
				assert_eq!(items.len(), 1, "Should return one item");
				assert!(items[0].value.is_some(), "Value should be present");
			},
			_ => panic!("Expected Ok result"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_returns_none_for_nonexistent_key() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let head_hash = format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		// Query a non-existent key
		let key_hex = format!("0x{}", hex::encode(b"nonexistent_key_12345"));

		let items = vec![serde_json::json!({
			"key": key_hex,
			"type": "value"
		})];

		let result: ArchiveStorageResult = client
			.request("archive_v1_storage", rpc_params![head_hash, items, Option::<String>::None])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageResult::Ok { items } => {
				assert_eq!(items.len(), 1, "Should return one item");
				assert!(items[0].value.is_none(), "Value should be None for non-existent key");
			},
			_ => panic!("Expected Ok result"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_header_rejects_invalid_hex() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Pass invalid hex
		let result: Result<Option<String>, _> =
			client.request("archive_v1_header", rpc_params!["not_valid_hex"]).await;

		assert!(result.is_err(), "Should reject invalid hex");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_call_rejects_invalid_hex_parameters() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let head_hash = format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		// Pass invalid hex for call_parameters
		let result: Result<Option<serde_json::Value>, _> = client
			.request("archive_v1_call", rpc_params![head_hash, "Core_version", "not_hex"])
			.await;

		assert!(result.is_err(), "Should reject invalid hex parameters");
	}

	/// Verifies that calling `Core_initialize_block` via `archive_v1_call` RPC does NOT
	/// persist storage changes.
	///
	/// `Core_initialize_block` writes to `System::Number` and other storage keys during
	/// block initialization. This test verifies those changes are discarded after the call.
	#[tokio::test(flavor = "multi_thread")]
	async fn archive_call_does_not_persist_storage_changes() {
		use crate::{DigestItem, consensus_engine, create_next_header};

		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.request_timeout(std::time::Duration::from_secs(120))
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Get head block info
		let head = ctx.blockchain().head().await;
		let head_hash = format!("0x{}", hex::encode(head.hash.as_bytes()));
		let head_number = head.number;

		// System::Number storage key = twox128("System") ++ twox128("Number")
		let system_number_key: Vec<u8> = [
			sp_core::twox_128(storage::SYSTEM_PALLET).as_slice(),
			sp_core::twox_128(storage::NUMBER_STORAGE).as_slice(),
		]
		.concat();

		// Query System::Number BEFORE
		let number_before = ctx
			.blockchain()
			.storage(&system_number_key)
			.await
			.expect("Failed to get System::Number")
			.map(|v| u32::from_le_bytes(v.try_into().expect("System::Number should be 4 bytes")))
			.expect("System::Number should exist");

		// Build header for the next block using the crate's helper
		let header = create_next_header(
			&head,
			vec![DigestItem::PreRuntime(consensus_engine::AURA, 0u64.to_le_bytes().to_vec())],
		);
		let header_hex = format!("0x{}", hex::encode(&header));

		// Call Core_initialize_block - this WOULD write System::Number = head_number + 1
		let init_result: Option<ArchiveCallResult> = client
			.request("archive_v1_call", rpc_params![head_hash, "Core_initialize_block", header_hex])
			.await
			.expect("Core_initialize_block RPC call failed");
		let init_result = init_result.expect("Block should exist");
		assert!(
			init_result.success,
			"Core_initialize_block should succeed: {:?}",
			init_result.error
		);

		// Query System::Number AFTER - should be UNCHANGED
		let number_after = ctx
			.blockchain()
			.storage(&system_number_key)
			.await
			.expect("Failed to get System::Number after")
			.map(|v| u32::from_le_bytes(v.try_into().expect("System::Number should be 4 bytes")))
			.expect("System::Number should still exist");

		assert_eq!(
			number_before,
			number_after,
			"System::Number should NOT be modified by archive_v1_call. \
			 Before: {}, After: {} (would have been {} if persisted)",
			number_before,
			number_after,
			head_number + 1
		);
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_returns_hash_when_requested() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let head_hash = format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		// Query System::Number storage key with hash type
		let mut key = Vec::new();
		key.extend(sp_core::twox_128(storage::SYSTEM_PALLET));
		key.extend(sp_core::twox_128(storage::NUMBER_STORAGE));
		let key_hex = format!("0x{}", hex::encode(&key));

		let items = vec![serde_json::json!({
			"key": key_hex,
			"type": "hash"
		})];

		let result: ArchiveStorageResult = client
			.request("archive_v1_storage", rpc_params![head_hash, items, Option::<String>::None])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageResult::Ok { items } => {
				assert_eq!(items.len(), 1, "Should return one item");
				assert!(items[0].hash.is_some(), "Hash should be present");
				assert!(items[0].value.is_none(), "Value should not be present");
				let hash = items[0].hash.as_ref().unwrap();
				assert!(hash.starts_with("0x"), "Hash should be hex-encoded");
				assert_eq!(hash.len(), 66, "Hash should be 32 bytes (0x + 64 hex chars)");
			},
			_ => panic!("Expected Ok result"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_queries_at_specific_block() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Build a block to change state
		ctx.blockchain().build_empty_block().await.unwrap();
		let block1_hash =
			format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		// Build another block
		ctx.blockchain().build_empty_block().await.unwrap();
		let block2_hash =
			format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));

		// Query System::Number at both blocks
		let mut key = Vec::new();
		key.extend(sp_core::twox_128(storage::SYSTEM_PALLET));
		key.extend(sp_core::twox_128(storage::NUMBER_STORAGE));
		let key_hex = format!("0x{}", hex::encode(&key));

		let items = vec![serde_json::json!({ "key": key_hex, "type": "value" })];

		let result1: ArchiveStorageResult = client
			.request(
				"archive_v1_storage",
				rpc_params![block1_hash, items.clone(), Option::<String>::None],
			)
			.await
			.expect("RPC call failed");

		let result2: ArchiveStorageResult = client
			.request("archive_v1_storage", rpc_params![block2_hash, items, Option::<String>::None])
			.await
			.expect("RPC call failed");

		// The block numbers should be different
		match (result1, result2) {
			(
				ArchiveStorageResult::Ok { items: items1 },
				ArchiveStorageResult::Ok { items: items2 },
			) => {
				assert_ne!(items1[0].value, items2[0].value, "Block numbers should differ");
			},
			_ => panic!("Expected Ok results"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_returns_error_for_unknown_block() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let unknown_hash = "0x0000000000000000000000000000000000000000000000000000000000000001";
		let items = vec![serde_json::json!({ "key": "0x1234", "type": "value" })];

		let result: ArchiveStorageResult = client
			.request("archive_v1_storage", rpc_params![unknown_hash, items, Option::<String>::None])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageResult::Err { error } => {
				assert!(
					error.contains("not found") || error.contains("Block"),
					"Should indicate block not found"
				);
			},
			_ => panic!("Expected Err result for unknown block"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_diff_detects_modified_value() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Create a test key
		let test_key = b"test_storage_diff_key";
		let test_key_hex = format!("0x{}", hex::encode(test_key));

		// Set initial value and build first block
		ctx.blockchain().set_storage_for_testing(test_key, Some(b"value1")).await;
		let block1 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block1_hash = format!("0x{}", hex::encode(block1.hash.as_bytes()));

		// Set modified value and build second block
		ctx.blockchain().set_storage_for_testing(test_key, Some(b"value2")).await;
		let block2 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block2_hash = format!("0x{}", hex::encode(block2.hash.as_bytes()));

		// Query storage diff
		let items = vec![serde_json::json!({
			"key": test_key_hex,
			"returnType": "value"
		})];

		let result: ArchiveStorageDiffResult = client
			.request("archive_v1_storageDiff", rpc_params![block2_hash, items, block1_hash])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageDiffResult::Ok { items } => {
				assert_eq!(items.len(), 1, "Should return one modified item");
				assert_eq!(items[0].key, test_key_hex);
				assert_eq!(items[0].diff_type, StorageDiffType::Modified);
				assert!(items[0].value.is_some(), "Value should be present");
				assert_eq!(
					items[0].value.as_ref().unwrap(),
					&format!("0x{}", hex::encode(b"value2"))
				);
			},
			ArchiveStorageDiffResult::Err { error } =>
				panic!("Expected Ok result, got error: {error}"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_diff_returns_empty_for_unchanged_keys() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Create a test key with value that won't change
		let test_key = b"test_unchanged_key";
		let test_key_hex = format!("0x{}", hex::encode(test_key));

		// Set value and build first block
		ctx.blockchain()
			.set_storage_for_testing(test_key, Some(b"constant_value"))
			.await;
		let block1 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block1_hash = format!("0x{}", hex::encode(block1.hash.as_bytes()));

		// Build second block without changing the value
		let block2 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block2_hash = format!("0x{}", hex::encode(block2.hash.as_bytes()));

		// Query storage diff
		let items = vec![serde_json::json!({
			"key": test_key_hex,
			"returnType": "value"
		})];

		let result: ArchiveStorageDiffResult = client
			.request("archive_v1_storageDiff", rpc_params![block2_hash, items, block1_hash])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageDiffResult::Ok { items } => {
				assert!(items.is_empty(), "Should return empty for unchanged keys");
			},
			ArchiveStorageDiffResult::Err { error } =>
				panic!("Expected Ok result, got error: {error}"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_diff_returns_added_for_new_key() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Build first block without the key
		let block1 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block1_hash = format!("0x{}", hex::encode(block1.hash.as_bytes()));

		// Add a new key and build second block
		let test_key = b"test_added_key";
		let test_key_hex = format!("0x{}", hex::encode(test_key));
		ctx.blockchain().set_storage_for_testing(test_key, Some(b"new_value")).await;
		let block2 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block2_hash = format!("0x{}", hex::encode(block2.hash.as_bytes()));

		// Query storage diff
		let items = vec![serde_json::json!({
			"key": test_key_hex,
			"returnType": "value"
		})];

		let result: ArchiveStorageDiffResult = client
			.request("archive_v1_storageDiff", rpc_params![block2_hash, items, block1_hash])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageDiffResult::Ok { items } => {
				assert_eq!(items.len(), 1, "Should return one added item");
				assert_eq!(items[0].key, test_key_hex);
				assert_eq!(items[0].diff_type, StorageDiffType::Added);
				assert!(items[0].value.is_some(), "Value should be present");
				assert_eq!(
					items[0].value.as_ref().unwrap(),
					&format!("0x{}", hex::encode(b"new_value"))
				);
			},
			ArchiveStorageDiffResult::Err { error } =>
				panic!("Expected Ok result, got error: {error}"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_diff_returns_deleted_for_removed_key() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Add a key and build first block
		let test_key = b"test_deleted_key";
		let test_key_hex = format!("0x{}", hex::encode(test_key));
		ctx.blockchain()
			.set_storage_for_testing(test_key, Some(b"will_be_deleted"))
			.await;
		let block1 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block1_hash = format!("0x{}", hex::encode(block1.hash.as_bytes()));

		// Delete the key and build second block
		ctx.blockchain().set_storage_for_testing(test_key, None).await;
		let block2 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block2_hash = format!("0x{}", hex::encode(block2.hash.as_bytes()));

		// Query storage diff
		let items = vec![serde_json::json!({
			"key": test_key_hex,
			"returnType": "value"
		})];

		let result: ArchiveStorageDiffResult = client
			.request("archive_v1_storageDiff", rpc_params![block2_hash, items, block1_hash])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageDiffResult::Ok { items } => {
				assert_eq!(items.len(), 1, "Should return one deleted item");
				assert_eq!(items[0].key, test_key_hex);
				assert_eq!(items[0].diff_type, StorageDiffType::Deleted);
				assert!(items[0].value.is_none(), "Value should be None for deleted key");
				assert!(items[0].hash.is_none(), "Hash should be None for deleted key");
			},
			ArchiveStorageDiffResult::Err { error } =>
				panic!("Expected Ok result, got error: {error}"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_diff_returns_hash_when_requested() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Create a test key
		let test_key = b"test_hash_key";
		let test_key_hex = format!("0x{}", hex::encode(test_key));

		// Set initial value and build first block
		ctx.blockchain().set_storage_for_testing(test_key, Some(b"value1")).await;
		let block1 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block1_hash = format!("0x{}", hex::encode(block1.hash.as_bytes()));

		// Set modified value and build second block
		let new_value = b"value2";
		ctx.blockchain().set_storage_for_testing(test_key, Some(new_value)).await;
		let block2 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block2_hash = format!("0x{}", hex::encode(block2.hash.as_bytes()));

		// Query storage diff with hash returnType
		let items = vec![serde_json::json!({
			"key": test_key_hex,
			"returnType": "hash"
		})];

		let result: ArchiveStorageDiffResult = client
			.request("archive_v1_storageDiff", rpc_params![block2_hash, items, block1_hash])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageDiffResult::Ok { items } => {
				assert_eq!(items.len(), 1, "Should return one modified item");
				assert_eq!(items[0].diff_type, StorageDiffType::Modified);
				assert!(items[0].value.is_none(), "Value should not be present");
				assert!(items[0].hash.is_some(), "Hash should be present");
				let expected_hash = format!("0x{}", hex::encode(sp_core::blake2_256(new_value)));
				assert_eq!(items[0].hash.as_ref().unwrap(), &expected_hash);
			},
			ArchiveStorageDiffResult::Err { error } =>
				panic!("Expected Ok result, got error: {error}"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_diff_returns_error_for_unknown_hash() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let unknown_hash = "0x0000000000000000000000000000000000000000000000000000000000000001";
		let valid_hash =
			format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));
		let items = vec![serde_json::json!({ "key": "0x1234", "returnType": "value" })];

		let result: ArchiveStorageDiffResult = client
			.request("archive_v1_storageDiff", rpc_params![unknown_hash, items, valid_hash])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageDiffResult::Err { error } => {
				assert!(
					error.contains("not found") || error.contains("Block"),
					"Should indicate block not found"
				);
			},
			_ => panic!("Expected Err result for unknown block"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_diff_returns_error_for_unknown_previous_hash() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		let valid_hash =
			format!("0x{}", hex::encode(ctx.blockchain().head_hash().await.as_bytes()));
		let unknown_hash = "0x0000000000000000000000000000000000000000000000000000000000000001";
		let items = vec![serde_json::json!({ "key": "0x1234", "returnType": "value" })];

		let result: ArchiveStorageDiffResult = client
			.request("archive_v1_storageDiff", rpc_params![valid_hash, items, unknown_hash])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageDiffResult::Err { error } => {
				assert!(
					error.contains("not found") || error.contains("Previous block"),
					"Should indicate previous block not found"
				);
			},
			_ => panic!("Expected Err result for unknown previous block"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_diff_uses_parent_when_previous_hash_omitted() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Create a test key
		let test_key = b"test_parent_key";
		let test_key_hex = format!("0x{}", hex::encode(test_key));

		// Set initial value and build first block (parent)
		ctx.blockchain().set_storage_for_testing(test_key, Some(b"parent_value")).await;
		ctx.blockchain().build_empty_block().await.expect("Failed to build block");

		// Set modified value and build second block (child)
		ctx.blockchain().set_storage_for_testing(test_key, Some(b"child_value")).await;

		let child_block =
			ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let child_hash = format!("0x{}", hex::encode(child_block.hash.as_bytes()));

		// Query storage diff without previous_hash (should use parent)
		let items = vec![serde_json::json!({
			"key": test_key_hex,
			"returnType": "value"
		})];

		let result: ArchiveStorageDiffResult = client
			.request(
				"archive_v1_storageDiff",
				rpc_params![child_hash, items, Option::<String>::None],
			)
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageDiffResult::Ok { items } => {
				assert_eq!(items.len(), 1, "Should return one modified item");
				assert_eq!(items[0].diff_type, StorageDiffType::Modified);
				assert_eq!(
					items[0].value.as_ref().unwrap(),
					&format!("0x{}", hex::encode(b"child_value"))
				);
			},
			ArchiveStorageDiffResult::Err { error } =>
				panic!("Expected Ok result, got error: {error}"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn archive_storage_diff_handles_multiple_items() {
		let ctx = TestContext::for_rpc_server().await;
		let client = WsClientBuilder::default()
			.build(&ctx.ws_url())
			.await
			.expect("Failed to connect");

		// Create test keys
		let added_key = b"test_multi_added";
		let modified_key = b"test_multi_modified";
		let deleted_key = b"test_multi_deleted";
		let unchanged_key = b"test_multi_unchanged";

		// Set up initial state for block 1
		ctx.blockchain().set_storage_for_testing(modified_key, Some(b"old_value")).await;
		ctx.blockchain().set_storage_for_testing(deleted_key, Some(b"to_delete")).await;
		ctx.blockchain().set_storage_for_testing(unchanged_key, Some(b"constant")).await;
		let block1 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block1_hash = format!("0x{}", hex::encode(block1.hash.as_bytes()));

		// Modify state for block 2
		ctx.blockchain().set_storage_for_testing(added_key, Some(b"new_key")).await;
		ctx.blockchain().set_storage_for_testing(modified_key, Some(b"new_value")).await;
		ctx.blockchain().set_storage_for_testing(deleted_key, None).await;
		// unchanged_key stays the same
		let block2 = ctx.blockchain().build_empty_block().await.expect("Failed to build block");
		let block2_hash = format!("0x{}", hex::encode(block2.hash.as_bytes()));

		// Query storage diff for all keys
		let items = vec![
			serde_json::json!({ "key": format!("0x{}", hex::encode(added_key)), "returnType": "value" }),
			serde_json::json!({ "key": format!("0x{}", hex::encode(modified_key)), "returnType": "value" }),
			serde_json::json!({ "key": format!("0x{}", hex::encode(deleted_key)), "returnType": "value" }),
			serde_json::json!({ "key": format!("0x{}", hex::encode(unchanged_key)), "returnType": "value" }),
		];

		let result: ArchiveStorageDiffResult = client
			.request("archive_v1_storageDiff", rpc_params![block2_hash, items, block1_hash])
			.await
			.expect("RPC call failed");

		match result {
			ArchiveStorageDiffResult::Ok { items } => {
				// Should have 3 items (added, modified, deleted) but NOT unchanged
				assert_eq!(items.len(), 3, "Should return 3 changed items (not unchanged)");

				// Find each item by key
				let added = items.iter().find(|i| i.key == format!("0x{}", hex::encode(added_key)));
				let modified =
					items.iter().find(|i| i.key == format!("0x{}", hex::encode(modified_key)));
				let deleted =
					items.iter().find(|i| i.key == format!("0x{}", hex::encode(deleted_key)));
				let unchanged =
					items.iter().find(|i| i.key == format!("0x{}", hex::encode(unchanged_key)));

				assert!(added.is_some(), "Added key should be in results");
				assert_eq!(added.unwrap().diff_type, StorageDiffType::Added);

				assert!(modified.is_some(), "Modified key should be in results");
				assert_eq!(modified.unwrap().diff_type, StorageDiffType::Modified);

				assert!(deleted.is_some(), "Deleted key should be in results");
				assert_eq!(deleted.unwrap().diff_type, StorageDiffType::Deleted);

				assert!(unchanged.is_none(), "Unchanged key should NOT be in results");
			},
			ArchiveStorageDiffResult::Err { error } =>
				panic!("Expected Ok result, got error: {error}"),
		}
	}
}