initial commit
Some checks failed
CI / lint (push) Successful in 1m37s
CI / test-python (push) Successful in 1m49s
CI / test-zig (push) Successful in 1m39s
CI / test-wasm (push) Successful in 1m54s
CI / test (push) Successful in 14m44s
CI / miri (push) Successful in 14m18s
CI / build (push) Successful in 1m9s
CI / fuzz-regression (push) Successful in 9m9s
CI / publish (push) Failing after 1m10s
CI / publish-python (push) Failing after 1m46s
CI / publish-wasm (push) Has been cancelled

Signed-off-by: Kamal Tufekcic <kamal@lo.sh>
This commit is contained in:
Kamal Tufekcic 2026-04-02 23:48:10 +03:00
commit 1d99048c95
No known key found for this signature in database
165830 changed files with 79062 additions and 0 deletions

57
soliton_py/src/auth.rs Normal file
View file

@ -0,0 +1,57 @@
//! LO-Auth: zero-knowledge authentication via KEM challenge-response.
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use crate::errors::to_py_err;
/// Generate an authentication challenge (server-side).
///
/// Returns (ciphertext, expected_token) as a tuple of bytes.
#[pyfunction]
fn auth_challenge<'py>(py: Python<'py>, client_pk: &[u8]) -> PyResult<(Py<PyBytes>, Py<PyBytes>)> {
let pk =
soliton::identity::IdentityPublicKey::from_bytes(client_pk.to_vec()).map_err(to_py_err)?;
let (ct, token) = soliton::auth::auth_challenge(&pk).map_err(to_py_err)?;
Ok((
PyBytes::new(py, ct.as_bytes()).into(),
PyBytes::new(py, &*token).into(),
))
}
/// Respond to an authentication challenge (client-side).
///
/// Returns the 32-byte proof.
#[pyfunction]
fn auth_respond<'py>(
py: Python<'py>,
client_sk: &[u8],
ciphertext: &[u8],
) -> PyResult<Py<PyBytes>> {
let sk =
soliton::identity::IdentitySecretKey::from_bytes(client_sk.to_vec()).map_err(to_py_err)?;
let ct = soliton::primitives::xwing::Ciphertext::from_bytes(ciphertext.to_vec())
.map_err(to_py_err)?;
let proof = soliton::auth::auth_respond(&sk, &ct).map_err(to_py_err)?;
Ok(PyBytes::new(py, &*proof).into())
}
/// Verify an authentication proof (server-side). Constant-time.
#[pyfunction]
fn auth_verify(expected_token: &[u8], proof: &[u8]) -> PyResult<bool> {
if expected_token.len() != 32 || proof.len() != 32 {
return Err(crate::errors::InvalidLengthError::new_err(
"both inputs must be 32 bytes",
));
}
let a: &[u8; 32] = expected_token.try_into().unwrap();
let b: &[u8; 32] = proof.try_into().unwrap();
Ok(soliton::auth::auth_verify(a, b))
}
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(auth_challenge, m)?)?;
m.add_function(wrap_pyfunction!(auth_respond, m)?)?;
m.add_function(wrap_pyfunction!(auth_verify, m)?)?;
Ok(())
}

84
soliton_py/src/call.rs Normal file
View file

@ -0,0 +1,84 @@
//! Call key derivation for encrypted voice/video.
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use crate::errors::to_py_err;
/// Call keys for encrypted voice/video media.
///
/// Derived from a ratchet session's root key and an ephemeral KEM shared secret.
/// Keys are role-assigned by fingerprint order — both parties get the same
/// send/recv assignment without coordination.
///
/// Use as a context manager for automatic zeroization::
///
/// with ratchet.derive_call_keys(kem_ss, call_id) as keys:
/// send = keys.send_key()
/// recv = keys.recv_key()
/// keys.advance() # derive next round
#[pyclass]
pub struct CallKeys {
inner: Option<soliton::call::CallKeys>,
}
#[pymethods]
impl CallKeys {
/// Current send key (32 bytes).
fn send_key<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("call keys consumed"))?;
Ok(PyBytes::new(py, inner.send_key()).into())
}
/// Current recv key (32 bytes).
fn recv_key<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("call keys consumed"))?;
Ok(PyBytes::new(py, inner.recv_key()).into())
}
/// Advance the call chain — derives fresh keys, zeroizes old ones.
///
/// Raises ``ChainExhaustedError`` after 2^24 advances.
fn advance(&mut self) -> PyResult<()> {
let inner = self
.inner
.as_mut()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("call keys consumed"))?;
inner.advance().map_err(to_py_err)
}
/// Zeroize all key material.
fn close(&mut self) {
self.inner = None;
}
fn __enter__(slf: Py<Self>) -> Py<Self> {
slf
}
fn __exit__(
&mut self,
_exc_type: Option<&Bound<'_, PyAny>>,
_exc_val: Option<&Bound<'_, PyAny>>,
_exc_tb: Option<&Bound<'_, PyAny>>,
) {
self.close();
}
}
impl CallKeys {
pub fn from_inner(inner: soliton::call::CallKeys) -> Self {
Self { inner: Some(inner) }
}
}
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<CallKeys>()?;
Ok(())
}

131
soliton_py/src/errors.rs Normal file
View file

@ -0,0 +1,131 @@
//! Error type mapping from soliton::error::Error to Python exceptions.
use pyo3::create_exception;
use pyo3::exceptions::PyException;
use pyo3::prelude::*;
// Each soliton error variant gets a dedicated Python exception class,
// all inheriting from SolitonError.
create_exception!(
soliton,
SolitonError,
PyException,
"Base exception for all soliton errors."
);
create_exception!(
soliton,
InvalidLengthError,
SolitonError,
"Wrong-size parameter."
);
create_exception!(
soliton,
InvalidDataError,
SolitonError,
"Structurally invalid content."
);
create_exception!(soliton, AeadError, SolitonError, "AEAD decryption failed.");
create_exception!(
soliton,
VerificationError,
SolitonError,
"Signature verification failed."
);
create_exception!(
soliton,
BundleVerificationError,
SolitonError,
"Pre-key bundle verification failed."
);
create_exception!(
soliton,
DecapsulationError,
SolitonError,
"KEM decapsulation failed."
);
create_exception!(
soliton,
DuplicateMessageError,
SolitonError,
"Replayed or already-seen message."
);
create_exception!(
soliton,
ChainExhaustedError,
SolitonError,
"Counter-space exhausted."
);
create_exception!(
soliton,
UnsupportedVersionError,
SolitonError,
"Unsupported blob version."
);
create_exception!(
soliton,
UnsupportedCryptoVersionError,
SolitonError,
"Unrecognized crypto version."
);
create_exception!(
soliton,
InternalError,
SolitonError,
"Internal invariant violated."
);
/// Convert a soliton::error::Error into the appropriate Python exception.
pub fn to_py_err(e: soliton::error::Error) -> PyErr {
use soliton::error::Error;
match e {
Error::InvalidLength { .. } => InvalidLengthError::new_err(e.to_string()),
Error::InvalidData => InvalidDataError::new_err(e.to_string()),
Error::AeadFailed => AeadError::new_err(e.to_string()),
Error::VerificationFailed => VerificationError::new_err(e.to_string()),
Error::BundleVerificationFailed => BundleVerificationError::new_err(e.to_string()),
Error::DecapsulationFailed => DecapsulationError::new_err(e.to_string()),
Error::DuplicateMessage => DuplicateMessageError::new_err(e.to_string()),
Error::ChainExhausted => ChainExhaustedError::new_err(e.to_string()),
Error::UnsupportedVersion => UnsupportedVersionError::new_err(e.to_string()),
Error::UnsupportedCryptoVersion => UnsupportedCryptoVersionError::new_err(e.to_string()),
Error::Internal => InternalError::new_err(e.to_string()),
_ => SolitonError::new_err(e.to_string()),
}
}
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add("SolitonError", m.py().get_type::<SolitonError>())?;
m.add(
"InvalidLengthError",
m.py().get_type::<InvalidLengthError>(),
)?;
m.add("InvalidDataError", m.py().get_type::<InvalidDataError>())?;
m.add("AeadError", m.py().get_type::<AeadError>())?;
m.add("VerificationError", m.py().get_type::<VerificationError>())?;
m.add(
"BundleVerificationError",
m.py().get_type::<BundleVerificationError>(),
)?;
m.add(
"DecapsulationError",
m.py().get_type::<DecapsulationError>(),
)?;
m.add(
"DuplicateMessageError",
m.py().get_type::<DuplicateMessageError>(),
)?;
m.add(
"ChainExhaustedError",
m.py().get_type::<ChainExhaustedError>(),
)?;
m.add(
"UnsupportedVersionError",
m.py().get_type::<UnsupportedVersionError>(),
)?;
m.add(
"UnsupportedCryptoVersionError",
m.py().get_type::<UnsupportedCryptoVersionError>(),
)?;
m.add("InternalError", m.py().get_type::<InternalError>())?;
Ok(())
}

