Struct matrix_sdk_crypto::store::Store

source ·
pub struct Store { /* private fields */ }
Expand description

A wrapper for our CryptoStore trait object.

This is needed because we want to have a generic interface so we can store/restore objects that we can serialize. Since trait objects and generics don’t mix let the CryptoStore store strings and this wrapper adds the generic interface on top.

Implementations§

source§

impl Store

source

pub async fn export_secret( &self, secret_name: &SecretName, ) -> Result<Option<String>, CryptoStoreError>

Try to export the secret with the given secret name.

The exported secret will be encoded as unpadded base64. Returns Null if the secret can’t be found.

§Arguments
  • secret_name - The name of the secret that should be exported.
source

pub async fn export_cross_signing_keys( &self, ) -> Result<Option<CrossSigningKeyExport>, CryptoStoreError>

Export all the private cross signing keys we have.

The export will contain the seed for the ed25519 keys as a unpadded base64 encoded string.

This method returns None if we don’t have any private cross signing keys.

source

pub async fn import_cross_signing_keys( &self, export: CrossSigningKeyExport, ) -> Result<CrossSigningStatus, SecretImportError>

Import our private cross signing keys.

The export needs to contain the seed for the Ed25519 keys as an unpadded base64 encoded string.

source

pub async fn export_secrets_bundle( &self, ) -> Result<SecretsBundle, SecretsBundleExportError>

Export all the secrets we have in the store into a SecretsBundle.

This method will export all the private cross-signing keys and, if available, the private part of a backup key and its accompanying version.

The method will fail if we don’t have all three private cross-signing keys available.

Warning: Only export this and share it with a trusted recipient, i.e. if an existing device is sharing this with a new device.

source

pub async fn import_secrets_bundle( &self, bundle: &SecretsBundle, ) -> Result<(), SecretImportError>

Import and persists secrets from a SecretsBundle.

This method will import all the private cross-signing keys and, if available, the private part of a backup key and its accompanying version into the store.

Warning: Only import this from a trusted source, i.e. if an existing device is sharing this with a new device. The imported cross-signing keys will create a OwnUserIdentity and mark it as verified.

The backup key will be persisted in the store and can be enabled using the BackupMachine.

source

pub async fn import_secret( &self, secret: &GossippedSecret, ) -> Result<(), SecretImportError>

Import the given secret named secret_name into the keystore.

source

pub async fn get_only_allow_trusted_devices(&self) -> Result<bool>

Check whether there is a global flag to only encrypt messages for trusted devices or for everyone.

source

pub async fn set_only_allow_trusted_devices( &self, block_untrusted_devices: bool, ) -> Result<()>

Set global flag whether to encrypt messages for untrusted devices, or whether they should be excluded from the conversation.

source

pub async fn get_value<T: DeserializeOwned>( &self, key: &str, ) -> Result<Option<T>>

Get custom stored value associated with a key

source

pub async fn set_value(&self, key: &str, value: &impl Serialize) -> Result<()>

Store custom value associated with a key

source

pub fn room_keys_received_stream(&self) -> impl Stream<Item = Vec<RoomKeyInfo>>

Receive notifications of room keys being received as a Stream.

Each time a room key is updated in any way, an update will be sent to the stream. Updates that happen at the same time are batched into a Vec.

If the reader of the stream lags too far behind, a warning will be logged and items will be dropped.

The stream will terminate once all references to the underlying CryptoStoreWrapper are dropped.

source

pub fn room_keys_withheld_received_stream( &self, ) -> impl Stream<Item = Vec<RoomKeyWithheldInfo>>

Receive notifications of received m.room_key.withheld messages.

Each time an m.room_key.withheld is received and stored, an update will be sent to the stream. Updates that happen at the same time are batched into a Vec.

If the reader of the stream lags too far behind, a warning will be logged and items will be dropped.

source

pub fn user_identities_stream(&self) -> impl Stream<Item = IdentityUpdates>

Returns a stream of user identity updates, allowing users to listen for notifications about new or changed user identities.

The stream produced by this method emits updates whenever a new user identity is discovered or when an existing identities information is changed. Users can subscribe to this stream and receive updates in real-time.

Caution: the returned stream will never terminate, and it holds a reference to the CryptoStore. Listeners should be careful to avoid resource leaks.

§Examples
let identities_stream = machine.store().user_identities_stream();
pin_mut!(identities_stream);

for identity_updates in identities_stream.next().await {
    for (_, identity) in identity_updates.new {
        println!("A new identity has been added {}", identity.user_id());
    }
}
source

pub fn devices_stream(&self) -> impl Stream<Item = DeviceUpdates>

Returns a stream of device updates, allowing users to listen for notifications about new or changed devices.

The stream produced by this method emits updates whenever a new device is discovered or when an existing device’s information is changed. Users can subscribe to this stream and receive updates in real-time.

Caution: the returned stream will never terminate, and it holds a reference to the CryptoStore. Listeners should be careful to avoid resource leaks.

§Examples
let devices_stream = machine.store().devices_stream();
pin_mut!(devices_stream);

for device_updates in devices_stream.next().await {
    if let Some(user_devices) = device_updates.new.get(machine.user_id()) {
        for device in user_devices.values() {
            println!("A new device has been added {}", device.device_id());
        }
    }
}
source

