# Guide

Welcome to zkID Login. This Document has two main sections: Guide (to present a overview of zkID Login), API Reference (for developers who want to build with zkID Login).

This is a technical documentation for zkID Login developers. zkID Login is one of the products launched by zCloak Network, which is designed to help users achieve a more explicit, private and fast '**Login Mechanism**'. It currently works as a Browser Extension (zkID Wallet), and the process of interaction is very user-friendly.

Users can store any Verifiable Credential that fits the *Credential Format Standard* in zkID Wallet. These credentials can be accessed with common APIs. Besides, Users can intuitivly see how their data is being used, **avoiding user information loss and leakage**.

* You can download the latest version of zkID Wallet at [Chrome Web Store](https://chrome.google.com/webstore/detail/zkid-wallet/ahkpfejaeoepmfopmbhjgjekibmfcfgo).
* If you encounter any technical problems or have any suggestion, please feel free to talk with us at [zCloak Discord](https://discord.com/invite/j3mATwNVSH).
* For more information about the relevant news or events, follow our [Twitter](https://twitter.com/zcloaknetwork), [Medium](https://zcloaknetwork.medium.com/), or our [Official Website](https://zcloak.network/#/).
* To find more technical details, please visit our [Github](https://github.com/zcloak-network).

##


# Introduction

## Why zkID Login

In the traditional 'Login Mechanism', users enter a password to log in. However, this Login Mode is inefficient and cannot reliably check the user's identity (for example, some website is oriented to zCloak Members, the website should check users' identity in the first place). So we designed zkID Login, which allows the Service Providers to add identity restrictions as they need, **authenticating and allowing** the user to LOGIN only if the user has a **qualified Credential** in the zkID Wallet that **meets the requirements**.

Advantage of zkID Login:

* It is compatible with Verifiable Credentials issued by different institutions and provides a unified way of use.
* With zkID Login, the Service Providers **do not** need to store user information in a centralized way, and **only needs** to check whether the credential used by users to login are valid.
* Users could have **full control** over the information they share. Indeed, they can decide with whom to share, to what extent, every use of credential need user's permission.
* **As long as user allows**, the Service Providers can have access to any credential owned by the user. They can obtain information by extracting them from credentials, which are attested by trusted attester. So, these information are **more reliable**.

Compared with Traditional Login Mechanism:

|                        |                             Tradition Login                            |                            zkID Login                           |
| :--------------------: | :--------------------------------------------------------------------: | :-------------------------------------------------------------: |
|       Identifier       |                          Account and Password                          |                      Verifiable Credential                      |
|  Source of information |            <p>Filled by User manually<br>(not reliable)</p>            |  <p>Extract from Verifiable Credentials<br>(very reliable)</p>  |
| Storage of information |            Stored by Service Providers in a centralized way            |                          Hold by Users                          |
|  Usage of information  | <p>Controlled by Service Providers<br>(don't need User permission)</p> | <p>Controlled by Users themselves<br>(need User permission)</p> |

Click here to learn more about some **Basic Concepts** and **API-Reference**.

* [Learn more about Verifiable Credential(VC)](/readme/did/vc)
* [Learn more about DID](/readme/did)
* [Learn more about our RPC API](/api)
* [Learn more about our SDK](/introduction)

## DID Account Management

zkID Wallet helps manage users' ***DID Accounts*** (hereinafter called 'account')) in a secure way. User accounts can only be **created** via mnemonic phrase, but can be **restored** by mnemonic phrase and DID-Keys File (which is automatically generated after an account is created).

zkID Wallet allows users to own different accounts and to use each account's keys to sign and create a reliable communication channel with others by 'Message Encryption and Decryption'. The DID-Keys File contains several keys which have different functions and are generated under different signature scheme.

{% hint style="warning" %}
**DID Accounts Backup**

The DID-Keys File and mnemonic phrase should be stored and backed up properly. Losing the DID-Keys File will result in **loss of one's identity data** permanently.
{% endhint %}

## VC Management

**Verifiable Credential (VC)** contains the user's detailed information. Once your credential is attested, you can import it into zkID Wallet at any time. The Verifiable Credential is a JSON File, which contains your personal details in plaintext. Users can check the credential details via zkID Wallet and use it to accomplish zkID Login process.

> If Verifiable Credential is new to you, we highly recommend you to experience the whole VC Application Process in our [Credential Platform](https://credential.zkid.app/#/account?redirect=claimer). Or follow the [guide](https://zcloaknetwork.medium.com/zcloak-membership-credential-event-tutorial-b315315ef62f) to participate our latest event to obtain a 'zCloak Membership Credential'

{% hint style="warning" %}
**VC Backup**

In zkID Wallet, all VCs are protected under **Storage Encryption**, which means that every use of VC needs decryption. At this stage, to make it easier for users to migrate their VCs to other storage tools, zkID Wallet temporarily *export VCs in plaintext*.

So, Users **MUST** store VCs safely to **avoid information leakage**.
{% endhint %}

## Blockchain Connection

> 'Users can store verifiable credential in any location, without affecting their verifiability and without the issuer knowing anything about where they are stored or when they are accessed.'
>
> \-- Verifiable Credentials Data Model v1.1

With this excellent property of VC, zCloak Network deploys the system on **mutiple blockchain networks**. Theoretically speaking, no matter which blockchain you are on, as long as **you're the owner** of Credential (which can be verified through cryptographic methods), **you can use that credential on&#x20;*****any*****&#x20;blockchain you like**.

Now, the system is deployed on an unique VD&#x52;*(Verifiable Data Registry)* -- [**Arweave**](https://www.arweave.org/). Arweave is a distributed, cryptographically verified permanent archive built on a cryptocurrency that aims to provide permanent data storage. It allows users to pay once and store their data permanently on the Arweave network.

It is worth mentioning that, zCloak Network has launched its own DID Method([ZK Method](https://github.com/w3c/did-spec-registries/blob/main/methods/zk.json)) and VC Protocol. More details about [DID](/readme/did/did) and [VC](/readme/did/vc) Protocol are represent in the next section.


# Basic Concepts

In this section, we will explore more  details about some basic concepts, starting with our ZK DID Method and Verifiable Credential. The following is the table of contents of this section.

* [DID](/readme/did/did)
  * [DID Protocol Main Architecture](/readme/did/did#did-protocol-main-architecture)
  * [ZK DID Method](/readme/did/did#zk-did-method)
  * [ZK DID Examples](/readme/did/did#zk-did-examples)
  * [DID-Keys](/readme/did/did#did-keys)
* [VC](/readme/did/vc)
  * [What are Verifiable Credentials](/readme/did/vc#what-are-verifiable-credentials)
  * [Key roles of VC](/readme/did/vc#key-roles-of-vc)
  * [Core Data Model](/readme/did/vc#core-data-model)


# DID

## DID Protocol Main Architecture

As conceptualized and standardized by the W3C, the Decentralized Identifiers, or DIDs, are **a new type of identifier that enables verifiable, decentralized digital identity**.

Before diving into the DID World, let's read the overview of DID architecture and the relationship between the basic components.

A **DID** may represent an entity - for example a person, an organization, or even a machine. A Decentralised Identifier (DID) is a string uniquely identifying each user. The DID can contain multiple different keys for purposes such as encryption, signature, authentication, etc.

![Overview of DID architecture and the relationship of the basic components. See also: narrative description.](https://i.imgur.com/9vUciCF.png)

{% hint style="info" %}
**Narrative Description**

<details>

<summary>☝️ Click Here To Expand</summary>

Six internally-labeled shapes appear in the diagram, with labeled arrows between them, as follows. In the center of the diagram is a rectangle labeled DID URL, containing small typewritten text 'did:example:123/path/to/rsrc/. At the center top of the diagram is a rectangle labeled, 'DID', containing small typewritten text 'did:example:123'. At the top left of the diagram is an oval, labeled 'DID Subject'. At the bottom center of the diagram is a rectangle labeled, 'DID document'. At the bottom left is an oval, labeled, 'DID Controller'. On the center right of the diagram is a two-dimensional rendering of a cylinder, labeled, 'Verifiable Data Registry'.\
\
From the top of the 'DID URL' rectangle, an arrow, labeled 'contains', extends upwards, pointing to the 'DID' rectangle. From the bottom of the 'DID URL' rectangle, an arrow, labeled 'refers, and dereferences, to', extends downward, pointing to the 'DID document' rectangle. An arrow from the 'DID' rectangle, labeled 'resolves to', points down to the 'DID document' rectangle. An arrow from the 'DID' rectangle, labeled 'refers to', points left to the 'DID subject' oval. An arrow from the 'DID controller' oval, labeled 'controls', points right to the 'DID document' rectangle. An arrow from the 'DID' rectangle, labeled 'recorded on', points downards to the right, to the 'Verifiable Data Registry' cylinder. An arrow from the 'DID document' rectangle, labeled 'recorded on', points upwards to the right to the 'Verifiable Data Registry' cylinder.

</details>
{% endhint %}

|     Core Component    |                                                                                                                                         Definition                                                                                                                                         |
| :-------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
|   DIDs and DID URLs   | A Decentralized Identifier, or [DID](https://www.w3.org/TR/did-core/#dfn-decentralized-identifiers), is a URI composed of three parts: the scheme `did:`, a method identifier, and a unique, method-specific identifier specified by the DID method. DIDs are resolvable to DID documents. |
|  DID subjects/holder  |                The [subject](https://www.w3.org/TR/did-core/#dfn-did-subjects)/[holder](https://identity.foundation/credential-manifest/#term:holder) of a DID is, by definition, the entity identified by the DID. The DID subject/holder might also be the DID controller.               |
|    DID controllers    |                                       A [DID controller](https://www.w3.org/TR/did-core/#did-controller) is an entity that is authorized to make changes to a DID document. The process of authorizing a DID controller is defined by the DID method.                                      |
|     DID documents     |                   [DID documents](https://www.w3.org/TR/did-core/#representations) contain information associated with a DID. They typically express verification methods, such as cryptographic public keys, and services relevant to interactions with the DID subject.                  |
|         Issuer        |                                                                                                                  Issuers are entities that issue credentials to a Holder.                                                                                                                  |
|         Claim         |                                                                                          An assertion made about a Subject. Used as an umbrella term for Credential, Assertion, Attestation, etc.                                                                                          |
| Verifiable Credential |                           A standard data model and representation format for cryptographically-verifiable digital credentials as defined by the W3C Verifiable Credentials specification [\[VC-DATA-MODEL\]](https://www.w3.org/TR/did-core/#bib-vc-data-model).                          |

> To get more details of DID architecture components, or to know more about the terminology of DID, you can reach out for [Credential Manifest by DIF](https://identity.foundation/credential-manifest/#terminology) and [Decentralized Identifiers (DIDs) v1.0 by W3C](https://www.w3.org/TR/did-core/#terminology)

## ZK DID Method

### ZK DID Method Name

The namestring that shall identify this DID method is: `zk`

A DID that uses this method **MUST** begin with the following prefix: `did:zk`. Per the DID specification, this string **MUST** be in lowercase.

The remainder of the DID, after the prefix, is specified below.

### ZK DID Method Specific Identifier

For now, the ZK DID method specific identifiers are categorized as two DID types, `EVM-based DID` and `Non-EVM-based DID`.

#### EVM-based DIDs

A ZK EVM-based DID has the following structure:

```
zk-did  = "did:zk:" + <user-ethereum-address> 
user-ethereum-address = "0x" 40*HEXDIG
```

#### Non-EVM-based DIDs

A ZK Non-EVM-based DID has the following structure:

```
zk-did  = "did:zk:" + <non-evm-chain-name>  + [ ":" + <user-address> ]
non-evm-chain-name = "sui" | "aptos" | ...
user-address = [a-zA-Z0-9]{1,64}
```

### ZK DID Examples

<table><thead><tr><th width="249.33333333333331">did</th><th>type</th><th>description</th></tr></thead><tbody><tr><td>did:zk:0x51fA67337...82EB6a9B22A</td><td>EVM-based DID</td><td>a <code>did</code> which relates to a brand new <code>Ethereum</code> address -- '0x51fA67337...82EB6a9B22A'</td></tr><tr><td>did:zk:sui:0xd5059a902ad02b...7ceaf7d6</td><td>Non-EVM-based DID</td><td>a <code>did</code> which relates to a brand new <code>Non-EVM-based</code> address -- '0xd5059a902ad02b...7ceaf7d6'</td></tr></tbody></table>

The example **DID** above *resolves* to a **DID document**. A DID document contains information associated with the DID, such as ways to cryptographically authenticate a DID controller.

The DID ecosystem is based on **public key infrastructures** where only the owner of the private key has full authorization of the DID. This is similar to blockchain-based systems, in which the users control their assets. This leads to the following issues regarding the system when in use:

* Recovering a lost private key is extremely difficult;
* Once your private keys are stolen, malicious acts like impersonation may cause 'you' to misbehave.

As described above, a DID is bound to an entity. So, the user could identify themselves with DID, the developers may distinguish them via DID. We design the [API (DID Request Method)](/api/provider_api#did-request-method) for developers to get user DID.

### DID-Keys

A DID can be resolved to a **DID document** stored in a Decentralized Data Registry (e.g. a blockchain). This document contains several keys: a **signing** key, an **encryption** key, etc., and optionally a link to a DID service endpoint. DIDs are URIs that associate a DID subject with a DID document allowing trustable interactions associated with that subject. Each DID document contains information regarding cryptographic material, verification methods, or service endpoints, which the document provides a set of mechanisms enabling a DID subject to prove ownership of control of the DID.

Currently, two public key and signing algorithms are supported:

* [`Ed25519`](https://en.wikipedia.org/wiki/EdDSA#Ed25519) -- the EdDSA signature scheme using [SHA-512](https://en.wikipedia.org/wiki/SHA-2) (SHA-2) and [Curve25519](https://en.wikipedia.org/wiki/Curve25519).
* [`Secp256k1`](https://en.bitcoin.it/wiki/Secp256k1) with the ECDSA algorithm -- defined in [*Standards for Efficient Cryptography (SEC)* (Certicom Research)](http://www.secg.org/sec2-v2.pdf).
* [`X25519`](https://en.wikipedia.org/wiki/Curve25519) -- is an elliptic curve[ Diffie-Hellman key exchange](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange) using [Curve25519](https://en.wikipedia.org/wiki/Curve25519). It allows two parties to jointly agree on a shared secret using an insecure channel.

**The construction of DID Document**

<pre class="language-json" data-line-numbers><code class="lang-json"><strong>{ 
</strong><strong> "@context":
</strong><strong>    " -------- content --------",
</strong> "id": [
    " -------- content --------"
 ],
 "controller": [
    " -------- content --------"
 ],
 "verificationMethod": [
    " -------- content --------"
 ],
 "authentication": [
    " -------- content --------"
 ],
 "assertionMethod": [
    " -------- content --------"
 ],
 "keyAgreement": [
    " -------- content --------"
 ],
 "capabilityInvocation": [
    " -------- content --------"
 ],
 "capabilityDelegation": [
    " -------- content --------"
 ],
 "service": [
    " -------- content --------"
 ]
}
</code></pre>

We offer several APIs for the usage of DID-Keys, please check the [API (DID-Keys Method)](/api/provider_api#did-key-method) for more specification.


# VC

Before embarking on a magic zkID Login Journey, we still need to acquire some new knowledge about VCs, starting with the concept:

## What are Verifiable Credentials

In the physical world, a credential consists of:

* **Owner**: Information related to identifying the owner of the credential
* **Attester**: Information related to the issuing authority (for example, a city government, national agency, or certification company)
* **Credential Type**: Information related to the data structure of a claim
* **Credential Content**: The data in a credential, which contains the personal information of the owner.

A verifiable credential (VC) can represent the same information as a physical credential represents. The addition of technologies, such as digital signatures, makes verifiable credentials tamper-proof and more trustworthy than their physical counterparts.

![Basic components of a verifiable credential](https://i.imgur.com/Xr5fyEy.png)

[Claim(s)](broken://pages/bCaIGQC43koAplCeKqDk#core-data-model) are assertions made about a subject. They are created by claimers without being attested yet. Once the Claim is successfully attested, the claim and some auxiliary attestation information will be packed into a Verifiable Credential and be sent back to the claimer.

Holders of verifiable credentials can generate verifiable presentations and then share these verifiable presentations with verifiers to prove they possess verifiable credentials with certain characteristics.

## Key roles of VC

Note that there are several organizations and communities aiming to define the terminology and the different roles and processes in the **Self-Sovereign Identity Ecosystem**. Our technology is **compatible** with a wide range of [Verifiable Credential](https://en.wikipedia.org/wiki/Verifiable_credentials) structure types.

|     Key Roles    |                                                                                                                                            Brief Introduction                                                                                                                                           |
| :--------------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
|  Holder(Claimer) |                                                                                    A role an entity might perform by possessing one or more verifiable credentials and generating verifiable presentations from them                                                                                    |
| Issuer(Attester) | A role an entity performs by asserting claims about one or more subjects, creating a verifiable credential from these claims, and transmitting the verifiable credential to a holder. Example issuers include corporations, non-profit organizations, trade associations, governments, and individuals. |
|     Verifier     |                                                                                                   A role an entity performs by receiving one or more verifiable credentials and verify their validity                                                                                                   |

## Core Data Model

### **cType**

Verifiable credentials *MUST* have a **type** property.

A `credential type` ('cType' for short) defines the **structure** of a claim. You can think of it as the data model for your claim.

**CTYPE** is a JSON description of a data structure. It contains a list of key value pairs, where each value is of a defined type.

**A Simple Example Of cType**

```javascript
   const base: BaseCType = {
      title: 'Test',
      description: 'Test',
      type: 'object',
      properties: {
        name: {
          type: 'string'
        },
        age: {
          type: 'integer'
        },
        level: {
          type: 'integer'
        }
      },
      required: ['name', 'age']
    };
```

> The example above forms a `base` cType, which can only contain three kinds of info, with the type 'string', 'integer' and 'integer' respectively:

* name (string)
* age (integer)
* level (integer)

The attester can create different types of cType according to their own need. Depending on the properties defined by the attester, the generation process will make different cTypes. However, such a cType JSON (like 'A Simple Example Of cType') is too large to be stored on the chain, so we perform the [Keccak256](https://en.wikipedia.org/wiki/SHA-3) hash algorithm to get a **hexadecimal string** (start with '0x'), which is called `cTypeHash` (the actual data stored on-chain.)

<figure><img src="/files/PuJnYzKGTpDQYcp5h4X7" alt=""><figcaption><p>cTypeHash Generation</p></figcaption></figure>

In a word, each `cTypeHash` is bound to a unique cType as shown above, this kind of structure can help us standardize the verifiable credential structure.

### RawCredential

RawCredential is holder's origin statements about a subject (usually themselves) with some other information. A subject is a thing about which statements can be made. Statements are expressed using subject-property-value relationships. The statesments are called `credentialSubject`.

![Subject-property-value relationships](https://i.imgur.com/N5CaqGW.png)

`RawCredential` contains the following six sections :

* `ctype`: the structure of a Credential;
* `credentialSubject`: holder's origin claim about the subject;&#x20;
* `credentialSubjectNonceMap`: each statement is bound to a unique and random UUID(a.k.a nonce), starting with '0x';
* `credentialSubjectHashes`: each statement can be hashed with its own UUID(nonce), and generate a hash result starting with '0x';
* `holder`: holder's DidUrl;
* `hasher`: the hash function used in this `RawCredential`, the first `HashType` is the Merkle Tree's hash function, the second is used at the other situations;

```typescript
export interface RawCredential {
  ctype: HexString;
  credentialSubject: CredentialSubject;
  credentialSubjectNonceMap: Record<HexString, HexString>;
  credentialSubjectHashes: HexString[];
  holder: DidUrl;
  hasher: [HashType, HashType];
}
```

When a Claimer(Holder) creates a new `RawCredential` for a cType, then the `RawCredential` will be associated with the Claimer’s identity (by filling the field `holder` with Claimer's DID).

To get an Attestation from an Attester, the `RawCredential` should involve some cryptographic methods. For example, we generate `claimHashes` from contents via [Recursive-length prefix (RLP) serialization](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/) and some hash function(picked by the holder) and get random Nonces via `uuid.v4()` and finally use some hash function to get `credentialSubjectHashes`.

<figure><img src="/files/ApjYlslCFbiV8E3rLmyr" alt=""><figcaption><p>Generation of rootHash</p></figcaption></figure>

Finally, we could obtain a `rootHash`, which is generated from a **claimHashTree**.&#x20;

### DigestHash

DigestHash is the unique identifier of a VC, it can be calculated(using `Hash Function`) via four data:&#x20;

* `rootHash`: the calculated rootHash of Holder's statements;
* `holder`: the Holder's DidUrl;
* `expirationDate`: the expiration date of the Credential
* `ctype`: the structure of a claim;

```typescript
export type DigestPayload = {
  // rootHash of credential subject
  rootHash: HexString;
  
  // the holder of vc
  holder: DidUrl;
  
  // expiration date
  expirationDate?: number;
  
  // ctype hash
  ctype: HexString;
};
```

```typescript
// calculate the DigestHash via picked hash function
export function calcDigest(
  payload: DigestPayload,
  hashType: HashType = DEFAULT_DIGEST_HASH_TYPE
): DigestResult
```

The `DigestHash` is what makes an attested Credential unique and immutable. With these cryptography, we could verify the credential's validity easily. Changing (or tampering with) an attested claim will always result in a different claimHash, so in such cases a verification will always fail.

> **`DigestHash` can be regarded as an identifier of VC**. For the reason that, even if a user request for two credential with the same content and the same cType, the user will get two credential with different `DigestHash` -- due to the existence of `UUID`.

In the SDK, we wrapped the **verification method** inside, which could help the developers to check whether a credential is valid.

**Verify Credential**

```typescript
export async function vcVerify(
  vc: VerifiableCredential,
  resolverOrDidDocument?: DidResolver | DidDocument
): Promise<boolean>
```


# Architecture

The architecture of zkID-Login essentially consists of two sides (Dapp, zkID Wallet) interacting through *some Message Transport System*.

![Architecture Figure](/files/FLr1vFC0JlpHxtrP7JtL)

## zkID Wallet

Users can experience a brand new way of 'Login Mechanism' via zkID Wallet. This is a product that overturns *Traditional Internet Thinking* by allowing users to login only when their identity meeting some certain KYC Requirements of Service Providers.

Any presentation of data must be authorized by its owner, and the user can select which data to be displayed instead of providing all the details of a credential, which achieves '*prove one's identity with the least data*'.

## Provider

Provider is the RPC-API interface. Developers could invoke the `Provider` to accomplish zkID Login easily. The Provider contains the API below:

* provider.isAuth()
  * To query if the authorization is permitted by the User
* provider.requestAuth()
  * To request for an authorization from the User
* provider.requestAuthAndLogin()
  * To send request for authorization and request DID login
* provider.isLocked()
  * To check whether the wallet is locked
* provider.getCurrentDid()
  * To get the DID information of the current DID
* provider.didLogin(`param`)
  * To help the User to login with DID
* provider.requestCredentialDigest(`params`)
  * To help the User to login with Credential Digest Disclosure
* provider.requestCredentialContent(`params`)
  * To help the User to login with Credential Selective Disclosure and All Credential Content Disclosure
* ...

> For more coding details of the `Provider`, please check [our Github](https://github.com/zCloak-Network/zkid-login/blob/master/packages/providers/src/base/Provider.ts).


# Usage of VC

With Verifiable Credential technology, users would have full control over the information they share. Indeed, they can decide with whom to share, to what extent and so on. In this section, we show three types of VC disclosures:

* **Digest Disclosure**, which aims to prove someone owns a certain cType verifiable credential without revealing any credential details
* **Selective disclosure**, makes it possible to choose exactly which data is disclosed.
* **All Credential Content Disclosure**, helps users to offer the full details of a credential.

Check [Use Case](/preliminary_preparation/use_case) for more details and experience our demo website which help illustrate this concept.

## Digest Disclosure

This kind of disclosure only contains unprivate info, such as cType, Attester, ClaimHash, Owner. Here, `Digest` indicates that this kind of disclosure implies some info about credential.

> As an instance, assuming cType `C1` is created by zCloak, and the purpose of creating this cType is to issue a 'zCloak Membership Credential'. Only the user who is a member of zCloak Membership could own such a `C1` Credential.
>
> So, if a user can show a Digest Disclosure of a valid Credential, which 'cType' is `C1`, 'Attester' is `zCloak`, then we can confirm that the user is a member of zCloak without looking into the whole credential which may contain more personal details.

In a word, **Digest Disclosure** is normally used when the ***valid existence of credential*** is what we care most, rather than the details.

<figure><img src="/files/UPHQYuK6u5lRUuCDO91n" alt=""><figcaption><p>Digest Disclosure</p></figcaption></figure>

Developers can request for **Digest Disclosure** via the [API (VC Request Method)](/api/provider_api#vc-request-method) we provided, click to check more specification.

## Selective Disclosure

Unlike the first case, Claimer can **select** one or more pieces of information to share. For example, in the case of verifying an identity, this method allows the user to share only their ID Number, without necessarily revealing their date or place of birth. This feature of digitized credentials makes the platform more targeted to privacy protection by providing individuals with *granular control* over the information shared with various institutions and entities.

<figure><img src="/files/OyLztE6ytrgMYLs2nik6" alt=""><figcaption><p>Selective Disclosure</p></figcaption></figure>

Developers can request for **Selective Disclosure** via the [API (VC Request Method)](/api/provider_api#requestcredentialcontent-params) we provided, click to check more specification.

## All Credential Content Disclosure

Through this kind of disclosure, the service provider has access to **all pieces of** the credential information if the Claimer chooses to **share them all**. This is the highest trust level of presentation, since the Claimer needs to reveal all information of that credential.

<figure><img src="/files/GUoRvShg4naVUCCNb5M1" alt=""><figcaption><p><strong>All Credential Content Disclosure</strong></p></figcaption></figure>

Developers can request for **All Credential Content Disclosure** via the [API (VC Request Method)](/api/provider_api#requestcredentialcontent-params) we provided, click to check more specification.


# API Reference

This section shows how your requests are handled and what are the expected responses.

For now, the communication between Dapp and zkID Wallet is established via [JSON-RPC 1.0](https://www.jsonrpc.org/).

All the API showed in this section are in the [`Provider`](https://github.com/zCloak-Network/zkid-login/tree/master/packages/providers) of zkID Login. (This section is using the **0.4.1-0** version for demonstration purposes).&#x20;

{% hint style="warning" %}
When using the Provider of zkID Login, please make sure you use the **same version** of SDK as the Provider in order to avoid unnecessary error.
{% endhint %}

> You can check how these APIs work in our [zkID Login Website](https://login.zkid.app) for more details.


# Provider API

{% hint style="info" %}
Each API contains at least 3 parts: `Description`, `Params`, `Return`, for the verification of several API (e.g. `did_login`, `did_requestCredentialDigest`, `did_requestCredentialContent`, `did_sign`) we provide the **Verification Method** in the [SDK](https://github.com/zCloak-Network/zkid-login/tree/master/packages/verify) respectively.
{% endhint %}

## All Methods

* [Provider API](/api/provider_api)
  * [All Methods](#all-methods)
    * [Authorization Method](#authorization-method)
      * [requestAuth( )](#requestauth)
      * [isAuth( )](#isauth)
    * [DID Request Method](#did-request-method)
      * [getCurrentDid( )](#getcurrentdid)
      * [did\_login(param)](#did_login-param)
      * [requestAuthAndLogin(param)](#requestauthandlogin-param)
    * [VC Request Method](#vc-request-method)
      * [requestCredentialDigest(params)](#requestcredentialdigest-params)
      * [requestCredentialContent(params)](#requestcredentialcontent-params)
    * [DID-Key Method](#did-key-method)
      * [sign(param)](#sign-param)
      * [encrypt(params)](#encrypt-params)
      * [decrypt(params)](#decrypt-params)
    * [ZKP Method](#zkp-method)
      * [generateZkp(params)](#generatezkp-params)

### Authorization Method

#### requestAuth( )

```typescript
public requestAuth(): Promise<boolean> {
    return this.request('wallet_requestAuth', undefined);
}
```

**Description**

This API is designed for websites to request authorization from Users. User permission is the *premise* of all interaction, if the website hasn't obtained User permission yet, it can not be able to use the following API to interact with the User.&#x20;

If this API returns Error Code `-32001`, it means that the User rejects this request.

**Return**

* `Boolean` - whether the User request for authorization is successfully allowed.

***

#### isAuth( )

```typescript
public isAuth(): Promise<boolean> {
    return this.request('wallet_isAuth', undefined);
}
```

**Description**

This API's return shows whether the authorization is allowed. It is used for developer to query the user's authorization permission status. If the query status is `true`, developer can continue to call other APIs. Otherwise, developer must first call `wallet_requestAuth()` to get permission.

**Return**

* `Boolean` - whether the user allows authorization already.

***

####

### DID Request Method

#### getCurrentDid( )

```typescript
public getCurrentDid(): Promise<RequestRpcs<'did_getCurrent'>['did_getCurrent'][1]> {
    return this.request('did_getCurrent', undefined);
  }
```

**Description**

As mentioned before, DID is the unique identifier of an entity. This API aims to fetch the current `didUri` in the zkID Wallet, which helps developers to identify each User.

**Return**

* `DidInfo` Object - an example is shown below:

```typescript
export type DidInfo = {
  didUri: DidUrl;
  document: DidDocument;
  authenticationKey: HexString;
  encryptionKey: HexString[];
  attestationKey?: HexString;
  delegationKey?: HexString;
};
```

***

#### did\_login(param)

```typescript
  public didLogin(
    data: HexString | Uint8Array | string | number
  ): Promise<RequestRpcs<'did_login'>['did_login'][1]> {
    const payload: HexString = isHex(data)
      ? data
      : isU8a(data)
      ? u8aToHex(data)
      : isString(data)
      ? stringToHex(data)
      : numberToHex(data);

    return this.request('did_login', { payload });
  }
```

**Description**

This API is for users to login the website with their DID. With this API, the user needs to make a signature on some message (given by the website) via the user's DID `AuthenticationKey`. Once the user has successfully signed, the API returns the result of the user's signature, and developers can verify the validity of the signature through the *Verify Method* in our SDK. If the verification passes, then the login request should be permitted.

If this API returns Error Code `-32001`, it means that the User rejects this request.

**Param:**

* data (required)

```json
// data is the one to be signed
param: [{
    "data": "0x....."
}]
```

**Return:**

* `HexString` - the user's signature on that data

**Usage Of Return**

After receiving the `HexString` signature, developers need to verify its validity in order to check user's identity. In the SDK, we offer this [verifyDidLogin function](/introduction/method#verifydidlogin) to help achieve that.

#### requestAuthAndLogin(param)

```typescript
  public requestAuthAndLogin(
    data: HexString | Uint8Array | string | number
  ): Promise<RequestRpcs<'wallet_requestAuthAndLogin'>['wallet_requestAuthAndLogin'][1]> {
    const payload: HexString = isHex(data)
      ? data
      : isU8a(data)
      ? u8aToHex(data)
      : isString(data)
      ? stringToHex(data)
      : numberToHex(data);

    return this.request('wallet_requestAuthAndLogin', { payload });
  }

```

**Description**

This API is used to request authorization from Users, and ask the User to sign on some specific data to achieve `DID Login`. You can see this API as the combination of [`requestAuth`](#requestauth) and [`did_login`](#did_login-param).&#x20;

If the User hasn't give an authorization to the website, this function will request for the authorization first, and then do [did\_login](#did_login-param).

If the User already give an authorization to the website, then this function does the same thing as [`did_login`](#did_login-param).

If this API returns Error Code `-32001`, it means that the User rejects this request.

**Param:**

* data (required)

```json
// data is the one to be signed
param: [{
    "data": "0x....."
}]
```

**Return:**

* `HexString` - the user's signature on that data

**Usage Of Return**

After receiving the `HexString` signature, developers need to verify its validity in order to check user's identity. In the SDK, we offer this [verifyDidLogin function](/introduction/method#verifydidlogin) to help achieve that.

### VC Request Method

#### requestCredentialDigest(params)

```typescript
  public requestCredentialDigest(
    challenge: string,
    ctypehash?: HexString,
    attester?: DidUrl
  ): Promise<VerifiablePresentation> {
    return this.request('did_requestCredentialDigest', { challenge, ctypehash, attester });
  }
```

**Description**

This API is used to obtain a **Digest Disclosure** of a credential, which won't reveal any details of other information. The return result contains some digest information(roothash, `attested` status, `revoked` status) and several helper information (including `ctypeHash`, `owner`, `attester`, `signature`)

If this API returns Error Code `-32001`, it means that the User rejects this request.

If this API returns Error Code `-32801`, it means that the Credential doesn't exist.

If this API returns Error Code `-32010`, it means that the User hasn't give any authorization to this website, the request is not legal.

**Params:**

* `challenge` (required): a random string
* `ctypehash` (optional),the ctypehash of credential, if passed, the wallet will only return the credential with the same `ctypehash`
* `attester` (optional): attester's DID Url

```json
params_example: [{
    "challenge": "..."
    "ctypehash": "0x....",
    "attester": "...",
}]
```

**Return:**

* VerifiablePresentation

**Usage Of Return**

This [`verifyCredentialDigest`](/introduction/method#verifycredentialdigest) method provided in our SDK can be used to check whether the Digest Disclosure is valid, whether the User is the Credential's Owner.

***

#### requestCredentialContent(params)

```typescript
  public requestCredentialContent(
    challenge: string,
    contentKeys?: string[],
    ctypehash?: HexString,
    attester?: DidUrl
  ): Promise<VerifiablePresentation> {
    return this.request('did_requestCredentialContent', {
      challenge,
      contentKeys,
      ctypehash,
      attester
    });
  }
```

**Description**

This API is used to obtain a **further disclosure** of a credential, developers could use this API to achieve [***Selective Disclosure***](/readme/usage_of_vc#selective-disclosure) or [***All Credential Content Disclosure***](/readme/usage_of_vc#all-credential-content-disclosure) via passing different params.

If this API returns Error Code `-32001`, it means that the User rejects this request.

If this API returns Error Code `-32801`, it means that the Credential doesn't exist.

If this API returns Error Code `-32802`, it means that the Credential Metadata doesn't match.

**Params:**

* `challenge` (required): a random string
* `contentKeys` (optional): the content keys need to be disclosed
* `ctypehash` (optional),the ctypehash of credential, if passed, the wallet will only return the credential with the same `ctypehash`
* `attester` (optional): attester's DID Url

```json
params_example: [{
    "challenge": "..."
    "contentKeys": ["...", "...", "..."],
    "ctypehash": "0x....",
    "attester": "...",
}]
```

> Developers will get the ***Selective Disclosure*** result if they pass specific `contentKeys` into this API; Otherwise, if the field `contentKeys` is empty, they will obtain a ***All Credential Content Disclosure***.

**Return:**

* VerifiablePresentation

**Usage Of Return**

This [`verifyCredentialContent`](#VerifyCredentialContent) method provided in our SDK can be used to check whether the Selective Disclosure or All Credential Content Disclosure is valid, whether the User is the Credential's Owner.

***

### DID-Key Method

#### sign(param)

```typescript
public sign(
    data: HexString | Uint8Array | string | number,
    keyId?: DidUrl
  ): Promise<RequestRpcs<'did_sign'>['did_sign'][1]> {
    const payload: HexString = isHex(data)
      ? data
      : isU8a(data)
      ? u8aToHex(data)
      : isString(data)
      ? stringToHex(data)
      : numberToHex(data);

    return this.request('did_sign', { payload, keyId });
  }
```

**Description**

This API is for users to make a signature on some data via the user's DID `AuthenticationKey`. Once the user has successfully signed, the API returns the result of the user's signature, and developers can verify the validity of the signature through the *Verify Method* in our SDK.

If this API returns Error Code `-32001`, it means that the User rejects this request.

**Param:**

* `data` (required): data to be signed
* `key_Id`(optional): the key used to sign, if not specified, use `authenticationkey` by defalut.

```json
// data is the one to be signed
param: [{
    "data": "0x....."
}]
```

**Return:**

* `HexString` - the user's signature on that data

***

#### encrypt(params)

```typescript
  public encrypt(
    data: HexString | Uint8Array | string | number,
    receiver: DidUrl
  ): Promise<RequestRpcs<'did_encrypt'>['did_encrypt'][1]> {
    const message: HexString = isHex(data)
      ? data
      : isU8a(data)
      ? u8aToHex(data)
      : isString(data)
      ? stringToHex(data)
      : numberToHex(data);

    return this.request('did_encrypt', { message, receiver });
  }
```

**Description**

This API uses user's and peer's `AgreementKey` to encrypt data, can be used for build secret communication channel. Using this API, both parties of message transmission do not need to worry about message eavesdropping or leakage, encrypted messages can only be read through [Decryption Method](#decrypt-params).

If this API returns Error Code `-32001`, it means that the User rejects this request.

**Params:**

* `data` (required) : the data to be encrypted
* `receiver`:(required): the DID Url of the receiver, used to encrypt

**Return:**

* `HexString` - the encryption result

***

#### decrypt(params)

```typescript
  public decrypt(
    data: HexString | Uint8Array | string | number,
    sender: DidUrl
  ): Promise<HexString> {
    const message: HexString = isHex(data)
      ? data
      : isU8a(data)
      ? u8aToHex(data)
      : isString(data)
      ? stringToHex(data)
      : numberToHex(data);

    return this.request('did_decrypt', { message, sender });
  }
```

**Description**

This API uses user's and peer's `AgreementKey` to decrypt data, can be used for decrypt message transferred by secret communication channel.

If this API returns Error Code `-32001`, it means that the User rejects this request.

**Params**

* `data` (required) : the data to be decrypted
* `sender`:(required): the DID Url of the sender, used to decrypt

**Return:**

* `HexString` - the decryption result

### ZKP Method

#### generateZkp(params)

```typescript
  public generateZkp(
    params: RequestRpcs<'proof_generate'>['proof_generate'][0]
  ): Promise<RequestRpcs<'proof_generate'>['proof_generate'][1]> {
    return this.request('proof_generate', params);
  }
```

**Description**

This API is used to generate zero-knowledge proof with specific `ZKP Program` and `VC`.&#x20;

The `ZKP Program` used should be passed as a parameter. Besides, the `VC` used to run such ZKP Program should also be specified via its `ctypehash` and `attester`.

**Params**

* *ZkpGenRequest*
  * `ctype` (optional) : the specified `ctypehash` of the VC
  * `attester`:(optional): the specified attester's DID Url
  * `program` :(required): String of the ZKP Program

**Return:**

* *ZkpGenResponse*
  * `outputs` - the execution result of the ZKP Program
  * `starkproof` - the zero-knowledge proof of running such ZKP Program
  * `programHash` - the ZKP Program's hash
  * `ctype` - the specified `ctypehash` of the VC
  * `attester` - the specified attester's DID Url


# Events

All providers implements the `EventEmitter` API. This sections details the events emitted via that API. All the common `Event` which may take place in the `zkID Login` are listed as follow.

* [zkID\_Wallet\_didLoggedChanged(did\_changed)](#zkid_wallet_didloggedchanged-did_changed)
* [zkID\_Wallet\_lock(lock)](#zkid_wallet_lock-lock)
* [zkID\_Wallet\_unlock(unlock)](#zkid_wallet_unlock-unlock)

{% hint style="info" %}
*These events are triggered when the internal state of the zkID Wallet changes.*
{% endhint %}

## zkID\_Wallet\_didLoggedChanged(did\_changed)

### Usage

* When the DID selected in the zkID Wallet is changed, this event will be emitted.

You can use `provider.on` to catch this event. Here is an example of using our [Provider](https://github.com/zCloak-Network/zkid-login/blob/5f026f806867b44a68cb23e7efd0b34798d48ab1/packages/providers/src/ZkidWalletProvider.ts#L49) to listen to this event.

### Example

```typescript
provider.on('did_changed', (did) => {
  // Handle the new did when wallet selected did changed
  // `did` is an Object of `DidInfo`
})
```

## zkID\_Wallet\_lock(lock)

### Usage

* When the zkID Wallet is locked,  this event will be emitted.

You can use `provider.on` to catch this event. Here is an example of using our [Provider](https://github.com/zCloak-Network/zkid-login/blob/5f026f806867b44a68cb23e7efd0b34798d48ab1/packages/providers/src/ZkidWalletProvider.ts#L53) to listen to this event.

### Example

```typescript
provider.on('lock', (did) => {
  // Handle the wallet locked
})
```

## zkID\_Wallet\_unlock(unlock)

### Usage

* When the zkID Wallet is unlocked,  this event will be emitted.

You can use `provider.on` to catch this event. Here is an example of using our [Provider](https://github.com/zCloak-Network/zkid-login/blob/5f026f806867b44a68cb23e7efd0b34798d48ab1/packages/providers/src/ZkidWalletProvider.ts#L57) to listen to this event.

### Example

<pre class="language-typescript"><code class="lang-typescript"><strong>provider.on('unlock', (did) => {
</strong>  // Handle the wallet unlock
})
</code></pre>


# Errors

All errors thrown or returned by the zkID Wallet follow this interface:

```typescript
export interface RPCErrorInterface {
  code: number;
  message: string;
  meaning?: string;
}
```

You can often use the error code property to determine why the invoke of API failed. Common Error Codes and their meaning include:

* `-32801`
  * **Credential not found** The Credential doesn't exist.
* `-32802`
  * **Credential metadata error** Metadata doesn't match.
* `-32700`
  * **Parse Error** An error occurred on the server while parsing the Credential JSON Text.
* `-32600`
  * **Invalid Request** The JSON sent is not a valid Request object.
* `-32601`
  * **Method not found** The method doesn't exist / is not available.
* `-32602`
  * **Invalid params** Invalid method parameters(s).
* `-32603`
  * **Internal Error** Internal JSON-RPC Error.
* `-32010`
  * **Illegal request** The User hasn't give authorization to the website, so this request is illegal.
* `-32001`
  * **User Reject** The User reject this request.


# Using The Provider

This snippet illustrates how to accomplish the APIs above, which includes:

* Request authorization from the User
* Get the User's DID Information
* Request kinds of Credential Disclosure from the User
* Ask the User to sign a message and return a signature
* ....

### **Install packages**

First, you need to install the following packages, you can install them with the command below.

* @zcloak/login-providers
* @zcloak/login-verify
* @zcloak/did-resolver

```bash
# use yarn
yarn add @zcloak/login-providers @zcloak/login-verify @zcloak/did-resolver

# use npm
npm install @zcloak/login-providers @zcloak/login-verify @zcloak/did-resolver
```

### **A Simple Example Of How To Use The Provider:**

```typescript
// import ZkidWalletProvider
import { ZkidWalletProvider } from "@zcloak/login-providers";
import { ArweaveDidResolver } from "@zcloak/did-resolver";

import {
  verifyCredentialContent,
  verifyCredentialDigest,
  verifyDidLogin>
  } from '@zcloak/login-verify';

// init zkid wallet provider, make sure zkid wallet is install
const provider = new ZkidWalletProvider();

// init zkid did resolver
const resolver = new ArweaveDidResolver({ server: "https://did-service.zkid.app" });

async function main() {
  // API for checking authorization status: can be used to check whether the User has permitted the authorization to this website. 
  const isAuth = await provider.isAuth();
  
  // API for request authorization: If the authorization has not been permitted yet, request authorization from the User
  await provider.requestAuth();
  
  // API for getting user DID: Get current DID of User from the zkID Wallet
  const currentDid = await provider.getCurrentDid();

  // Create a message to sign    
  const message = 'Test_String';
  
  const signature = await provider.sign(message);
  
  const verifyDidLoginResult = await verifyDidLogin(message, signature, resolver);
  
  
  const challenge = 'Some_Random_Challenge';
    
  // API for obtaining a credential Digest Disclosure from the User     
  const credentialDigest = await provider.requestCredentialDigest(challenge);
  
  const credentialDigestResult = await verifyCredentialDigest(credentialDigest, challenge, currentDid.didUri, resolver);
  
  // API for getting a credential Selective Disclosure from the User (e.g. disclose `name` and `age`)    
  const credential = await provider.requestCredentialContent(challenge, ['name', 'age']);
  
  const credentialContentResult = await verifyCredentialContent(credential, challenge, currentDid.didUri, resolver);
  
}

```


# SDK

## Overview

zCloak login-verify is a SDK provided by zCloak Network and designed to help developers to do verification and authentication.

**zCloak login-verify 0.4.1-0** **Highlights:**

1. Support verification for *DIDLogin*
2. Support verification for Credential *Digest Disclosure*, *Selective Disclosure*, *All Credential Content Disclosure*

{% hint style="info" %}
Check more coding details on our [**Github**](https://github.com/zCloak-Network/zkid-login/tree/master/packages/verify).
{% endhint %}

## Process Flow Diagram

zCloak login-verify aims to help developers to verify several Return Value of zkID Login Provider. The corresponding relation between are showed in the following figure. More details about what each function do, how the parameters looks like and other information are present in the [Method section](/introduction/method).

![Process Flow Diagram](https://i.imgur.com/aRW69EP.jpg)

## Installation

```bash
yarn add @zcloak/login-verify
```


# Method

## verifyDidLogin

```typescript
export async function verifyDidLogin<T extends 'did_login' | 'did_login$Kilt' = 'did_login'>(
  message: HexString | Uint8Array | string,
  data: RequestRpcs<T>[T][1],
  resolver?: DidResolver
): Promise<boolean> {
......
}
```

**Description**

This SDK function aims for helping developers to authenticate User. This should be invoked after using the `didLogin(params)` function in the Provider, `verifyDidLogin(params)` function helps verify whether the User is actually the Owner of the DID.

**Params**

* `message`: the message which the User signed on (this should be the same with the `massage` in `didLogin(params)`)
* `signature`: the signature on that message, started with '0x'
* `publicKey`: the publicKey of User's `AuthenticationKey`, which is contains in the DID info (can be obtained by `getCurrentDid()` function in the Provider.

**Return** `Boolean` -- Whether the signature is actually signed by the User (in other word -- Whether developers should allow the User to login)

**Usage**

Check more details about [this SDK Function on our Github](https://github.com/zCloak-Network/zkid-login/tree/master/packages/verify).

```typescript
import { verifyDidLogin } from '@zcloak/login-verify';

// to sign message
const message = '';

const did = await provider.getCurrentDid();

const signature = await provider.didLogin(message);

// to verify the signature in order to authenticate the user
const result = verifyDidLogin(message, signature, did.authenticationKey);

console.log(result)
```

## verifyCredentialDigest

```typescript
export async function verifyCredentialDigest<
  T extends
    | 'did_requestCredentialDigest'
    | 'did_requestCredentialDigest$Kilt' = 'did_requestCredentialDigest'
>(
  credentialDigest: RequestRpcs<T>[T][1],
  challenge: string,
  owner: T extends 'did_requestCredentialDigest' ? DidUrl : DidUri,
  resolver?: DidResolver
): Promise<boolean> {
......
}
```

**Description**

This [`verifyCredentialDigest`](https://github.com/zCloak-Network/zkid-login/blob/master/packages/verify/src/verifyCredentialDigest.ts#L27) method provided in our SDK can be used to check whether the Digest Disclosure is valid, whether the User is the Credential’s Owner.

**Params**

* `credentialDigest`: the `RequestCredentialDigestReponse` of login-rpc, can be obtained use `did_requestCredentialDigest` method
* `challenge`: a random string, the same with the `challenge` in the `did_requestCredentialDigest` method
* `owner`: the credential owner

**Return**

`boolean` -- The Verification result of the Digest Disclosure

**Usage**

Check more details about [this SDK Function on our Github](https://github.com/zCloak-Network/zkid-login/tree/master/packages/verify).

```typescript
import { verifyCredentialDigest } from '@zcloak/login-verify';

const challenge = '';

const did = await provider.getCurrentDid();

// verify credential digest
const credentialDigest = await provider.requestCredentialDigest(challenge);

const result = await verifyCredentialDigest(credentialDigest, challenge, did.didUri);
```

## verifyCredentialContent

```typescript
export async function verifyCredentialContent<
  T extends
    | 'did_requestCredentialContent'
    | 'did_requestCredentialContent$Kilt' = 'did_requestCredentialContent'
>(
  credential: RequestRpcs<T>[T][1],
  challenge: string,
  owner: T extends 'did_requestCredentialContent' ? DidUrl : DidUri,
  resolver?: DidResolver
): Promise<boolean> {
......
}
```

**Description**

This [`verifyCredentialContent`](https://github.com/zCloak-Network/zkid-login/blob/master/packages/verify/src/verifyCredentialContent.ts#L27) method provided in our SDK can be used to check whether the Selective Disclosure or All Credential Content Disclosure is valid, whether the User is the Credential's Owner.

**Params**

* `credentialDigest`: the `RequestCredentialContentReponse` of login-rpc, can be obtained use `did_requestCredentialContent` method
* `challenge`: a random string, the same with the `challenge` in the `did_requestCredentialDigest` method
* `owner`: the credential owner

**Return**

`boolean` -- The Verification result of the **Selective Disclosure** or **All Credential Content Disclosure**.

**Usage**

Check more details about [this SDK Function on our Github](https://github.com/zCloak-Network/zkid-login/tree/master/packages/verify).

```typescript
import { verifyCredentialContent } from '@zcloak/login-verify';

const challenge = '';

const did = await provider.getCurrentDid();

const credential = await provider.requestCredentialContent(challenge);

// verify credential content
const result = await verifyCredentialContent(credential, challenge, did.didUri);

console.log(result);
```


# Getting Started

To develop for zkID Login, install zkID Wallet in the browser of your choice on your development machine. [Download here](https://chrome.google.com/webstore/detail/zkid-wallet/ahkpfejaeoepmfopmbhjgjekibmfcfgo).

Before starting to develop a Dapp interating with zkID Login, let's learn the zkID Wallet's primary function.

## Preliminary Preparation

### Create A New Account

A user who enters the zkID Wallet for the first time needs to generate an account by mnemonic phrases and a specific password.

Once the account is created successfully, a DID-Keys File will be downloaded automatically. You should store the file, mnemonic phrases and password properly, for the reason that if they are leaked, the account may be at risk.

**Create A New Account:**

![](https://i.imgur.com/Nj6KEuu.png) ![](https://i.imgur.com/WNQiELO.png) ![](https://i.imgur.com/FpbDPw3.png)

### **Backup Your Account**

Your account can only be restored via **DID-Keys File** or **Original Mnemonic Phrases**. So both of them should be kept safely. zkID Wallet will automatically download your DID-Keys File at the *Account Creation Phase*.

When you want to check your DID Information, you can go to the DID Profile Page. And download your DID-Keys File via **Export DID-Keys** at any time.

**Backup DID-Keys:**

![](https://i.imgur.com/kGKg4aR.png) ![](https://i.imgur.com/5N29Wbc.png)

### Import An Existing Account

Once you log out, you should restore your account with **DID-Keys File** or **Mnemonic Phrase** at the 'Restore account' Page.

**Import DID From DID-Keys File:**

![](https://i.imgur.com/qa5LUFT.png) ![](https://i.imgur.com/UnL7onL.png) ![](https://i.imgur.com/JkTpFYm.png)\\

**Import DID From Mnemonic Phrase:**

![](https://i.imgur.com/qa5LUFT.png) ![](https://i.imgur.com/HLlekIZ.png) ![](https://i.imgur.com/EPlHEDz.png)

### Import Your VC

We can import our obtained Verifiable Credential and check the credential details in zkID Wallet. During the import process, zkID Wallet will automatically help users check whether the credential is valid, the *Validity Check* ensures the credential meets all cryptography restrictions and the claimHash (roothash) is exist on chain.

**Import Your VC:**

![](https://i.imgur.com/gpontPC.png) ![](https://i.imgur.com/hCZtWpA.png) ![](https://i.imgur.com/NlBhRRj.png)


# Use Case

{% hint style="info" %}
This section is used to demonstrate several usage scenarios of zkID Login. You can follow the [**zkID Login Website**](https://login.zkid.app) for a further understanding. Each use case matches with a scenario in the website guide.
{% endhint %}

## Login with DID

As we mentioned before, DID could represent an entity. A Decentralised Identifier (DID) is a string uniquely identifying each user. Apart from the DID, the owner of DID should also own [DID-Keys](broken://pages/bCaIGQC43koAplCeKqDk#did-keys-currently-use), which contains different keys for multiple usage. Do not ignore DID-Keys, it plays a very important role here.

In the DID Login Process, the developer would ask the User to sign on a specific data and thus receives a Signature. By verifying the Signature's validity, the developer could authenticate the User's identity.

<figure><img src="https://i.imgur.com/rPM2uWf.jpg" alt=""><figcaption><p>DID Login</p></figcaption></figure>

## Login with Digest Disclosure

zkID Login provides a brand new way for Service Providers who need to verify users identity. With the advent of the web3.0 era, users are more and more aware of protecting their private data, and they are more inclined to keep their data in their own hands rather than hand it over to a third party.

All the service provider needs to do is to set the identity restriction of their target users. Here is a simply example (You could check more details about the example is our [zkID Login Website](https://login.zkid.app):

> `mockDao` only allow their employees to login its official website. Each employee obtains a `mockDao Membership Credential` on the first day of their work, which is attested and issued by `mockDao`. The credential contains each worker's *Name, Birthday, Membership Level*, as the Credential Example shows below.

![Credential Example](https://i.imgur.com/FSP62V3.jpg)

> Assuming that, Alice imports this verifiable credential to zkID Wallet and tries to login mockDao's official website. All Alice needs to do is to prove that she owns a `mockDao Membership Credential` attested by `mockDao` using zkID Wallet. The Method to be used, which best fits this situation, should be [**Digest Disclosure**](/readme/usage_of_vc#digest-disclosure) of a credential.(Because, what matters here is the existence of such a Membership Credential, [**Click Here**](/readme/usage_of_vc) to learn more about three types of Disclosure)
>
> So, all the things that `mockDao` needs to do is using the API offered by zkID Login to request a **Digest Disclosure** (in the case above) and can then easily determine whether the user is allowed to login.

## Login with Selective Disclosure

zkID Wallet enables users to manage the usage of VCs more granular. They can make fine-grained decisions about what information to share in a credential, without handing over the whole credential.

> For example, a `mockDao Membership Credential` contains *Name, Birthday, Membership Level*. In the Voting Process, the `Voting Website` only allows those whose `Membership Level > 2` to vote on some proposals. In this scenario, `Voting Website` only care about this property, it definitely could use zkID Login [**Selective Disclosure**](/readme/usage_of_vc#selective-disclosure) to accomplish that. Via zkID Login, the `Voting Website` **won't have access to any other information** of Alice expect her `Membership Level`, which protect Alice's privacy to the greatest extent.

To explore how zkID Login works, start with the [Basic Concept](/readme/did) which illustrates several key components in zkID Login.

Read [API Reference](/api) to get more specific details about how to interact with zkID Login system.