112
soliton_py/src/identity.rs Normal file
View file

@ -0,0 +1,112 @@
//! Identity key management: keygen, sign, verify, fingerprint.
use crate::errors::to_py_err;
use pyo3::prelude::*;
use pyo3::types::PyBytes;
/// An identity keypair (X-Wing + Ed25519 + ML-DSA-65).
///
/// Secret key material is zeroized when this object is garbage collected.
/// For deterministic cleanup, call `close()` explicitly or use as a context
/// manager: `with Identity.generate() as id: ...`
#[pyclass]
pub struct Identity {
pk: soliton::identity::IdentityPublicKey,
sk: Option<soliton::identity::IdentitySecretKey>,
}
#[pymethods]
impl Identity {
/// Generate a fresh identity keypair.
#[staticmethod]
fn generate() -> PyResult<Self> {
let id = soliton::identity::generate_identity().map_err(to_py_err)?;
Ok(Self {
pk: id.public_key,
sk: Some(id.secret_key),
})
}
/// Reconstruct from serialized public + secret key bytes.
#[staticmethod]
fn from_bytes(pk_bytes: &[u8], sk_bytes: &[u8]) -> PyResult<Self> {
let pk = soliton::identity::IdentityPublicKey::from_bytes(pk_bytes.to_vec())
.map_err(to_py_err)?;
let sk = soliton::identity::IdentitySecretKey::from_bytes(sk_bytes.to_vec())
.map_err(to_py_err)?;
Ok(Self { pk, sk: Some(sk) })
}
/// Reconstruct a public-key-only identity (cannot sign).
#[staticmethod]
fn from_public_bytes(pk_bytes: &[u8]) -> PyResult<Self> {
let pk = soliton::identity::IdentityPublicKey::from_bytes(pk_bytes.to_vec())
.map_err(to_py_err)?;
Ok(Self { pk, sk: None })
}
/// Public key bytes.
fn public_key<'py>(&self, py: Python<'py>) -> Py<PyBytes> {
PyBytes::new(py, self.pk.as_bytes()).into()
}
/// Secret key bytes. Raises if this is a public-key-only identity.
fn secret_key<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let sk = self
.sk
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("no secret key"))?;
Ok(PyBytes::new(py, sk.as_bytes()).into())
}
/// SHA3-256 fingerprint of the public key (32 bytes).
fn fingerprint<'py>(&self, py: Python<'py>) -> Py<PyBytes> {
let fp = soliton::primitives::sha3_256::hash(self.pk.as_bytes());
PyBytes::new(py, &fp).into()
}
/// Hex-encoded fingerprint.
fn fingerprint_hex(&self) -> String {
soliton::primitives::sha3_256::fingerprint_hex(self.pk.as_bytes())
}
/// Hybrid sign (Ed25519 + ML-DSA-65).
fn sign<'py>(&self, py: Python<'py>, message: &[u8]) -> PyResult<Py<PyBytes>> {
let sk = self
.sk
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("no secret key"))?;
let sig = soliton::identity::hybrid_sign(sk, message).map_err(to_py_err)?;
Ok(PyBytes::new(py, sig.as_bytes()).into())
}
/// Verify a hybrid signature against this identity's public key.
fn verify(&self, message: &[u8], signature: &[u8]) -> PyResult<()> {
let sig = soliton::identity::HybridSignature::from_bytes(signature.to_vec())
.map_err(to_py_err)?;
soliton::identity::hybrid_verify(&self.pk, message, &sig).map_err(to_py_err)
}
/// Zeroize the secret key immediately.
fn close(&mut self) {
self.sk = None;
}
fn __enter__(slf: Py<Self>) -> Py<Self> {
slf
}
fn __exit__(
&mut self,
_exc_type: Option<&Bound<'_, PyAny>>,
_exc_val: Option<&Bound<'_, PyAny>>,
_exc_tb: Option<&Bound<'_, PyAny>>,
) {
self.close();
}
}
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Identity>()?;
Ok(())
}

424
soliton_py/src/kex.rs Normal file
View file

