1use std::collections::{BTreeSet, HashMap};
26
27use base64::Engine;
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30
31use crate::keys::node_public;
32use crate::manifest::Manifest;
33use crate::negative_unl::NegativeUnl;
34use crate::quorum::{
35 Decision, Key, Observed, Policy, PublishedList, assess, decide, default_threshold,
36};
37use crate::skiplist;
38use crate::stateproof::StateProof;
39use crate::txproof::TxProof;
40use crate::unl::verify_list;
41use crate::validation::Validation;
42
43pub const FORMAT: &str = "xrpl-witness/evidence/1";
44pub const FORMAT_V2: &str = "xrpl-witness/evidence/2";
46pub const FORMAT_V3: &str = "xrpl-witness/evidence/3";
49pub const FORMAT_V4: &str = "xrpl-witness/evidence/4";
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct Bundle {
54 pub format: String,
55 pub ledger_index: u32,
56 pub ledger_hash: String,
58 pub policy: PolicySpec,
60 pub publisher_responses: Vec<PublisherResponse>,
61 pub manifests: Vec<String>,
63 pub negative_unl: Option<NegativeUnlEvidence>,
64 pub validations: Vec<ValidationEvidence>,
65 pub provenance: Provenance,
66 #[serde(default, skip_serializing_if = "Vec::is_empty")]
68 pub transactions: Vec<TxProof>,
69 #[serde(default, skip_serializing_if = "Vec::is_empty")]
73 pub chain: Vec<String>,
74 #[serde(default, skip_serializing_if = "Vec::is_empty")]
76 pub objects: Vec<StateProof>,
77 #[serde(default, skip_serializing_if = "Vec::is_empty")]
81 pub skips: Vec<SkipHop>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct SkipHop {
89 pub list: StateProof,
91 pub headers: Vec<String>,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
98pub struct ObjectCheck {
99 pub key: Option<String>,
100 pub present: Option<bool>,
102 pub ledger_index: Option<u32>,
103 pub proven: bool,
106 pub via_chain: bool,
108 pub error: Option<String>,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
113pub struct TxCheck {
114 pub tx_hash: Option<String>,
115 pub included: bool,
117 pub in_confirmed_ledger: bool,
120 #[serde(default)]
122 pub via_chain: bool,
123 pub error: Option<String>,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127pub struct PolicySpec {
128 pub publishers: Vec<String>,
130 pub threshold: usize,
132 pub trusted_directly: Vec<String>,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137pub struct PublisherResponse {
138 pub site: String,
139 pub body: String,
141 pub first_seen_ms: Option<u64>,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146pub struct NegativeUnlEvidence {
147 pub flag_ledger: u32,
148 pub flag_ledger_hash: Option<String>,
149 pub node_binary: Option<String>,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154pub struct ValidationEvidence {
155 pub data: String,
157 pub received_ms: u64,
158}
159
160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161pub struct Provenance {
162 pub source: String,
164 pub exported_ms: u64,
165 pub seals: Vec<String>,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct Trust {
172 pub publishers: Vec<Key>,
173 pub threshold: usize,
174 pub trusted_directly: BTreeSet<Key>,
175}
176
177#[derive(Debug, Default)]
179pub struct FromResponse {
180 pub lists: Vec<PublishedList>,
182 pub manifests: Vec<Manifest>,
184 pub untrusted: usize,
187 pub publisher_manifests: Vec<Manifest>,
190}
191
192pub fn lists_from_response(body: &[u8], publishers: &[Key]) -> Result<FromResponse, String> {
195 let b64 = |s: &str| base64::engine::general_purpose::STANDARD.decode(s).ok();
196 let v: Value =
197 serde_json::from_slice(body).map_err(|e| format!("response is not json: {e}"))?;
198 let manifest = v.get("manifest").and_then(Value::as_str).and_then(b64);
199 let item = |o: &Value, fallback: Option<&Vec<u8>>| -> Option<(Vec<u8>, Vec<u8>, Vec<u8>)> {
202 let own = o.get("manifest").and_then(Value::as_str).and_then(b64);
203 Some((
204 b64(o.get("blob")?.as_str()?)?,
205 own.or_else(|| fallback.cloned())?,
206 hex::decode(o.get("signature")?.as_str()?).ok()?,
207 ))
208 };
209 let mut blobs: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> =
210 item(&v, manifest.as_ref()).into_iter().collect();
211 for o in v
212 .get("blobs_v2")
213 .and_then(Value::as_array)
214 .into_iter()
215 .flatten()
216 {
217 blobs.extend(item(o, manifest.as_ref()));
218 }
219 if blobs.is_empty() && manifest.is_none() {
220 return Err("response has no publisher manifest".into());
221 }
222 let mut out = FromResponse::default();
223 let mut seen_manifests: Vec<&Vec<u8>> = manifest.iter().collect();
224 seen_manifests.extend(blobs.iter().map(|(_, m, _)| m));
225 for raw in seen_manifests {
226 if let Ok(m) = Manifest::parse(raw)
227 && m.verify().is_ok()
228 && publishers.contains(&m.master_key)
229 && !out
230 .publisher_manifests
231 .iter()
232 .any(|x| x.master_key == m.master_key && x.sequence == m.sequence)
233 {
234 out.publisher_manifests.push(m);
235 }
236 }
237 for (blob, manifest, sig) in blobs {
238 let Some((publisher, pm)) = publishers
239 .iter()
240 .find_map(|p| verify_list(p, &manifest, &blob, &sig).ok().map(|m| (p, m)))
241 else {
242 out.untrusted += 1;
243 continue;
244 };
245 let list: Value =
246 serde_json::from_slice(&blob).map_err(|e| format!("list is not json: {e}"))?;
247 let mut validators = BTreeSet::new();
248 for e in list
249 .get("validators")
250 .and_then(Value::as_array)
251 .into_iter()
252 .flatten()
253 {
254 if let Some(k) = e
255 .get("validation_public_key")
256 .and_then(Value::as_str)
257 .and_then(|h| hex::decode(h).ok())
258 {
259 validators.insert(k);
260 }
261 if let Some(m) = e
262 .get("manifest")
263 .and_then(Value::as_str)
264 .and_then(b64)
265 .and_then(|raw| Manifest::parse(&raw).ok())
266 {
267 out.manifests.push(m);
268 }
269 }
270 let secs = |k: &str| {
271 list.get(k)
272 .and_then(Value::as_u64)
273 .and_then(|v| u32::try_from(v).ok())
274 };
275 out.lists.push(PublishedList {
276 publisher: publisher.clone(),
277 sequence: list.get("sequence").and_then(Value::as_u64).unwrap_or(0),
278 validators,
279 effective: secs("effective"),
280 expiration: secs("expiration"),
281 manifest_sequence: pm.sequence,
282 });
283 }
284 Ok(out)
285}
286
287pub fn current_lists(
298 lists: &mut Vec<PublishedList>,
299 publisher_manifests: &[Manifest],
300 problems: &mut Vec<String>,
301) {
302 let mut latest: HashMap<&Key, &Manifest> = HashMap::new();
303 for m in publisher_manifests {
304 if m.verify().is_err() {
305 continue;
306 }
307 let e = latest.entry(&m.master_key).or_insert(m);
308 if m.sequence > e.sequence {
309 *e = m;
310 }
311 }
312 let mut revoked = BTreeSet::new();
313 for (p, m) in &latest {
314 if m.is_revoked() {
315 revoked.insert((*p).clone());
316 problems.push(format!(
317 "publisher {}: key revoked, its lists are ignored",
318 hex::encode_upper(p)
319 ));
320 }
321 }
322 lists.retain(|l| match latest.get(&l.publisher) {
323 _ if revoked.contains(&l.publisher) => false,
324 Some(m) => l.manifest_sequence >= m.sequence,
325 None => true,
326 });
327}
328
329pub fn signing_to_master(manifests: &[Manifest]) -> (HashMap<Key, Key>, usize) {
337 let mut latest: HashMap<Key, &Manifest> = HashMap::new();
338 let mut rejected = 0;
339 for m in manifests {
340 if m.verify().is_err() {
341 rejected += 1;
342 continue;
343 }
344 let e = latest.entry(m.master_key.clone()).or_insert(m);
345 if m.sequence > e.sequence {
346 *e = m;
347 }
348 }
349 let mut out: HashMap<Key, Key> = HashMap::new();
350 let mut contested = BTreeSet::new();
351 for (master, m) in &latest {
352 if m.is_revoked() {
353 continue;
354 }
355 let Some(sk) = &m.signing_key else { continue };
356 match out.get(sk) {
357 Some(other) if other != master => {
358 contested.insert(sk.clone());
359 }
360 _ => {
361 out.insert(sk.clone(), master.clone());
362 }
363 }
364 }
365 for sk in contested {
366 out.remove(&sk);
367 }
368 (out, rejected)
369}
370
371#[derive(Debug, Clone, PartialEq, Serialize)]
373pub struct Report {
374 pub ledger_index: u32,
375 pub confirmed_hash: Option<String>,
377 pub matches_claim: bool,
379 pub unl_size: usize,
380 pub effective_size: usize,
381 pub quorum: usize,
382 pub signers: usize,
383 pub policy_differs: bool,
385 pub policy_observed_after: bool,
387 pub rule: &'static str,
392 pub policy_window: Option<(u32, u32)>,
396 pub missing_publishers: Vec<String>,
399 pub policies: Vec<PolicyUsed>,
402 pub negative_unl: Vec<String>,
404 pub with_claimed_negative_unl: Option<ClaimedNegativeUnl>,
406 pub not_seen: Vec<String>,
407 pub conflicting: Vec<String>,
408 pub unattributed: usize,
409 pub untrusted_publishers: Vec<String>,
411 pub problems: Vec<String>,
413 pub transactions: Vec<TxCheck>,
415 pub chain_ok: bool,
417 pub target_ledger: Option<u32>,
420 pub target_hash: Option<String>,
421 pub objects: Vec<ObjectCheck>,
423 pub skip_hops: usize,
425}
426
427#[derive(Debug, Clone, PartialEq, Serialize)]
430pub struct ClaimedNegativeUnl {
431 pub effective_size: usize,
432 pub quorum: usize,
433 pub confirmed_hash: Option<String>,
434 pub signers: usize,
435}
436
437#[derive(Debug, Clone, PartialEq, Serialize)]
439pub struct ListUsed {
440 pub publisher: String,
441 pub sequence: u64,
442 pub effective: Option<u32>,
443 pub expiration: Option<u32>,
444}
445
446#[derive(Debug, Clone, PartialEq, Serialize)]
448pub struct PolicyUsed {
449 pub lists: Vec<ListUsed>,
450 pub unl_size: usize,
451 pub quorum: usize,
452 pub confirmed_hash: Option<String>,
453}
454
455pub const RULE_FULL_UNL: &str = "full-unl";
457
458pub fn verify(bundle: &Bundle, trust: &Trust) -> Report {
460 let mut problems = Vec::new();
461 if ![FORMAT, FORMAT_V2, FORMAT_V3, FORMAT_V4].contains(&bundle.format.as_str()) {
462 problems.push(format!(
463 "format {}, expected {FORMAT}, {FORMAT_V2}, {FORMAT_V3} or {FORMAT_V4}",
464 bundle.format
465 ));
466 }
467 let hex_set =
468 |v: &[String]| -> BTreeSet<Key> { v.iter().filter_map(|h| hex::decode(h).ok()).collect() };
469 let policy_differs = hex_set(&bundle.policy.publishers)
470 != trust.publishers.iter().cloned().collect()
471 || hex_set(&bundle.policy.trusted_directly) != trust.trusted_directly
472 || bundle.policy.threshold != trust.threshold;
473
474 let mut lists: Vec<PublishedList> = Vec::new();
475 let mut manifests: Vec<Manifest> = Vec::new();
476 let mut publisher_manifests: Vec<Manifest> = Vec::new();
477 let mut first_seen = u64::MAX;
478 let mut untrusted = Vec::new();
479 for r in &bundle.publisher_responses {
480 let Ok(body) = base64::engine::general_purpose::STANDARD.decode(&r.body) else {
481 problems.push(format!("{}: body is not base64", r.site));
482 continue;
483 };
484 match lists_from_response(&body, &trust.publishers) {
485 Ok(got) => {
486 if got.untrusted > 0 {
487 untrusted.push(r.site.clone());
488 }
489 if !got.lists.is_empty() {
490 first_seen = first_seen.min(r.first_seen_ms.unwrap_or(u64::MAX));
491 }
492 lists.extend(got.lists);
493 manifests.extend(got.manifests);
494 publisher_manifests.extend(got.publisher_manifests);
495 }
496 Err(e) => problems.push(format!("{}: {e}", r.site)),
497 }
498 }
499 for m in &bundle.manifests {
500 match hex::decode(m)
501 .ok()
502 .and_then(|raw| Manifest::parse(&raw).ok())
503 {
504 Some(m) => {
505 if trust.publishers.contains(&m.master_key) {
506 publisher_manifests.push(m.clone());
507 }
508 manifests.push(m);
509 }
510 None => problems.push("cannot parse manifest".into()),
511 }
512 }
513 current_lists(&mut lists, &publisher_manifests, &mut problems);
514 let (to_master, rejected) = signing_to_master(&manifests);
515 if rejected > 0 {
516 problems.push(format!("manifests with an invalid signature: {rejected}"));
517 }
518
519 let negative: BTreeSet<Key> = match &bundle.negative_unl {
520 None => BTreeSet::new(),
521 Some(n) => {
522 if n.flag_ledger >= bundle.ledger_index {
523 problems.push("Negative UNL is not from the previous flag ledger".into());
524 }
525 match n.node_binary.as_deref().map(hex::decode) {
526 None => BTreeSet::new(),
527 Some(Ok(raw)) => match NegativeUnl::parse(&raw) {
528 Ok(x) => x.disabled.into_iter().map(|d| d.master_key).collect(),
529 Err(e) => {
530 problems.push(format!("Negative UNL: {e}"));
531 BTreeSet::new()
532 }
533 },
534 Some(Err(_)) => {
535 problems.push("Negative UNL is not hex".into());
536 BTreeSet::new()
537 }
538 }
539 }
540 };
541
542 let mut observed = Vec::new();
543 let mut first_validation = u64::MAX;
544 for (i, v) in bundle.validations.iter().enumerate() {
545 let parsed = hex::decode(&v.data)
546 .map_err(|_| "not hex".to_string())
547 .and_then(|raw| Validation::parse(&raw).map_err(|e| e.to_string()));
548 let val = match parsed {
549 Ok(x) => x,
550 Err(e) => {
551 problems.push(format!("validation {i}: {e}"));
552 continue;
553 }
554 };
555 if let Err(e) = val.verify() {
556 problems.push(format!("validation {i}: {e}"));
557 continue;
558 }
559 if val.ledger_sequence != bundle.ledger_index {
560 problems.push(format!("validation {i}: ledger {}", val.ledger_sequence));
561 continue;
562 }
563 first_validation = first_validation.min(v.received_ms);
564 observed.push(Observed {
565 master_key: to_master.get(&val.signing_pub_key).cloned(),
566 full: val.is_full(),
567 ledger_hash: val.ledger_hash,
568 signing_key: val.signing_pub_key,
569 signing_time: val.signing_time,
570 });
571 }
572
573 let hashes: BTreeSet<[u8; 32]> = observed
580 .iter()
581 .filter(|o| o.full)
582 .map(|o| o.ledger_hash)
583 .collect();
584 let decisions: Vec<([u8; 32], Decision)> = hashes
585 .iter()
586 .map(|h| {
587 let d = decide(
588 &lists,
589 &trust.publishers,
590 trust.threshold,
591 &trust.trusted_directly,
592 &observed,
593 h,
594 );
595 (*h, d)
596 })
597 .collect();
598 let confirmed_all: Vec<[u8; 32]> = decisions
599 .iter()
600 .filter(|(_, d)| d.confirmed)
601 .map(|(h, _)| *h)
602 .collect();
603 let agreed = (confirmed_all.len() == 1).then(|| confirmed_all[0]);
604 let claimed = hex::decode(&bundle.ledger_hash)
607 .ok()
608 .and_then(|b| <[u8; 32]>::try_from(b).ok())
609 .filter(|h| hashes.contains(h));
610 let most_voted = hashes.iter().copied().max_by_key(|h| {
611 observed
612 .iter()
613 .filter(|o| o.full && o.ledger_hash == *h)
614 .count()
615 });
616 let decision = agreed
617 .or(claimed)
618 .or(most_voted)
619 .and_then(|h| decisions.iter().find(|(x, _)| *x == h))
620 .map(|(_, d)| d.clone());
621 let (policy_window, policies, assessed, missing) = match decision {
622 Some(d) => (d.window, d.set.policies, d.assessed, d.set.missing),
623 None => (None, Vec::new(), Vec::new(), Vec::new()),
624 };
625 for m in &missing {
626 problems.push(format!(
627 "publisher {}: no list in effect at the ledger's time, policy is incomplete",
628 hex::encode_upper(m)
629 ));
630 }
631 let empty = Policy {
632 lists: Vec::new(),
633 threshold: default_threshold(trust.publishers.len()),
634 local: trust.trusted_directly.clone(),
635 negative_unl: BTreeSet::new(),
636 };
637 let base = policies.first().cloned().unwrap_or(empty);
638 let a = assessed
639 .iter()
640 .max_by_key(|a| a.quorum)
641 .cloned()
642 .unwrap_or_else(|| assess(&base, &observed));
643 let with_claimed_negative_unl = (!negative.is_empty()).then(|| {
644 let claimed = Policy {
645 negative_unl: negative.clone(),
646 ..base.clone()
647 };
648 let c = assess(&claimed, &observed);
649 ClaimedNegativeUnl {
650 effective_size: c.effective_size,
651 quorum: c.quorum,
652 confirmed_hash: c.confirmed.map(hex::encode_upper),
653 signers: c.confirmed.map_or(0, |h| c.by_hash[&h].len()),
654 }
655 });
656 let policies_used: Vec<PolicyUsed> = policies
657 .iter()
658 .zip(&assessed)
659 .map(|(p, a)| PolicyUsed {
660 lists: p
661 .lists
662 .iter()
663 .map(|l| ListUsed {
664 publisher: hex::encode_upper(&l.publisher),
665 sequence: l.sequence,
666 effective: l.effective,
667 expiration: l.expiration,
668 })
669 .collect(),
670 unl_size: a.unl_size,
671 quorum: a.quorum,
672 confirmed_hash: a.confirmed.map(hex::encode_upper),
673 })
674 .collect();
675 let confirmed_hash = agreed.map(hex::encode_upper);
676 let signers = agreed.map_or(0, |h| {
677 assessed
678 .iter()
679 .map(|a| a.by_hash.get(&h).map_or(0, BTreeSet::len))
680 .min()
681 .unwrap_or(0)
682 });
683 let (chain_ok, linked, target) = check_chain(bundle, confirmed_hash.as_deref(), &mut problems);
686 let (chain_ok, linked, target, skip_hops) = if chain_ok {
687 check_skips(bundle, linked, target, &mut problems)
688 } else {
689 (false, linked, target, 0)
690 };
691 let in_linked = |hash: &str| {
692 linked
693 .iter()
694 .find(|(h, _)| h.eq_ignore_ascii_case(hash))
695 .map(|(_, s)| *s)
696 };
697 let transactions = bundle
698 .transactions
699 .iter()
700 .map(|p| match p.verify() {
701 Ok(proven) => {
702 let at = in_linked(&proven.ledger_hash).filter(|s| *s == proven.ledger_index);
703 TxCheck {
704 in_confirmed_ledger: at.is_some(),
705 via_chain: at.is_some_and(|s| s != bundle.ledger_index),
706 tx_hash: Some(proven.tx_hash),
707 included: true,
708 error: None,
709 }
710 }
711 Err(e) => TxCheck {
712 tx_hash: None,
713 included: false,
714 in_confirmed_ledger: false,
715 via_chain: false,
716 error: Some(e),
717 },
718 })
719 .collect();
720 let objects = bundle
721 .objects
722 .iter()
723 .map(|p| match p.verify() {
724 Ok(proven) => {
725 let at = in_linked(&proven.ledger_hash).filter(|s| *s == proven.ledger_index);
726 ObjectCheck {
727 key: Some(proven.key),
728 present: Some(proven.present),
729 ledger_index: Some(proven.ledger_index),
730 proven: at.is_some(),
731 via_chain: at.is_some_and(|s| s != bundle.ledger_index),
732 error: None,
733 }
734 }
735 Err(e) => ObjectCheck {
736 key: None,
737 present: None,
738 ledger_index: None,
739 proven: false,
740 via_chain: false,
741 error: Some(e),
742 },
743 })
744 .collect();
745 Report {
746 ledger_index: bundle.ledger_index,
747 matches_claim: confirmed_hash
748 .as_deref()
749 .is_some_and(|h| h.eq_ignore_ascii_case(&bundle.ledger_hash)),
750 confirmed_hash,
751 unl_size: a.unl_size,
752 effective_size: a.effective_size,
753 quorum: a.quorum,
754 signers,
755 policy_differs,
756 policy_observed_after: first_seen > first_validation,
757 rule: RULE_FULL_UNL,
758 policy_window,
759 missing_publishers: missing.iter().map(hex::encode_upper).collect(),
760 policies: policies_used,
761 negative_unl: negative.iter().map(|k| node_public(k)).collect(),
762 with_claimed_negative_unl,
763 not_seen: a.not_seen.iter().map(|k| node_public(k)).collect(),
764 conflicting: a.conflicting.iter().map(|k| node_public(k)).collect(),
765 unattributed: a.unattributed.len(),
766 untrusted_publishers: untrusted,
767 problems,
768 transactions,
769 chain_ok,
770 target_ledger: target.as_ref().map(|t| t.0),
771 target_hash: target.map(|t| t.1),
772 objects,
773 skip_hops,
774 }
775}
776
777type Linked = (bool, Vec<(String, u32)>, Option<(u32, String)>);
780type LinkedSkips = (bool, Vec<(String, u32)>, Option<(u32, String)>, usize);
782
783fn check_chain(bundle: &Bundle, confirmed: Option<&str>, problems: &mut Vec<String>) -> Linked {
784 let Some(confirmed) = confirmed else {
785 return (false, Vec::new(), None);
786 };
787 let anchor = (confirmed.to_owned(), bundle.ledger_index);
788 if bundle.chain.is_empty() {
789 return (
790 true,
791 vec![anchor],
792 Some((bundle.ledger_index, confirmed.to_owned())),
793 );
794 }
795 let Some(headers) = parse_headers(&bundle.chain, "chain", problems) else {
796 return (false, vec![anchor], None);
797 };
798 let last = &headers[headers.len() - 1];
799 if last.sequence != bundle.ledger_index
800 || !hex::encode_upper(last.hash()).eq_ignore_ascii_case(confirmed)
801 {
802 problems.push("chain does not end at the confirmed ledger".into());
803 return (false, vec![anchor], None);
804 }
805 let linked = headers
806 .iter()
807 .map(|h| (hex::encode_upper(h.hash()), h.sequence))
808 .collect();
809 let first = &headers[0];
810 (
811 true,
812 linked,
813 Some((first.sequence, hex::encode_upper(first.hash()))),
814 )
815}
816
817fn parse_headers(
818 hex_headers: &[String],
819 what: &str,
820 problems: &mut Vec<String>,
821) -> Option<Vec<crate::ledger::LedgerHeader>> {
822 let mut headers = Vec::with_capacity(hex_headers.len());
823 for (i, h) in hex_headers.iter().enumerate() {
824 match hex::decode(h)
825 .ok()
826 .and_then(|b| crate::ledger::LedgerHeader::parse(&b).ok())
827 {
828 Some(x) => headers.push(x),
829 None => {
830 problems.push(format!("{what}: cannot parse header {i}"));
831 return None;
832 }
833 }
834 }
835 for w in headers.windows(2) {
836 if w[1].sequence != w[0].sequence + 1 || w[1].parent_hash != w[0].hash() {
837 problems.push(format!("{what} breaks at ledger {}", w[1].sequence));
838 return None;
839 }
840 }
841 Some(headers)
842}
843
844fn check_skips(
849 bundle: &Bundle,
850 mut linked: Vec<(String, u32)>,
851 mut target: Option<(u32, String)>,
852 problems: &mut Vec<String>,
853) -> LinkedSkips {
854 for (i, hop) in bundle.skips.iter().enumerate() {
855 let what = format!("skip hop {i}");
856 let fail = |problems: &mut Vec<String>, m: String| {
857 problems.push(format!("{what}: {m}"));
858 };
859 let proven = match hop.list.verify() {
860 Ok(p) => p,
861 Err(e) => {
862 fail(problems, format!("list proof: {e}"));
863 return (false, linked, target, i);
864 }
865 };
866 let in_linked = linked
867 .iter()
868 .any(|(h, s)| *s == proven.ledger_index && h.eq_ignore_ascii_case(&proven.ledger_hash));
869 if !proven.present || !in_linked {
870 fail(
871 problems,
872 "the list is not proven present in a ledger the bundle proves".into(),
873 );
874 return (false, linked, target, i);
875 }
876 let Some(headers) = parse_headers(&hop.headers, &what, problems) else {
877 return (false, linked, target, i);
878 };
879 let Some(last) = headers.last() else {
880 fail(problems, "no headers".into());
881 return (false, linked, target, i);
882 };
883 let is_key = |k: [u8; 32]| proven.key.eq_ignore_ascii_case(&hex::encode(k));
884 let long = last.sequence.is_multiple_of(256) && is_key(skiplist::long_key(last.sequence));
885 if !long && !is_key(skiplist::short_key()) {
886 fail(
887 problems,
888 "the object is not the skip list for this ledger".into(),
889 );
890 return (false, linked, target, i);
891 }
892 let object = hop
893 .list
894 .object
895 .as_deref()
896 .and_then(|o| hex::decode(o).ok())
897 .unwrap_or_default();
898 match skiplist::hashes(&object) {
899 Ok(hs) if hs.contains(&last.hash()) => {}
900 Ok(_) => {
901 fail(
902 problems,
903 format!("ledger {} is not in the skip list", last.sequence),
904 );
905 return (false, linked, target, i);
906 }
907 Err(e) => {
908 fail(problems, e);
909 return (false, linked, target, i);
910 }
911 }
912 linked.extend(
913 headers
914 .iter()
915 .map(|h| (hex::encode_upper(h.hash()), h.sequence)),
916 );
917 let first = &headers[0];
918 target = Some((first.sequence, hex::encode_upper(first.hash())));
919 }
920 (true, linked, target, bundle.skips.len())
921}
922
923#[cfg(test)]
924mod chain_tests {
925 use super::*;
926 use crate::ledger::LedgerHeader;
927
928 fn header(seq: u32, parent: [u8; 32]) -> Vec<u8> {
929 let mut h = vec![0u8; 118];
930 h[..4].copy_from_slice(&seq.to_be_bytes());
931 h[12..44].copy_from_slice(&parent);
932 h
933 }
934
935 fn bundle(anchor: u32, chain: Vec<String>) -> Bundle {
936 Bundle {
937 format: FORMAT_V3.into(),
938 ledger_index: anchor,
939 ledger_hash: String::new(),
940 policy: PolicySpec {
941 publishers: Vec::new(),
942 threshold: 0,
943 trusted_directly: Vec::new(),
944 },
945 publisher_responses: Vec::new(),
946 manifests: Vec::new(),
947 negative_unl: None,
948 validations: Vec::new(),
949 provenance: Provenance {
950 source: String::new(),
951 exported_ms: 0,
952 seals: Vec::new(),
953 },
954 transactions: Vec::new(),
955 chain,
956 objects: Vec::new(),
957 skips: Vec::new(),
958 }
959 }
960
961 #[test]
962 fn header_chain_links_target_to_confirmed() {
963 let h0 = header(10, [7; 32]);
964 let h1 = header(11, LedgerHeader::parse(&h0).unwrap().hash());
965 let h2 = header(12, LedgerHeader::parse(&h1).unwrap().hash());
966 let anchor = hex::encode_upper(LedgerHeader::parse(&h2).unwrap().hash());
967 let chain: Vec<String> = [&h0, &h1, &h2].iter().map(hex::encode_upper).collect();
968
969 let mut problems = Vec::new();
970 let (ok, linked, target) =
971 check_chain(&bundle(12, chain.clone()), Some(&anchor), &mut problems);
972 assert!(ok && problems.is_empty(), "{problems:?}");
973 assert_eq!(linked.len(), 3);
974 assert_eq!(target.unwrap().0, 10);
975
976 let (ok, linked, _) = check_chain(&bundle(12, chain.clone()), None, &mut problems);
978 assert!(!ok && linked.is_empty());
979
980 let mut broken = chain.clone();
982 broken[1] = hex::encode_upper(header(11, [9; 32]));
983 let mut problems = Vec::new();
984 assert!(!check_chain(&bundle(12, broken), Some(&anchor), &mut problems).0);
985 assert!(problems.iter().any(|p| p.contains("breaks")));
986
987 let mut problems = Vec::new();
989 assert!(
990 !check_chain(
991 &bundle(12, chain[..2].to_vec()),
992 Some(&anchor),
993 &mut problems
994 )
995 .0
996 );
997 }
998
999 #[test]
1000 fn skip_hop_links_an_older_ledger() {
1001 use crate::shamap::{prove, root, state_leaf_hash};
1002 let mut old = vec![header(1000, [5; 32])];
1004 for seq in 1001..=1024 {
1005 let parent = LedgerHeader::parse(old.last().unwrap()).unwrap().hash();
1006 old.push(header(seq, parent));
1007 }
1008 let m = LedgerHeader::parse(old.last().unwrap()).unwrap().hash();
1009 let key = skiplist::long_key(1024);
1011 let mut list = vec![0x11, 0x00, 0x68, 0x02, 0x13, 64];
1012 list.extend([3u8; 32]);
1013 list.extend(m);
1014 let other = ([0xAB; 32], vec![1u8, 2, 3]);
1015 let leaves = vec![
1016 (key, state_leaf_hash(&list, &key)),
1017 (other.0, state_leaf_hash(&other.1, &other.0)),
1018 ];
1019 let mut confirmed = header(90_000, [8; 32]);
1020 confirmed[76..108].copy_from_slice(&root(&leaves));
1021 let anchor = hex::encode_upper(LedgerHeader::parse(&confirmed).unwrap().hash());
1022 let mut b = bundle(90_000, vec![hex::encode_upper(&confirmed)]);
1023 let proof = StateProof::new(
1024 &confirmed,
1025 &key,
1026 Some(&list),
1027 None,
1028 &prove(&leaves, &key).unwrap(),
1029 );
1030 b.skips = vec![SkipHop {
1031 list: proof,
1032 headers: old.iter().map(hex::encode_upper).collect(),
1033 }];
1034 let check = |b: &Bundle| {
1035 let mut problems = Vec::new();
1036 let (ok, linked, target) = check_chain(b, Some(&anchor), &mut problems);
1037 let r = check_skips(b, linked, target, &mut problems);
1038 (ok && r.0, r.2.map(|t| t.0), r.1.len(), problems)
1039 };
1040 let (ok, target, linked, problems) = check(&b);
1041 assert!(ok, "{problems:?}");
1042 assert_eq!((target, linked), (Some(1000), 26));
1043
1044 let mut short = b.clone();
1046 short.skips[0].headers.pop();
1047 let (ok, _, _, problems) = check(&short);
1048 assert!(
1049 !ok && problems.iter().any(|p| p.contains("skip list")),
1050 "{problems:?}"
1051 );
1052
1053 let mut stray = b.clone();
1055 stray.chain = vec![hex::encode_upper(header(90_000, [9; 32]))];
1056 let stray_anchor = hex::encode_upper(
1057 LedgerHeader::parse(&hex::decode(&stray.chain[0]).unwrap())
1058 .unwrap()
1059 .hash(),
1060 );
1061 let mut problems = Vec::new();
1062 let (_, linked, target) = check_chain(&stray, Some(&stray_anchor), &mut problems);
1063 assert!(!check_skips(&stray, linked, target, &mut problems).0);
1064 }
1065}