scp_util/lib.rs
1//! Helpers shared by the SCP kernel and `scpd`: XDR marshalling
2//! ([`marshal_xdr`], [`unmarshal_xdr`]), SHA-256 hashing ([`hash_bytes`],
3//! [`hash_xdr`]), Ed25519 signing and verification of XDR structures and SCP
4//! envelopes ([`sign_xdr`], [`verify_xdr`], [`verify_envelope`]) and key
5//! helpers ([`generate_secret_key`], [`derive_public_key`],
6//! [`parse_secret_key_from_base64`]).
7//!
8//! Keys and signatures are `thruput-xdr`'s
9//! [`PublicKey`](thruput_xdr::types::PublicKey) and
10//! [`Signature`](thruput_xdr::types::Signature) unions. Only their Ed25519
11//! arms are supported: signing with another scheme panics, and verifying a
12//! key or signature of another scheme fails like any bad signature.
13//! Signatures are plain Ed25519 (RFC 8032, no pre-hash) over the XDR encoding
14//! of the signed value, verified under the ZIP-215 rules.
15
16pub mod xdr;
17pub use xdr::*;
18
19pub mod hash;
20pub use hash::*;
21
22pub mod sign;
23pub use sign::*;
24
25pub mod keygen;
26pub use keygen::*;
27
28#[cfg(test)]
29mod tests {
30 use xdr_common::*;
31 use xdrs::txs;
32
33 #[test]
34 fn roundtrip() {
35 let v: thruput_xdr::types::uint128_xdr =
36 thruput_xdr::types::uint128_xdr {
37 highbits: 1,
38 lowbits: 2,
39 };
40 let bytes = txs::encode(&v).expect("encode failed");
41 let w: thruput_xdr::types::uint128_xdr =
42 txs::decode(&bytes).expect("decode failed");
43 assert!(v == w, "unequal");
44 }
45
46 use std::mem::MaybeUninit;
47
48 fn as_maybe_uninit(slice: &mut [u8]) -> &mut [MaybeUninit<u8>] {
49 // SAFETY: MaybeUninit<u8> has the same layout as u8
50 unsafe {
51 std::slice::from_raw_parts_mut(
52 slice.as_mut_ptr() as *mut MaybeUninit<u8>,
53 slice.len(),
54 )
55 }
56 }
57
58 #[test]
59 fn roundtrip_into() {
60 let v: thruput_xdr::types::uint128_xdr =
61 thruput_xdr::types::uint128_xdr {
62 highbits: 1,
63 lowbits: 2,
64 };
65 let mut buf = BytesM::<100>(vec![0; 20]);
66 let n = txs::encode_into(&v, as_maybe_uninit(buf.0.as_mut_slice()))
67 .expect("encode failed");
68 assert!(n == 16, "size");
69 let w: thruput_xdr::types::uint128_xdr =
70 txs::decode(&buf.as_slice()[..16]).expect("decode failed");
71 assert!(v == w, "unequal");
72 }
73}