Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

40 changes: 40 additions & 0 deletions pallets/confidential-docs/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
[package]
name = "pallet-confidential-docs"
version = "4.0.0-dev"
description = "Provides backend services for the confidentials docs solution"
authors = ["Hashed <https://github.com/hashed-io"]
homepage = "https://hashed.io"
edition = "2021"
license = "Unlicense"
publish = false
repository = "https://github.com/hashed-io/hashed-substrate"

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [
"derive",
] }
scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
frame-support = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.23"}
frame-system = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.23" }
frame-benchmarking = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.23", optional = true }

[dev-dependencies]
sp-core = { default-features = false, version = "6.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.23" }
sp-io = { default-features = false, version = "6.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.23" }
sp-runtime = { default-features = false, version = "6.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.23" }

[features]
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-support/std",
"frame-system/std",
"frame-benchmarking/std",
]

runtime-benchmarks = ["frame-benchmarking/runtime-benchmarks"]
try-runtime = ["frame-support/try-runtime"]
163 changes: 163 additions & 0 deletions pallets/confidential-docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# Confidential documents
Provides the backend services and metadata storage for the confidential docs solution

- [Confidential documents](#confidential-documents)
- [Overview](#overview)
- [Interface](#interface)
- [Dispachable functions](#dispachable-functions)
- [Getters](#getters)
- [Usage](#usage)
- [Polkadot-js api (javascript library)](#polkadot-js-api-javascript-library)
- [Create a vault](#create-a-vault)
- [Get a vault](#get-a-vault)
- [Get a public key](#get-a-public-key)
- [Create an owned confidential document](#create-an-owned-confidential-document)
- [Get an owned confidential document by CID](#get-an-owned-confidential-document-by-cid)
- [Remove an owned confidential document](#remove-an-owned-confidential-document)
- [Share a confidential document](#share-a-confidential-document)
- [Get a shared confidential document by CID](#get-a-shared-confidential-document-by-cid)
- [Update a shared confidential document's metadata](#update-a-shared-confidential-documents-metadata)
- [Remove a shared confidential document](#remove-a-shared-confidential-document)
## Overview

This module allows a user to:
- Create their vault. The vault stores the cipher private key used to cipher the user documents. The way the user vault is ciphered depends on the login method used by the user.
- Create on owned confidential document that only the user has access to
- Update the metadata of an owned confidential document
- Share a confidential document with another user

## Interface

### Dispachable functions
- `set_vault` Creates/Updates the calling user's vault and sets their public cipher key
- `set_owned_document` Creates a new owned document or updates an existing owned document's metadata
- `remove_owned_document` Removes an owned document
- `share_document` Creates a shared document
- `update_shared_document_metadata` Updates share document metadata
- `remove_shared_document` Removes a shared document

### Getters
- `vaults`
- `public_keys`
- `owned_docs`
- `owned_docs_by_owner`
- `shared_docs`
- `shared_docs_by_to`
- `shared_docs_by_from`

## Usage

The following examples will be using these prefunded accounts and testing data:

```bash
# Alice's mnemonic seed
"//Alice"
# Alice's public address
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"

# Bob's mnemonic seed
"//Bob"
# Bob's public address
"5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"
```

### Polkadot-js api (javascript library)

#### Create a vault
```js
const response = await api.tx.confidentialDocs.setVault(userId, publicKey, cid).signAndSend(alice);
```

#### Get a vault
```js
const vault = await api.query.confidentialDocs.vaults(userId);
console.log(vault.toHuman());
```
```bash
# Output should look like this:
{
cid: 'QmeHEb5TF4zkP2H6Mg5TcrvDs5egPCJgWFBB7YZaLmK7jr',
owner: '5FSuxe2q7qCYKie8yqmM56U4ovD1YtBb3DoPzGKjwZ98vxua'
}
```

#### Get a public key
```js
const publicKey = await api.query.confidentialDocs.publicKeys(address);
console.log(markets.toHuman());
```
```bash
# Output should look like this:
'0xabe44a53e2c1a5c7fa2f920338136d0ddc3aba23eacaf708e3871bc856a34b75'
```

#### Create an owned confidential document
```js
const response = await api.tx.confidentialDocs.setOwnedDocument({
"cid": "QmeHEb5TF4zkP2H6Mg5TcrvDs5egPCJgWFBB7YZaLmK7jr",
"name": "name",
"description": "desc",
"owner": "5FSuxe2q7qCYKie8yqmM56U4ovD1YtBb3DoPzGKjwZ98vxua"
}).signAndSend(alice);
```

#### Get an owned confidential document by CID
```js
const ownedDoc = await api.query.confidentialDocs.ownedDocs(cid);
console.log(ownedDoc.toHuman());
```
```bash
# Output should look like this:
{
"cid": "QmeHEb5TF4zkP2H6Mg5TcrvDs5egPCJgWFBB7YZaLmK7jr",
"name": "name",
"description": "desc",
"owner": "5FSuxe2q7qCYKie8yqmM56U4ovD1YtBb3DoPzGKjwZ98vxua"
}
```

#### Remove an owned confidential document
```js
const response = await api.tx.confidentialDocs.removeOwnedDocument("QmeHEb5TF4zkP2H6Mg5TcrvDs5egPCJgWFBB7YZaLmK7jr").signAndSend(alice);
```

#### Share a confidential document
```js
const response = await api.tx.confidentialDocs.shareDocument({
"cid": "QmeHEb5TF4zkP2H6Mg5TcrvDs5egPCJgWFBB7YZaLmK7jr",
"name": "name",
"description": "desc",
"to": "5FSuxe2q7qCYKie8yqmM56U4ovD1YtBb3DoPzGKjwZ98vxua",
"from": "5FWtfhKTuGKm9yWqzApwTfiUL4UPWukJzEcCTGYDiYHsdKaG"
}).signAndSend(alice);
```

#### Get a shared confidential document by CID
```js
const sharedDoc = await api.query.confidentialDocs.sharedDocs(cid);
console.log(sharedDoc.toHuman());
```
```bash
# Output should look like this:
{
"cid": "QmeHEb5TF4zkP2H6Mg5TcrvDs5egPCJgWFBB7YZaLmK7jr",
"name": "name",
"description": "desc",
"to": "5FSuxe2q7qCYKie8yqmM56U4ovD1YtBb3DoPzGKjwZ98vxua",
"from": "5FWtfhKTuGKm9yWqzApwTfiUL4UPWukJzEcCTGYDiYHsdKaG"
}
```

#### Update a shared confidential document's metadata
```js
const response = await api.tx.confidentialDocs.updateSharedDocumentMetadata({
"cid": "QmeHEb5TF4zkP2H6Mg5TcrvDs5egPCJgWFBB7YZaLmK7jr",
"name": "name",
"description": "desc"
}).signAndSend(alice);
```

#### Remove a shared confidential document
```js
const response = await api.tx.confidentialDocs.removeSharedDocument("QmeHEb5TF4zkP2H6Mg5TcrvDs5egPCJgWFBB7YZaLmK7jr").signAndSend(alice);
```
163 changes: 163 additions & 0 deletions pallets/confidential-docs/src/functions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
use super::*;
use frame_support::pallet_prelude::*;
use frame_support::sp_io::hashing::blake2_256;
//use frame_system::pallet_prelude::*;
use crate::types::*;

impl<T: Config> Pallet<T> {

pub fn do_set_vault(owner: T::AccountId, user_id: UserId, public_key: PublicKey, cid: CID) -> DispatchResult {
Self::validate_cid(&cid)?;
let hashed_account = owner.using_encoded(blake2_256);
if let Some(uid) = <UserIds<T>>::get(&hashed_account){
ensure!(uid == user_id, <Error<T>>::NotOwnerOfUserId);
} else {
ensure!(!<Vaults<T>>::contains_key(&user_id), <Error<T>>::NotOwnerOfVault);
}

let vault = Vault{
cid: cid.clone(),
owner: owner.clone()
};
<Vaults<T>>::insert(user_id, vault.clone());
<PublicKeys<T>>::insert(owner.clone(), public_key);
<UserIds<T>>::insert(hashed_account.clone(), user_id);

Self::deposit_event(Event::VaultStored(user_id, public_key, vault));
Ok(())
}

pub fn do_set_owned_document(owner: T::AccountId, mut owned_doc: OwnedDoc<T>) -> DispatchResult {
owned_doc.owner = owner.clone();
Self::validate_owned_doc(&owned_doc)?;
let OwnedDoc {
cid,
..
} = owned_doc.clone();
if let Some(doc) = <OwnedDocs<T>>::get(&cid) {
ensure!(doc.owner == owner, <Error<T>>::NotDocOwner);
} else {
<OwnedDocsByOwner<T>>::try_mutate(&owner, |owned_vec| {
owned_vec.try_push(cid.clone())
}).map_err(|_| <Error<T>>::ExceedMaxOwnedDocs)?;
}
<OwnedDocs<T>>::insert(cid.clone(), owned_doc.clone());
Self::deposit_event(Event::OwnedDocStored(owned_doc));
Ok(())
}

pub fn do_remove_owned_document(owner: T::AccountId, cid: CID) -> DispatchResult {
let doc = <OwnedDocs<T>>::try_get(&cid).map_err(|_| <Error<T>>::DocNotFound)?;
ensure!(doc.owner == owner, <Error<T>>::NotDocOwner);
<OwnedDocsByOwner<T>>::try_mutate(&owner, |owned_vec| {
let cid_index = owned_vec.iter().position(|c| *c==cid).ok_or(<Error<T>>::CIDNotFound)?;
owned_vec.remove(cid_index);
Ok(())
}).map_err(|_:Error::<T>| <Error<T>>::CIDNotFound)?;
<OwnedDocs<T>>::remove(cid.clone());
Self::deposit_event(Event::OwnedDocRemoved(doc));
Ok(())
}

pub fn do_share_document(owner: T::AccountId, mut shared_doc: SharedDoc<T>) -> DispatchResult {
shared_doc.from = owner;
Self::validate_shared_doc(&shared_doc)?;
let SharedDoc {
cid,
to,
from,
..
} = shared_doc.clone();

<SharedDocsByFrom<T>>::try_mutate(&from, |shared_vec| {
shared_vec.try_push(cid.clone())
}).map_err(|_| <Error<T>>::ExceedMaxSharedFromDocs)?;

<SharedDocsByTo<T>>::try_mutate(&to, |shared_vec| {
shared_vec.try_push(cid.clone())
}).map_err(|_| <Error<T>>::ExceedMaxSharedToDocs)?;

<SharedDocs<T>>::insert(cid.clone(), shared_doc.clone());
Self::deposit_event(Event::SharedDocStored(shared_doc));
Ok(())
}

pub fn do_update_shared_document_metadata(to: T::AccountId, mut shared_doc: SharedDoc<T>) -> DispatchResult {
let doc = <SharedDocs<T>>::try_get(&shared_doc.cid).map_err(|_| <Error<T>>::DocNotFound)?;
ensure!(doc.to == to, <Error<T>>::NotDocSharee);
shared_doc.from = doc.from;
shared_doc.to = to;
<SharedDocs<T>>::insert(doc.cid.clone(), shared_doc.clone());
Self::deposit_event(Event::SharedDocUpdated(shared_doc));
Ok(())
}

pub fn do_remove_shared_document(to: T::AccountId, cid: CID) -> DispatchResult {
let doc = <SharedDocs<T>>::try_get(&cid).map_err(|_| <Error<T>>::DocNotFound)?;
ensure!(doc.to == to, <Error<T>>::NotDocSharee);
<SharedDocsByTo<T>>::try_mutate(&to, |shared_vec| {
let cid_index = shared_vec.iter().position(|c| *c==cid).ok_or(<Error<T>>::CIDNotFound)?;
shared_vec.remove(cid_index);
Ok(())
}).map_err(|_:Error::<T>| <Error<T>>::CIDNotFound)?;
<SharedDocsByFrom<T>>::try_mutate(&doc.from, |shared_vec| {
let cid_index = shared_vec.iter().position(|c| *c==cid).ok_or(<Error<T>>::CIDNotFound)?;
shared_vec.remove(cid_index);
Ok(())
}).map_err(|_:Error::<T>| <Error<T>>::CIDNotFound)?;
<SharedDocs<T>>::remove(cid.clone());
Self::deposit_event(Event::SharedDocRemoved(doc));
Ok(())
}

fn validate_owned_doc(owned_doc: &OwnedDoc<T>)->DispatchResult{
let OwnedDoc {
cid,
name,
description,
owner
} = owned_doc;
Self::validate_cid(cid)?;
Self::validate_doc_name(name)?;
Self::validate_doc_desc(description)?;
Self::validate_has_public_key(owner)?;
Ok(())
}

fn validate_shared_doc(shared_doc: &SharedDoc<T>)->DispatchResult{
let SharedDoc {
cid,
name,
description,
from,
to,
} = shared_doc;
Self::validate_cid(cid)?;
Self::validate_doc_name(name)?;
Self::validate_doc_desc(description)?;
ensure!(from != to, <Error<T>>::DocSharedWithSelf);
ensure!(!<SharedDocs<T>>::contains_key(cid), <Error<T>>::DocAlreadyShared);
Self::validate_has_public_key(from)?;
Self::validate_has_public_key(to)?;
Ok(())
}

fn validate_has_public_key(who: &T::AccountId)->DispatchResult{
ensure!(<PublicKeys<T>>::contains_key(who), <Error<T>>::AccountHasNoPublicKey);
Ok(())
}
fn validate_cid(cid: &CID)->DispatchResult{
ensure!(cid.len() > 0, <Error<T>>::CIDNoneValue);
Ok(())
}

fn validate_doc_name(doc_name: &DocName<T>)->DispatchResult{
ensure!(doc_name.len() >= T::DocNameMinLen::get().try_into().unwrap(), <Error<T>>::DocNameTooShort);
Ok(())
}

fn validate_doc_desc(doc_desc: &DocDesc<T>)->DispatchResult{
ensure!(doc_desc.len() >= T::DocDescMinLen::get().try_into().unwrap(), <Error<T>>::DocDescTooShort);
Ok(())
}
}
Loading