@ -0,0 +1,424 @@
//! LO-KEX: asynchronous key exchange (KEM-based, similar to X3DH).
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use crate::errors::to_py_err;
/// Sign a pre-key with the identity key.
///
/// Returns the hybrid signature bytes (3373 bytes).
#[pyfunction]
fn kex_sign_prekey<'py>(py: Python<'py>, ik_sk: &[u8], spk_pub: &[u8]) -> PyResult<Py<PyBytes>> {
let sk = soliton::identity::IdentitySecretKey::from_bytes(ik_sk.to_vec()).map_err(to_py_err)?;
let spk =
soliton::primitives::xwing::PublicKey::from_bytes(spk_pub.to_vec()).map_err(to_py_err)?;
let sig = soliton::kex::sign_prekey(&sk, &spk).map_err(to_py_err)?;
Ok(PyBytes::new(py, sig.as_bytes()).into())
}
/// Verify a pre-key bundle.
///
/// Args:
/// bundle_ik_pk: Identity public key from the bundle.
/// known_ik_pk: Known identity public key for this peer.
/// spk_pub: Signed pre-key public key (1216 bytes).
/// spk_id: Signed pre-key ID.
/// spk_sig: Hybrid signature over spk_pub (3373 bytes).
/// crypto_version: Protocol version string (e.g. "lo-crypto-v1").
/// opk_pub: Optional one-time pre-key public key.
/// opk_id: Optional one-time pre-key ID.
///
/// Raises ``BundleVerificationError`` on failure.
#[pyfunction]
#[pyo3(signature = (bundle_ik_pk, known_ik_pk, spk_pub, spk_id, spk_sig, crypto_version, opk_pub=None, opk_id=None))]
#[allow(clippy::too_many_arguments)]
fn kex_verify_bundle(
bundle_ik_pk: &[u8],
known_ik_pk: &[u8],
spk_pub: &[u8],
spk_id: u32,
spk_sig: &[u8],
crypto_version: &str,
opk_pub: Option<&[u8]>,
opk_id: Option<u32>,
) -> PyResult<()> {
let bik = soliton::identity::IdentityPublicKey::from_bytes(bundle_ik_pk.to_vec())
.map_err(to_py_err)?;
let kik = soliton::identity::IdentityPublicKey::from_bytes(known_ik_pk.to_vec())
.map_err(to_py_err)?;
let spk =
soliton::primitives::xwing::PublicKey::from_bytes(spk_pub.to_vec()).map_err(to_py_err)?;
let sig =
soliton::identity::HybridSignature::from_bytes(spk_sig.to_vec()).map_err(to_py_err)?;
let opk = match opk_pub {
Some(data) => Some(
soliton::primitives::xwing::PublicKey::from_bytes(data.to_vec()).map_err(to_py_err)?,
),
None => None,
};
let bundle = soliton::kex::PreKeyBundle {
ik_pub: bik,
crypto_version: crypto_version.to_string(),
spk_pub: spk,
spk_id,
spk_sig: sig,
opk_pub: opk,
opk_id,
};
// verify_bundle consumes the bundle and returns VerifiedBundle on success.
soliton::kex::verify_bundle(bundle, &kik).map_err(to_py_err)?;
Ok(())
}
/// Result of session initiation (Alice's side).
///
/// Contains the session init data to send to Bob, plus secret keys for
/// ratchet initialization. Use ``take_root_key`` and ``take_initial_chain_key``
/// to extract keys (destructive — second call returns zeros).
#[pyclass]
pub struct InitiatedSession {
inner: Option<soliton::kex::InitiatedSession>,
}
#[pymethods]
impl InitiatedSession {
/// Encoded session init message bytes.
fn session_init_encoded<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
let encoded = soliton::kex::encode_session_init(&s.session_init).map_err(to_py_err)?;
Ok(PyBytes::new(py, &encoded).into())
}
/// Extract root key (32 bytes). Destructive — zeroed after first call.
fn take_root_key<'py>(&mut self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_mut()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
let rk = s.take_root_key();
Ok(PyBytes::new(py, &*rk).into())
}
/// Extract initial chain key (32 bytes). Destructive — zeroed after first call.
fn take_initial_chain_key<'py>(&mut self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_mut()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
let ck = s.take_initial_chain_key();
Ok(PyBytes::new(py, &*ck).into())
}
/// Alice's ephemeral public key bytes (1216 bytes).
fn ek_pk<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
Ok(PyBytes::new(py, s.ek_pk.as_bytes()).into())
}
/// Alice's ephemeral secret key bytes (2432 bytes).
fn ek_sk<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
Ok(PyBytes::new(py, s.ek_sk().as_bytes()).into())
}
/// Sender hybrid signature bytes (3373 bytes).
fn sender_sig<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
Ok(PyBytes::new(py, s.sender_sig.as_bytes()).into())
}
/// Whether an OPK was used.
fn opk_used(&self) -> PyResult<bool> {
let s = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
Ok(s.opk_used)
}
/// Sender fingerprint (SHA3-256 of Alice's IK).
fn sender_fingerprint<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
Ok(PyBytes::new(py, &s.session_init.sender_ik_fingerprint).into())
}
/// Recipient fingerprint (SHA3-256 of Bob's IK).
fn recipient_fingerprint<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
Ok(PyBytes::new(py, &s.session_init.recipient_ik_fingerprint).into())
}
fn close(&mut self) {
self.inner = None;
}
fn __enter__(slf: Py<Self>) -> Py<Self> {
slf
}
fn __exit__(
&mut self,
_exc_type: Option<&Bound<'_, PyAny>>,
_exc_val: Option<&Bound<'_, PyAny>>,
_exc_tb: Option<&Bound<'_, PyAny>>,
) {
self.close();
}
}
/// Initiate a session (Alice's side).
///
/// Args:
/// alice_ik_pk: Alice's identity public key.
/// alice_ik_sk: Alice's identity secret key.
/// bundle_ik_pk: Bob's identity public key (from bundle).
/// spk_pub: Bob's signed pre-key public key.
/// spk_id: Bob's signed pre-key ID.
/// spk_sig: Hybrid signature over spk_pub.
/// crypto_version: Protocol version string.
/// opk_pub: Optional one-time pre-key public key.
/// opk_id: Optional one-time pre-key ID.
#[pyfunction]
#[pyo3(signature = (alice_ik_pk, alice_ik_sk, bundle_ik_pk, spk_pub, spk_id, spk_sig, crypto_version, opk_pub=None, opk_id=None))]
#[allow(clippy::too_many_arguments)]
fn kex_initiate(
alice_ik_pk: &[u8],
alice_ik_sk: &[u8],
bundle_ik_pk: &[u8],
spk_pub: &[u8],
spk_id: u32,
spk_sig: &[u8],
crypto_version: &str,
opk_pub: Option<&[u8]>,
opk_id: Option<u32>,
) -> PyResult<InitiatedSession> {
let a_pk = soliton::identity::IdentityPublicKey::from_bytes(alice_ik_pk.to_vec())
.map_err(to_py_err)?;
let a_sk = soliton::identity::IdentitySecretKey::from_bytes(alice_ik_sk.to_vec())
.map_err(to_py_err)?;
let b_pk = soliton::identity::IdentityPublicKey::from_bytes(bundle_ik_pk.to_vec())
.map_err(to_py_err)?;
let spk =
soliton::primitives::xwing::PublicKey::from_bytes(spk_pub.to_vec()).map_err(to_py_err)?;
let sig =
soliton::identity::HybridSignature::from_bytes(spk_sig.to_vec()).map_err(to_py_err)?;
let opk = match opk_pub {
Some(data) => Some(
soliton::primitives::xwing::PublicKey::from_bytes(data.to_vec()).map_err(to_py_err)?,
),
None => None,
};
// Clone Bob's PK before moving it into the bundle — verify_bundle
// consumes the bundle but needs the known IK as a separate reference.
let known_ik = soliton::identity::IdentityPublicKey::from_bytes(bundle_ik_pk.to_vec())
.map_err(to_py_err)?;
let bundle = soliton::kex::PreKeyBundle {
ik_pub: b_pk,
crypto_version: crypto_version.to_string(),
spk_pub: spk,
spk_id,
spk_sig: sig,
opk_pub: opk,
opk_id,
};
// verify_bundle checks that the bundle's IK matches known_ik (Bob's PK)
// and that the SPK signature is valid. The TOFU check (whether Bob's PK
// is the one the caller trusts) is the caller's responsibility.
let verified = soliton::kex::verify_bundle(bundle, &known_ik).map_err(to_py_err)?;
let session = soliton::kex::initiate_session(&a_pk, &a_sk, &verified).map_err(to_py_err)?;
Ok(InitiatedSession {
inner: Some(session),
})
}
/// Result of session receipt (Bob's side).
#[pyclass]
pub struct ReceivedSession {
inner: Option<soliton::kex::ReceivedSession>,
}
#[pymethods]
impl ReceivedSession {
/// Extract root key (32 bytes). Destructive.
fn take_root_key<'py>(&mut self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_mut()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
let rk = s.take_root_key();
Ok(PyBytes::new(py, &*rk).into())
}
/// Extract initial chain key (32 bytes). Destructive.
fn take_initial_chain_key<'py>(&mut self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_mut()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
let ck = s.take_initial_chain_key();
Ok(PyBytes::new(py, &*ck).into())
}
/// Peer's ephemeral public key (1216 bytes).
fn peer_ek<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let s = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
Ok(PyBytes::new(py, s.peer_ek.as_bytes()).into())
}
fn close(&mut self) {
self.inner = None;
}
fn __enter__(slf: Py<Self>) -> Py<Self> {
slf
}
fn __exit__(
&mut self,
_exc_type: Option<&Bound<'_, PyAny>>,
_exc_val: Option<&Bound<'_, PyAny>>,
_exc_tb: Option<&Bound<'_, PyAny>>,
) {
self.close();
}
}
/// Receive a session (Bob's side).
///
/// Args:
/// bob_ik_pk: Bob's identity public key.
/// bob_ik_sk: Bob's identity secret key.
/// alice_ik_pk: Alice's identity public key.
/// session_init_encoded: Encoded session init bytes from Alice.
/// sender_sig: Alice's hybrid signature (3373 bytes).
/// spk_sk: Bob's signed pre-key secret key.
/// opk_sk: Optional one-time pre-key secret key.
#[pyfunction]
#[pyo3(signature = (bob_ik_pk, bob_ik_sk, alice_ik_pk, session_init_encoded, sender_sig, spk_sk, opk_sk=None))]
fn kex_receive(
bob_ik_pk: &[u8],
bob_ik_sk: &[u8],
alice_ik_pk: &[u8],
session_init_encoded: &[u8],
sender_sig: &[u8],
spk_sk: &[u8],
opk_sk: Option<&[u8]>,
) -> PyResult<ReceivedSession> {
let b_pk =
soliton::identity::IdentityPublicKey::from_bytes(bob_ik_pk.to_vec()).map_err(to_py_err)?;
let b_sk =
soliton::identity::IdentitySecretKey::from_bytes(bob_ik_sk.to_vec()).map_err(to_py_err)?;
let a_pk = soliton::identity::IdentityPublicKey::from_bytes(alice_ik_pk.to_vec())
.map_err(to_py_err)?;
let si = soliton::kex::decode_session_init(session_init_encoded).map_err(to_py_err)?;
let sig =
soliton::identity::HybridSignature::from_bytes(sender_sig.to_vec()).map_err(to_py_err)?;
let spk_secret =
soliton::primitives::xwing::SecretKey::from_bytes(spk_sk.to_vec()).map_err(to_py_err)?;
let opk_secret = match opk_sk {
Some(data) => Some(
soliton::primitives::xwing::SecretKey::from_bytes(data.to_vec()).map_err(to_py_err)?,
),
None => None,
};
let session = soliton::kex::receive_session(
&b_pk,
&b_sk,
&a_pk,
&si,
&sig,
&spk_secret,
opk_secret.as_ref(),
)
.map_err(to_py_err)?;
Ok(ReceivedSession {
inner: Some(session),
})
}
/// Encode a session init to wire bytes.
#[pyfunction]
fn kex_encode_session_init<'py>(
py: Python<'py>,
session_init_encoded: &[u8],
) -> PyResult<Py<PyBytes>> {
// This re-encodes from decoded form — useful for round-trip testing.
let si = soliton::kex::decode_session_init(session_init_encoded).map_err(to_py_err)?;
let encoded = soliton::kex::encode_session_init(&si).map_err(to_py_err)?;
Ok(PyBytes::new(py, &encoded).into())
}
/// Decode session init from wire bytes.
///
/// Returns a dict with the decoded fields.
#[pyfunction]
fn kex_decode_session_init<'py>(py: Python<'py>, data: &[u8]) -> PyResult<Py<PyBytes>> {
// For simplicity, just validate it decodes and return the same bytes.
// The full structured access is via kex_receive which takes encoded bytes.
let _si = soliton::kex::decode_session_init(data).map_err(to_py_err)?;
Ok(PyBytes::new(py, data).into())
}
/// Build first-message AAD from fingerprints and encoded session init.
#[pyfunction]
fn kex_build_first_message_aad<'py>(
py: Python<'py>,
sender_fp: &[u8],
recipient_fp: &[u8],
session_init_encoded: &[u8],
) -> PyResult<Py<PyBytes>> {
if sender_fp.len() != 32 || recipient_fp.len() != 32 {
return Err(crate::errors::InvalidLengthError::new_err(
"fingerprints must be 32 bytes",
));
}
let sfp: &[u8; 32] = sender_fp.try_into().unwrap();
let rfp: &[u8; 32] = recipient_fp.try_into().unwrap();
let aad = soliton::kex::build_first_message_aad_from_encoded(sfp, rfp, session_init_encoded)
.map_err(to_py_err)?;
Ok(PyBytes::new(py, &aad).into())
}
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<InitiatedSession>()?;
m.add_class::<ReceivedSession>()?;
m.add_function(wrap_pyfunction!(kex_sign_prekey, m)?)?;
m.add_function(wrap_pyfunction!(kex_verify_bundle, m)?)?;
m.add_function(wrap_pyfunction!(kex_initiate, m)?)?;
m.add_function(wrap_pyfunction!(kex_receive, m)?)?;
m.add_function(wrap_pyfunction!(kex_encode_session_init, m)?)?;
m.add_function(wrap_pyfunction!(kex_decode_session_init, m)?)?;
m.add_function(wrap_pyfunction!(kex_build_first_message_aad, m)?)?;
Ok(())
}

