thruput-scp-util 3.0.0

Hashing, Ed25519 signing and XDR helpers for the Stellar Consensus Protocol (SCP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use ed25519::Error as SignatureError;
use ed25519_zebra::{Signature, SigningKey, VerificationKey};
use thiserror::Error;
use xdrs::txs;
use xdrs::write_xdr::WriteXDR;

/// Creates an ed25519_zebra::SigningKey from a thruput_xdr::types::Ed25519SecretKey
fn signing_key_from_secret_key(
    secret_key: &thruput_xdr::types::Ed25519SecretKey,
) -> SigningKey {
    // Ed25519SecretKey contains 64 bytes, but SigningKey expects 32 bytes
    // The first 32 bytes are the secret key, the last 32 bytes are typically the public key
    let secret_bytes: [u8; 32] = secret_key[..32].try_into().unwrap();
    SigningKey::from(secret_bytes)
}

/// Any 32 bytes decode as an `Ed25519PublicKey`, but not every 32 bytes are
/// a valid curve point, and a peer can send such a key: decoding fails like
/// any other bad signature instead of panicking.
fn verification_key_from_public_key(
    public_key: &thruput_xdr::types::Ed25519PublicKey,
) -> Result<VerificationKey, SignatureError> {
    let bytes: [u8; 32] = public_key[..].try_into().unwrap();
    VerificationKey::try_from(bytes).map_err(|_| SignatureError::new())
}

fn sign_bytes_ed25519(
    secret_key: &thruput_xdr::types::Ed25519SecretKey,
    msg: &[u8],
) -> thruput_xdr::types::Ed25519Signature {
    let signature = signing_key_from_secret_key(secret_key).sign(msg);
    thruput_xdr::types::Ed25519Signature::from(signature.to_bytes())
}

/// ZIP-215 verification: the cofactored equation, accepting non-canonical
/// point encodings. hogd and chuckd verify with the same rules, so every
/// node accepts exactly the same signatures.
fn verify_bytes_ed25519(
    public_key: &thruput_xdr::types::Ed25519PublicKey,
    msg: &[u8],
    signature: &thruput_xdr::types::Ed25519Signature,
) -> Result<(), SignatureError> {
    let signature_bytes: [u8; 64] = signature[..].try_into().unwrap();
    verification_key_from_public_key(public_key)?
        .verify(&Signature::from_bytes(&signature_bytes), msg)
        .map_err(|_| SignatureError::new())
}

/// Verifies `signature` over `msg` with `public_key`: plain Ed25519
/// (RFC 8032) under the ZIP-215 validation rules.
///
/// Fails for a bad signature, for a key or signature in a scheme other than
/// Ed25519, and for an Ed25519 key whose 32 bytes are not a valid curve
/// point; none of these panic.
pub fn verify_bytes(
    public_key: &thruput_xdr::types::PublicKey,
    msg: &[u8],
    signature: &thruput_xdr::types::Signature,
) -> Result<(), SignatureError> {
    match (public_key, signature) {
        (
            thruput_xdr::types::PublicKey::Ed25519 { ed25519: key },
            thruput_xdr::types::Signature::Ed25519 { ed25519: sig },
        ) => verify_bytes_ed25519(key, msg, sig),
        // Only Ed25519 is supported. The key and signature types also decode
        // other schemes, which a peer can send, so those fail verification.
        _ => Err(SignatureError::new()),
    }
}

/// Signs `msg` with `secret_key`: plain Ed25519 (RFC 8032), no pre-hash.
///
/// # Panics
///
/// If `secret_key` is not an Ed25519 key.
pub fn sign_bytes(
    secret_key: &thruput_xdr::types::SecretKey,
    msg: &[u8],
) -> thruput_xdr::types::Signature {
    let ed25519_key = match secret_key {
        thruput_xdr::types::SecretKey::Ed25519 { ed25519 } => Some(ed25519),
        _ => panic!("Unsupported secret key type"),
    }
    .unwrap();

    thruput_xdr::types::Signature::Ed25519 {
        ed25519: sign_bytes_ed25519(ed25519_key, msg),
    }
}

#[derive(Copy, Clone, Debug, Error)]
pub enum SigningError {
    #[error("encoding error")]
    EncodingError(xdrs::serialize::writer::WriteError),
}

#[derive(Debug, Error)]
pub enum VerifyingError {
    #[error("encoding error")]
    EncodingError(xdrs::serialize::writer::WriteError),

    #[error("verifying error")]
    VerifyingError(SignatureError),
}

pub fn sign_xdr<T>(
    secret_key: &thruput_xdr::types::SecretKey,
    v: &T,
) -> Result<thruput_xdr::types::Signature, SigningError>
where
    T: WriteXDR + ?Sized,
{
    let x = txs::encode(v).map_err(SigningError::EncodingError)?;
    Ok(sign_bytes(secret_key, x.as_slice()))
}

pub fn verify_xdr<T>(
    public_key: &thruput_xdr::types::PublicKey,
    v: &T,
    signature: &thruput_xdr::types::Signature,
) -> Result<(), VerifyingError>
where
    T: WriteXDR + ?Sized,
{
    let x = txs::encode(v).map_err(VerifyingError::EncodingError)?;
    verify_bytes(public_key, x.as_slice(), signature)
        .map_err(VerifyingError::VerifyingError)
}

/// Verifies that `envelope.signature` is a valid signature over the XDR
/// encoding of `envelope.statement` produced by the secret key matching
/// `envelope.statement.node_id`.
pub fn verify_envelope(
    envelope: &thruput_scp::SCPEnvelope,
) -> Result<(), VerifyingError> {
    verify_xdr(
        &envelope.statement.node_id,
        &envelope.statement,
        &envelope.signature,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keygen::{
        derive_node_id, derive_public_key, generate_secret_key,
    };
    use xdr_common::{BytesM, VecM};

    fn make_statement(
        node_id: thruput_scp::SCPNodeID,
    ) -> thruput_scp::SCPStatement {
        thruput_scp::SCPStatement {
            node_id,
            slot_index: 42,
            pledges: thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
                nominate: thruput_scp::SCPStatementNominate {
                    quorum_set_hash: [7u8; 32],
                    votes: VecM(vec![BytesM(b"vote-1".to_vec())]),
                    accepted: VecM(vec![]),
                },
            },
        }
    }

    #[test]
    fn sign_bytes_verify_bytes_roundtrip() {
        let sk = generate_secret_key(b"sign-roundtrip");
        let pk = derive_public_key(&sk);
        let msg = b"the quick brown fox jumps over the lazy dog";
        let sig = sign_bytes(&sk, msg);
        verify_bytes(&pk, msg, &sig).expect("signature should verify");
    }

    #[test]
    fn sign_bytes_is_deterministic_for_ed25519() {
        let sk = generate_secret_key(b"sign-deterministic");
        let msg = b"some payload";
        let sig1 = sign_bytes(&sk, msg);
        let sig2 = sign_bytes(&sk, msg);
        let bytes1 = match &sig1 {
            thruput_xdr::types::Signature::Ed25519 { ed25519 } => ed25519,
            _ => panic!("unexpected signature variant"),
        };
        let bytes2 = match &sig2 {
            thruput_xdr::types::Signature::Ed25519 { ed25519 } => ed25519,
            _ => panic!("unexpected signature variant"),
        };
        assert_eq!(&bytes1[..], &bytes2[..]);
    }

    #[test]
    fn verify_bytes_rejects_modified_message() {
        let sk = generate_secret_key(b"sign-tamper-msg");
        let pk = derive_public_key(&sk);
        let sig = sign_bytes(&sk, b"original message");
        assert!(verify_bytes(&pk, b"tampered message", &sig).is_err());
    }

    #[test]
    fn verify_bytes_rejects_wrong_public_key() {
        let sk1 = generate_secret_key(b"sign-key-1");
        let sk2 = generate_secret_key(b"sign-key-2");
        let pk2 = derive_public_key(&sk2);
        let msg = b"hello";
        let sig = sign_bytes(&sk1, msg);
        assert!(verify_bytes(&pk2, msg, &sig).is_err());
    }

    #[test]
    fn verify_bytes_rejects_unsupported_schemes() {
        let sk = generate_secret_key(b"sign-unsupported");
        let pk = derive_public_key(&sk);
        let msg = b"hello";
        let sig = sign_bytes(&sk, msg);
        let mldsa_pk = thruput_xdr::types::PublicKey::MlDsa65 {
            mldsa65: Box::new([0u8; 1952].into()),
        };
        let mldsa_sig = thruput_xdr::types::Signature::MlDsa65 {
            mldsa65: Box::new([0u8; 3309].into()),
        };
        assert!(verify_bytes(&mldsa_pk, msg, &sig).is_err());
        assert!(verify_bytes(&pk, msg, &mldsa_sig).is_err());
        assert!(verify_bytes(&mldsa_pk, msg, &mldsa_sig).is_err());
    }

    #[test]
    fn verify_rejects_malformed_public_key() {
        // Decodes as an Ed25519PublicKey but is not a point on the curve.
        let malformed = thruput_xdr::types::PublicKey::Ed25519 {
            ed25519: thruput_xdr::types::Ed25519PublicKey::from([0x02u8; 32]),
        };
        let sk = generate_secret_key(b"malformed-key");
        let msg = b"hello";
        let sig = sign_bytes(&sk, msg);
        assert!(verify_bytes(&malformed, msg, &sig).is_err());

        // The same key as a statement's node_id, the path a peer controls.
        let statement = make_statement(malformed);
        let signature =
            sign_xdr(&sk, &statement).expect("sign_xdr should succeed");
        let envelope = thruput_scp::SCPEnvelope {
            statement,
            signature,
        };
        assert!(verify_envelope(&envelope).is_err());
    }

    #[test]
    fn verify_envelope_roundtrip() {
        let sk = generate_secret_key(b"envelope-roundtrip");
        let node_id = derive_node_id(&sk);
        let statement = make_statement(node_id);
        let signature =
            sign_xdr(&sk, &statement).expect("sign_xdr should succeed");
        let envelope = thruput_scp::SCPEnvelope {
            statement,
            signature,
        };
        verify_envelope(&envelope).expect("envelope should verify");
    }

    #[test]
    fn verify_envelope_rejects_wrong_signer() {
        let signer_sk = generate_secret_key(b"envelope-signer");
        let claimed_sk = generate_secret_key(b"envelope-claimed");
        let claimed_node_id = derive_node_id(&claimed_sk);
        let statement = make_statement(claimed_node_id);
        let signature =
            sign_xdr(&signer_sk, &statement).expect("sign_xdr should succeed");
        let envelope = thruput_scp::SCPEnvelope {
            statement,
            signature,
        };
        assert!(verify_envelope(&envelope).is_err());
    }

    #[test]
    fn verify_envelope_rejects_tampered_statement() {
        let sk = generate_secret_key(b"envelope-tamper");
        let node_id = derive_node_id(&sk);
        let statement = make_statement(node_id);
        let signature =
            sign_xdr(&sk, &statement).expect("sign_xdr should succeed");
        let mut envelope = thruput_scp::SCPEnvelope {
            statement,
            signature,
        };
        envelope.statement.slot_index += 1;
        assert!(verify_envelope(&envelope).is_err());
    }

    /// RFC 8032 section 7.1, TEST 1-3: seed, public key, message, signature.
    /// chuckd's protoutil tests check the same vectors, so both sides sign
    /// and verify the same scheme.
    const RFC8032_VECTORS: [(&str, &str, &str, &str); 3] = [
        (
            "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
            "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
            "",
            "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b",
        ),
        (
            "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
            "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",
            "72",
            "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00",
        ),
        (
            "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
            "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",
            "af82",
            "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a",
        ),
    ];

    /// ZIP-215 vectors over the message "Zcash": small-order A and R with
    /// s = 0. ZIP-215 accepts all four; a cofactorless verifier such as Go's
    /// crypto/ed25519 rejects all four. In order: A and R canonical, R
    /// non-canonical, A non-canonical, both non-canonical. chuckd's protoutil
    /// tests check the same vectors.
    const ZIP215_VECTORS: [(&str, &str); 4] = [
        (
            "0100000000000000000000000000000000000000000000000000000000000000",
            "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a0000000000000000000000000000000000000000000000000000000000000000",
        ),
        (
            "0100000000000000000000000000000000000000000000000000000000000000",
            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000",
        ),
        (
            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
            "01000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
        ),
        (
            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000",
        ),
    ];

    /// RFC 8032 TEST 2's key and message signed as Ed25519ph (the message
    /// pre-hashed with SHA-512), the scheme before 3.0.0.
    const RFC8032_TEST2_ED25519PH_SIGNATURE: &str = "ab9b4115731fa999280183209d73f33b0b68c04f5d495fb7e493ff36c660d73ec537aa7ff7a138cafc3e31d86a31c33a02b5d72e67676b584dd98754c9910a0a";

    fn unhex<const N: usize>(s: &str) -> [u8; N] {
        assert_eq!(s.len(), 2 * N, "hex length");
        let mut out = [0u8; N];
        for (i, byte) in out.iter_mut().enumerate() {
            *byte = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).unwrap();
        }
        out
    }

    fn unhex_vec(s: &str) -> Vec<u8> {
        (0..s.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
            .collect()
    }

    fn ed25519_public_key(hex: &str) -> thruput_xdr::types::PublicKey {
        thruput_xdr::types::PublicKey::Ed25519 {
            ed25519: thruput_xdr::types::Ed25519PublicKey::from(unhex::<32>(
                hex,
            )),
        }
    }

    fn ed25519_signature(hex: &str) -> thruput_xdr::types::Signature {
        thruput_xdr::types::Signature::Ed25519 {
            ed25519: thruput_xdr::types::Ed25519Signature::from(unhex::<64>(
                hex,
            )),
        }
    }

    #[test]
    fn sign_bytes_matches_rfc8032_vectors() {
        for (seed, public_key, msg, expected) in RFC8032_VECTORS {
            let mut secret_key_bytes = [0u8; 64];
            secret_key_bytes[..32].copy_from_slice(&unhex::<32>(seed));
            secret_key_bytes[32..].copy_from_slice(&unhex::<32>(public_key));
            let secret_key = thruput_xdr::types::SecretKey::Ed25519 {
                ed25519: thruput_xdr::types::Ed25519SecretKey::from(
                    secret_key_bytes,
                ),
            };
            let signature = sign_bytes(&secret_key, &unhex_vec(msg));
            let thruput_xdr::types::Signature::Ed25519 { ed25519 } = &signature
            else {
                panic!("unexpected signature variant");
            };
            assert_eq!(&ed25519[..], &unhex::<64>(expected)[..]);
            assert_eq!(
                derive_public_key(&secret_key),
                ed25519_public_key(public_key)
            );
        }
    }

    #[test]
    fn verify_bytes_accepts_rfc8032_vectors() {
        for (_, public_key, msg, signature) in RFC8032_VECTORS {
            verify_bytes(
                &ed25519_public_key(public_key),
                &unhex_vec(msg),
                &ed25519_signature(signature),
            )
            .expect("RFC 8032 vector should verify");
        }
    }

    #[test]
    fn verify_bytes_applies_zip215_rules() {
        for (public_key, signature) in ZIP215_VECTORS {
            verify_bytes(
                &ed25519_public_key(public_key),
                b"Zcash",
                &ed25519_signature(signature),
            )
            .expect("ZIP-215 vector should verify");
        }
    }

    #[test]
    fn verify_bytes_rejects_ed25519ph_signatures() {
        let (_, public_key, msg, _) = RFC8032_VECTORS[1];
        assert!(
            verify_bytes(
                &ed25519_public_key(public_key),
                &unhex_vec(msg),
                &ed25519_signature(RFC8032_TEST2_ED25519PH_SIGNATURE),
            )
            .is_err()
        );
    }
}