Skip to content

Commit

Permalink
docs: add missing documentation comments and improve code readability
Browse files Browse the repository at this point in the history
  • Loading branch information
itsyaasir committed Nov 27, 2024
1 parent b885b6e commit 7d44ceb
Show file tree
Hide file tree
Showing 30 changed files with 112 additions and 54 deletions.
3 changes: 1 addition & 2 deletions examples/0_basic/5_create_vc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ async fn main() -> anyhow::Result<()> {
// create new issuer account with did document
let issuer_storage = get_memstorage()?;
let issuer_identity_client = get_client_and_create_account(&issuer_storage).await?;
let (issuer_document, issuer_vm_fragment) =
create_did_document(&issuer_identity_client, &issuer_storage).await?;
let (issuer_document, issuer_vm_fragment) = create_did_document(&issuer_identity_client, &issuer_storage).await?;

// create new holder account with did document
let holder_storage = get_memstorage()?;
Expand Down
6 changes: 2 additions & 4 deletions examples/0_basic/6_create_vp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,12 @@ async fn main() -> anyhow::Result<()> {
// create new issuer account with did document
let issuer_storage = get_memstorage()?;
let issuer_identity_client = get_client_and_create_account(&issuer_storage).await?;
let (issuer_document, issuer_vm_fragment) =
create_did_document(&issuer_identity_client, &issuer_storage).await?;
let (issuer_document, issuer_vm_fragment) = create_did_document(&issuer_identity_client, &issuer_storage).await?;

// create new holder account with did document
let holder_storage = get_memstorage()?;
let holder_identity_client = get_client_and_create_account(&holder_storage).await?;
let (holder_document, holder_vm_fragment) =
create_did_document(&holder_identity_client, &holder_storage).await?;
let (holder_document, holder_vm_fragment) = create_did_document(&holder_identity_client, &holder_storage).await?;

// create new client for verifier
// new client actually not necessary, but shows, that client is independent from issuer and holder
Expand Down
3 changes: 1 addition & 2 deletions examples/0_basic/7_revoke_vc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ async fn main() -> anyhow::Result<()> {
// create new issuer account with did document
let issuer_storage = get_memstorage()?;
let issuer_identity_client = get_client_and_create_account(&issuer_storage).await?;
let (mut issuer_document, issuer_vm_fragment) =
create_did_document(&issuer_identity_client, &issuer_storage).await?;
let (mut issuer_document, issuer_vm_fragment) = create_did_document(&issuer_identity_client, &issuer_storage).await?;

// create new holder account with did document
let holder_storage = get_memstorage()?;
Expand Down
4 changes: 2 additions & 2 deletions examples/1_advanced/4_identity_history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ async fn main() -> anyhow::Result<()> {
.into_iter()
.map(|data| IotaDocument::unpack_from_iota_object_data(&did, &data, true))
.collect::<Result<_, _>>()?;
println!("Current version: {}", documents[0].to_string());
println!("Previous version: {}", documents[1].to_string());
println!("Current version: {}", documents[0]);
println!("Previous version: {}", documents[1]);

// Depending on your use case, you can also page through the results
// Alternative Step 2 - Page by looping until no result is returned (here with page size 1)
Expand Down
6 changes: 2 additions & 4 deletions examples/1_advanced/7_sd_jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,12 @@ async fn main() -> anyhow::Result<()> {
// Create an identity for the issuer with one verification method `key-1`.
let issuer_storage = get_memstorage()?;
let issuer_identity_client = get_client_and_create_account(&issuer_storage).await?;
let (issuer_document, issuer_vm_fragment) =
create_did_document(&issuer_identity_client, &issuer_storage).await?;
let (issuer_document, issuer_vm_fragment) = create_did_document(&issuer_identity_client, &issuer_storage).await?;

// Create an identity for the holder, in this case also the subject.
let holder_storage = get_memstorage()?;
let holder_identity_client = get_client_and_create_account(&holder_storage).await?;
let (holder_document, holder_vm_fragment) =
create_did_document(&holder_identity_client, &holder_storage).await?;
let (holder_document, holder_vm_fragment) = create_did_document(&holder_identity_client, &holder_storage).await?;

// ===========================================================================
// Step 2: Issuer creates and signs a selectively disclosable JWT verifiable credential.
Expand Down
3 changes: 1 addition & 2 deletions examples/1_advanced/8_status_list_2021.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ async fn main() -> anyhow::Result<()> {
// create new issuer account with did document
let issuer_storage = get_memstorage()?;
let issuer_identity_client = get_client_and_create_account(&issuer_storage).await?;
let (issuer_document, issuer_vm_fragment) =
create_did_document(&issuer_identity_client, &issuer_storage).await?;
let (issuer_document, issuer_vm_fragment) = create_did_document(&issuer_identity_client, &issuer_storage).await?;

// create new holder account with did document
let holder_storage = get_memstorage()?;
Expand Down
4 changes: 2 additions & 2 deletions identity_iota/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ pub mod prelude {
pub use identity_iota_core::IotaDID;
pub use identity_iota_core::IotaDocument;

#[cfg(feature = "client")]
#[cfg_attr(docsrs, doc(cfg(feature = "client")))]
#[cfg(feature = "resolver")]
#[cfg_attr(docsrs, doc(cfg(feature = "resolver")))]
pub use identity_iota_core::DidResolutionHandler;

#[cfg(feature = "resolver")]
Expand Down
5 changes: 3 additions & 2 deletions identity_iota_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ iota-sdk = { git = "https://github.com/iotaledger/iota.git", package = "iota-sdk
itertools = { version = "0.13.0", optional = true }
move-core-types = { git = "https://github.com/iotaledger/iota.git", package = "move-core-types", rev = "39c83ddcf07894cdee2abd146381d8704205e6e9", optional = true }
rand = { version = "0.8.5", optional = true }
secret-storage = { git = "https://github.com/iotaledger/secret-storage.git", branch = "main", optional = true }
secret-storage = { git = "https://github.com/iotaledger/secret-storage.git", tag = "v0.1.0", optional = true }
serde-aux = { version = "4.5.0", optional = true }
shared-crypto = { git = "https://github.com/iotaledger/iota.git", package = "shared-crypto", rev = "39c83ddcf07894cdee2abd146381d8704205e6e9", optional = true }
tokio = { version = "1.29.0", default-features = false, optional = true, features = ["macros", "sync", "rt", "process"] }
Expand All @@ -51,9 +51,10 @@ iota-crypto = { version = "0.23", default-features = false, features = ["bip39",
proptest = { version = "1.0.0", default-features = false, features = ["std"] }

# for feature iota-client tests
identity_iota_core= { path = ".", features = ["iota-client"] } # enable for e2e tests
identity_iota_core = { path = ".", features = ["iota-client"] } # enable for e2e tests
identity_storage = { path = "../identity_storage", features = ["send-sync-storage", "storage-signer"] }
jsonpath-rust = "0.5.1"
lazy_static = "1.5.0"
serial_test = "3.1.1"

[package.metadata.docs.rs]
Expand Down
15 changes: 7 additions & 8 deletions identity_iota_core/src/document/iota_document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ impl IotaDocument {
}

#[cfg(feature = "iota-client")]
pub mod client_document {
mod client_document {
use identity_core::common::Timestamp;
use iota_sdk::rpc_types::IotaObjectData;

Expand All @@ -421,7 +421,7 @@ pub mod client_document {
data: &IotaObjectData,
allow_empty: bool,
) -> Result<IotaDocument> {
let unpacked = unpack_identity_data(&did, data).map_err(|_| {
let unpacked = unpack_identity_data(did, data).map_err(|_| {
Error::InvalidDoc(identity_document::Error::InvalidDocument(
"could not unpack identity data from IotaObjectData",
None,
Expand All @@ -437,7 +437,7 @@ pub mod client_document {
}
};
let did_doc =
Self::from_iota_document_data(multi_controller.controlled_value(), allow_empty, &did, created, updated)?;
Self::from_iota_document_data(multi_controller.controlled_value(), allow_empty, did, created, updated)?;

Ok(did_doc)
}
Expand All @@ -451,7 +451,7 @@ pub mod client_document {
/// * document related parsing Errors from `StateMetadataDocument::unpack`
/// * possible parsing errors when trying to parse `created` and `updated` to a `Timestamp`
pub fn from_iota_document_data(
data: &Vec<u8>,
data: &[u8],
allow_empty: bool,
did: &IotaDID,
created: Timestamp,
Expand All @@ -465,8 +465,7 @@ pub mod client_document {
empty_document
} else {
// we have a value, therefore unpack it
StateMetadataDocument::unpack(data)
.and_then(|state_metadata_doc| state_metadata_doc.into_iota_document(&did))?
StateMetadataDocument::unpack(data).and_then(|state_metadata_doc| state_metadata_doc.into_iota_document(did))?
};

// Overwrite `created` and `updated` with given timestamps
Expand Down Expand Up @@ -732,7 +731,7 @@ mod tests {
.parse()
.unwrap();
let document = IotaDocument::from_iota_document_data(
&vec![],
&[],
true,
&did,
Timestamp::from_unix(12).unwrap(),
Expand All @@ -750,7 +749,7 @@ mod tests {

// INVALID: reject empty document.
assert!(IotaDocument::from_iota_document_data(
&vec![],
&[],
false,
&did,
Timestamp::from_unix(12).unwrap(),
Expand Down
1 change: 1 addition & 0 deletions identity_iota_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,6 @@ mod document;
mod error;
mod network;
#[cfg(feature = "iota-client")]
/// Contains the rebased Identity and the interaction with the IOTA Client.
pub mod rebased;
mod state_metadata;
8 changes: 8 additions & 0 deletions identity_iota_core/src/rebased/assets/public_available_vc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ impl MoveType for IotaVerifiableCredential {
}
}

/// A publicly available verifiable credential.
#[derive(Debug, Clone)]
pub struct PublicAvailableVC {
asset: AuthenticatedAsset<IotaVerifiableCredential>,
Expand All @@ -74,16 +75,22 @@ impl Deref for PublicAvailableVC {
}

impl PublicAvailableVC {
/// Get the ID of the asset.
pub fn object_id(&self) -> ObjectID {
self.asset.id()
}

/// Get the JWT of the credential.
pub fn jwt(&self) -> Jwt {
String::from_utf8(self.asset.content().data.clone())
.map(Jwt::new)
.expect("JWT is valid UTF8")
}

/// Create a new publicly available VC.
///
/// # Returns
/// A new `PublicAvailableVC`.
pub async fn new<S>(jwt: Jwt, gas_budget: Option<u64>, client: &IdentityClient<S>) -> Result<Self, anyhow::Error>
where
S: Signer<IotaKeySignature> + Sync,
Expand All @@ -102,6 +109,7 @@ impl PublicAvailableVC {
Ok(Self { credential, asset })
}

/// Get a publicly available VC by its ID.
pub async fn get_by_id(id: ObjectID, client: &IdentityClientReadOnly) -> Result<Self, crate::rebased::Error> {
let asset = client
.get_object_by_id::<AuthenticatedAsset<IotaVerifiableCredential>>(id)
Expand Down
9 changes: 9 additions & 0 deletions identity_iota_core/src/rebased/client/full_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,11 @@ use crate::rebased::Error;
use super::get_object_id_from_did;
use super::IdentityClientReadOnly;

/// A signature which is used to sign transactions.
pub struct IotaKeySignature {
/// The public key of the signature.
pub public_key: Vec<u8>,
/// The signature of the transaction.
pub signature: Vec<u8>,
}

Expand Down Expand Up @@ -85,11 +88,16 @@ impl From<KeyId> for String {
}
}

/// A client for interacting with the IOTA network.
#[derive(Clone)]
pub struct IdentityClient<S> {
/// [`IdentityClientReadOnly`] instance, used for read-only operations.
read_client: IdentityClientReadOnly,
/// The address of the client.
address: IotaAddress,
/// The public key of the client.
public_key: Vec<u8>,
/// The signer of the client.
signer: S,
}

Expand All @@ -104,6 +112,7 @@ impl<S> IdentityClient<S>
where
S: Signer<IotaKeySignature> + Sync,
{
/// Create a new [`IdentityClient`].
pub async fn new(client: IdentityClientReadOnly, signer: S) -> Result<Self, Error> {
let public_key = signer
.public_key()
Expand Down
5 changes: 5 additions & 0 deletions identity_iota_core/src/rebased/client/read_only.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,11 @@ async fn resolve_unmigrated(client: &IdentityClientReadOnly, object_id: ObjectID
Ok(unmigrated_alias.map(Identity::Legacy))
}

/// Extracts the object ID from the given `IotaDID`.
///
/// # Arguments
///
/// * `did` - A reference to the `IotaDID` to be converted.
pub fn get_object_id_from_did(did: &IotaDID) -> Result<ObjectID, Error> {
ObjectID::from_str(did.tag_str())
.map_err(|err| Error::DIDResolutionError(format!("could not parse object id from did {did}; {err}")))
Expand Down
9 changes: 5 additions & 4 deletions identity_iota_core/src/rebased/migration/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ const MODULE: &str = "identity";
const NAME: &str = "Identity";
const HISTORY_DEFAULT_PAGE_SIZE: usize = 10;

/// The data stored in an on-chain identity.
pub type IdentityData = (UID, Multicontroller<Vec<u8>>, Timestamp, Timestamp);

/// An on-chain object holding a DID Document.
pub enum Identity {
/// A legacy IOTA Stardust's Identity.
Expand Down Expand Up @@ -230,6 +233,7 @@ impl OnChainIdentity {
}
}

/// Returns the previous version of the given `history_item`.
pub fn has_previous_version(history_item: &IotaObjectData) -> Result<bool, Error> {
if let Some(Owner::Shared { initial_shared_version }) = history_item.owner {
Ok(history_item.version != initial_shared_version)
Expand Down Expand Up @@ -373,10 +377,7 @@ fn is_identity(value: &IotaParsedMoveObject) -> bool {
/// # Errors:
/// * in case given data for DID is not an object
/// * parsing identity data from object fails
pub(crate) fn unpack_identity_data(
did: &IotaDID,
data: &IotaObjectData,
) -> Result<Option<(UID, Multicontroller<Vec<u8>>, Timestamp, Timestamp)>, Error> {
pub(crate) fn unpack_identity_data(did: &IotaDID, data: &IotaObjectData) -> Result<Option<IdentityData>, Error> {
let content = data
.clone()
.content
Expand Down
12 changes: 7 additions & 5 deletions identity_iota_core/src/rebased/migration/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@ use crate::rebased::client::IdentityClientReadOnly;
use super::get_identity;
use super::OnChainIdentity;

/// Errors that can occur during migration registry operations.
#[derive(thiserror::Error, Debug)]
pub enum Error {
/// An error occurred while interacting with the IOTA Client.
#[error(transparent)]
ClientError(anyhow::Error),
Client(anyhow::Error),
/// The MigrationRegistry object was not found.
#[error("could not locate MigrationRegistry object: {0}")]
NotFound(String),
/// The MigrationRegistry object is malformed.
#[error("malformed MigrationRegistry's entry: {0}")]
Malformed(String),
}
Expand All @@ -36,7 +40,7 @@ pub async fn lookup(
.read_api()
.get_dynamic_field_object(iota_client.migration_registry_id(), dynamic_field_name)
.await
.map_err(|e| Error::ClientError(e.into()))?
.map_err(|e| Error::Client(e.into()))?
.data
.map(|data| {
data
Expand All @@ -51,9 +55,7 @@ pub async fn lookup(
.transpose()?;

if let Some(id) = identity_id {
get_identity(iota_client, id)
.await
.map_err(|e| Error::ClientError(e.into()))
get_identity(iota_client, id).await.map_err(|e| Error::Client(e.into()))
} else {
Ok(None)
}
Expand Down
6 changes: 6 additions & 0 deletions identity_iota_core/src/rebased/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
// Copyright 2020-2024 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

/// Module for handling assets.
pub mod assets;
/// Module for handling client operations.
pub mod client;
mod error;
/// Module for handling migration operations.
pub mod migration;
/// Contains the operations of proposals.
pub mod proposals;
mod sui;
/// Module for handling transactions.
pub mod transaction;
/// Contains utility functions.
pub mod utils;

pub use assets::*;
Expand Down
1 change: 1 addition & 0 deletions identity_iota_core/src/rebased/proposals/borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ impl ProposalT for Proposal<BorrowAction> {
}
}

/// A transaction to execute a borrow proposal.
pub struct ExecuteBorrowTx<'i, B> {
identity: &'i mut OnChainIdentity,
borrow_action: B,
Expand Down
1 change: 1 addition & 0 deletions identity_iota_core/src/rebased/proposals/config_change.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ impl<'i> ProposalBuilder<'i, ConfigChange> {
}

impl ConfigChange {
/// Creates a new [`ConfigChange`] proposal action.
pub fn new() -> Self {
Self::default()
}
Expand Down
1 change: 1 addition & 0 deletions identity_iota_core/src/rebased/proposals/deactivate_did.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use super::ProposalT;
pub struct DeactivateDid;

impl DeactivateDid {
/// Creates a new [`DeactivateDid`] action.
pub const fn new() -> Self {
Self
}
Expand Down
Loading

0 comments on commit 7d44ceb

Please sign in to comment.