39
soliton_py/src/lib.rs Normal file
View file

@ -0,0 +1,39 @@
//! Python bindings for libsoliton via PyO3.
//!
//! This crate wraps the core Rust API (not the CAPI) to provide a safe,
//! ergonomic Python interface. The Zig binding covers the CAPI path.
use pyo3::prelude::*;
mod auth;
mod call;
mod errors;
mod identity;
mod kex;
mod primitives;
mod ratchet;
mod storage;
mod stream;
mod verification;
/// libsoliton — post-quantum cryptographic library.
#[pymodule]
fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> {
// Version
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
m.add("VERSION", soliton::VERSION)?;
// Register submodules.
errors::register(m)?;
primitives::register(m)?;
identity::register(m)?;
auth::register(m)?;
kex::register(m)?;
ratchet::register(m)?;
storage::register(m)?;
stream::register(m)?;
call::register(m)?;
verification::register(m)?;
Ok(())
}

View file

@ -0,0 +1,77 @@
//! Primitive cryptographic operations: SHA3-256, HMAC, HKDF.
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use crate::errors::to_py_err;
/// SHA3-256 hash.
#[pyfunction]
fn sha3_256(py: Python<'_>, data: &[u8]) -> PyResult<Py<PyBytes>> {
let hash = soliton::primitives::sha3_256::hash(data);
Ok(PyBytes::new(py, &hash).into())
}
/// SHA3-256 hex fingerprint of a public key or arbitrary data.
#[pyfunction]
fn fingerprint_hex(data: &[u8]) -> String {
soliton::primitives::sha3_256::fingerprint_hex(data)
}
/// HMAC-SHA3-256.
#[pyfunction]
fn hmac_sha3_256(py: Python<'_>, key: &[u8], data: &[u8]) -> PyResult<Py<PyBytes>> {
let tag = soliton::primitives::hmac::hmac_sha3_256(key, data);
Ok(PyBytes::new(py, &tag).into())
}
/// Constant-time HMAC-SHA3-256 verification.
#[pyfunction]
fn hmac_sha3_256_verify(a: &[u8], b: &[u8]) -> PyResult<bool> {
if a.len() != 32 || b.len() != 32 {
return Err(crate::errors::InvalidLengthError::new_err(
"both inputs must be 32 bytes",
));
}
let a: &[u8; 32] = a.try_into().unwrap();
let b: &[u8; 32] = b.try_into().unwrap();
Ok(soliton::primitives::hmac::hmac_sha3_256_verify_raw(a, b))
}
/// HKDF-SHA3-256 extract-and-expand.
#[pyfunction]
#[pyo3(signature = (salt, ikm, info, *, length))]
fn hkdf_sha3_256(
py: Python<'_>,
salt: &[u8],
ikm: &[u8],
info: &[u8],
length: usize,
) -> PyResult<Py<PyBytes>> {
let mut out = vec![0u8; length];
soliton::primitives::hkdf::hkdf_sha3_256(salt, ikm, info, &mut out).map_err(to_py_err)?;
Ok(PyBytes::new(py, &out).into())
}
/// Generate an X-Wing keypair.
///
/// Returns (public_key, secret_key) as a tuple of bytes.
/// Public key is 1216 bytes, secret key is 2432 bytes.
#[pyfunction]
fn xwing_keygen(py: Python<'_>) -> PyResult<(Py<PyBytes>, Py<PyBytes>)> {
let (pk, sk) = soliton::primitives::xwing::keygen().map_err(to_py_err)?;
Ok((
PyBytes::new(py, pk.as_bytes()).into(),
PyBytes::new(py, sk.as_bytes()).into(),
))
}
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sha3_256, m)?)?;
m.add_function(wrap_pyfunction!(fingerprint_hex, m)?)?;
m.add_function(wrap_pyfunction!(hmac_sha3_256, m)?)?;
m.add_function(wrap_pyfunction!(hmac_sha3_256_verify, m)?)?;
m.add_function(wrap_pyfunction!(hkdf_sha3_256, m)?)?;
m.add_function(wrap_pyfunction!(xwing_keygen, m)?)?;
Ok(())
}

