Skip to main content

witness_core/
keys.rs

1//! XRPL keys and signatures.
2//!
3//! Two algorithms. An ed25519 key is 33 bytes, the first one `0xED`; the
4//! message itself is signed. A secp256k1 key is a 33-byte compressed point,
5//! first byte `0x02` or `0x03`; the SHA-512Half of the message is signed, and
6//! the signature is DER. This is what xrpld does (`ripple::verify`), and this
7//! is how we check.
8//!
9//! secp256k1 canonicality: a validator that sets the "fully canonical
10//! signature" flag must produce a signature with low S. Without the flag
11//! xrpld also accepts high S, and so do we, normalizing it to low S: it is
12//! mathematically the same signature.
13
14use std::fmt;
15
16use ed25519_dalek::Verifier as _;
17use k256::ecdsa::signature::hazmat::PrehashVerifier as _;
18use sha2::{Digest, Sha256};
19
20use crate::sha512_half;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum KeyType {
24    Secp256k1,
25    Ed25519,
26}
27
28pub fn key_type(pk: &[u8]) -> Option<KeyType> {
29    match (pk.len(), pk.first()) {
30        (33, Some(0xED)) => Some(KeyType::Ed25519),
31        (33, Some(0x02 | 0x03)) => Some(KeyType::Secp256k1),
32        _ => None,
33    }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum VerifyError {
38    BadKey,
39    BadSignatureEncoding,
40    /// A high-S signature where a canonical one was required.
41    NotCanonical,
42    /// The signature does not match the key and message.
43    Mismatch,
44}
45
46impl fmt::Display for VerifyError {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.write_str(match self {
49            VerifyError::BadKey => "cannot parse key",
50            VerifyError::BadSignatureEncoding => "cannot parse signature",
51            VerifyError::NotCanonical => "signature is not canonical",
52            VerifyError::Mismatch => "signature does not match",
53        })
54    }
55}
56
57impl std::error::Error for VerifyError {}
58
59/// Checks signature `sig` over `message` with key `pk`.
60pub fn verify(
61    pk: &[u8],
62    message: &[u8],
63    sig: &[u8],
64    require_canonical: bool,
65) -> Result<(), VerifyError> {
66    match key_type(pk).ok_or(VerifyError::BadKey)? {
67        KeyType::Ed25519 => {
68            let key: [u8; 32] = pk[1..].try_into().map_err(|_| VerifyError::BadKey)?;
69            let vk =
70                ed25519_dalek::VerifyingKey::from_bytes(&key).map_err(|_| VerifyError::BadKey)?;
71            let s = ed25519_dalek::Signature::from_slice(sig)
72                .map_err(|_| VerifyError::BadSignatureEncoding)?;
73            vk.verify(message, &s).map_err(|_| VerifyError::Mismatch)
74        }
75        KeyType::Secp256k1 => {
76            let vk =
77                k256::ecdsa::VerifyingKey::from_sec1_bytes(pk).map_err(|_| VerifyError::BadKey)?;
78            let mut s = k256::ecdsa::Signature::from_der(sig)
79                .map_err(|_| VerifyError::BadSignatureEncoding)?;
80            // A high S is the malleable twin of a low one; `require_canonical` refuses it.
81            let low = s.normalize_s();
82            if low != s {
83                if require_canonical {
84                    return Err(VerifyError::NotCanonical);
85                }
86                s = low;
87            }
88            vk.verify_prehash(&sha512_half(message), &s)
89                .map_err(|_| VerifyError::Mismatch)
90        }
91    }
92}
93
94const ALPHABET: &[u8; 58] = b"rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz";
95
96/// Version prefix for node and validator public keys: strings like `n9…`.
97pub const NODE_PUBLIC: u8 = 28;
98
99fn checksum(data: &[u8]) -> [u8; 4] {
100    let h = Sha256::digest(Sha256::digest(data));
101    [h[0], h[1], h[2], h[3]]
102}
103
104/// Base58Check in the XRPL alphabet.
105pub fn encode_base58(version: u8, payload: &[u8]) -> String {
106    let mut data = Vec::with_capacity(payload.len() + 5);
107    data.push(version);
108    data.extend_from_slice(payload);
109    let sum = checksum(&data);
110    data.extend_from_slice(&sum);
111
112    let zeros = data.iter().take_while(|&&b| b == 0).count();
113    let mut digits: Vec<u8> = Vec::new();
114    for &byte in &data {
115        let mut carry = u32::from(byte);
116        for d in digits.iter_mut() {
117            carry += u32::from(*d) << 8;
118            *d = (carry % 58) as u8;
119            carry /= 58;
120        }
121        while carry > 0 {
122            digits.push((carry % 58) as u8);
123            carry /= 58;
124        }
125    }
126    let mut out = String::with_capacity(zeros + digits.len());
127    out.extend(std::iter::repeat_n(ALPHABET[0] as char, zeros));
128    out.extend(
129        digits
130            .iter()
131            .rev()
132            .map(|&d| ALPHABET[usize::from(d)] as char),
133    );
134    out
135}
136
137/// Base58Check decoding: version and payload, if the checksum matches.
138pub fn decode_base58(s: &str) -> Option<(u8, Vec<u8>)> {
139    let mut bytes: Vec<u8> = Vec::new();
140    for c in s.bytes() {
141        let mut carry = ALPHABET.iter().position(|&a| a == c)? as u32;
142        for b in bytes.iter_mut() {
143            carry += u32::from(*b) * 58;
144            *b = (carry & 0xFF) as u8;
145            carry >>= 8;
146        }
147        while carry > 0 {
148            bytes.push((carry & 0xFF) as u8);
149            carry >>= 8;
150        }
151    }
152    let zeros = s.bytes().take_while(|&c| c == ALPHABET[0]).count();
153    bytes.extend(std::iter::repeat_n(0, zeros));
154    bytes.reverse();
155    if bytes.len() < 5 {
156        return None;
157    }
158    let (data, sum) = bytes.split_at(bytes.len() - 4);
159    (checksum(data) == sum).then(|| (data[0], data[1..].to_vec()))
160}
161
162/// A validator public key as `n9…`.
163pub fn node_public(pk: &[u8]) -> String {
164    encode_base58(NODE_PUBLIC, pk)
165}
166
167/// A key from an `n9…` string.
168pub fn parse_node_public(s: &str) -> Option<Vec<u8>> {
169    match decode_base58(s)? {
170        (NODE_PUBLIC, pk) if key_type(&pk).is_some() => Some(pk),
171        _ => None,
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn base58_roundtrip_and_checksum() {
181        let pk = hex::decode("0371ED125A7B4EA88D33EB92A12783D27A287FD7FEB95294C9183044624DC0D0A2")
182            .unwrap();
183        let s = node_public(&pk);
184        assert!(s.starts_with('n'), "{s}");
185        assert_eq!(parse_node_public(&s).unwrap(), pk);
186        // A corrupted character breaks the checksum.
187        let mut bad = s.into_bytes();
188        let last = bad.len() - 1;
189        bad[last] = if bad[last] == b'r' { b'p' } else { b'r' };
190        assert!(parse_node_public(std::str::from_utf8(&bad).unwrap()).is_none());
191    }
192
193    #[test]
194    fn known_publisher_key_decodes() {
195        // Master key of the vl.ripple.com publisher, from its site's response.
196        let pk = hex::decode("ED2677ABFFD1B33AC6FBC3062B71F1E8397C1505E1C42C64D11AD1B28FF73F4734")
197            .unwrap();
198        assert_eq!(key_type(&pk), Some(KeyType::Ed25519));
199        assert_eq!(parse_node_public(&node_public(&pk)).unwrap(), pk);
200    }
201
202    #[test]
203    fn key_types() {
204        assert_eq!(key_type(&[0x02; 33]), Some(KeyType::Secp256k1));
205        assert_eq!(key_type(&[0xED; 33]), Some(KeyType::Ed25519));
206        assert_eq!(key_type(&[0x04; 33]), None);
207        assert_eq!(key_type(&[0x02; 32]), None);
208    }
209}