Skip to main content

ogmios_client/chain_synchronization/
mod.rs

1//! Chain Synchronization client for Ogmios.
2//!
3//! This module provides functionality for synchronizing with the Cardano blockchain
4//! using the Ouroboros mini-protocols via Ogmios.
5
6mod client;
7
8pub use client::*;
9
10use crate::connection::InteractionContext;
11use crate::error::Result;
12use crate::schema::{Block, Point, Tip, responses::{FindIntersectionResponse, NextBlockResponse}};
13use serde::{Deserialize, Serialize};
14
15/// Intersection result from findIntersection.
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17#[serde(rename_all = "camelCase")]
18pub struct Intersection {
19    /// The intersection point found.
20    pub point: Point,
21    /// Current tip.
22    pub tip: Tip,
23}
24
25/// Message handlers for chain synchronization events.
26///
27/// These callbacks are invoked when blocks are received or rolled back.
28pub trait ChainSynchronizationMessageHandlers: Send + Sync {
29    /// Called when a new block is received (roll forward).
30    fn on_roll_forward(&mut self, block: Block, tip: Tip) -> Result<()>;
31
32    /// Called when a rollback occurs (roll backward).
33    fn on_roll_backward(&mut self, point: Point, tip: Tip) -> Result<()>;
34}
35
36/// Find an intersection point between the client and the node.
37///
38/// This function attempts to find a common point in the blockchain history
39/// between the provided points and the node's chain.
40///
41/// # Arguments
42///
43/// * `context` - The interaction context.
44/// * `points` - A list of points to try to intersect with.
45///
46/// # Returns
47///
48/// The intersection point and current tip if found.
49pub async fn find_intersection(
50    context: &InteractionContext,
51    points: Vec<Point>,
52) -> Result<Intersection> {
53    #[derive(Serialize)]
54    struct Params {
55        points: Vec<Point>,
56    }
57
58    let response: FindIntersectionResponse = context
59        .request("findIntersection", Some(Params { points }))
60        .await?;
61
62    if let Some(point) = response.intersection {
63        Ok(Intersection {
64            point,
65            tip: response.tip,
66        })
67    } else {
68        Err(crate::error::OgmiosError::IntersectionNotFound {
69            tip: Some(format!("{:?}", response.tip)),
70        })
71    }
72}
73
74/// Request the next block from the chain.
75///
76/// This function requests the next block in the chain synchronization sequence.
77///
78/// # Arguments
79///
80/// * `context` - The interaction context.
81///
82/// # Returns
83///
84/// The next block response, which can be either a roll forward with a new block
85/// or a roll backward indicating a rollback.
86pub async fn next_block(context: &InteractionContext) -> Result<NextBlockResponse> {
87    context.request("nextBlock", None::<()>).await
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn test_intersection_creation() {
96        let intersection = Intersection {
97            point: Point::origin(),
98            tip: Tip::Origin("origin".to_string()),
99        };
100        assert!(matches!(intersection.point, Point::Origin(_)));
101    }
102}