349
soliton_py/src/ratchet.rs Normal file
View file

@ -0,0 +1,349 @@
//! Double ratchet session: encrypt, decrypt, serialize, deserialize.
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use zeroize::Zeroize;
use crate::call::CallKeys;
use crate::errors::to_py_err;
/// Double ratchet session state.
///
/// Manages the symmetric ratchet for ongoing message encryption/decryption.
/// Initialized after KEX completes (from root_key + chain_key + peer_ek).
///
/// Use as a context manager for automatic zeroization::
///
/// with Ratchet.init_alice(root_key, chain_key, local_fp, remote_fp, peer_ek, ek_sk) as r:
/// header, ciphertext = r.encrypt(b"hello")
#[pyclass]
pub struct Ratchet {
inner: Option<soliton::ratchet::RatchetState>,
}
#[pymethods]
impl Ratchet {
/// Initialize Alice's side (initiator).
#[staticmethod]
fn init_alice(
root_key: &[u8],
chain_key: &[u8],
local_fp: &[u8],
remote_fp: &[u8],
peer_ek: &[u8],
ek_sk: &[u8],
) -> PyResult<Self> {
let mut rk = to_32("root_key", root_key)?;
let mut ck = to_32("chain_key", chain_key)?;
let lfp = to_32("local_fp", local_fp)?;
let rfp = to_32("remote_fp", remote_fp)?;
let ek_pub = soliton::primitives::xwing::PublicKey::from_bytes(peer_ek.to_vec())
.map_err(to_py_err)?;
let ek_secret =
soliton::primitives::xwing::SecretKey::from_bytes(ek_sk.to_vec()).map_err(to_py_err)?;
let state = soliton::ratchet::RatchetState::init_alice(rk, ck, lfp, rfp, ek_pub, ek_secret)
.map_err(to_py_err)?;
rk.zeroize();
ck.zeroize();
Ok(Self { inner: Some(state) })
}
/// Initialize Bob's side (responder).
#[staticmethod]
fn init_bob(
root_key: &[u8],
chain_key: &[u8],
local_fp: &[u8],
remote_fp: &[u8],
peer_ek: &[u8],
) -> PyResult<Self> {
let mut rk = to_32("root_key", root_key)?;
let mut ck = to_32("chain_key", chain_key)?;
let lfp = to_32("local_fp", local_fp)?;
let rfp = to_32("remote_fp", remote_fp)?;
let ek_pub = soliton::primitives::xwing::PublicKey::from_bytes(peer_ek.to_vec())
.map_err(to_py_err)?;
let state = soliton::ratchet::RatchetState::init_bob(rk, ck, lfp, rfp, ek_pub)
.map_err(to_py_err)?;
rk.zeroize();
ck.zeroize();
Ok(Self { inner: Some(state) })
}
/// Encrypt a plaintext message.
///
/// Returns:
/// Tuple of (header_bytes, ciphertext). header_bytes is the serialized
/// RatchetHeader (ratchet_pk + optional kem_ct + n + pn); ciphertext is
/// the AEAD output. Both must be sent to the recipient.
fn encrypt<'py>(
&mut self,
py: Python<'py>,
plaintext: &[u8],
) -> PyResult<(Py<PyBytes>, Py<PyBytes>)> {
let state = self.inner.as_mut().ok_or_else(|| {
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
})?;
let msg = state.encrypt(plaintext).map_err(to_py_err)?;
// Serialize the header to bytes for transport.
let header_bytes = encode_header(&msg.header);
Ok((
PyBytes::new(py, &header_bytes).into(),
PyBytes::new(py, &msg.ciphertext).into(),
))
}
/// Decrypt a received message.
///
/// Args:
/// header: Serialized RatchetHeader bytes (from sender's encrypt()).
/// ciphertext: AEAD ciphertext bytes.
///
/// Returns:
/// Decrypted plaintext bytes.
fn decrypt<'py>(
&mut self,
py: Python<'py>,
header: &[u8],
ciphertext: &[u8],
) -> PyResult<Py<PyBytes>> {
let state = self.inner.as_mut().ok_or_else(|| {
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
})?;
let rh = decode_header(header)?;
let pt = state.decrypt(&rh, ciphertext).map_err(to_py_err)?;
Ok(PyBytes::new(py, &pt).into())
}
/// Encrypt the first message (pre-ratchet, uses initial chain key).
///
/// This is a static method — called before the ratchet is initialized.
///
/// Args:
/// chain_key: 32-byte initial chain key from KEX.
/// plaintext: First application message.
/// aad: Additional authenticated data (from build_first_message_aad).
///
/// Returns:
/// Tuple of (encrypted_payload, ratchet_init_key). Pass ratchet_init_key
/// as chain_key to init_alice/init_bob.
#[staticmethod]
fn encrypt_first_message<'py>(
py: Python<'py>,
chain_key: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> PyResult<(Py<PyBytes>, Py<PyBytes>)> {
let ck = zeroizing_32("chain_key", chain_key)?;
let (ct, rik) = soliton::ratchet::RatchetState::encrypt_first_message(ck, plaintext, aad)
.map_err(to_py_err)?;
Ok((PyBytes::new(py, &ct).into(), PyBytes::new(py, &*rik).into()))
}
/// Decrypt the first message (pre-ratchet).
///
/// Returns:
/// Tuple of (plaintext, ratchet_init_key).
#[staticmethod]
fn decrypt_first_message<'py>(
py: Python<'py>,
chain_key: &[u8],
encrypted_payload: &[u8],
aad: &[u8],
) -> PyResult<(Py<PyBytes>, Py<PyBytes>)> {
let ck = zeroizing_32("chain_key", chain_key)?;
let (pt, rik) =
soliton::ratchet::RatchetState::decrypt_first_message(ck, encrypted_payload, aad)
.map_err(to_py_err)?;
Ok((PyBytes::new(py, &pt).into(), PyBytes::new(py, &*rik).into()))
}
/// Serialize the ratchet state. Consumes the ratchet.
///
/// Returns:
/// Tuple of (blob, epoch). Persist the blob encrypted (e.g., with
/// StorageKeyRing). Store epoch separately for anti-rollback.
#[allow(clippy::wrong_self_convention)]
fn to_bytes<'py>(&mut self, py: Python<'py>) -> PyResult<(Py<PyBytes>, u64)> {
let state = self
.inner
.take()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("ratchet already consumed"))?;
let (blob, epoch) = state.to_bytes().map_err(to_py_err)?;
Ok((PyBytes::new(py, &blob).into(), epoch))
}
/// Deserialize ratchet state with anti-rollback protection.
///
/// Args:
/// data: Serialized ratchet blob.
/// min_epoch: Minimum acceptable epoch. Use saved_epoch - 1.
#[staticmethod]
fn from_bytes(data: &[u8], min_epoch: u64) -> PyResult<Self> {
let state = soliton::ratchet::RatchetState::from_bytes_with_min_epoch(data, min_epoch)
.map_err(to_py_err)?;
Ok(Self { inner: Some(state) })
}
/// Whether the ratchet can be serialized (counters not exhausted).
fn can_serialize(&self) -> PyResult<bool> {
let state = self.inner.as_ref().ok_or_else(|| {
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
})?;
Ok(state.can_serialize())
}
/// Current epoch number.
fn epoch(&self) -> PyResult<u64> {
let state = self.inner.as_ref().ok_or_else(|| {
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
})?;
Ok(state.epoch())
}
/// Reset the ratchet (zeroize all keys). The session is dead after this.
fn reset(&mut self) -> PyResult<()> {
let state = self.inner.as_mut().ok_or_else(|| {
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
})?;
state.reset();
Ok(())
}
/// Derive call keys for encrypted voice/video.
fn derive_call_keys(&self, kem_ss: &[u8], call_id: &[u8]) -> PyResult<CallKeys> {
let state = self.inner.as_ref().ok_or_else(|| {
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
})?;
if kem_ss.len() != 32 {
return Err(crate::errors::InvalidLengthError::new_err(
"kem_ss must be 32 bytes",
));
}
if call_id.len() != 16 {
return Err(crate::errors::InvalidLengthError::new_err(
"call_id must be 16 bytes",
));
}
let ss: &[u8; 32] = kem_ss.try_into().unwrap();
let cid: &[u8; 16] = call_id.try_into().unwrap();
let keys = state.derive_call_keys(ss, cid).map_err(to_py_err)?;
Ok(CallKeys::from_inner(keys))
}
fn close(&mut self) {
if let Some(mut state) = self.inner.take() {
state.reset();
}
}
fn __enter__(slf: Py<Self>) -> Py<Self> {
slf
}
fn __exit__(
&mut self,
_exc_type: Option<&Bound<'_, PyAny>>,
_exc_val: Option<&Bound<'_, PyAny>>,
_exc_tb: Option<&Bound<'_, PyAny>>,
) {
self.close();
}
}
// ── Header serialization ────────────────────────────────────────────────
//
// Simple wire format for Python: ratchet_pk (1216) + has_kem_ct (1) +
// [kem_ct (1120) if present] + n (4 BE) + pn (4 BE).
// This matches the CAPI's encode_ratchet_header layout.
fn encode_header(h: &soliton::ratchet::RatchetHeader) -> Vec<u8> {
let pk_bytes = h.ratchet_pk.as_bytes();
let has_ct = h.kem_ct.is_some();
let size = 1216 + 1 + if has_ct { 2 + 1120 } else { 0 } + 4 + 4;
let mut buf = Vec::with_capacity(size);
buf.extend_from_slice(pk_bytes);
if let Some(ref ct) = h.kem_ct {
buf.push(0x01);
let ct_bytes = ct.as_bytes();
buf.extend_from_slice(&(ct_bytes.len() as u16).to_be_bytes());
buf.extend_from_slice(ct_bytes);
} else {
buf.push(0x00);
}
buf.extend_from_slice(&h.n.to_be_bytes());
buf.extend_from_slice(&h.pn.to_be_bytes());
buf
}
fn decode_header(data: &[u8]) -> PyResult<soliton::ratchet::RatchetHeader> {
if data.len() < 1216 + 1 + 4 + 4 {
return Err(crate::errors::InvalidDataError::new_err("header too short"));
}
let ratchet_pk = soliton::primitives::xwing::PublicKey::from_bytes(data[..1216].to_vec())
.map_err(to_py_err)?;
let has_ct = data[1216];
if has_ct != 0x00 && has_ct != 0x01 {
return Err(crate::errors::InvalidDataError::new_err(
"invalid has_kem_ct flag (expected 0x00 or 0x01)",
));
}
let rest = if has_ct == 0x01 {
if data.len() < 1216 + 1 + 2 + 1120 + 4 + 4 {
return Err(crate::errors::InvalidDataError::new_err(
"header too short for kem_ct",
));
}
&data[1216 + 1 + 2 + 1120..]
} else {
&data[1216 + 1..]
};
let kem_ct = if has_ct == 0x01 {
Some(
soliton::primitives::xwing::Ciphertext::from_bytes(
data[1216 + 1 + 2..1216 + 1 + 2 + 1120].to_vec(),
)
.map_err(to_py_err)?,
)
} else {
None
};
if rest.len() < 8 {
return Err(crate::errors::InvalidDataError::new_err(
"header missing counters",
));
}
let n = u32::from_be_bytes(rest[..4].try_into().unwrap());
let pn = u32::from_be_bytes(rest[4..8].try_into().unwrap());
Ok(soliton::ratchet::RatchetHeader {
ratchet_pk,
kem_ct,
n,
pn,
})
}
// ── Helpers ─────────────────────────────────────────────────────────────
fn to_32(name: &str, data: &[u8]) -> PyResult<[u8; 32]> {
data.try_into()
.map_err(|_| crate::errors::InvalidLengthError::new_err(format!("{name} must be 32 bytes")))
}
fn zeroizing_32(name: &str, data: &[u8]) -> PyResult<zeroize::Zeroizing<[u8; 32]>> {
let arr = to_32(name, data)?;
Ok(zeroize::Zeroizing::new(arr))
}
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Ratchet>()?;
Ok(())
}

