use rollblock::types::{Operation, StoreKey as Key};
use rollblock::{SimpleStoreFacade, StoreConfig, StoreFacade};
fn acct(id: u8) -> Key {
Key::from_prefix([id, 0, 0, 0, 0, 0, 0, 0])
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("🔗 Blockchain Reorganization Example\n");
let config = StoreConfig::new(
"./data/blockchain_example",
4, 1000, 1, false, )?
.without_remote_server();
println!("📦 Creating store with manual reorg handling\n");
let store = SimpleStoreFacade::new(config)?;
println!("📖 Building initial chain:\n");
println!(" Block 100: Alice receives 1000 coins");
let alice = acct(1);
store.set(
100,
vec![Operation {
key: alice,
value: 1000.into(),
}],
)?;
println!(" Block 101: Alice sends 200 to Bob");
let bob = acct(2);
store.set(
101,
vec![
Operation {
key: alice,
value: 800.into(), },
Operation {
key: bob,
value: 200.into(), },
],
)?;
println!(" Block 102: Bob sends 50 to Charlie");
let charlie = acct(3);
store.set(
102,
vec![
Operation {
key: bob,
value: 150.into(), },
Operation {
key: charlie,
value: 50.into(), },
],
)?;
println!("\n📊 Current state (at block 102):");
println!(" Alice: {} coins", store.get(alice)?);
println!(" Bob: {} coins", store.get(bob)?);
println!(" Charlie: {} coins", store.get(charlie)?);
println!("\n⚠️ CHAIN REORGANIZATION DETECTED!\n");
println!(" Alternative chain fork starting from block 101");
println!(" (Different transaction history)\n");
println!(" Rolling back to block 100 before applying alternative history...");
store.rollback(100)?;
println!(" ✓ Rollback completed\n");
println!(" Block 101 (new): Alice sends 300 to David instead");
let david = acct(4);
store.set(
101,
vec![
Operation {
key: alice,
value: 700.into(), },
Operation {
key: david,
value: 300.into(), },
],
)?;
println!(" ✓ New block 101 applied\n");
println!("📊 State after reorganization (at block 101):");
println!(" Alice: {} coins", store.get(alice)?);
println!(" Bob: {} coins (should be 0)", store.get(bob)?);
println!(" Charlie: {} coins (should be 0)", store.get(charlie)?);
println!(" David: {} coins", store.get(david)?);
println!("\n Block 102 (new): David sends 100 to Eve");
let eve = acct(5);
store.set(
102,
vec![
Operation {
key: david,
value: 200.into(), },
Operation {
key: eve,
value: 100.into(), },
],
)?;
println!("\n📊 Final state (at block 102 on new chain):");
println!(" Alice: {} coins", store.get(alice)?);
println!(" David: {} coins", store.get(david)?);
println!(" Eve: {} coins", store.get(eve)?);
println!("\n✅ Reorganization handled with explicit rollback!");
println!("\nTip: Attempting to apply block 101 without rolling back first");
println!("would return a BlockIdNotIncreasing error.");
Ok(())
}