pub fn identities_stream_raw( &self, ) -> impl Stream<Item = (IdentityChanges, DeviceChanges)>

Returns a Stream of user identity and device updates

The stream returned by this method returns the same data as Store::user_identities_stream and Store::devices_stream but does not include references to the VerificationMachine. It is therefore a lower-level view on that data.

The stream will terminate once all references to the underlying CryptoStoreWrapper are dropped.

source

pub fn create_store_lock( &self, lock_key: String, lock_value: String, ) -> CrossProcessStoreLock<LockableCryptoStore>

Creates a CrossProcessStoreLock for this store, that will contain the given key and value when hold.

source

pub fn secrets_stream(&self) -> impl Stream<Item = GossippedSecret>

Receive notifications of gossipped secrets being received and stored in the secret inbox as a Stream.

The gossipped secrets are received using the m.secret.send event type and are guaranteed to have been received over a 1-to-1 Olm Session from a verified Device.

The GossippedSecret can also be later found in the secret inbox and retrieved using the CryptoStore::get_secrets_from_inbox() method.

After a suitable secret of a certain type has been found it can be removed from the store using the CryptoStore::delete_secrets_from_inbox() method.

The only secret this will currently broadcast is the m.megolm_backup.v1.

If the reader of the stream lags too far behind, a warning will be logged and items will be dropped.

§Examples

let secret_stream = machine.store().secrets_stream();
pin_mut!(secret_stream);

for secret in secret_stream.next().await {
    // Accept the secret if it's valid, then delete all the secrets of this type.
    machine.store().delete_secrets_from_inbox(&secret.secret_name);
}
source

pub async fn import_room_keys( &self, exported_keys: Vec<ExportedRoomKey>, from_backup_version: Option<&str>, progress_listener: impl Fn(usize, usize), ) -> Result<RoomKeyImportResult>

Import the given room keys into the store.

§Arguments
  • exported_keys - The keys to be imported.
  • from_backup_version - If the keys came from key backup, the key backup version. This will cause the keys to be marked as already backed up, and therefore not requiring another backup.
  • progress_listener - Callback which will be called after each key is processed. Called with arguments (processed, total) where processed is the number of keys processed so far, and total is the total number of keys (i.e., exported_keys.len()).
source

pub async fn import_exported_room_keys( &self, exported_keys: Vec<ExportedRoomKey>, progress_listener: impl Fn(usize, usize), ) -> Result<RoomKeyImportResult>

Import the given room keys into our store.

§Arguments
  • exported_keys - A list of previously exported keys that should be imported into our store. If we already have a better version of a key the key will not be imported.

Returns a tuple of numbers that represent the number of sessions that were imported and the total number of sessions that were found in the key export.

§Examples
let exported_keys = decrypt_room_key_export(export, "1234").unwrap();
machine.store().import_exported_room_keys(exported_keys, |_, _| {}).await.unwrap();
source

pub async fn export_room_keys( &self, predicate: impl FnMut(&InboundGroupSession) -> bool, ) -> Result<Vec<ExportedRoomKey>>

Export the keys that match the given predicate.

§Arguments
  • predicate - A closure that will be called for every known InboundGroupSession, which represents a room key. If the closure returns true the InboundGroupSession will be included in the export, if the closure returns false it will not be included.
§Examples
let room_id = room_id!("!test:localhost");
let exported_keys = machine.store().export_room_keys(|s| s.room_id() == room_id).await.unwrap();
let encrypted_export = encrypt_room_key_export(&exported_keys, "1234", 1);
source

pub async fn export_room_keys_stream( &self, predicate: impl FnMut(&InboundGroupSession) -> bool, ) -> Result<impl Stream<Item = ExportedRoomKey>>

Export room keys matching a predicate, providing them as an async Stream.

§Arguments
  • predicate - A closure that will be called for every known InboundGroupSession, which represents a room key. If the closure returns true the InboundGroupSession will be included in the export, if the closure returns false it will not be included.
§Examples
use std::pin::pin;

use matrix_sdk_crypto::{olm::ExportedRoomKey, OlmMachine};
use ruma::{device_id, room_id, user_id};
use tokio_stream::StreamExt;
let alice = user_id!("@alice:example.org");
let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
let room_id = room_id!("!test:localhost");
let mut keys = pin!(machine
    .store()
    .export_room_keys_stream(|s| s.room_id() == room_id)
    .await
    .unwrap());
while let Some(key) = keys.next().await {
    println!("{}", key.room_id);
}

Trait Implementations§

source§

impl Clone for Store

source§

fn clone(&self) -> Store

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Store

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Deref for Store

§

type Target = dyn CryptoStore<Error = CryptoStoreError>

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.

Auto Trait Implementations§

§

impl Freeze for Store

§

impl !RefUnwindSafe for Store

§

impl Send for Store

§

impl Sync for Store

§

impl Unpin for Store

§

impl !UnwindSafe for Store

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

source§

const WITNESS: W = W::MAKE

A constant of the type witness
source§

impl<T> Identity for T
where T: ?Sized,

§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> AsyncTraitDeps for T

source§

impl<T> SendOutsideWasm for T
where T: Send,

source§

impl<T> SyncOutsideWasm for T
where T: Sync,