199
soliton_py/src/storage.rs Normal file
View file

@ -0,0 +1,199 @@
//! Encrypted storage: community blobs and DM queue blobs.
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use crate::errors::to_py_err;
/// Encrypted storage key ring.
///
/// Manages versioned encryption keys for community storage and DM queues.
/// Multiple key versions can coexist for key rotation — old keys decrypt
/// existing blobs while new keys encrypt new writes.
///
/// Use as a context manager for automatic zeroization::
///
/// with soliton.StorageKeyRing(1, key_bytes) as ring:
/// blob = ring.encrypt_blob("channel-1", "seg-0", plaintext)
/// data = ring.decrypt_blob("channel-1", "seg-0", blob)
#[pyclass]
pub struct StorageKeyRing {
inner: Option<soliton::storage::StorageKeyRing>,
}
#[pymethods]
impl StorageKeyRing {
/// Create a keyring with an initial active key.
///
/// Args:
/// version: Key version (1-255). Version 0 is rejected.
/// key: 32-byte encryption key.
#[new]
fn new(version: u8, key: &[u8]) -> PyResult<Self> {
if key.len() != 32 {
return Err(crate::errors::InvalidLengthError::new_err(
"key must be 32 bytes",
));
}
let key_arr: [u8; 32] = key.try_into().unwrap();
let storage_key = soliton::storage::StorageKey::new(version, key_arr).map_err(to_py_err)?;
let ring = soliton::storage::StorageKeyRing::new(storage_key).map_err(to_py_err)?;
Ok(Self { inner: Some(ring) })
}
/// Add a key to the ring.
///
/// Args:
/// version: Key version (1-255).
/// key: 32-byte encryption key.
/// make_active: If True, this key becomes the active key for new writes.
fn add_key(&mut self, version: u8, key: &[u8], make_active: bool) -> PyResult<()> {
if key.len() != 32 {
return Err(crate::errors::InvalidLengthError::new_err(
"key must be 32 bytes",
));
}
let ring = self
.inner
.as_mut()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
let key_arr: [u8; 32] = key.try_into().unwrap();
let storage_key = soliton::storage::StorageKey::new(version, key_arr).map_err(to_py_err)?;
ring.add_key(storage_key, make_active).map_err(to_py_err)?;
Ok(())
}
/// Remove a key version from the ring.
///
/// The active version cannot be removed — set a new active key first.
fn remove_key(&mut self, version: u8) -> PyResult<()> {
let ring = self
.inner
.as_mut()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
ring.remove_key(version).map_err(to_py_err)?;
Ok(())
}
/// Encrypt a community storage blob.
///
/// Args:
/// channel_id: Channel identifier (bound into AAD).
/// segment_id: Segment identifier (bound into AAD).
/// plaintext: Data to encrypt.
///
/// Returns:
/// Encrypted blob bytes (self-describing — contains key version).
#[pyo3(signature = (channel_id, segment_id, plaintext, compress=false))]
fn encrypt_blob<'py>(
&self,
py: Python<'py>,
channel_id: &str,
segment_id: &str,
plaintext: &[u8],
compress: bool,
) -> PyResult<Py<PyBytes>> {
let ring = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
let key = ring
.active_key()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("no active key"))?;
let blob = soliton::storage::encrypt_blob(key, plaintext, channel_id, segment_id, compress)
.map_err(to_py_err)?;
Ok(PyBytes::new(py, &blob).into())
}
/// Decrypt a community storage blob.
///
/// The blob's embedded key version selects the decryption key from the ring.
fn decrypt_blob<'py>(
&self,
py: Python<'py>,
channel_id: &str,
segment_id: &str,
blob: &[u8],
) -> PyResult<Py<PyBytes>> {
let ring = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
let pt = soliton::storage::decrypt_blob(ring, blob, channel_id, segment_id)
.map_err(to_py_err)?;
Ok(PyBytes::new(py, &pt).into())
}
/// Encrypt a DM queue blob.
#[pyo3(signature = (recipient_fp, batch_id, plaintext, compress=false))]
fn encrypt_dm_queue<'py>(
&self,
py: Python<'py>,
recipient_fp: &[u8],
batch_id: &str,
plaintext: &[u8],
compress: bool,
) -> PyResult<Py<PyBytes>> {
if recipient_fp.len() != 32 {
return Err(crate::errors::InvalidLengthError::new_err(
"recipient_fp must be 32 bytes",
));
}
let ring = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
let key = ring
.active_key()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("no active key"))?;
let fp: &[u8; 32] = recipient_fp.try_into().unwrap();
let blob = soliton::storage::encrypt_dm_queue_blob(key, plaintext, fp, batch_id, compress)
.map_err(to_py_err)?;
Ok(PyBytes::new(py, &blob).into())
}
/// Decrypt a DM queue blob.
fn decrypt_dm_queue<'py>(
&self,
py: Python<'py>,
recipient_fp: &[u8],
batch_id: &str,
blob: &[u8],
) -> PyResult<Py<PyBytes>> {
if recipient_fp.len() != 32 {
return Err(crate::errors::InvalidLengthError::new_err(
"recipient_fp must be 32 bytes",
));
}
let ring = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
let fp: &[u8; 32] = recipient_fp.try_into().unwrap();
let pt =
soliton::storage::decrypt_dm_queue_blob(ring, blob, fp, batch_id).map_err(to_py_err)?;
Ok(PyBytes::new(py, &pt).into())
}
fn close(&mut self) {
self.inner = None;
}
fn __enter__(slf: Py<Self>) -> Py<Self> {
slf
}
fn __exit__(
&mut self,
_exc_type: Option<&Bound<'_, PyAny>>,
_exc_val: Option<&Bound<'_, PyAny>>,
_exc_tb: Option<&Bound<'_, PyAny>>,
) {
self.close();
}
}
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<StorageKeyRing>()?;
Ok(())
}

