Skip to main content

ledger_engine/
source.rs

1//! Ledger source: xrpld gRPC, as in Clio.
2//!
3//! `GetLedger` with transactions and objects returns, in one request, the header,
4//! all transactions with metadata, and the state changes relative to the
5//! previous ledger. Without rate limits only for hosts listed in
6//! `secure_gateway` in the xrpld config; the `user` field is needed for the same reason.
7
8use tonic::transport::{Channel, Endpoint};
9use witness_core::ledger::{HEADER_LEN, LedgerHeader};
10
11use crate::ledger::{Change, Ledger, StateChange};
12use crate::proto::get_ledger_response::Transactions;
13use crate::proto::ledger_specifier::{Ledger as Spec, Shortcut};
14use crate::proto::raw_ledger_object::ModificationType;
15use crate::proto::xrp_ledger_api_service_client::XrpLedgerApiServiceClient;
16use crate::proto::{GetLedgerDataRequest, GetLedgerRequest, LedgerSpecifier};
17
18/// A message with a full ledger can be tens of megabytes.
19const MAX_MESSAGE: usize = 256 << 20;
20
21/// Header from gRPC: xrpld appends the ledger hash (32 bytes) to the 118-byte
22/// header. We cut it off and compare it with the hash we compute ourselves; we
23/// don't take the node's word for it.
24fn split_header(raw: Vec<u8>) -> Result<Vec<u8>, String> {
25    match raw.len() {
26        HEADER_LEN => Ok(raw),
27        n if n == HEADER_LEN + 32 => {
28            let header = raw[..HEADER_LEN].to_vec();
29            let h = LedgerHeader::parse(&header).map_err(|e| e.to_string())?;
30            if h.hash()[..] != raw[HEADER_LEN..] {
31                return Err(format!(
32                    "ledger {}: hash from the node does not match the computed one",
33                    h.sequence
34                ));
35            }
36            Ok(header)
37        }
38        n => Err(format!("ledger header from the node is {n} bytes")),
39    }
40}
41
42#[derive(Debug, Clone)]
43pub struct Source {
44    client: XrpLedgerApiServiceClient<Channel>,
45    user: String,
46}
47
48impl Source {
49    pub async fn connect(url: &str, user: &str) -> Result<Source, String> {
50        let channel = Endpoint::from_shared(url.to_owned())
51            .map_err(|e| format!("address {url}: {e}"))?
52            .connect()
53            .await
54            .map_err(|e| format!("connecting to {url}: {e}"))?;
55        Ok(Source {
56            client: XrpLedgerApiServiceClient::new(channel).max_decoding_message_size(MAX_MESSAGE),
57            user: user.to_owned(),
58        })
59    }
60
61    async fn get(
62        &mut self,
63        spec: Spec,
64        full: bool,
65    ) -> Result<crate::proto::GetLedgerResponse, String> {
66        let req = GetLedgerRequest {
67            ledger: Some(LedgerSpecifier { ledger: Some(spec) }),
68            transactions: full,
69            expand: full,
70            get_objects: full,
71            user: self.user.clone(),
72            ..Default::default()
73        };
74        self.client
75            .get_ledger(req)
76            .await
77            .map(tonic::Response::into_inner)
78            .map_err(|e| format!("GetLedger: {} {}", e.code(), e.message()))
79    }
80
81    /// Ledger state objects with keys strictly greater than `marker` and strictly
82    /// less than `end` (empty means unbounded). Returns the objects and a
83    /// continuation marker; an empty marker means the range is exhausted.
84    pub async fn state_page(
85        &mut self,
86        sequence: u32,
87        marker: &[u8],
88        end: &[u8],
89    ) -> Result<(Vec<([u8; 32], Vec<u8>)>, Vec<u8>), String> {
90        let req = GetLedgerDataRequest {
91            ledger: Some(LedgerSpecifier {
92                ledger: Some(Spec::Sequence(sequence)),
93            }),
94            marker: marker.to_vec(),
95            end_marker: end.to_vec(),
96            user: self.user.clone(),
97            ..Default::default()
98        };
99        let r = self
100            .client
101            .get_ledger_data(req)
102            .await
103            .map(tonic::Response::into_inner)
104            .map_err(|e| format!("GetLedgerData: {} {}", e.code(), e.message()))?;
105        // xrpld does not fill in the sequence in GetLedgerData responses (checked on 3.4.1),
106        // so we reject only if it is present and different. Objects from another ledger
107        // would fail anyway: the state root is checked against the header.
108        if r.ledger_index != 0 && r.ledger_index != sequence {
109            return Err(format!(
110                "asked for {sequence}, node returned {} ({} objects, hash {} bytes, marker {} bytes)",
111                r.ledger_index,
112                r.ledger_objects.as_ref().map_or(0, |o| o.objects.len()),
113                r.ledger_hash.len(),
114                r.marker.len()
115            ));
116        }
117        let mut out = Vec::new();
118        for o in r.ledger_objects.map(|x| x.objects).unwrap_or_default() {
119            let key: [u8; 32] = o
120                .key
121                .as_slice()
122                .try_into()
123                .map_err(|_| "object key is not 32 bytes".to_string())?;
124            out.push((key, o.data));
125        }
126        Ok((out, r.marker))
127    }
128
129    /// Ledger header (118 bytes) without transactions.
130    pub async fn header(&mut self, sequence: u32) -> Result<Vec<u8>, String> {
131        let r = self.get(Spec::Sequence(sequence), false).await?;
132        if !r.validated {
133            return Err(format!("ledger {sequence} is not validated on the node"));
134        }
135        split_header(r.ledger_header)
136    }
137
138    /// Requires the node to exempt us from rate limits
139    /// (`is_unlimited` in the response).
140    ///
141    /// xrpld charges by address, not by client: without the exemption, heavy
142    /// requests are charged to an address shared with neighboring services.
143    ///
144    /// The exemption alone is not enough. A state snapshot taken on a machine
145    /// running Clio had the exemption but still loaded the machine: 4.8 GB in
146    /// 3.6 minutes over a tunnel and onto disk. Clio fell behind reading its
147    /// subscriptions, both upstream nodes treated it as a slow client and dropped
148    /// it, and it went down twice. Don't run heavy jobs on a machine running Clio.
149    pub async fn require_unlimited(&mut self) -> Result<(), String> {
150        let r = self
151            .get(Spec::Shortcut(Shortcut::Validated as i32), false)
152            .await?;
153        if r.is_unlimited {
154            Ok(())
155        } else {
156            Err(
157                "node does not exempt us from rate limits (is_unlimited = false): \
158                 charges will go to the shared address and get neighboring services disconnected; \
159                 check secure_gateway in [port_grpc] and the user field"
160                    .into(),
161            )
162        }
163    }
164
165    /// Sequence of the latest validated ledger.
166    pub async fn validated(&mut self) -> Result<u32, String> {
167        let r = self
168            .get(Spec::Shortcut(Shortcut::Validated as i32), false)
169            .await?;
170        let h = LedgerHeader::parse(&split_header(r.ledger_header)?).map_err(|e| e.to_string())?;
171        Ok(h.sequence)
172    }
173
174    /// The whole ledger. Fails if the node does not consider it validated or
175    /// did not return the state changes.
176    pub async fn ledger(&mut self, sequence: u32) -> Result<Ledger, String> {
177        let r = self.get(Spec::Sequence(sequence), true).await?;
178        if !r.validated {
179            return Err(format!("ledger {sequence} is not validated on the node"));
180        }
181        if !r.objects_included {
182            return Err(format!(
183                "node did not return state changes for ledger {sequence}"
184            ));
185        }
186        let transactions = match r.transactions {
187            Some(Transactions::TransactionsList(l)) => l
188                .transactions
189                .into_iter()
190                .map(|t| (t.transaction_blob, t.metadata_blob))
191                .collect(),
192            Some(Transactions::HashesList(_)) => {
193                return Err("node returned hashes instead of transactions".into());
194            }
195            None => Vec::new(),
196        };
197        let mut changes = Vec::new();
198        for o in r.ledger_objects.map(|x| x.objects).unwrap_or_default() {
199            let key: [u8; 32] = o
200                .key
201                .as_slice()
202                .try_into()
203                .map_err(|_| "object key is not 32 bytes".to_string())?;
204            let change = match ModificationType::try_from(o.mod_type) {
205                Ok(ModificationType::Created) => Change::Created,
206                Ok(ModificationType::Deleted) => Change::Deleted,
207                Ok(ModificationType::Modified) => Change::Modified,
208                // Older xrpld versions don't mark the type: a deleted object has no data.
209                _ if o.data.is_empty() => Change::Deleted,
210                _ => Change::Modified,
211            };
212            changes.push(StateChange {
213                key,
214                change,
215                data: o.data,
216            });
217        }
218        Ok(Ledger {
219            header: split_header(r.ledger_header)?,
220            transactions,
221            changes,
222        })
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn grpc_header_with_appended_hash_is_checked() {
232        let header = vec![1u8; HEADER_LEN];
233        let hash = LedgerHeader::parse(&header).unwrap().hash();
234        let mut raw = header.clone();
235        raw.extend_from_slice(&hash);
236        assert_eq!(split_header(raw.clone()).unwrap(), header);
237        let last = raw.len() - 1;
238        raw[last] ^= 1;
239        assert!(split_header(raw).is_err());
240        assert_eq!(split_header(header.clone()).unwrap(), header);
241        assert!(split_header(vec![0; 100]).is_err());
242    }
243}