Skip to main content

witness_core/
validation.rs

1//! A validation is a statement signed by a validator: "ledger N has hash H".
2//!
3//! The signature covers the `VAL\0` prefix and every field except the
4//! signature itself. Checking the signature proves one thing: this key signed
5//! this statement. That the key belongs to a particular validator is what the
6//! manifest says; that the network confirmed the ledger is a quorum under a
7//! trust policy. These are different claims and must not be mixed here.
8
9use crate::HashPrefix;
10use crate::keys::{VerifyError, verify};
11use crate::stobject::{self, Error, fields as f};
12
13/// Full validation: the validator considers this ledger accepted.
14pub const FLAG_FULL: u32 = 0x0000_0001;
15/// The secp256k1 signature must be canonical (low S).
16pub const FLAG_FULLY_CANONICAL: u32 = 0x8000_0000;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Validation {
20    pub flags: u32,
21    pub ledger_sequence: u32,
22    /// Signing time, seconds since the XRPL epoch (2000-01-01).
23    pub signing_time: u32,
24    pub ledger_hash: [u8; 32],
25    pub consensus_hash: Option<[u8; 32]>,
26    pub validated_hash: Option<[u8; 32]>,
27    pub cookie: Option<u64>,
28    pub server_version: Option<u64>,
29    /// Amendments the validator votes for (only in flag ledgers).
30    pub amendments: Vec<[u8; 32]>,
31    pub signing_pub_key: Vec<u8>,
32    pub signature: Vec<u8>,
33    /// Exactly what is signed: the prefix and the fields without the signature.
34    signing_data: Vec<u8>,
35}
36
37fn hash32(v: &[u8]) -> Result<[u8; 32], Error> {
38    v.try_into()
39        .map_err(|_| Error::Malformed("hash is not 32 bytes".into()))
40}
41
42fn required<'a>(
43    fs: &[stobject::Field<'a>],
44    id: stobject::FieldId,
45    name: &str,
46) -> Result<&'a [u8], Error> {
47    stobject::find(fs, id).ok_or_else(|| Error::Malformed(format!("missing field {name}")))
48}
49
50impl Validation {
51    pub fn parse(raw: &[u8]) -> Result<Validation, Error> {
52        let fs = stobject::fields(raw)?;
53        let u32_req = |id, name: &str| -> Result<u32, Error> {
54            stobject::u32_of(required(&fs, id, name)?)
55                .ok_or_else(|| Error::Malformed(format!("{name} is not 4 bytes")))
56        };
57        let amendments = match stobject::find(&fs, f::AMENDMENTS) {
58            None => Vec::new(),
59            Some(v) if v.len() % 32 == 0 => v.as_chunks::<32>().0.to_vec(),
60            Some(_) => {
61                return Err(Error::Malformed(
62                    "Amendments is not a multiple of 32".into(),
63                ));
64            }
65        };
66        let mut signing_data = HashPrefix::Validation.to_bytes().to_vec();
67        signing_data.extend(stobject::signing_bytes(&fs));
68        Ok(Validation {
69            flags: u32_req(f::FLAGS, "Flags")?,
70            ledger_sequence: u32_req(f::LEDGER_SEQUENCE, "LedgerSequence")?,
71            signing_time: u32_req(f::SIGNING_TIME, "SigningTime")?,
72            ledger_hash: hash32(required(&fs, f::LEDGER_HASH, "LedgerHash")?)?,
73            consensus_hash: stobject::find(&fs, f::CONSENSUS_HASH)
74                .map(hash32)
75                .transpose()?,
76            validated_hash: stobject::find(&fs, f::VALIDATED_HASH)
77                .map(hash32)
78                .transpose()?,
79            cookie: stobject::find(&fs, f::COOKIE).and_then(stobject::u64_of),
80            server_version: stobject::find(&fs, f::SERVER_VERSION).and_then(stobject::u64_of),
81            amendments,
82            signing_pub_key: required(&fs, f::SIGNING_PUB_KEY, "SigningPubKey")?.to_vec(),
83            signature: required(&fs, f::SIGNATURE, "Signature")?.to_vec(),
84            signing_data,
85        })
86    }
87
88    pub fn is_full(&self) -> bool {
89        self.flags & FLAG_FULL != 0
90    }
91
92    /// The signature matches the signing key from the validation itself.
93    pub fn verify(&self) -> Result<(), VerifyError> {
94        verify(
95            &self.signing_pub_key,
96            &self.signing_data,
97            &self.signature,
98            self.flags & FLAG_FULLY_CANONICAL != 0,
99        )
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106    use crate::keys::node_public;
107
108    /// Live validations from an archive, 2026-10-23: two from mainnet
109    /// (ledger 107846611) and one from testnet, relayed by peers.
110    const MAINNET_A: &str = "228000000126066D9BD329326DE6C13A0393278390661EE1517C636107510AFFB3DFDD322187331C35D8071589D3CA451D39F13991D276159C501734B0E4E7762FA70177CDF225EF358D84A6C48805DB80A5531B6B52C2530A9F3B501985F573AEA90B3469CDE60E58202164B0B48CD74985EE0879E39F4DE55D841AA973210371ED125A7B4EA88D33EB92A12783D27A287FD7FEB95294C9183044624DC0D0A2764630440220798C71D5FE0C70BF0BE9C960854619A0DD3486D6D9462AD06DD8D7C70592456A02207808AFFBC83B6634EF22D2366F20B48363DE2468B73D1404A9ABEC0F72D0A19C";
111    const MAINNET_B: &str = "220000000126066D9BD329326DE6C23A6AD9FE5EF53AE707517C636107510AFFB3DFDD322187331C35D8071589D3CA451D39F13991D276159C50197C636107510AFFB3DFDD322187331C35D8071589D3CA451D39F13991D276159C73210225BBFD07C6083A30470140ED89D850E145FA93517E9002B2EA254E1A8AAE67997646304402200E641559263D3A580A2727A04F48D488493AE75876B1C81F449C93AEECB1914302203DF88E856A9051C00CD9764C59ECF5776E174D9C78937A940E27B1B8776A8340";
112    const TESTNET: &str = "228000000126014BFCE429326DE6C23A0221BB1AF1BE4BFD51694407F6CC5CCE9420EFD697A3B615158EE30D35AD8FA53F42DE61AF207CCB7F5017EA4EF6159D49CA382FF252D5232A59D979A61661B92BE15F6AEE5189305A4EEE5019062589656583C340F7B3255484884B8FE30524E9C0E3CC968A40C26C5AD8A23373210366985A2A58FCDD64004A0A1B0FE5C7550891436775AD50562DA6DFACE13AE62F7646304402207E50BDFD6B546DF7071E4E2DDCA21587FCF47CC01C66BC645371F684E307E0D802207713AF0411219528AF5E63F0F2ABED589F8E3265D0FDDB7B44CAB707B98712E7";
113
114    fn parse(h: &str) -> Validation {
115        Validation::parse(&hex::decode(h).unwrap()).unwrap()
116    }
117
118    #[test]
119    fn live_validations_parse_and_verify() {
120        let a = parse(MAINNET_A);
121        assert_eq!(a.ledger_sequence, 107_846_611);
122        assert!(a.is_full());
123        assert!(a.consensus_hash.is_some() && a.validated_hash.is_some());
124        assert!(node_public(&a.signing_pub_key).starts_with('n'));
125        a.verify().unwrap();
126
127        let b = parse(MAINNET_B);
128        assert_eq!(b.ledger_sequence, 107_846_611);
129        assert_eq!(b.ledger_hash, a.ledger_hash, "both signed the same ledger");
130        b.verify().unwrap();
131
132        let t = parse(TESTNET);
133        assert_eq!(t.ledger_sequence, 21_757_156);
134        t.verify().unwrap();
135    }
136
137    #[test]
138    fn any_changed_byte_breaks_the_signature() {
139        let raw = hex::decode(MAINNET_A).unwrap();
140        // Ledger sequence: 4 bytes after the 0x26 header at offset 5.
141        let mut forged = raw.clone();
142        forged[9] ^= 1;
143        let v = Validation::parse(&forged).unwrap();
144        assert_eq!(v.ledger_sequence, 107_846_611 ^ 1);
145        assert_eq!(v.verify(), Err(VerifyError::Mismatch));
146        // Tampered ledger hash.
147        let mut forged = raw;
148        forged[30] ^= 0x80;
149        assert_eq!(
150            Validation::parse(&forged).unwrap().verify(),
151            Err(VerifyError::Mismatch)
152        );
153    }
154
155    #[test]
156    fn missing_fields_are_errors() {
157        // Flags only.
158        assert!(Validation::parse(&[0x22, 0x80, 0, 0, 1]).is_err());
159    }
160}