241
soliton_py/src/stream.rs Normal file
View file

@ -0,0 +1,241 @@
//! Streaming AEAD: chunked encryption/decryption for files and media.
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use crate::errors::to_py_err;
/// Streaming encryptor for chunked file/media encryption.
///
/// Produces a 26-byte header (sent first) and one ciphertext chunk per call
/// to ``encrypt_chunk``. Non-final chunks must be exactly 1 MiB of plaintext;
/// the final chunk may be shorter.
///
/// Use as a context manager::
///
/// with soliton.StreamEncryptor(key) as enc:
/// header = enc.header()
/// ct1 = enc.encrypt_chunk(data1)
/// ct2 = enc.encrypt_chunk(data2, is_last=True)
#[pyclass]
pub struct StreamEncryptor {
inner: Option<soliton::streaming::StreamEncryptor>,
}
#[pymethods]
impl StreamEncryptor {
/// Create a streaming encryptor.
///
/// Args:
/// key: 32-byte encryption key.
/// aad: Optional additional authenticated data (bound to all chunks).
/// compress: Enable zstd compression per chunk (default False).
#[new]
#[pyo3(signature = (key, aad=None, compress=false))]
fn new(key: &[u8], aad: Option<&[u8]>, compress: bool) -> PyResult<Self> {
if key.len() != 32 {
return Err(crate::errors::InvalidLengthError::new_err(
"key must be 32 bytes",
));
}
let key_arr: &[u8; 32] = key.try_into().unwrap();
let aad_bytes = aad.unwrap_or(&[]);
let enc = soliton::streaming::stream_encrypt_init(key_arr, aad_bytes, compress)
.map_err(to_py_err)?;
Ok(Self { inner: Some(enc) })
}
/// The 26-byte stream header. Send this before any chunks.
fn header<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("encryptor closed"))?;
Ok(PyBytes::new(py, &inner.header()).into())
}
/// Encrypt one chunk.
///
/// Args:
/// plaintext: Chunk data. Non-final chunks must be exactly 1,048,576 bytes.
/// is_last: True for the final chunk.
///
/// Returns:
/// Encrypted chunk bytes.
#[pyo3(signature = (plaintext, is_last=false))]
fn encrypt_chunk<'py>(
&mut self,
py: Python<'py>,
plaintext: &[u8],
is_last: bool,
) -> PyResult<Py<PyBytes>> {
let inner = self
.inner
.as_mut()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("encryptor closed"))?;
let ct = inner.encrypt_chunk(plaintext, is_last).map_err(to_py_err)?;
Ok(PyBytes::new(py, &ct).into())
}
/// Encrypt a specific chunk by index (random access, stateless).
fn encrypt_chunk_at<'py>(
&self,
py: Python<'py>,
index: u64,
plaintext: &[u8],
is_last: bool,
) -> PyResult<Py<PyBytes>> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("encryptor closed"))?;
let ct = inner
.encrypt_chunk_at(index, is_last, plaintext)
.map_err(to_py_err)?;
Ok(PyBytes::new(py, &ct).into())
}
/// Whether the encryptor has been finalized.
fn is_finalized(&self) -> PyResult<bool> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("encryptor closed"))?;
Ok(inner.is_finalized())
}
fn close(&mut self) {
self.inner = None;
}
fn __enter__(slf: Py<Self>) -> Py<Self> {
slf
}
fn __exit__(
&mut self,
_exc_type: Option<&Bound<'_, PyAny>>,
_exc_val: Option<&Bound<'_, PyAny>>,
_exc_tb: Option<&Bound<'_, PyAny>>,
) {
self.close();
}
}
/// Streaming decryptor for chunked file/media decryption.
///
/// Use as a context manager::
///
/// with soliton.StreamDecryptor(key, header) as dec:
/// pt1, is_last = dec.decrypt_chunk(ct1)
/// pt2, is_last = dec.decrypt_chunk(ct2)
#[pyclass]
pub struct StreamDecryptor {
inner: Option<soliton::streaming::StreamDecryptor>,
}
#[pymethods]
impl StreamDecryptor {
/// Create a streaming decryptor.
///
/// Args:
/// key: 32-byte decryption key (same key used for encryption).
/// header: 26-byte stream header from the encryptor.
/// aad: Optional additional authenticated data (must match encryption).
#[new]
#[pyo3(signature = (key, header, aad=None))]
fn new(key: &[u8], header: &[u8], aad: Option<&[u8]>) -> PyResult<Self> {
if key.len() != 32 {
return Err(crate::errors::InvalidLengthError::new_err(
"key must be 32 bytes",
));
}
if header.len() != 26 {
return Err(crate::errors::InvalidLengthError::new_err(
"header must be 26 bytes",
));
}
let key_arr: &[u8; 32] = key.try_into().unwrap();
let hdr_arr: &[u8; 26] = header.try_into().unwrap();
let aad_bytes = aad.unwrap_or(&[]);
let dec = soliton::streaming::stream_decrypt_init(key_arr, hdr_arr, aad_bytes)
.map_err(to_py_err)?;
Ok(Self { inner: Some(dec) })
}
/// Decrypt the next sequential chunk.
///
/// Returns:
/// Tuple of (plaintext: bytes, is_last: bool).
fn decrypt_chunk<'py>(
&mut self,
py: Python<'py>,
chunk: &[u8],
) -> PyResult<(Py<PyBytes>, bool)> {
let inner = self
.inner
.as_mut()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("decryptor closed"))?;
let (pt, is_last) = inner.decrypt_chunk(chunk).map_err(to_py_err)?;
Ok((PyBytes::new(py, &pt).into(), is_last))
}
/// Decrypt a specific chunk by index (random access).
///
/// Returns:
/// Tuple of (plaintext: bytes, is_last: bool).
fn decrypt_chunk_at<'py>(
&self,
py: Python<'py>,
index: u64,
chunk: &[u8],
) -> PyResult<(Py<PyBytes>, bool)> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("decryptor closed"))?;
let (pt, is_last) = inner.decrypt_chunk_at(index, chunk).map_err(to_py_err)?;
Ok((PyBytes::new(py, &pt).into(), is_last))
}
/// Whether the decryptor has seen the final chunk.
fn is_finalized(&self) -> PyResult<bool> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("decryptor closed"))?;
Ok(inner.is_finalized())
}
/// Next expected sequential chunk index.
fn expected_index(&self) -> PyResult<u64> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| crate::errors::InvalidDataError::new_err("decryptor closed"))?;
Ok(inner.expected_index())
}
fn close(&mut self) {
self.inner = None;
}
fn __enter__(slf: Py<Self>) -> Py<Self> {
slf
}
fn __exit__(
&mut self,
_exc_type: Option<&Bound<'_, PyAny>>,
_exc_val: Option<&Bound<'_, PyAny>>,
_exc_tb: Option<&Bound<'_, PyAny>>,
) {
self.close();
}
}
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<StreamEncryptor>()?;
m.add_class::<StreamDecryptor>()?;
Ok(())
}

View file

@ -0,0 +1,20 @@
//! Verification phrases for out-of-band identity verification.
use pyo3::prelude::*;
use crate::errors::to_py_err;
/// Generate a verification phrase from two identity public keys.
///
/// Each key must be 3200 bytes (full identity public key, not fingerprint).
/// Returns a human-readable phrase (6 words from the EFF large wordlist).
/// The phrase is symmetric — swapping the keys produces the same phrase.
#[pyfunction]
fn verification_phrase(pk_a: &[u8], pk_b: &[u8]) -> PyResult<String> {
soliton::verification::verification_phrase(pk_a, pk_b).map_err(to_py_err)
}
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(verification_phrase, m)?)?;
Ok(())
}