From 0a7b2890870e9636c0830e2d2fe3f5fa9c392a56 Mon Sep 17 00:00:00 2001 From: Sosthene00 <674694@protonmail.ch> Date: Tue, 9 Apr 2024 12:45:13 +0200 Subject: [PATCH 01/30] tabula rasa --- Cargo.toml | 10 +- migrations.toml | 0 src/main.rs | 5 - src/models/commitment_method.rs | 11 - src/models/condition_cap.rs | 25 -- src/models/condition_commitment.rs | 23 -- src/models/condition_deposit.rs | 24 -- src/models/condition_orchestration.rs | 19 - src/models/condition_payment.rs | 25 -- src/models/condition_prd_address_set.rs | 141 ------- src/models/condition_publish.rs | 49 --- src/models/deposit_method.rs | 8 - src/models/item.rs | 94 ----- src/models/item_artefact.rs | 131 ------ src/models/item_commitment.rs | 239 ----------- src/models/item_deposit.rs | 277 ------------- src/models/item_enum.rs | 18 - src/models/item_member.rs | 374 ------------------ src/models/item_payment.rs | 315 --------------- src/models/item_peer.rs | 233 ----------- src/models/item_process.rs | 86 ---- src/models/key_encryption.rs | 248 ------------ src/models/message.rs | 108 ----- src/models/message_client.rs | 51 --- src/models/message_connect.rs | 19 - src/models/metadata.rs | 145 ------- src/models/metadata_contract_public.rs | 143 ------- src/models/metadata_private.rs | 143 ------- src/models/metadata_role_confidential.rs | 152 ------- src/models/mod.rs | 54 --- src/models/pagination.rs | 25 -- src/models/payment_method.rs | 8 - src/models/pcd_item_enc.rs | 63 --- src/models/pcd_item_enc_attribute_private.rs | 27 -- src/models/pcd_item_enc_attribute_public.rs | 25 -- ...cd_item_enc_attribute_role_confidential.rs | 29 -- src/models/pcd_item_generic_enc.rs | 63 --- src/models/request.rs | 46 --- src/models/request_pcd.rs | 143 ------- src/models/request_prd.rs | 108 ----- src/models/request_prd_confirm.rs | 100 ----- src/models/request_prd_key_backup.rs | 108 ----- src/models/request_prd_key_hello.rs | 98 ----- src/models/request_prd_list.rs | 90 ----- src/models/request_prd_message.rs | 89 ----- src/models/request_prd_response.rs | 178 --------- src/models/request_prd_update.rs | 127 ------ src/models/role.rs | 201 ---------- src/models/role_artefact.rs | 20 - src/models/role_commitment.rs | 20 - src/models/role_deposit.rs | 20 - src/models/role_member.rs | 18 - src/models/role_payment.rs | 20 - src/models/role_peer.rs | 20 - src/models/role_process.rs | 18 - src/models/roles_group.rs | 129 ------ src/models/shared_peer.rs | 221 ----------- src/models/shared_process.rs | 35 -- src/wallet.rs | 27 -- src/workflows/lib.rs | 0 src/workflows/mod.rs | 1 - .../workflow_pcd_create_and_send_all.rs | 253 ------------ 62 files changed, 1 insertion(+), 5499 deletions(-) delete mode 100644 migrations.toml delete mode 100644 src/main.rs delete mode 100644 src/models/commitment_method.rs delete mode 100644 src/models/condition_cap.rs delete mode 100644 src/models/condition_commitment.rs delete mode 100644 src/models/condition_deposit.rs delete mode 100644 src/models/condition_orchestration.rs delete mode 100644 src/models/condition_payment.rs delete mode 100644 src/models/condition_prd_address_set.rs delete mode 100644 src/models/condition_publish.rs delete mode 100644 src/models/deposit_method.rs delete mode 100644 src/models/item.rs delete mode 100644 src/models/item_artefact.rs delete mode 100644 src/models/item_commitment.rs delete mode 100644 src/models/item_deposit.rs delete mode 100644 src/models/item_enum.rs delete mode 100644 src/models/item_member.rs delete mode 100644 src/models/item_payment.rs delete mode 100644 src/models/item_peer.rs delete mode 100644 src/models/item_process.rs delete mode 100644 src/models/key_encryption.rs delete mode 100644 src/models/message.rs delete mode 100644 src/models/message_client.rs delete mode 100644 src/models/message_connect.rs delete mode 100644 src/models/metadata.rs delete mode 100644 src/models/metadata_contract_public.rs delete mode 100644 src/models/metadata_private.rs delete mode 100644 src/models/metadata_role_confidential.rs delete mode 100644 src/models/mod.rs delete mode 100644 src/models/pagination.rs delete mode 100644 src/models/payment_method.rs delete mode 100644 src/models/pcd_item_enc.rs delete mode 100644 src/models/pcd_item_enc_attribute_private.rs delete mode 100644 src/models/pcd_item_enc_attribute_public.rs delete mode 100644 src/models/pcd_item_enc_attribute_role_confidential.rs delete mode 100644 src/models/pcd_item_generic_enc.rs delete mode 100644 src/models/request.rs delete mode 100644 src/models/request_pcd.rs delete mode 100644 src/models/request_prd.rs delete mode 100644 src/models/request_prd_confirm.rs delete mode 100644 src/models/request_prd_key_backup.rs delete mode 100644 src/models/request_prd_key_hello.rs delete mode 100644 src/models/request_prd_list.rs delete mode 100644 src/models/request_prd_message.rs delete mode 100644 src/models/request_prd_response.rs delete mode 100644 src/models/request_prd_update.rs delete mode 100644 src/models/role.rs delete mode 100644 src/models/role_artefact.rs delete mode 100644 src/models/role_commitment.rs delete mode 100644 src/models/role_deposit.rs delete mode 100644 src/models/role_member.rs delete mode 100644 src/models/role_payment.rs delete mode 100644 src/models/role_peer.rs delete mode 100644 src/models/role_process.rs delete mode 100644 src/models/roles_group.rs delete mode 100644 src/models/shared_peer.rs delete mode 100644 src/models/shared_process.rs delete mode 100644 src/wallet.rs delete mode 100644 src/workflows/lib.rs delete mode 100644 src/workflows/mod.rs delete mode 100644 src/workflows/workflow_pcd_create_and_send_all.rs diff --git a/Cargo.toml b/Cargo.toml index 44f1c53..6dcc1a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,17 +7,9 @@ edition = "2021" crate-type = ["cdylib", "rlib"] [dependencies] -wasm-bindgen = "0.2.90" serde = { version = "1.0.193", features = ["derive"] } serde_json = "1.0.108" -# sp_backend = { git = "https://github.com/Sosthene00/sp-backend.git", branch = "master" } -# silentPayments = { git = "https://github.com/Sosthene00/rust-silentPayments", branch = "utils" } -rand = "0.8.5" -hex = "0.4.3" +sp_backend = { git = "https://github.com/Sosthene00/sp-backend.git", branch = "master" } uuid = { version = "1.6.1", features = ["serde", "v4"] } -sha2 = "0.10.8" -chrono = "0.4.31" aes-gcm = "0.10.3" aes = "0.8.3" -base64 = "0.21.7" -rocket = { version = "0.5.0", features = ["json"] } diff --git a/migrations.toml b/migrations.toml deleted file mode 100644 index e69de29..0000000 diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index 95f7962..0000000 --- a/src/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -use sdk_common::models; -use sdk_common::wallet; -use sdk_common::workflows; - -fn main() {} diff --git a/src/models/commitment_method.rs b/src/models/commitment_method.rs deleted file mode 100644 index b997e0d..0000000 --- a/src/models/commitment_method.rs +++ /dev/null @@ -1,11 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct commitMethod { - pub method: String, -} -impl commitMethod { - pub fn new(method: String) -> Self { - commitMethod { method } - } -} diff --git a/src/models/condition_cap.rs b/src/models/condition_cap.rs deleted file mode 100644 index f6871bc..0000000 --- a/src/models/condition_cap.rs +++ /dev/null @@ -1,25 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::TransactionMode; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct ConditionCap { - pub role_deposit: String, - pub role_transaction: TransactionMode, -} - -impl ConditionCap { - pub fn new(role_deposit: String, role_transaction: TransactionMode) -> Self { - ConditionCap { - role_deposit, - role_transaction, - } - } - // Affiche les informations de la structure - pub fn display_info(&self) { - println!("ConditionCap:"); - println!("Role Deposit: {}", self.role_deposit); - println!("Role Transaction:"); - self.role_transaction.display_info(); // Appelle display_info sur role_transaction - } -} diff --git a/src/models/condition_commitment.rs b/src/models/condition_commitment.rs deleted file mode 100644 index 715b3c1..0000000 --- a/src/models/condition_commitment.rs +++ /dev/null @@ -1,23 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::TransactionMode; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct Conditioncommit { - pub role_artefact: String, - pub role_transaction: TransactionMode, -} - -impl Conditioncommit { - pub fn new(role_artefact: String, role_transaction: TransactionMode) -> Self { - Conditioncommit { - role_artefact, - role_transaction, - } - } - pub fn display_info(&self) { - println!("Conditioncommit:"); - println!("Role Artefact: {}", self.role_artefact); - println!("Role Transaction:"); - self.role_transaction.display_info(); // Appelle display_info sur role_transaction - } -} diff --git a/src/models/condition_deposit.rs b/src/models/condition_deposit.rs deleted file mode 100644 index acccd9f..0000000 --- a/src/models/condition_deposit.rs +++ /dev/null @@ -1,24 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::TransactionMode; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct ConditionDeposit { - pub role_deposit: String, - pub role_transaction: TransactionMode, -} - -impl ConditionDeposit { - pub fn new(role_deposit: String, role_transaction: TransactionMode) -> Self { - ConditionDeposit { - role_deposit, - role_transaction, - } - } - pub fn display_info(&self) { - println!("ConditionDeposit:"); - println!("Role Deposit: {}", self.role_deposit); - println!("Role Transaction:"); - self.role_transaction.display_info(); // Appelle display_info sur role_transaction - } -} diff --git a/src/models/condition_orchestration.rs b/src/models/condition_orchestration.rs deleted file mode 100644 index 1b79efa..0000000 --- a/src/models/condition_orchestration.rs +++ /dev/null @@ -1,19 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct ConditionOrchestration { - pub role_ok: String, - pub role_ko: String, -} - -impl ConditionOrchestration { - pub fn new(role_ok: String, role_ko: String) -> Self { - ConditionOrchestration { role_ok, role_ko } - } - pub fn display_info(&self) { - println!("ConditionOrchestration:"); - println!("Role OK: {}", self.role_ok); - println!("Role KO: {}", self.role_ko); - } -} diff --git a/src/models/condition_payment.rs b/src/models/condition_payment.rs deleted file mode 100644 index 37d9437..0000000 --- a/src/models/condition_payment.rs +++ /dev/null @@ -1,25 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::TransactionMode; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct ConditionPayments { - pub role_Payments: String, - pub role_transaction: TransactionMode, -} - -impl ConditionPayments { - pub fn new(role_Payments: String, role_transaction: TransactionMode) -> Self { - ConditionPayments { - role_Payments, - role_transaction, - } - } - pub fn display_info(&self) { - println!("ConditionPayments:"); - println!("Role Payments: {}", self.role_Payments); - println!("Role Transaction:"); - self.role_transaction.display_info(); // Appelle display_info sur role_transaction - } -} diff --git a/src/models/condition_prd_address_set.rs b/src/models/condition_prd_address_set.rs deleted file mode 100644 index 32bc820..0000000 --- a/src/models/condition_prd_address_set.rs +++ /dev/null @@ -1,141 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct ConditionPrdAddressSet { - pub from_role: String, - pub prd_sp_address_list: Vec, - pub prd_sp_address_required_list: Vec, - pub prd_sp_address_quota: i32, - pub prd_prd_value_ok_list: Vec, - pub prd_value_ko_list: Vec, - pub prd_value_none_list: Vec, - pub prd_sp_address_value_min: i64, - pub prd_sp_address_value_min_per: i64, - pub prd_sp_address_value_min_ok: bool, - pub prd_sp_adddress_value_ok_min_per: i64, - pub prd_sp_address_value_ok_max: i64, - pub prd_sp_adderss_value_ko_max_per: i64, - pub prd_sp_address_value_none_max: i64, - pub prd_sp_adderss_value_none_max_per: i64, - pub prd_sp_address_score_min: i32, - pub prd_sp_address_score_min_min_required: i32, - pub prd_sp_address_score_min_min_ok: bool, - pub prd_sp_address_score_min_min_per: i64, - pub prd_value_auto_ok: bool, - pub prd_value_auto_ko: bool, - pub prd_value_auto_none: bool, -} - -impl ConditionPrdAddressSet { - // Constructor for PrdAddressSet with all fields - pub fn new( - from_role: String, - prd_sp_address_list: Vec, - prd_sp_address_required_list: Vec, - prd_sp_address_quota: i32, - prd_prd_value_ok_list: Vec, - prd_value_ko_list: Vec, - prd_value_none_list: Vec, - prd_sp_address_value_min: i64, - prd_sp_address_value_min_per: i64, - prd_sp_address_value_min_ok: bool, - prd_sp_adddress_value_ok_min_per: i64, - prd_sp_address_value_ok_max: i64, - prd_sp_adderss_value_ko_max_per: i64, - prd_sp_address_value_none_max: i64, - prd_sp_adderss_value_none_max_per: i64, - prd_sp_address_score_min: i32, - prd_sp_address_score_min_min_required: i32, - prd_sp_address_score_min_min_ok: bool, - prd_sp_address_score_min_min_per: i64, - prd_value_auto_ok: bool, - prd_value_auto_ko: bool, - prd_value_auto_none: bool, - ) -> Self { - ConditionPrdAddressSet { - from_role, - prd_sp_address_list, - prd_sp_address_required_list, - prd_sp_address_quota, - prd_prd_value_ok_list, - prd_value_ko_list, - prd_value_none_list, - prd_sp_address_value_min, - prd_sp_address_value_min_per, - prd_sp_address_value_min_ok, - prd_sp_adddress_value_ok_min_per, - prd_sp_address_value_ok_max, - prd_sp_adderss_value_ko_max_per, - prd_sp_address_value_none_max, - prd_sp_adderss_value_none_max_per, - prd_sp_address_score_min, - prd_sp_address_score_min_min_required, - prd_sp_address_score_min_min_ok, - prd_sp_address_score_min_min_per, - prd_value_auto_ok, - prd_value_auto_ko, - prd_value_auto_none, - } - } - pub fn display_info(&self) { - println!("ConditionPrdAddressSet:"); - println!("From Role: {}", self.from_role); - println!("SP Address List: {:?}", self.prd_sp_address_list); - println!( - "SP Address Required List: {:?}", - self.prd_sp_address_required_list - ); - println!("SP Address Quota: {}", self.prd_sp_address_quota); - println!("PRD Value OK List: {:?}", self.prd_prd_value_ok_list); - println!("Value KO List: {:?}", self.prd_value_ko_list); - println!("Value None List: {:?}", self.prd_value_none_list); - println!("SP Address Value Min: {}", self.prd_sp_address_value_min); - println!( - "SP Address Value Min Percentage: {}", - self.prd_sp_address_value_min_per - ); - println!( - "SP Address Value Min OK: {}", - self.prd_sp_address_value_min_ok - ); - println!( - "SP Address Value OK Min Percentage: {}", - self.prd_sp_adddress_value_ok_min_per - ); - println!( - "SP Address Value OK Max: {}", - self.prd_sp_address_value_ok_max - ); - println!( - "SP Address Value KO Max Percentage: {}", - self.prd_sp_adderss_value_ko_max_per - ); - println!( - "SP Address Value None Max: {}", - self.prd_sp_address_value_none_max - ); - println!( - "SP Address Value None Max Percentage: {}", - self.prd_sp_adderss_value_none_max_per - ); - println!("SP Address Score Min: {}", self.prd_sp_address_score_min); - println!( - "SP Address Score Min Required: {}", - self.prd_sp_address_score_min_min_required - ); - println!( - "SP Address Score Min OK: {}", - self.prd_sp_address_score_min_min_ok - ); - println!( - "SP Address Score Min Percentage: {}", - self.prd_sp_address_score_min_min_per - ); - println!("Value Auto OK: {}", self.prd_value_auto_ok); - println!("Value Auto KO: {}", self.prd_value_auto_ko); - println!("Value Auto None: {}", self.prd_value_auto_none); - } - - // Methods for manipulating the struct can be added here as needed. -} diff --git a/src/models/condition_publish.rs b/src/models/condition_publish.rs deleted file mode 100644 index 1207c3c..0000000 --- a/src/models/condition_publish.rs +++ /dev/null @@ -1,49 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::metadata::Amount; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct ConditionPublish { - pub pcd_data_size_max_unit: String, - pub pcd_data_size_max_total: i64, - pub pcd_number_min: i32, - pub pcd_number_max: i32, - pub pcd_amount_max_total: Amount, - pub Prd_waiting_timeout: u64, - pub pcd_waiting_timeout: u64, -} - -impl ConditionPublish { - pub fn new( - pcd_data_size_max_unit: String, - pcd_data_size_max_total: i64, - pcd_number_min: i32, - pcd_number_max: i32, - pcd_amount_max_total: Amount, - Prd_waiting_timeout: u64, - pcd_waiting_timeout: u64, - ) -> Self { - ConditionPublish { - pcd_data_size_max_unit, - pcd_data_size_max_total, - pcd_number_min, - pcd_number_max, - pcd_amount_max_total, - Prd_waiting_timeout, - pcd_waiting_timeout, - } - } - pub fn display_info(&self) { - println!("ConditionPublish:"); - println!("PCD Data Size Max Unit: {}", self.pcd_data_size_max_unit); - println!("PCD Data Size Max Total: {}", self.pcd_data_size_max_total); - println!("PCD Number Min: {}", self.pcd_number_min); - println!("PCD Number Max: {}", self.pcd_number_max); - self.pcd_amount_max_total.display_info(); - println!( - " Prd Waiting Timeout: {}", - self.Prd_waiting_timeout - ); - println!("PCD Waiting Timeout: {}", self.pcd_waiting_timeout); - } -} diff --git a/src/models/deposit_method.rs b/src/models/deposit_method.rs deleted file mode 100644 index f2cde70..0000000 --- a/src/models/deposit_method.rs +++ /dev/null @@ -1,8 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct DepositMethod { - pub method: String, -} -impl DepositMethod {} diff --git a/src/models/item.rs b/src/models/item.rs deleted file mode 100644 index 8db96ad..0000000 --- a/src/models/item.rs +++ /dev/null @@ -1,94 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use uuid::Uuid; - -use super::{ - key_encryption::KeyEncryption, metadata_contract_public::MetadataContractPublic, - metadata_private::MetadataPrivate, metadata_role_confidential::MetadataRoleConfidential, - pcd_item_enc::PcdItemEnc, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Item { - pub uuid: String, - pub version: i64, - pub hash: Option, - pub item_type: String, // `type` is a reserved keyword in Rust, renamed to `item_type` - pub name: String, - pub pagination_number_per_pcd: u32, - pub metadata_contract_public: MetadataContractPublic, - pub metadata_role_confidential: MetadataRoleConfidential, - pub metadata_private: MetadataPrivate, -} - -impl Item { - pub fn new( - version: i64, - item_type: String, - name: String, - pagination_number_per_pcd: u32, - metadata_contract_public: MetadataContractPublic, - metadata_role_confidential: MetadataRoleConfidential, - metadata_private: MetadataPrivate, - ) -> Self { - let uuid: String = Uuid::new_v4().to_string(); - Item { - uuid, - version, - item_type, - name, - pagination_number_per_pcd, - metadata_contract_public, - metadata_role_confidential, - metadata_private, - hash: None, - } - } - pub fn display_info(&self) { - println!("Item:"); - println!("UUID: {}", self.uuid); - println!("Version: {}", self.version); - println!("Item Type: {}", self.item_type); - println!("Name: {}", self.name); - println!( - "Pagination Number Per PCD: {}", - self.pagination_number_per_pcd - ); - - println!("Metadata Contract Public:"); - self.metadata_contract_public.display_info(); // Display information for `metadata_contract_public` - - println!("Metadata Role Confidential:"); - self.metadata_role_confidential.display_info(); // Display information for `metadata_role_confidential` - - println!("Metadata Private:"); - self.metadata_private.display_info(); // Display information for `metadata_private` - } - - pub fn enc( - &self, - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - ) -> PcdItemEnc { - let enc_metadata_contract_public = self - .metadata_contract_public - .enc_list(process_public_enc_key); - - let enc_metadata_role_confidential = self.metadata_role_confidential.enc_list(); - - let enc_metadata_private = self.metadata_private.enc_list(Member_private_enc_key); - - PcdItemEnc::new( - self.version, - self.item_type.clone(), - self.name.clone(), - self.pagination_number_per_pcd, - enc_metadata_contract_public, - enc_metadata_role_confidential, - enc_metadata_private, - ) - } - - // Additional methods for Item can be added here -} diff --git a/src/models/item_artefact.rs b/src/models/item_artefact.rs deleted file mode 100644 index dddd05e..0000000 --- a/src/models/item_artefact.rs +++ /dev/null @@ -1,131 +0,0 @@ -use serde::{Deserialize, Serialize}; -use serde_json::json; -use std::hash::Hash; - -use super::item::Item; -use super::key_encryption::KeyEncryption; -use super::pcd_item_enc_attribute_private::PcdItemEncAttributePrivate; -use super::pcd_item_enc_attribute_public::PcdItemEncAttributePublic; -use super::pcd_item_enc_attribute_role_confidential::PcdItemEncAttributeRoleConfidential; -use super::pcd_item_generic_enc::PcdItemGenericEnc; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct Artefact { - pub item: Item, - pub public_attribute_group: Vec, // Assuming list of attributes - pub role_confidential_attribute_group: Vec, - pub private_attribute_group: Vec, -} - -impl Artefact { - pub fn new( - item: Item, - public_attribute_group: Vec, - role_confidential_attribute_group: Vec, - private_attribute_group: Vec, - ) -> Self { - Artefact { - item, - public_attribute_group, - role_confidential_attribute_group, - private_attribute_group, - } - } - pub fn enc_public_attribute_group( - &self, - process_public_enc_key: KeyEncryption, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let mut count = 0; - for public_attribute in &self.public_attribute_group { - let name = "index".to_owned() + &count.to_string(); - let value = serde_json::to_value(public_attribute).unwrap_or_else(|_| json!({})); - let enc_attribute = - PcdItemEncAttributePublic::new(name, process_public_enc_key.enc(value)); - enc_attribute_list.push(enc_attribute); - count += 1; - } - - enc_attribute_list - } - pub fn enc_role_confidential_attribute_group( - &self, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let mut count = 0; - for role_confidential_attribute in &self.role_confidential_attribute_group { - let name = "index".to_owned() + &count.to_string(); - let value = - serde_json::to_value(role_confidential_attribute).unwrap_or_else(|_| json!({})); - let mut role_confidential_attribute_key = - KeyEncryption::new(Some(name.clone()), None, None); - if let Ok(_new) = role_confidential_attribute_key.key_new_random() { - let enc_attribute = PcdItemEncAttributeRoleConfidential::new( - name, - role_confidential_attribute_key.enc(value), - role_confidential_attribute_key, - ); - enc_attribute_list.push(enc_attribute); - } - count += 1; - } - - enc_attribute_list - } - pub fn enc_private_attribute_group( - &self, - Member_private_enc_key: KeyEncryption, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let mut count = 0; - for private_attribute in &self.public_attribute_group { - let name = "index".to_owned() + &count.to_string(); - let value = serde_json::to_value(private_attribute).unwrap_or_else(|_| json!({})); - let enc_attribute = - PcdItemEncAttributePrivate::new(name, Member_private_enc_key.enc(value)); - enc_attribute_list.push(enc_attribute); - count += 1; - } - - enc_attribute_list - } - - pub fn enc( - &self, - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - ) -> PcdItemGenericEnc { - let enc_metadata_contract_public = - self.enc_public_attribute_group(process_public_enc_key.clone()); - - let enc_role_confidential_attribute_group = self.enc_role_confidential_attribute_group(); - - let enc_metadata_private = self.enc_private_attribute_group(Member_private_enc_key.clone()); - - PcdItemGenericEnc::new( - self.item - .enc(process_public_enc_key, Member_private_enc_key), - Some(enc_metadata_contract_public), - Some(enc_role_confidential_attribute_group), - Some(enc_metadata_private), - ) - } - pub fn display_info(&self) { - println!("Artefact:"); - println!("Item:"); - self.item.display_info(); // Appelle display_info sur item - - println!("Public Attribute Group: {:?}", self.public_attribute_group); - println!( - "Role Confidential Attribute Group: {:?}", - self.role_confidential_attribute_group - ); - println!( - "Private Attribute Group: {:?}", - self.private_attribute_group - ); - } -} diff --git a/src/models/item_commitment.rs b/src/models/item_commitment.rs deleted file mode 100644 index 00565fa..0000000 --- a/src/models/item_commitment.rs +++ /dev/null @@ -1,239 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - item::Item, key_encryption::KeyEncryption, - pcd_item_enc_attribute_private::PcdItemEncAttributePrivate, - pcd_item_enc_attribute_public::PcdItemEncAttributePublic, - pcd_item_enc_attribute_role_confidential::PcdItemEncAttributeRoleConfidential, - pcd_item_generic_enc::PcdItemGenericEnc, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct CommitPublicAttributeGroup { - pub for_sp_address_list: Vec, - pub goal_list: Vec, - pub provider_type: String, - pub commit_pcd_hash_list: Vec, - pub ref_item_hash_list: Vec, - pub ref_pcd_hash_list: Vec, - pub payload_public_list: Vec, -} - -impl CommitPublicAttributeGroup { - pub fn new( - for_sp_address_list: Vec, - goal_list: Vec, - provider_type: String, - commit_pcd_hash_list: Vec, - ref_item_hash_list: Vec, - ref_pcd_hash_list: Vec, - payload_public_list: Vec, - ) -> Self { - CommitPublicAttributeGroup { - for_sp_address_list, - goal_list, - provider_type, - commit_pcd_hash_list, - ref_item_hash_list, - ref_pcd_hash_list, - payload_public_list, - } - } - pub fn enc_group( - &self, - process_public_enc_key: KeyEncryption, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let for_sp_address_list_enc = PcdItemEncAttributePublic::new( - "for_sp_address_list".to_owned(), - process_public_enc_key.enc_vec_string(self.for_sp_address_list.clone()), - ); - enc_attribute_list.push(for_sp_address_list_enc); - - let goal_list_enc = PcdItemEncAttributePublic::new( - "goal_list".to_owned(), - process_public_enc_key.enc_vec_string(self.goal_list.clone()), - ); - enc_attribute_list.push(goal_list_enc); - - let provider_type_enc = PcdItemEncAttributePublic::new( - "provider_type".to_owned(), - process_public_enc_key.enc_string(self.provider_type.clone()), - ); - enc_attribute_list.push(provider_type_enc); - - let commit_pcd_hash_list_enc = PcdItemEncAttributePublic::new( - "commit_pcd_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.commit_pcd_hash_list.clone()), - ); - enc_attribute_list.push(commit_pcd_hash_list_enc); - - let ref_item_hash_list_enc = PcdItemEncAttributePublic::new( - "ref_item_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.ref_item_hash_list.clone()), - ); - enc_attribute_list.push(ref_item_hash_list_enc); - - let ref_pcd_hash_list_enc = PcdItemEncAttributePublic::new( - "ref_pcd_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.ref_pcd_hash_list.clone()), - ); - enc_attribute_list.push(ref_pcd_hash_list_enc); - - let payload_public_list_enc = PcdItemEncAttributePublic::new( - "payload_public_list".to_owned(), - process_public_enc_key.enc_vec_string(self.payload_public_list.clone()), - ); - enc_attribute_list.push(payload_public_list_enc); - - enc_attribute_list - } - pub fn display_info(&self) { - println!("CommitPublicAttributeGroup:"); - println!("For SP Address List: {:?}", self.for_sp_address_list); - println!("Goal List: {:?}", self.goal_list); - println!("Provider Type: {}", self.provider_type); - println!( - "commit PCD Hash List: {:?}", - self.commit_pcd_hash_list - ); - println!("Ref Item Hash List: {:?}", self.ref_item_hash_list); - println!("Ref PCD Hash List: {:?}", self.ref_pcd_hash_list); - println!("Payload Public List: {:?}", self.payload_public_list); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct CommitRoleConfidentialAttributeGroup { - pub payload_list_confidential: Vec, -} - -impl CommitRoleConfidentialAttributeGroup { - pub fn new(payload_list_confidential: Vec) -> Self { - CommitRoleConfidentialAttributeGroup { - payload_list_confidential, - } - } - pub fn enc_group(&self) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let mut payload_list_confidential_key = - KeyEncryption::new(Some("payload_list_confidential".to_owned()), None, None); - if let Ok(_new) = payload_list_confidential_key.key_new_random() { - let payload_list_confidential_enc = PcdItemEncAttributeRoleConfidential::new( - "payload_list_confidential".to_owned(), - payload_list_confidential_key - .enc_vec_string(self.payload_list_confidential.clone()), - payload_list_confidential_key, - ); - enc_attribute_list.push(payload_list_confidential_enc); - } - - return enc_attribute_list; - } - pub fn display_info(&self) { - println!("CommitRoleConfidentialAttributeGroup:"); - for (index, payload) in self.payload_list_confidential.iter().enumerate() { - println!("Confidential Payload {}: {}", index + 1, payload); - } - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct CommitPrivateAttributeGroup { - pub payload_list_private: Vec, -} - -impl CommitPrivateAttributeGroup { - pub fn new(payload_list_private: Vec) -> Self { - CommitPrivateAttributeGroup { - payload_list_private, - } - } - pub fn enc_group(&self, Member_enc_key: KeyEncryption) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let payload_list_private_enc = PcdItemEncAttributePrivate::new( - "payload_list_private".to_owned(), - Member_enc_key.enc_vec_string(self.payload_list_private.clone()), - ); - enc_attribute_list.push(payload_list_private_enc); - - enc_attribute_list - } - pub fn display_info(&self) { - println!("CommitRoleConfidentialAttributeGroup:"); - for (index, payload) in self.payload_list_private.iter().enumerate() { - println!("Private Payload {}: {}", index + 1, payload); - } - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Commit { - pub item: Item, - pub public_attribute_group: CommitPublicAttributeGroup, - pub role_confidential_attribute_group: CommitRoleConfidentialAttributeGroup, - pub private_attribute_group: CommitPrivateAttributeGroup, -} - -impl Commit { - pub const ITEM_NAME: &'static str = "commit"; - pub fn new( - mut item: Item, - public_attribute_group: CommitPublicAttributeGroup, - role_confidential_attribute_group: CommitRoleConfidentialAttributeGroup, - private_attribute_group: CommitPrivateAttributeGroup, - ) -> Self { - item.name = Self::ITEM_NAME.to_string(); - Commit { - item, - public_attribute_group, - role_confidential_attribute_group, - private_attribute_group, - } - } - pub fn enc( - &self, - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - ) -> PcdItemGenericEnc { - let enc_metadata_contract_public = self - .public_attribute_group - .enc_group(process_public_enc_key.clone()); - - let enc_role_confidential_attribute_group = - self.role_confidential_attribute_group.enc_group(); - - let enc_metadata_private = self - .private_attribute_group - .enc_group(Member_private_enc_key.clone()); - - PcdItemGenericEnc::new( - self.item - .enc(process_public_enc_key, Member_private_enc_key), - Some(enc_metadata_contract_public), - Some(enc_role_confidential_attribute_group), - Some(enc_metadata_private), - ) - } - pub fn display_info(&self) { - println!("Commit:"); - println!("Item:"); - self.item.display_info(); // Affiche les informations de `item` - - println!("Public Attribute Group:"); - self.public_attribute_group.display_info(); // Affiche les informations de `public_attribute_group` - - println!("Role Confidential Attribute Group:"); - self.role_confidential_attribute_group.display_info(); // Affiche les informations de `role_confidential_attribute_group` - - println!("Private Attribute Group:"); - self.private_attribute_group.display_info(); // Affiche les informations de `private_attribute_group` - } -} diff --git a/src/models/item_deposit.rs b/src/models/item_deposit.rs deleted file mode 100644 index f12a37b..0000000 --- a/src/models/item_deposit.rs +++ /dev/null @@ -1,277 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - item::Item, key_encryption::KeyEncryption, - pcd_item_enc_attribute_private::PcdItemEncAttributePrivate, - pcd_item_enc_attribute_public::PcdItemEncAttributePublic, - pcd_item_enc_attribute_role_confidential::PcdItemEncAttributeRoleConfidential, - pcd_item_generic_enc::PcdItemGenericEnc, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct DepositPublicAttributeGroup { - pub for_sp_address_list: Vec, - pub for_address_list: Vec, - pub goal_list: Vec, - pub provider_type: String, - pub ref_item_hash_list: Vec, - pub ref_pcd_hash_list: Vec, - pub payload_list_public: Vec, - pub audit_code_list_public: Vec, -} - -impl DepositPublicAttributeGroup { - pub fn new( - for_sp_address_list: Vec, - for_address_list: Vec, - goal_list: Vec, - provider_type: String, - ref_item_hash_list: Vec, - ref_pcd_hash_list: Vec, - payload_list_public: Vec, - audit_code_list_public: Vec, - ) -> Self { - DepositPublicAttributeGroup { - for_sp_address_list, - for_address_list, - goal_list, - provider_type, - ref_item_hash_list, - ref_pcd_hash_list, - payload_list_public, - audit_code_list_public, - } - } - pub fn enc_group( - &self, - process_public_enc_key: KeyEncryption, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let for_sp_address_list_enc = PcdItemEncAttributePublic::new( - "for_sp_address_list".to_owned(), - process_public_enc_key.enc_vec_string(self.for_sp_address_list.clone()), - ); - enc_attribute_list.push(for_sp_address_list_enc); - - let for_address_list_enc = PcdItemEncAttributePublic::new( - "for_address_list".to_owned(), - process_public_enc_key.enc_vec_string(self.for_address_list.clone()), - ); - enc_attribute_list.push(for_address_list_enc); - - let goal_list_enc = PcdItemEncAttributePublic::new( - "goal_list".to_owned(), - process_public_enc_key.enc_vec_string(self.goal_list.clone()), - ); - enc_attribute_list.push(goal_list_enc); - - let provider_type_enc = PcdItemEncAttributePublic::new( - "provider_type".to_owned(), - process_public_enc_key.enc_string(self.provider_type.clone()), - ); - enc_attribute_list.push(provider_type_enc); - - let ref_item_hash_list_enc = PcdItemEncAttributePublic::new( - "ref_item_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.ref_item_hash_list.clone()), - ); - enc_attribute_list.push(ref_item_hash_list_enc); - - let ref_pcd_hash_list_enc = PcdItemEncAttributePublic::new( - "ref_pcd_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.ref_pcd_hash_list.clone()), - ); - enc_attribute_list.push(ref_pcd_hash_list_enc); - - let payload_list_public_enc = PcdItemEncAttributePublic::new( - "payload_list_public".to_owned(), - process_public_enc_key.enc_vec_string(self.payload_list_public.clone()), - ); - enc_attribute_list.push(payload_list_public_enc); - - let audit_code_list_public_enc = PcdItemEncAttributePublic::new( - "audit_code_list_public".to_owned(), - process_public_enc_key.enc_vec_string(self.audit_code_list_public.clone()), - ); - enc_attribute_list.push(audit_code_list_public_enc); - - enc_attribute_list - } - pub fn display_info(&self) { - println!("DepositPublicAttributeGroup:"); - println!("For SP Address List: {:?}", self.for_sp_address_list); - println!("For Address List: {:?}", self.for_address_list); - println!("Goal List: {:?}", self.goal_list); - println!("Provider Type: {}", self.provider_type); - println!("Ref Item Hash List: {:?}", self.ref_item_hash_list); - println!("Ref PCD Hash List: {:?}", self.ref_pcd_hash_list); - println!("Payload List Public: {:?}", self.payload_list_public); - println!("Audit Code List Public: {:?}", self.audit_code_list_public); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct DepositRoleConfidentialAttributeGroup { - pub payload_list_confidential: Vec, - pub audit_code_list_confidential: Vec, -} - -impl DepositRoleConfidentialAttributeGroup { - pub fn new( - payload_list_confidential: Vec, - audit_code_list_confidential: Vec, - ) -> Self { - DepositRoleConfidentialAttributeGroup { - payload_list_confidential, - audit_code_list_confidential, - } - } - pub fn enc_group(&self) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let mut payload_list_confidential_key = - KeyEncryption::new(Some("payload_list_confidential".to_owned()), None, None); - - if let Ok(_new) = payload_list_confidential_key.key_new_random() { - let payload_list_confidential_enc = PcdItemEncAttributeRoleConfidential::new( - "payload_list_confidential".to_owned(), - payload_list_confidential_key - .enc_vec_string(self.payload_list_confidential.clone()), - payload_list_confidential_key, - ); - enc_attribute_list.push(payload_list_confidential_enc); - } - - let mut audit_code_list_confidential_key = - KeyEncryption::new(Some("audit_code_list_confidential".to_owned()), None, None); - if let Ok(_new) = audit_code_list_confidential_key.key_new_random() { - let audit_code_list_confidential_enc = PcdItemEncAttributeRoleConfidential::new( - "audit_code_list_confidential".to_owned(), - audit_code_list_confidential_key - .enc_vec_string(self.audit_code_list_confidential.clone()), - audit_code_list_confidential_key, - ); - enc_attribute_list.push(audit_code_list_confidential_enc); - } - - return enc_attribute_list; - } - pub fn display_info(&self) { - println!("DepositRoleConfidentialAttributeGroup:"); - println!( - "Confidential Payload List: {:?}", - self.payload_list_confidential - ); - println!( - "Confidential Audit Code List: {:?}", - self.audit_code_list_confidential - ); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct DepositPrivateAttributeGroup { - pub payload_list_private: Vec, - pub audit_code_private: String, -} - -impl DepositPrivateAttributeGroup { - pub fn new(payload_list_private: Vec, audit_code_private: String) -> Self { - DepositPrivateAttributeGroup { - payload_list_private, - audit_code_private, - } - } - - pub fn enc_group(&self, Member_enc_key: KeyEncryption) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let payload_list_private_enc = PcdItemEncAttributePrivate::new( - "payload_list_private".to_owned(), - Member_enc_key.enc_vec_string(self.payload_list_private.clone()), - ); - enc_attribute_list.push(payload_list_private_enc); - - let audit_code_private_enc = PcdItemEncAttributePrivate::new( - "audit_code_private".to_owned(), - Member_enc_key.enc_string(self.audit_code_private.clone()), - ); - enc_attribute_list.push(audit_code_private_enc); - - enc_attribute_list - } - pub fn display_info(&self) { - println!("DepositPrivateAttributeGroup:"); - println!("Private Payload List: {:?}", self.payload_list_private); - println!("Private Audit Code: {}", self.audit_code_private); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Deposit { - pub item: Item, - pub public_attribute_group: DepositPublicAttributeGroup, - pub role_confidential_attribute_group: DepositRoleConfidentialAttributeGroup, - pub private_attribute_group: DepositPrivateAttributeGroup, -} - -impl Deposit { - pub const ITEM_NAME: &'static str = "deposit"; - pub fn new( - mut item: Item, - public_attribute_group: DepositPublicAttributeGroup, - role_confidential_attribute_group: DepositRoleConfidentialAttributeGroup, - private_attribute_group: DepositPrivateAttributeGroup, - ) -> Self { - item.name = Self::ITEM_NAME.to_string(); - Deposit { - item, - public_attribute_group, - role_confidential_attribute_group, - private_attribute_group, - } - } - pub fn enc( - &self, - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - ) -> PcdItemGenericEnc { - let enc_metadata_contract_public = self - .public_attribute_group - .enc_group(process_public_enc_key.clone()); - - let enc_role_confidential_attribute_group = - self.role_confidential_attribute_group.enc_group(); - - let enc_metadata_private = self - .private_attribute_group - .enc_group(Member_private_enc_key.clone()); - - PcdItemGenericEnc::new( - self.item - .enc(process_public_enc_key, Member_private_enc_key), - Some(enc_metadata_contract_public), - Some(enc_role_confidential_attribute_group), - Some(enc_metadata_private), - ) - } - pub fn display_info(&self) { - println!("Deposit:"); - println!("Item:"); - self.item.display_info(); // Affiche les informations de l'objet `item` - - println!("Public Attribute Group:"); - self.public_attribute_group.display_info(); // Affiche les informations du groupe d'attributs publics - - println!("Role Confidential Attribute Group:"); - self.role_confidential_attribute_group.display_info(); // Affiche les informations du groupe d'attributs confidentiels - - println!("Private Attribute Group:"); - self.private_attribute_group.display_info(); // Affiche les informations du groupe d'attributs privés - } -} diff --git a/src/models/item_enum.rs b/src/models/item_enum.rs deleted file mode 100644 index eae2dd8..0000000 --- a/src/models/item_enum.rs +++ /dev/null @@ -1,18 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - item_artefact::Artefact, item_commit::Commit, item_deposit::Deposit, - item_Member::Member, item_Payments::Payments, item_peer::Peer, - item_process::Process, -}; - -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub enum ItemEnum { - Process(Process), - Peer(Peer), - Member(Member), - Payments(Payments), - Deposit(Deposit), - Artefact(Artefact), - commit(Commit), -} diff --git a/src/models/item_member.rs b/src/models/item_member.rs deleted file mode 100644 index 1150121..0000000 --- a/src/models/item_member.rs +++ /dev/null @@ -1,374 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - item::Item, key_encryption::KeyEncryption, - pcd_item_enc_attribute_private::PcdItemEncAttributePrivate, - pcd_item_enc_attribute_public::PcdItemEncAttributePublic, - pcd_item_enc_attribute_role_confidential::PcdItemEncAttributeRoleConfidential, - pcd_item_generic_enc::PcdItemGenericEnc, -}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct MemberPublicAttributeGroup { - pub sp_address_public: String, - pub sp_address_public_sig: String, - pub sp_address_revoke_public: String, - pub sp_address_revoke_public_sig: String, - pub third_sp_address_list_public: Vec, - pub data_size_max: i64, - pub Payments_method_list_public: Vec, - pub succession_process_hash: String, -} - -impl MemberPublicAttributeGroup { - pub fn new( - sp_address_public: String, - sp_address_public_sig: String, - sp_address_revoke_public: String, - sp_address_revoke_public_sig: String, - third_sp_address_list_public: Vec, - data_size_max: i64, - Payments_method_list_public: Vec, - succession_process_hash: String, - ) -> Self { - MemberPublicAttributeGroup { - sp_address_public, - sp_address_public_sig, - sp_address_revoke_public, - sp_address_revoke_public_sig, - third_sp_address_list_public, - data_size_max, - Payments_method_list_public, - succession_process_hash, - } - } - pub fn enc_group( - &self, - process_public_enc_key: KeyEncryption, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let sp_address_public_enc = PcdItemEncAttributePublic::new( - "sp_address_public".to_owned(), - process_public_enc_key.enc_string(self.sp_address_public.clone()), - ); - enc_attribute_list.push(sp_address_public_enc); - - let sp_address_public_sig_enc = PcdItemEncAttributePublic::new( - "sp_address_public_sig".to_owned(), - process_public_enc_key.enc_string(self.sp_address_public_sig.clone()), - ); - enc_attribute_list.push(sp_address_public_sig_enc); - - let sp_address_revoke_public_enc = PcdItemEncAttributePublic::new( - "sp_address_revoke_public".to_owned(), - process_public_enc_key.enc_string(self.sp_address_revoke_public.clone()), - ); - enc_attribute_list.push(sp_address_revoke_public_enc); - - let sp_address_revoke_public_sig_enc = PcdItemEncAttributePublic::new( - "sp_address_revoke_public_sig".to_owned(), - process_public_enc_key.enc_string(self.sp_address_revoke_public_sig.clone()), - ); - enc_attribute_list.push(sp_address_revoke_public_sig_enc); - - let third_sp_address_list_public_enc = PcdItemEncAttributePublic::new( - "third_sp_address_list_public".to_owned(), - process_public_enc_key.enc_vec_string(self.third_sp_address_list_public.clone()), - ); - enc_attribute_list.push(third_sp_address_list_public_enc); - - let data_size_max_enc = PcdItemEncAttributePublic::new( - "data_size_max".to_owned(), - process_public_enc_key.enc_i64(self.data_size_max), - ); - enc_attribute_list.push(data_size_max_enc); - - let Payments_method_list_public_enc = PcdItemEncAttributePublic::new( - "Payments_method_list_public".to_owned(), - process_public_enc_key.enc_vec_string(self.Payments_method_list_public.clone()), - ); - enc_attribute_list.push(Payments_method_list_public_enc); - - let succession_process_hash_enc = PcdItemEncAttributePublic::new( - "succession_process_hash".to_owned(), - process_public_enc_key.enc_string(self.succession_process_hash.clone()), - ); - enc_attribute_list.push(succession_process_hash_enc); - - enc_attribute_list - } - pub fn display_info(&self) { - println!("MemberPublicAttributeGroup:"); - println!("SP Address Public: {}", self.sp_address_public); - println!( - "SP Address Public Signature: {}", - self.sp_address_public_sig - ); - println!( - "SP Address Revoke Public: {}", - self.sp_address_revoke_public - ); - println!( - "SP Address Revoke Public Signature: {}", - self.sp_address_revoke_public_sig - ); - println!( - "Third SP Address List Public: {:?}", - self.third_sp_address_list_public - ); - println!("Data Size Max: {}", self.data_size_max); - println!( - "Payments Method List Public: {:?}", - self.Payments_method_list_public - ); - println!("Succession Process Hash: {}", self.succession_process_hash); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct MemberRoleConfidentialAttributeGroup { - pub Payments_method_list_confidential: Vec, - pub id_shard_info: String, -} - -impl MemberRoleConfidentialAttributeGroup { - pub fn new(Payments_method_list_confidential: Vec, id_shard_info: String) -> Self { - MemberRoleConfidentialAttributeGroup { - Payments_method_list_confidential, - id_shard_info, - } - } - - pub fn enc_group(&self) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let mut enc_Payments_method_list_confidential_key = KeyEncryption::new( - Some("Payments_method_list_confidential".to_owned()), - None, - None, - ); - if let Ok(_new) = enc_Payments_method_list_confidential_key.key_new_random() { - let Payments_method_list_confidential_enc = PcdItemEncAttributeRoleConfidential::new( - "Payments_method_list_confidential".to_owned(), - enc_Payments_method_list_confidential_key - .enc_vec_string(self.Payments_method_list_confidential.clone()), - enc_Payments_method_list_confidential_key, - ); - enc_attribute_list.push(Payments_method_list_confidential_enc); - } - - let mut enc_id_shard_info_key = - KeyEncryption::new(Some("id_shard_info".to_owned()), None, None); - - if let Ok(_new) = enc_id_shard_info_key.key_new_random() { - let id_shard_info_enc = PcdItemEncAttributeRoleConfidential::new( - "id_shard_info".to_owned(), - enc_id_shard_info_key.enc_string(self.id_shard_info.clone()), - enc_id_shard_info_key, - ); - enc_attribute_list.push(id_shard_info_enc); - } - - return enc_attribute_list; - } - pub fn display_info(&self) { - println!("MemberRoleConfidentialAttributeGroup:"); - println!( - "Confidential Payments Method List: {:?}", - self.Payments_method_list_confidential - ); - println!("ID Shard Info: {}", self.id_shard_info); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct MemberPrivateAttributeGroup { - pub Payments_method_list_private: Vec, - pub pcd_list: Vec, // Assuming this is a list of strings - pub prd_list_list: Vec, - pub prd_update_list: Vec, - pub prd_response_list: Vec, - pub prd_message_list: Vec, - pub prd_confirm_list: Vec, - pub prd_key_backup_list: Vec, - pub prd_key_hello_list: Vec, - pub tx_sp_list: Vec, -} - -impl MemberPrivateAttributeGroup { - pub fn new( - Payments_method_list_private: Vec, - pcd_list: Vec, - prd_list_list: Vec, - prd_update_list: Vec, - prd_response_list: Vec, - prd_message_list: Vec, - prd_confirm_list: Vec, - prd_key_backup_list: Vec, - prd_key_hello_list: Vec, - tx_sp_list: Vec, - ) -> Self { - MemberPrivateAttributeGroup { - Payments_method_list_private, - pcd_list, - prd_list_list, - prd_update_list, - prd_response_list, - prd_message_list, - prd_confirm_list, - prd_key_backup_list, - prd_key_hello_list, - tx_sp_list, - } - } - - pub fn enc_group(&self, Member_enc_key: KeyEncryption) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let Payments_method_list_private_enc = PcdItemEncAttributePrivate::new( - "Payments_method_list_private".to_owned(), - Member_enc_key.enc_vec_string(self.Payments_method_list_private.clone()), - ); - enc_attribute_list.push(Payments_method_list_private_enc); - - let pcd_list_enc = PcdItemEncAttributePrivate::new( - "pcd_list".to_owned(), - Member_enc_key.enc_vec_string(self.pcd_list.clone()), - ); - enc_attribute_list.push(pcd_list_enc); - - let prd_list_list_enc = PcdItemEncAttributePrivate::new( - "prd_list_list".to_owned(), - Member_enc_key.enc_vec_string(self.prd_list_list.clone()), - ); - enc_attribute_list.push(prd_list_list_enc); - - let prd_update_list_enc = PcdItemEncAttributePrivate::new( - "prd_update_list".to_owned(), - Member_enc_key.enc_vec_string(self.prd_update_list.clone()), - ); - enc_attribute_list.push(prd_update_list_enc); - - let prd_response_list_enc = PcdItemEncAttributePrivate::new( - "prd_response_list".to_owned(), - Member_enc_key.enc_vec_string(self.prd_response_list.clone()), - ); - enc_attribute_list.push(prd_response_list_enc); - - let prd_message_list_enc = PcdItemEncAttributePrivate::new( - "prd_message_list".to_owned(), - Member_enc_key.enc_vec_string(self.prd_message_list.clone()), - ); - enc_attribute_list.push(prd_message_list_enc); - - let prd_confirm_list_enc = PcdItemEncAttributePrivate::new( - "prd_confirm_list".to_owned(), - Member_enc_key.enc_vec_string(self.prd_confirm_list.clone()), - ); - enc_attribute_list.push(prd_confirm_list_enc); - - let prd_key_backup_list_enc = PcdItemEncAttributePrivate::new( - "prd_key_backup_list".to_owned(), - Member_enc_key.enc_vec_string(self.prd_key_backup_list.clone()), - ); - enc_attribute_list.push(prd_key_backup_list_enc); - - let prd_key_hello_list_enc = PcdItemEncAttributePrivate::new( - "prd_key_hello_list".to_owned(), - Member_enc_key.enc_vec_string(self.prd_key_hello_list.clone()), - ); - enc_attribute_list.push(prd_key_hello_list_enc); - - let tx_sp_list_enc = PcdItemEncAttributePrivate::new( - "tx_sp_list".to_owned(), - Member_enc_key.enc_vec_string(self.tx_sp_list.clone()), - ); - enc_attribute_list.push(tx_sp_list_enc); - - enc_attribute_list - } - pub fn display_info(&self) { - println!("MemberPrivateAttributeGroup:"); - println!( - "Private Payments Method List: {:?}", - self.Payments_method_list_private - ); - println!("PCD List: {:?}", self.pcd_list); - println!("PRD List List: {:?}", self.prd_list_list); - println!("PRD Update List: {:?}", self.prd_update_list); - println!("PRD Response List: {:?}", self.prd_response_list); - println!("PRD `Envelope` List: {:?}", self.prd_message_list); - println!("PRD Confirm List: {:?}", self.prd_confirm_list); - println!("PRD Key Backup List: {:?}", self.prd_key_backup_list); - println!("PRD Key Hello List: {:?}", self.prd_key_hello_list); - println!("TX SP List: {:?}", self.tx_sp_list); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Member { - pub item: Item, - pub public_attribute_group: MemberPublicAttributeGroup, - pub role_confidential_attribute_group: MemberRoleConfidentialAttributeGroup, - pub private_attribute_group: MemberPrivateAttributeGroup, -} - -impl Member { - pub const ITEM_NAME: &'static str = "Member"; - pub fn new( - mut item: Item, - public_attribute_group: MemberPublicAttributeGroup, - role_confidential_attribute_group: MemberRoleConfidentialAttributeGroup, - private_attribute_group: MemberPrivateAttributeGroup, - ) -> Self { - item.name = Self::ITEM_NAME.to_string(); - Member { - item, - public_attribute_group, - role_confidential_attribute_group, - private_attribute_group, - } - } - pub fn enc( - &self, - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - ) -> PcdItemGenericEnc { - let enc_metadata_contract_public = self - .public_attribute_group - .enc_group(process_public_enc_key.clone()); - - let enc_role_confidential_attribute_group = - self.role_confidential_attribute_group.enc_group(); - - let enc_metadata_private = self - .private_attribute_group - .enc_group(Member_private_enc_key.clone()); - - PcdItemGenericEnc::new( - self.item - .enc(process_public_enc_key, Member_private_enc_key), - Some(enc_metadata_contract_public), - Some(enc_role_confidential_attribute_group), - Some(enc_metadata_private), - ) - } - pub fn display_info(&self) { - println!("Member:"); - println!("Item:"); - self.item.display_info(); // Affiche les informations de l'objet `item` - - println!("Member Public Attribute Group:"); - self.public_attribute_group.display_info(); // Affiche les informations du groupe d'attributs publics - - println!("Member Role Confidential Attribute Group:"); - self.role_confidential_attribute_group.display_info(); // Affiche les informations du groupe d'attributs confidentiels - - println!("Member Private Attribute Group:"); - self.private_attribute_group.display_info(); // Affiche les informations du groupe d'attributs privés - } -} diff --git a/src/models/item_payment.rs b/src/models/item_payment.rs deleted file mode 100644 index 33753c4..0000000 --- a/src/models/item_payment.rs +++ /dev/null @@ -1,315 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - item::Item, key_encryption::KeyEncryption, - pcd_item_enc_attribute_private::PcdItemEncAttributePrivate, - pcd_item_enc_attribute_public::PcdItemEncAttributePublic, - pcd_item_enc_attribute_role_confidential::PcdItemEncAttributeRoleConfidential, - pcd_item_generic_enc::PcdItemGenericEnc, -}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PaymentsPublicAttributeGroup { - pub for_sp_address_list: Vec, - pub goal_list: Vec, - pub provider_type: String, - pub commit_pcd_hash_list: Vec, - pub order_pcd_hash_list: Vec, - pub invoice_pcd_hash_list: Vec, - pub pay_pcd_hash_list: Vec, - pub ref_item_hash_list: Vec, - pub ref_pcd_hash_list: Vec, - pub payload_list_public: Vec, - pub audit_code_list_public: Vec, -} - -impl PaymentsPublicAttributeGroup { - pub fn new( - for_sp_address_list: Vec, - goal_list: Vec, - provider_type: String, - commit_pcd_hash_list: Vec, - order_pcd_hash_list: Vec, - invoice_pcd_hash_list: Vec, - pay_pcd_hash_list: Vec, - ref_item_hash_list: Vec, - ref_pcd_hash_list: Vec, - payload_list_public: Vec, - audit_code_list_public: Vec, - ) -> Self { - PaymentsPublicAttributeGroup { - for_sp_address_list, - goal_list, - provider_type, - commit_pcd_hash_list, - order_pcd_hash_list, - invoice_pcd_hash_list, - pay_pcd_hash_list, - ref_item_hash_list, - ref_pcd_hash_list, - payload_list_public, - audit_code_list_public, - } - } - pub fn enc_group( - &self, - process_public_enc_key: KeyEncryption, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let for_sp_address_list_enc = PcdItemEncAttributePublic::new( - "for_sp_address_list".to_owned(), - process_public_enc_key.enc_vec_string(self.for_sp_address_list.clone()), - ); - enc_attribute_list.push(for_sp_address_list_enc); - - let goal_list_enc = PcdItemEncAttributePublic::new( - "goal_list".to_owned(), - process_public_enc_key.enc_vec_string(self.goal_list.clone()), - ); - enc_attribute_list.push(goal_list_enc); - - let provider_type_enc = PcdItemEncAttributePublic::new( - "provider_type".to_owned(), - process_public_enc_key.enc_string(self.provider_type.clone()), - ); - enc_attribute_list.push(provider_type_enc); - - let commit_pcd_hash_list_enc = PcdItemEncAttributePublic::new( - "commit_pcd_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.commit_pcd_hash_list.clone()), - ); - enc_attribute_list.push(commit_pcd_hash_list_enc); - - let order_pcd_hash_list_enc = PcdItemEncAttributePublic::new( - "order_pcd_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.order_pcd_hash_list.clone()), - ); - enc_attribute_list.push(order_pcd_hash_list_enc); - - let invoice_pcd_hash_list_enc = PcdItemEncAttributePublic::new( - "invoice_pcd_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.invoice_pcd_hash_list.clone()), - ); - enc_attribute_list.push(invoice_pcd_hash_list_enc); - - let pay_pcd_hash_list_enc = PcdItemEncAttributePublic::new( - "pay_pcd_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.pay_pcd_hash_list.clone()), - ); - enc_attribute_list.push(pay_pcd_hash_list_enc); - - let ref_item_hash_list_enc = PcdItemEncAttributePublic::new( - "ref_item_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.ref_item_hash_list.clone()), - ); - enc_attribute_list.push(ref_item_hash_list_enc); - - let ref_pcd_hash_list_enc = PcdItemEncAttributePublic::new( - "ref_pcd_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.ref_pcd_hash_list.clone()), - ); - enc_attribute_list.push(ref_pcd_hash_list_enc); - - let payload_list_public_enc = PcdItemEncAttributePublic::new( - "payload_list_public".to_owned(), - process_public_enc_key.enc_vec_string(self.payload_list_public.clone()), - ); - enc_attribute_list.push(payload_list_public_enc); - - let audit_code_list_public_enc = PcdItemEncAttributePublic::new( - "audit_code_list_public".to_owned(), - process_public_enc_key.enc_vec_string(self.audit_code_list_public.clone()), - ); - enc_attribute_list.push(audit_code_list_public_enc); - - enc_attribute_list - } - pub fn display_info(&self) { - println!("PaymentsPublicAttributeGroup:"); - println!("For SP Address List: {:?}", self.for_sp_address_list); - println!("Goal List: {:?}", self.goal_list); - println!("Provider Type: {}", self.provider_type); - println!( - "commit PCD Hash List: {:?}", - self.commit_pcd_hash_list - ); - println!("Order PCD Hash List: {:?}", self.order_pcd_hash_list); - println!("Invoice PCD Hash List: {:?}", self.invoice_pcd_hash_list); - println!("Pay PCD Hash List: {:?}", self.pay_pcd_hash_list); - println!("Ref Item Hash List: {:?}", self.ref_item_hash_list); - println!("Ref PCD Hash List: {:?}", self.ref_pcd_hash_list); - println!("Payload List Public: {:?}", self.payload_list_public); - println!("Audit Code List Public: {:?}", self.audit_code_list_public); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PaymentsRoleConfidentialAttributeGroup { - pub payload_list_confidential: Vec, - pub audit_code_list_confidential: Vec, -} - -impl PaymentsRoleConfidentialAttributeGroup { - pub fn new( - payload_list_confidential: Vec, - audit_code_list_confidential: Vec, - ) -> Self { - PaymentsRoleConfidentialAttributeGroup { - payload_list_confidential, - audit_code_list_confidential, - } - } - pub fn display_info(&self) { - println!("PaymentsRoleConfidentialAttributeGroup:"); - println!( - "Confidential Payload List: {:?}", - self.payload_list_confidential - ); - println!( - "Confidential Audit Code List: {:?}", - self.audit_code_list_confidential - ); - } - - pub fn enc_group(&self) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - // tag_list - let mut enc_payload_list_confidential = - KeyEncryption::new(Some("payload_list_confidential".to_owned()), None, None); - if let Ok(_new) = enc_payload_list_confidential.key_new_random() { - let enc_attribute_payload_list_confidential = PcdItemEncAttributeRoleConfidential::new( - "payload_list_confidential".to_owned(), - enc_payload_list_confidential - .enc_vec_string(self.payload_list_confidential.clone()), - enc_payload_list_confidential, - ); - enc_attribute_list.push(enc_attribute_payload_list_confidential); - } - - // zone_listaudit_code_list_confidential - let mut enc_attribute_audit_code_list_confidential_key = - KeyEncryption::new(Some("zone_list".to_owned()), None, None); - if let Ok(_new) = enc_attribute_audit_code_list_confidential_key.key_new_random() { - let enc_attribute_audit_code_list_confidential = - PcdItemEncAttributeRoleConfidential::new( - "zone_list".to_owned(), - enc_attribute_audit_code_list_confidential_key - .enc_vec_string(self.audit_code_list_confidential.clone()), - enc_attribute_audit_code_list_confidential_key, - ); - enc_attribute_list.push(enc_attribute_audit_code_list_confidential); - } - - return enc_attribute_list; - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PaymentsPrivateAttributeGroup { - pub payload_list_private: Vec, - pub audit_code_private: String, -} - -impl PaymentsPrivateAttributeGroup { - pub fn new(payload_list_private: Vec, audit_code_private: String) -> Self { - PaymentsPrivateAttributeGroup { - payload_list_private, - audit_code_private, - } - } - pub fn display_info(&self) { - println!("PaymentsRoleConfidentialAttributeGroup:"); - println!("Confidential Payload List: {:?}", self.payload_list_private); - println!( - "Confidential Audit Code List: {:?}", - self.audit_code_private - ); - } - - pub fn enc_group(&self, Member_enc_key: KeyEncryption) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let payload_list_private_enc = PcdItemEncAttributePrivate::new( - "payload_list".to_owned(), - Member_enc_key.enc_vec_string(self.payload_list_private.clone()), - ); - enc_attribute_list.push(payload_list_private_enc); - - let audit_code_private_enc = PcdItemEncAttributePrivate::new( - "audit_code_private".to_owned(), - Member_enc_key.enc_string(self.audit_code_private.clone()), - ); - enc_attribute_list.push(audit_code_private_enc); - - enc_attribute_list - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Payments { - pub item: Item, - pub public_attribute_group: PaymentsPublicAttributeGroup, - pub role_confidential_attribute_group: PaymentsRoleConfidentialAttributeGroup, - pub private_attribute_group: PaymentsPrivateAttributeGroup, -} - -impl Payments { - pub const ITEM_NAME: &'static str = "Payments"; - pub fn new( - mut item: Item, - public_attribute_group: PaymentsPublicAttributeGroup, - role_confidential_attribute_group: PaymentsRoleConfidentialAttributeGroup, - private_attribute_group: PaymentsPrivateAttributeGroup, - ) -> Self { - item.name = Self::ITEM_NAME.to_string(); - Payments { - item, - public_attribute_group, - role_confidential_attribute_group, - private_attribute_group, - } - } - pub fn enc( - &self, - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - ) -> PcdItemGenericEnc { - let enc_metadata_contract_public = self - .public_attribute_group - .enc_group(process_public_enc_key.clone()); - - let enc_role_confidential_attribute_group = - self.role_confidential_attribute_group.enc_group(); - - let enc_metadata_private = self - .private_attribute_group - .enc_group(Member_private_enc_key.clone()); - - PcdItemGenericEnc::new( - self.item - .enc(process_public_enc_key, Member_private_enc_key), - Some(enc_metadata_contract_public), - Some(enc_role_confidential_attribute_group), - Some(enc_metadata_private), - ) - } - pub fn display_info(&self) { - println!("Payments:"); - println!("Item:"); - self.item.display_info(); // Affiche les informations de l'objet `item` - - println!("Public Attribute Group:"); - self.public_attribute_group.display_info(); // Affiche les informations du groupe d'attributs publics - - println!("Role Confidential Attribute Group:"); - self.role_confidential_attribute_group.display_info(); // Affiche les informations du groupe d'attributs confidentiels - - println!("Private Attribute Group:"); - self.private_attribute_group.display_info(); // Affiche les informations du groupe d'attributs privés - } -} diff --git a/src/models/item_peer.rs b/src/models/item_peer.rs deleted file mode 100644 index 846a702..0000000 --- a/src/models/item_peer.rs +++ /dev/null @@ -1,233 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - item::Item, key_encryption::KeyEncryption, - pcd_item_enc_attribute_private::PcdItemEncAttributePrivate, - pcd_item_enc_attribute_public::PcdItemEncAttributePublic, - pcd_item_generic_enc::PcdItemGenericEnc, -}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PeerPublicAttributeGroup { - pub sp_address: String, - pub domain: String, - pub ip_address: String, - pub pow_difficulty: u32, - pub pow_pattern: String, - pub pow_prefix: String, - pub data_size_max: i64, - pub timestamp_delay_max: u64, - pub daily_hash_list: Vec, - pub daily_sp_tx_mine_list: Vec, - pub daily_sp_tx_mine_reward_list: Vec, -} - -impl PeerPublicAttributeGroup { - pub fn new( - sp_address: String, - domain: String, - ip_address: String, - pow_difficulty: u32, - pow_pattern: String, - pow_prefix: String, - data_size_max: i64, - timestamp_delay_max: u64, - daily_hash_list: Vec, - daily_sp_tx_mine_list: Vec, - daily_sp_tx_mine_reward_list: Vec, - ) -> Self { - PeerPublicAttributeGroup { - sp_address, - domain, - ip_address, - pow_difficulty, - pow_pattern, - pow_prefix, - data_size_max, - timestamp_delay_max, - daily_hash_list, - daily_sp_tx_mine_list, - daily_sp_tx_mine_reward_list, - } - } - pub fn enc_group( - &self, - process_public_enc_key: KeyEncryption, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let sp_address_enc = PcdItemEncAttributePublic::new( - "sp_address".to_owned(), - process_public_enc_key.enc_string(self.sp_address.clone()), - ); - enc_attribute_list.push(sp_address_enc); - - let domain_enc = PcdItemEncAttributePublic::new( - "domain".to_owned(), - process_public_enc_key.enc_string(self.domain.clone()), - ); - enc_attribute_list.push(domain_enc); - - let ip_address_enc = PcdItemEncAttributePublic::new( - "ip_address".to_owned(), - process_public_enc_key.enc_string(self.ip_address.clone()), - ); - enc_attribute_list.push(ip_address_enc); - - let pow_difficulty_enc = PcdItemEncAttributePublic::new( - "pow_difficulty".to_owned(), - process_public_enc_key.enc_u32(self.pow_difficulty), - ); - enc_attribute_list.push(pow_difficulty_enc); - - let pow_pattern_enc = PcdItemEncAttributePublic::new( - "pow_pattern".to_owned(), - process_public_enc_key.enc_string(self.pow_pattern.clone()), - ); - enc_attribute_list.push(pow_pattern_enc); - - let pow_prefix_enc = PcdItemEncAttributePublic::new( - "pow_prefix".to_owned(), - process_public_enc_key.enc_string(self.pow_prefix.clone()), - ); - enc_attribute_list.push(pow_prefix_enc); - - let data_size_max_enc = PcdItemEncAttributePublic::new( - "data_size_max".to_owned(), - process_public_enc_key.enc_i64(self.data_size_max), - ); - enc_attribute_list.push(data_size_max_enc); - - let timestamp_delay_max_enc = PcdItemEncAttributePublic::new( - "timestamp_delay_max".to_owned(), - process_public_enc_key.enc_u64(self.timestamp_delay_max), - ); - enc_attribute_list.push(timestamp_delay_max_enc); - - let daily_hash_list_enc = PcdItemEncAttributePublic::new( - "daily_hash_list".to_owned(), - process_public_enc_key.enc_vec_string(self.daily_hash_list.clone()), - ); - enc_attribute_list.push(daily_hash_list_enc); - - let daily_sp_tx_mine_list_enc = PcdItemEncAttributePublic::new( - "daily_sp_tx_mine_list".to_owned(), - process_public_enc_key.enc_vec_string(self.daily_sp_tx_mine_list.clone()), - ); - enc_attribute_list.push(daily_sp_tx_mine_list_enc); - - let daily_sp_tx_mine_reward_list_enc = PcdItemEncAttributePublic::new( - "daily_sp_tx_mine_reward_list".to_owned(), - process_public_enc_key.enc_vec_string(self.daily_sp_tx_mine_reward_list.clone()), - ); - enc_attribute_list.push(daily_sp_tx_mine_reward_list_enc); - - enc_attribute_list - } - pub fn display_info(&self) { - println!("PeerPublicAttributeGroup:"); - println!("SP Address: {}", self.sp_address); - println!("Domain: {}", self.domain); - println!("IP Address: {}", self.ip_address); - println!("PoW Difficulty: {}", self.pow_difficulty); - println!("PoW Pattern: {}", self.pow_pattern); - println!("PoW Prefix: {}", self.pow_prefix); - println!("Data Size Max: {}", self.data_size_max); - println!("Timestamp Delay Max: {}", self.timestamp_delay_max); - println!("Daily Hash List: {:?}", self.daily_hash_list); - println!("Daily SP Tx Mine List: {:?}", self.daily_sp_tx_mine_list); - println!( - "Daily SP Tx Mine Reward List: {:?}", - self.daily_sp_tx_mine_reward_list - ); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PeerPrivateAttributeGroup { - pub config: String, // Assuming it's a simple string for now -} - -impl PeerPrivateAttributeGroup { - pub fn new(config: String) -> Self { - PeerPrivateAttributeGroup { config } - } - pub fn display_info(&self) { - println!("PeerPrivateAttributeGroup:"); - println!("Config: {}", self.config); - } - - pub fn enc_group(&self, Member_enc_key: KeyEncryption) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let config_enc = PcdItemEncAttributePrivate::new( - "config".to_owned(), - Member_enc_key.enc_string(self.config.clone()), - ); - enc_attribute_list.push(config_enc); - - enc_attribute_list - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Peer { - pub item: Item, - pub layer_list: Vec, - pub public_attribute_group: PeerPublicAttributeGroup, - pub private_attribute_group: PeerPrivateAttributeGroup, -} - -impl Peer { - pub const ITEM_NAME: &'static str = "peer"; - pub fn new( - mut item: Item, - layer_list: Vec, - public_attribute_group: PeerPublicAttributeGroup, - private_attribute_group: PeerPrivateAttributeGroup, - ) -> Self { - item.name = Self::ITEM_NAME.to_string(); - Peer { - item, - layer_list, - public_attribute_group, - private_attribute_group, - } - } - pub fn enc( - &self, - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - ) -> PcdItemGenericEnc { - let enc_metadata_contract_public = self - .public_attribute_group - .enc_group(process_public_enc_key.clone()); - - let enc_metadata_private = self - .private_attribute_group - .enc_group(Member_private_enc_key.clone()); - - PcdItemGenericEnc::new( - self.item - .enc(process_public_enc_key, Member_private_enc_key), - Some(enc_metadata_contract_public), - None, - Some(enc_metadata_private), - ) - } - pub fn display_info(&self) { - println!("Peer:"); - println!("Item:"); - self.item.display_info(); // Affiche les informations de l'objet `item` - - println!("Layer List: {:?}", self.layer_list); - - println!("Peer Public Attribute Group:"); - self.public_attribute_group.display_info(); // Affiche les informations du groupe d'attributs publics - - println!("Peer Private Attribute Group:"); - self.private_attribute_group.display_info(); // Affiche les informations du groupe d'attributs privés - } -} diff --git a/src/models/item_process.rs b/src/models/item_process.rs deleted file mode 100644 index d2cfece..0000000 --- a/src/models/item_process.rs +++ /dev/null @@ -1,86 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - item::Item, key_encryption::KeyEncryption, - pcd_item_enc_attribute_public::PcdItemEncAttributePublic, - pcd_item_generic_enc::PcdItemGenericEnc, roles_group::RolesGroup, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct ProcessPublicAttributeGroup { - // Fields for public attributes - // Example field - pub roles_group: RolesGroup, -} - -impl ProcessPublicAttributeGroup { - pub fn new(roles_group: RolesGroup) -> Self { - ProcessPublicAttributeGroup { roles_group } - } - pub fn display_info(&self) { - println!("ProcessPublicAttributeGroup:"); - println!("Roles Group:"); - self.roles_group.display_info(); // Display information for `roles_group` - } - pub fn enc_group( - &self, - process_public_enc_key: KeyEncryption, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - let roles_group_enc = PcdItemEncAttributePublic::new( - "roles_group".to_owned(), - process_public_enc_key.enc_roles_group(self.roles_group.clone()), - ); - enc_attribute_list.push(roles_group_enc); - enc_attribute_list - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Process { - pub item: Item, - pub item_process_public_attribute_group: ProcessPublicAttributeGroup, -} - -impl Process { - pub const ITEM_NAME: &'static str = "process"; - pub fn new( - mut item: Item, - item_process_public_attribute_group: ProcessPublicAttributeGroup, - ) -> Self { - item.name = Self::ITEM_NAME.to_string(); - Process { - item, - item_process_public_attribute_group, - } - } - pub fn display_info(&self) { - println!("Process:"); - println!("Item:"); - self.item.display_info(); // Display information for `item` - - println!("Process Public Attribute Group:"); - self.item_process_public_attribute_group.display_info(); // Display information for `item_process_public_attribute_group` - } - pub fn enc( - &self, - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - ) -> PcdItemGenericEnc { - let enc_metadata_contract_public = self - .item_process_public_attribute_group - .enc_group(process_public_enc_key.clone()); - - PcdItemGenericEnc::new( - self.item - .enc(process_public_enc_key, Member_private_enc_key), - Some(enc_metadata_contract_public), - None, - None, - ) - } - - // Additional methods for Process can be added here -} diff --git a/src/models/key_encryption.rs b/src/models/key_encryption.rs deleted file mode 100644 index 068a32e..0000000 --- a/src/models/key_encryption.rs +++ /dev/null @@ -1,248 +0,0 @@ -use rand::RngCore; - -use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; - -use core::result::Result as CoreResult; - -use super::metadata::Amount; -use super::metadata::Number; -use super::request_pcd::Pcd; -use super::request_prd_confirm::PrdConfirm; -use super::request_prd_key_backup::PrdKeyBackup; -use super::request_prd_key_hello::PrdKeyHello; -use super::request_prd_list::PrdList; -use super::request_prd_message::PrdMessage; -use super::request_prd_response::PrdResponse; -use super::request_prd_update::PrdUpdate; -use super::roles_group::RolesGroup; - -use aes::cipher::consts::U32; -use aes::cipher::generic_array::GenericArray; -use aes_gcm::{ - aead::{AeadInPlace, KeyInit}, - Aes256Gcm, -}; -use rand::rngs::OsRng; - -pub struct Aes256GcmIv96Bit { - pub key: GenericArray, -} - -impl Aes256GcmIv96Bit { - pub fn new() -> Self { - let mut key_bytes = [0u8; 32]; - OsRng.fill_bytes(&mut key_bytes); - let key = GenericArray::from_slice(&key_bytes); - Aes256GcmIv96Bit { key: key.clone() } - } - - pub fn encrypt(&self, data: &[u8]) -> CoreResult, aes_gcm::Error> { - let cipher = Aes256Gcm::new(&self.key); - let mut nonce = [0u8; 12]; - OsRng.fill_bytes(&mut nonce); - - let mut buffer = data.to_vec(); - cipher.encrypt_in_place(GenericArray::from_slice(&nonce), b"", &mut buffer)?; - - Ok([nonce.to_vec(), buffer].concat()) - } - - pub fn decrypt(&self, data: &[u8]) -> CoreResult, aes_gcm::Error> { - if data.len() < 12 { - return Err(aes_gcm::Error); // Remplacer par une erreur appropriée - } - - let (nonce, encrypted_data) = data.split_at(12); - let mut buffer = encrypted_data.to_vec(); - let cipher = Aes256Gcm::new(&self.key); - cipher.decrypt_in_place(GenericArray::from_slice(nonce), b"", &mut buffer)?; - - Ok(buffer) - } - pub fn encrypt_string(&self, data: &str) -> CoreResult { - match self.encrypt(data.as_bytes()) { - Ok(encrypted_data) => Ok(base64::encode(encrypted_data)), - Err(_) => Err("Erreur de chiffrement".to_string()), - } - } - - pub fn decrypt_string(&self, data: &str) -> CoreResult { - let decoded_data = match base64::decode(data) { - Ok(data) => data, - Err(_) => return Err("Erreur de décodage Base64".to_string()), - }; - - match self.decrypt(&decoded_data) { - Ok(decrypted_data) => match String::from_utf8(decrypted_data) { - Ok(text) => Ok(text), - Err(_) => Err("Erreur de conversion UTF-8".to_string()), - }, - Err(_) => Err("Erreur de déchiffrement".to_string()), - } - } - pub fn export_key(&self) -> String { - base64::encode(&self.key) - } - - pub fn import_key(encoded_key: &str) -> CoreResult { - match base64::decode(encoded_key) { - Ok(decoded_key) => { - if decoded_key.len() == 32 { - let key = GenericArray::from_slice(&decoded_key); - Ok(Aes256GcmIv96Bit { key: key.clone() }) - } else { - Err("La taille de la clé n'est pas valide".to_string()) - } - } - Err(_) => Err("Échec du décodage de la clé".to_string()), - } - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct KeyEncryption { - pub attribute_name: Option, - pub key: Option, - pub algorithm: Option, -} - -impl KeyEncryption { - pub fn new( - attribute_name: Option, - key: Option, - algorithm: Option, - ) -> Self { - KeyEncryption { - attribute_name, - key, - algorithm, - } - } - pub fn key_new_random(&mut self) -> CoreResult { - let new_key = Aes256GcmIv96Bit::new().export_key(); - self.key = Some(new_key.clone()); - Ok(new_key) - } - pub fn encode(&self, data: String) -> CoreResult { - if let Some(ref key) = self.key { - let decoded_key = Aes256GcmIv96Bit::import_key(key)?; - let encrypted_data = decoded_key.encrypt_string(&data)?; - Ok(encrypted_data) - } else { - Err("Aucune clé n'est définie".to_string()) - } - } - - pub fn decode(&self, encrypted_data: String) -> CoreResult { - if let Some(ref key) = self.key { - let decoded_key = Aes256GcmIv96Bit::import_key(key)?; - let decrypted_data = decoded_key.decrypt_string(&encrypted_data)?; - Ok(decrypted_data) - } else { - Err("Aucune clé n'est définie".to_string()) - } - } - - pub fn display_info(&self) { - println!("KeyEncryption:"); - println!("Attribute Name: {:?}", self.attribute_name); - println!("Key: {:?}", self.key); - println!("Algorithm: {:?}", self.algorithm); - } - pub fn enc(&self, data: Value) -> String { - let data_string = serde_json::to_string(&data).unwrap_or_else(|_| "".to_string()); - self.encode(data_string).unwrap_or_else(|_| "".to_string()) - } - pub fn enc_string(&self, data: String) -> String { - self.enc(Value::String(data)) - } - pub fn enc_i64(&self, data: i64) -> String { - self.enc(Value::Number(data.into())) - } - pub fn enc_u64(&self, data: u64) -> String { - self.enc(Value::Number(data.into())) - } - pub fn enc_u32(&self, data: u32) -> String { - self.enc(Value::Number(data.into())) - } - pub fn enc_vec_string(&self, list: Vec) -> String { - self.enc(Value::Array(list.into_iter().map(Value::String).collect())) - } - pub fn enc_vec_key_encryption(&self, list: Vec) -> String { - // Utilisez `serde_json::to_value` pour convertir chaque `KeyEncryption` en `Value` - let json_list: Vec = list - .into_iter() - .map(|key_enc| serde_json::to_value(key_enc).unwrap_or_else(|_| json!({}))) - .collect(); - - self.enc(Value::Array(json_list)) - } - pub fn enc_amount(&self, amount: Amount) -> String { - let amount_value = serde_json::to_value(amount).unwrap_or_else(|_| json!({})); - self.enc(amount_value) - } - pub fn enc_number(&self, number: Number) -> String { - let number_value = serde_json::to_value(number).unwrap_or_else(|_| json!({})); - self.enc(number_value) - } - pub fn enc_bool(&self, data: bool) -> String { - self.enc(Value::Bool(data)) - } - pub fn enc_vec_u32(&self, list: Vec) -> String { - let number_list: Vec = list - .into_iter() - .map(|num| Value::Number(serde_json::Number::from(num))) - .collect(); - - self.enc(Value::Array(number_list)) - } - - pub fn enc_vec_i64(&self, list: Vec) -> String { - let number_list: Vec = list - .into_iter() - .map(|num| Value::Number(serde_json::Number::from(num))) - .collect(); - - self.enc(Value::Array(number_list)) - } - pub fn enc_vec_bool(&self, list: Vec) -> String { - self.enc(Value::Array(list.into_iter().map(Value::Bool).collect())) - } - pub fn enc_pcd(&self, pcd: Pcd) -> String { - let pcd_value = serde_json::to_value(pcd).unwrap_or_else(|_| json!({})); - self.enc(pcd_value) - } - pub fn enc_prd_update(&self, prd: PrdUpdate) -> String { - let prd_value = serde_json::to_value(prd).unwrap_or_else(|_| json!({})); - self.enc(prd_value) - } - pub fn enc_prd_list(&self, pcd: PrdList) -> String { - let prd_value = serde_json::to_value(pcd).unwrap_or_else(|_| json!({})); - self.enc(prd_value) - } - pub fn enc_prd_response(&self, prd: PrdResponse) -> String { - let prd_value = serde_json::to_value(prd).unwrap_or_else(|_| json!({})); - self.enc(prd_value) - } - pub fn enc_prd_confirm(&self, prd: PrdConfirm) -> String { - let prd_value = serde_json::to_value(prd).unwrap_or_else(|_| json!({})); - self.enc(prd_value) - } - pub fn enc_prd_message(&self, prd: PrdMessage) -> String { - let prd_value = serde_json::to_value(prd).unwrap_or_else(|_| json!({})); - self.enc(prd_value) - } - pub fn enc_prd_key_backup(&self, prd: PrdKeyBackup) -> String { - let prd_value = serde_json::to_value(prd).unwrap_or_else(|_| json!({})); - self.enc(prd_value) - } - pub fn enc_prd_key_hello(&self, prd: PrdKeyHello) -> String { - let prd_value = serde_json::to_value(prd).unwrap_or_else(|_| json!({})); - self.enc(prd_value) - } - pub fn enc_roles_group(&self, roles: RolesGroup) -> String { - let roles_value = serde_json::to_value(roles).unwrap_or_else(|_| json!({})); - self.enc(roles_value) - } -} diff --git a/src/models/message.rs b/src/models/message.rs deleted file mode 100644 index 14dd598..0000000 --- a/src/models/message.rs +++ /dev/null @@ -1,108 +0,0 @@ -use chrono::Utc; - -use sha2::{Digest, Sha256}; - -use serde::{Deserialize, Serialize}; - -use super::shared_peer::Peer; -use super::shared_process::Process; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Pow { - pub data_hash: String, - timestamp: Option, - pub nonce: Option, - pub pathern: String, - pub difficulty: usize, -} - -impl Pow { - pub fn new(data_hash: String, pathern: String, difficulty: usize) -> Self { - let mut pow = Pow { - data_hash, - nonce: None, - timestamp: None, - pathern, - difficulty, - }; - pow.find(); - return pow; - } - pub fn display_info(&self) { - println!("Pow:"); - println!("Data Hash: {}", self.data_hash); - println!("Timestamp: {}", self.timestamp.as_ref().unwrap_or(&0)); - println!("Nonce: {}", self.nonce.as_ref().unwrap_or(&0)); - println!("Pathern: {}", self.pathern); - println!("Difficulty: {}", self.difficulty); - } - pub fn find(&mut self) { - let mut nonce: u64 = 0; - loop { - // Mise à jour du timestamp à chaque itération - let current_timestamp = Utc::now().timestamp() as u64; - self.timestamp = Some(current_timestamp); - - // Créer une chaîne avec le hash actuel, le timestamp et le nonce - let data: String = format!("{}{}{}", self.data_hash, current_timestamp, nonce); - - // Calculer le hash SHA-256 - let mut hasher = Sha256::new(); - hasher.update(data); - let result = hasher.finalize(); - let hash_str: String = format!("{:x}", result); - - // Vérifier si le hash correspond au motif de difficulté - if hash_str.starts_with(&"0".repeat(self.difficulty as usize)) { - self.nonce = Some(nonce); - break; - } - - nonce += 1; - } - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct `Envelope` { - pub shared_peer_list: Vec, - pub shared_process_list: Vec, - pub faucet_sp_address: String, - pub pow: Pow, // Assuming Pow is a predefined struct -} - -impl `Envelope` { - pub fn new( - shared_peer_list: Vec, - shared_process_list: Vec, - faucet_sp_address: String, - pow_data_hash: String, - pow_pathern: String, - pow_difficulty: usize, - ) -> Self { - let pow: Pow = Pow::new(pow_data_hash, pow_pathern, pow_difficulty); - `Envelope` { - shared_peer_list, - shared_process_list, - faucet_sp_address, - pow, - } - } - pub fn display_info(&self) { - println!("Message:"); - println!("Shared Peer List:"); - for shared_peer in &self.shared_peer_list { - shared_peer.display_info(); // Assuming Peers has a display_info method - } - - println!("Shared Process List:"); - for shared_process in &self.shared_process_list { - shared_process.display_info(); // Assuming Process has a display_info method - } - - println!("Faucet SP Address: {}", self.faucet_sp_address); - println!("PoW:"); - self.pow.display_info(); // Assuming Pow has a display_info method - } -} diff --git a/src/models/message_client.rs b/src/models/message_client.rs deleted file mode 100644 index f7d2cfa..0000000 --- a/src/models/message_client.rs +++ /dev/null @@ -1,51 +0,0 @@ -use super::{message::Message, shared_peer::Peer, shared_process::Process}; - -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct `Envelope` Client { - pub `Envelope` : `Envelope` , // Assuming `Envelope` is a predefined struct - pub request_enc: String, - pub request_hash: String, -} - -impl `Envelope` Client { - pub fn new( - request_enc: String, - request_hash: String, - `Envelope` _shared_peer_list: Vec, - `Envelope` _shared_process_list: Vec, - `Envelope` _faucet_sp_address: String, - pow_pathern: String, - pow_difficulty: usize, - ) -> Self { - let pow_data_hash = request_hash; - let `Envelope` : `Envelope` = `Envelope` ::new( - `Envelope` _shared_peer_list, - `Envelope` _shared_process_list, - `Envelope` _faucet_sp_address, - pow_data_hash.clone(), - pow_pathern, - pow_difficulty, - ); - `Envelope` Client { - `Envelope` , - request_enc, - request_hash: pow_data_hash, - } - } - pub fn send(&self) { - for shared_peer in &self.`Envelope`.shared_peer_list { - shared_peer.send_message_client(self.clone()); // Assuming Peers has a send method - } - } - pub fn display_info(&self) { - println!("EnvelopeClient:"); - println!("Message:"); - self.`Envelope`.display_info(); // Assuming `Envelope` has a display_info method - println!("Envelope hash: {}", self.request_hash); - - println!("Request Enc: {}", self.request_enc); - } -} diff --git a/src/models/message_connect.rs b/src/models/message_connect.rs deleted file mode 100644 index bd3811d..0000000 --- a/src/models/message_connect.rs +++ /dev/null @@ -1,19 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::message::Message; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct `Envelope` Connect { - pub `Envelope` : `Envelope` , // Assuming `Envelope` is a predefined struct -} - -impl `Envelope` Connect { - pub fn new(message: `Envelope` ) -> Self { - `Envelope` Connect { `Envelope` } - } - pub fn display_info(&self) { - println!("EnvelopeConnect:"); - println!("Message:"); - self.`Envelope`.display_info(); // Assuming `Envelope` has a display_info method - } -} diff --git a/src/models/metadata.rs b/src/models/metadata.rs deleted file mode 100644 index fa6ba62..0000000 --- a/src/models/metadata.rs +++ /dev/null @@ -1,145 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::key_encryption::KeyEncryption; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Number { - pub fixed_state: bool, - pub number: i32, - pub number_unit: String, -} - -impl Number { - // Constructor for Number struct - pub fn new(fixed_state: bool, number: i32, number_unit: String) -> Self { - Number { - fixed_state, - number, - number_unit, - } - } - pub fn display_info(&self) { - println!("Number:"); - println!("Fixed State: {}", self.fixed_state); - println!("Number: {}", self.number); - println!("Number Unit: {}", self.number_unit); - } - - // Additional methods for Number can be added here. -} - -// Struct for representing an amount with various attributes. -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Amount { - pub timestamp: u64, - pub change_source_list: Vec, - pub amount_cent: i64, - pub amount_unit: String, - pub amount_unit_ref: String, // This can be a reference to an external unit system. -} - -impl Amount { - // Constructor for Amount struct - pub fn new( - timestamp: u64, - change_source_list: Vec, - amount_cent: i64, - amount_unit: String, - amount_unit_ref: String, - ) -> Self { - Amount { - timestamp, - change_source_list, - amount_cent, - amount_unit, - amount_unit_ref, - } - } - pub fn display(&self) -> String { - format!( - "Amount: {} {} {} {} {}", - self.timestamp, - self.change_source_list.join(","), - self.amount_cent, - self.amount_unit, - self.amount_unit_ref - ) - } - pub fn display_info(&self) { - println!("Amount:"); - println!("Timestamp: {}", self.timestamp); - println!("Change Source List: {:?}", self.change_source_list); - println!("Amount cent: {}", self.amount_cent); - println!("Amount Unit: {}", self.amount_unit); - println!("Amount Unit Reference: {}", self.amount_unit_ref); - } - // Additional methods for Amount can be added here. -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct MetaData { - pub tag_list: Vec, - pub zone_list: Vec, - pub label_list: Vec, - pub ref_list: Vec, - pub data_list: Vec, - pub amount: Amount, - pub number: Number, - pub render_template_list: Vec, - pub legal_text_list: Vec, - pub key_list: Vec, -} - -impl MetaData { - pub fn new( - tag_list: Vec, - zone_list: Vec, - label_list: Vec, - ref_list: Vec, - data_list: Vec, - amount: Amount, - number: Number, - render_template_list: Vec, - legal_text_list: Vec, - key_list: Vec, - ) -> Self { - MetaData { - tag_list, - zone_list, - label_list, - ref_list, - data_list, - amount, - number, - render_template_list, - legal_text_list, - key_list, - } - } - pub fn display_info(&self) { - println!("MetaData:"); - println!("Tag List: {:?}", self.tag_list); - println!("Zone List: {:?}", self.zone_list); - println!("Label List: {:?}", self.label_list); - println!("Ref List: {:?}", self.ref_list); - println!("Data List: {:?}", self.data_list); - - println!("Amount:"); - self.amount.display_info(); // Assuming Amount has a display_info method - - println!("Number:"); - self.number.display_info(); // Assuming Number has a display_info method - - println!("Render Template List: {:?}", self.render_template_list); - println!("Legal Text List: {:?}", self.legal_text_list); - - println!("Key List:"); - for key in &self.key_list { - key.display_info(); // Assuming KeyEncryption has a display_info method - } - } - - // Methods for manipulating MetaData can be added here. -} diff --git a/src/models/metadata_contract_public.rs b/src/models/metadata_contract_public.rs deleted file mode 100644 index 0c0844a..0000000 --- a/src/models/metadata_contract_public.rs +++ /dev/null @@ -1,143 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - key_encryption::KeyEncryption, metadata::MetaData, - pcd_item_enc_attribute_public::PcdItemEncAttributePublic, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct MetadataContractPublic { - pub meta_data: MetaData, -} - -impl MetadataContractPublic { - pub fn new(meta_data: MetaData) -> Self { - MetadataContractPublic { meta_data } - } - pub fn display_info(&self) { - println!("MetadataContractPublic:"); - // Assuming MetaData has a display_info method - self.meta_data.display_info(); // Display information for `meta_data` - } - pub fn enc_list( - &self, - process_public_enc_key: KeyEncryption, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let enc_attribute_tag_list_key = KeyEncryption::new( - Some("tag_list".to_owned()), - process_public_enc_key.key.clone(), - process_public_enc_key.algorithm.clone(), - ); - let enc_attribute_tag_list = PcdItemEncAttributePublic::new( - "tag_list".to_owned(), - enc_attribute_tag_list_key.enc_vec_string(self.meta_data.tag_list.clone()), - ); - enc_attribute_list.push(enc_attribute_tag_list); - - let enc_attribute_zone_list_key = KeyEncryption::new( - Some("zone_list".to_owned()), - process_public_enc_key.key.clone(), - process_public_enc_key.algorithm.clone(), - ); - let enc_attribute_zone_list = PcdItemEncAttributePublic::new( - "zone_list".to_owned(), - enc_attribute_zone_list_key.enc_vec_string(self.meta_data.zone_list.clone()), - ); - enc_attribute_list.push(enc_attribute_zone_list); - - let enc_attribute_label_list_key = KeyEncryption::new( - Some("label_list".to_owned()), - process_public_enc_key.key.clone(), - process_public_enc_key.algorithm.clone(), - ); - let enc_attribute_label_list = PcdItemEncAttributePublic::new( - "label_list".to_owned(), - enc_attribute_label_list_key.enc_vec_string(self.meta_data.label_list.clone()), - ); - enc_attribute_list.push(enc_attribute_label_list); - - let enc_attribute_ref_list_key = KeyEncryption::new( - Some("ref_list".to_owned()), - process_public_enc_key.key.clone(), - process_public_enc_key.algorithm.clone(), - ); - let enc_attribute_ref_list = PcdItemEncAttributePublic::new( - "ref_list".to_owned(), - enc_attribute_ref_list_key.enc_vec_string(self.meta_data.ref_list.clone()), - ); - enc_attribute_list.push(enc_attribute_ref_list); - - let enc_attribute_data_list_key = KeyEncryption::new( - Some("data_list".to_owned()), - process_public_enc_key.key.clone(), - process_public_enc_key.algorithm.clone(), - ); - let enc_attribute_data_list = PcdItemEncAttributePublic::new( - "data_list".to_owned(), - enc_attribute_data_list_key.enc_vec_string(self.meta_data.data_list.clone()), - ); - enc_attribute_list.push(enc_attribute_data_list); - - let enc_attribute_amount_key = KeyEncryption::new( - Some("amount".to_owned()), - process_public_enc_key.key.clone(), - process_public_enc_key.algorithm.clone(), - ); - let enc_attribute_amount = PcdItemEncAttributePublic::new( - "amount".to_owned(), - enc_attribute_amount_key.enc_amount(self.meta_data.amount.clone()), - ); - enc_attribute_list.push(enc_attribute_amount); - - let enc_attribute_number_key = KeyEncryption::new( - Some("number".to_owned()), - process_public_enc_key.key.clone(), - process_public_enc_key.algorithm.clone(), - ); - let enc_attribute_number = PcdItemEncAttributePublic::new( - "number".to_owned(), - enc_attribute_number_key.enc_number(self.meta_data.number.clone()), - ); - enc_attribute_list.push(enc_attribute_number); - - let enc_attribute_render_template_list_key = KeyEncryption::new( - Some("render_template_list".to_owned()), - process_public_enc_key.key.clone(), - process_public_enc_key.algorithm.clone(), - ); - let enc_attribute_render_template_list = PcdItemEncAttributePublic::new( - "render_template_list".to_owned(), - enc_attribute_render_template_list_key - .enc_vec_string(self.meta_data.render_template_list.clone()), - ); - enc_attribute_list.push(enc_attribute_render_template_list); - - let enc_attribute_legal_text_list_key = KeyEncryption::new( - Some("legal_text_list".to_owned()), - process_public_enc_key.key.clone(), - process_public_enc_key.algorithm.clone(), - ); - let enc_attribute_legal_text_list = PcdItemEncAttributePublic::new( - "legal_text_list".to_owned(), - enc_attribute_legal_text_list_key - .enc_vec_string(self.meta_data.legal_text_list.clone()), - ); - enc_attribute_list.push(enc_attribute_legal_text_list); - - let enc_attribute_key_list_key = KeyEncryption::new( - Some("key_list".to_owned()), - process_public_enc_key.key.clone(), - process_public_enc_key.algorithm.clone(), - ); - let enc_attribute_key_list = PcdItemEncAttributePublic::new( - "key_list".to_owned(), - enc_attribute_key_list_key.enc_vec_key_encryption(self.meta_data.key_list.clone()), - ); - enc_attribute_list.push(enc_attribute_key_list); - - return enc_attribute_list; - } -} diff --git a/src/models/metadata_private.rs b/src/models/metadata_private.rs deleted file mode 100644 index a55473a..0000000 --- a/src/models/metadata_private.rs +++ /dev/null @@ -1,143 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - key_encryption::KeyEncryption, metadata::MetaData, - pcd_item_enc_attribute_private::PcdItemEncAttributePrivate, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct MetadataPrivate { - pub meta_data: MetaData, -} - -impl MetadataPrivate { - pub fn new(meta_data: MetaData) -> Self { - MetadataPrivate { meta_data } - } - pub fn display_info(&self) { - println!("MetadataPrivate:"); - // Assuming MetaData has a display_info method - self.meta_data.display_info(); // Display information for `meta_data` - } - pub fn enc_list( - &self, - Member_private_enc_key: KeyEncryption, - ) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - let enc_attribute_tag_list_key = KeyEncryption::new( - Some("tag_list".to_owned()), - Member_private_enc_key.key.clone(), - Member_private_enc_key.algorithm.clone(), - ); - let enc_attribute_tag_list = PcdItemEncAttributePrivate::new( - "tag_list".to_owned(), - enc_attribute_tag_list_key.enc_vec_string(self.meta_data.tag_list.clone()), - ); - enc_attribute_list.push(enc_attribute_tag_list); - - let enc_attribute_zone_list_key = KeyEncryption::new( - Some("zone_list".to_owned()), - Member_private_enc_key.key.clone(), - Member_private_enc_key.algorithm.clone(), - ); - let enc_attribute_zone_list = PcdItemEncAttributePrivate::new( - "zone_list".to_owned(), - enc_attribute_zone_list_key.enc_vec_string(self.meta_data.zone_list.clone()), - ); - enc_attribute_list.push(enc_attribute_zone_list); - - let enc_attribute_label_list_key = KeyEncryption::new( - Some("label_list".to_owned()), - Member_private_enc_key.key.clone(), - Member_private_enc_key.algorithm.clone(), - ); - let enc_attribute_label_list = PcdItemEncAttributePrivate::new( - "label_list".to_owned(), - enc_attribute_label_list_key.enc_vec_string(self.meta_data.label_list.clone()), - ); - enc_attribute_list.push(enc_attribute_label_list); - - let enc_attribute_ref_list_key = KeyEncryption::new( - Some("ref_list".to_owned()), - Member_private_enc_key.key.clone(), - Member_private_enc_key.algorithm.clone(), - ); - let enc_attribute_ref_list = PcdItemEncAttributePrivate::new( - "ref_list".to_owned(), - enc_attribute_ref_list_key.enc_vec_string(self.meta_data.ref_list.clone()), - ); - enc_attribute_list.push(enc_attribute_ref_list); - - let enc_attribute_data_list_key = KeyEncryption::new( - Some("data_list".to_owned()), - Member_private_enc_key.key.clone(), - Member_private_enc_key.algorithm.clone(), - ); - let enc_attribute_data_list = PcdItemEncAttributePrivate::new( - "data_list".to_owned(), - enc_attribute_data_list_key.enc_vec_string(self.meta_data.data_list.clone()), - ); - enc_attribute_list.push(enc_attribute_data_list); - - let enc_attribute_amount_key = KeyEncryption::new( - Some("amount".to_owned()), - Member_private_enc_key.key.clone(), - Member_private_enc_key.algorithm.clone(), - ); - let enc_attribute_amount = PcdItemEncAttributePrivate::new( - "amount".to_owned(), - enc_attribute_amount_key.enc_amount(self.meta_data.amount.clone()), - ); - enc_attribute_list.push(enc_attribute_amount); - - let enc_attribute_number_key = KeyEncryption::new( - Some("number".to_owned()), - Member_private_enc_key.key.clone(), - Member_private_enc_key.algorithm.clone(), - ); - let enc_attribute_number = PcdItemEncAttributePrivate::new( - "number".to_owned(), - enc_attribute_number_key.enc_number(self.meta_data.number.clone()), - ); - enc_attribute_list.push(enc_attribute_number); - - let enc_attribute_render_template_list_key = KeyEncryption::new( - Some("render_template_list".to_owned()), - Member_private_enc_key.key.clone(), - Member_private_enc_key.algorithm.clone(), - ); - let enc_attribute_render_template_list = PcdItemEncAttributePrivate::new( - "render_template_list".to_owned(), - enc_attribute_render_template_list_key - .enc_vec_string(self.meta_data.render_template_list.clone()), - ); - enc_attribute_list.push(enc_attribute_render_template_list); - - let enc_attribute_legal_text_list_key = KeyEncryption::new( - Some("legal_text_list".to_owned()), - Member_private_enc_key.key.clone(), - Member_private_enc_key.algorithm.clone(), - ); - let enc_attribute_legal_text_list = PcdItemEncAttributePrivate::new( - "legal_text_list".to_owned(), - enc_attribute_legal_text_list_key - .enc_vec_string(self.meta_data.legal_text_list.clone()), - ); - enc_attribute_list.push(enc_attribute_legal_text_list); - - let enc_attribute_key_list_key = KeyEncryption::new( - Some("key_list".to_owned()), - Member_private_enc_key.key.clone(), - Member_private_enc_key.algorithm.clone(), - ); - let enc_attribute_key_list = PcdItemEncAttributePrivate::new( - "key_list".to_owned(), - enc_attribute_key_list_key.enc_vec_key_encryption(self.meta_data.key_list.clone()), - ); - enc_attribute_list.push(enc_attribute_key_list); - - return enc_attribute_list; - } -} diff --git a/src/models/metadata_role_confidential.rs b/src/models/metadata_role_confidential.rs deleted file mode 100644 index 578e1d9..0000000 --- a/src/models/metadata_role_confidential.rs +++ /dev/null @@ -1,152 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - key_encryption::KeyEncryption, metadata::MetaData, - pcd_item_enc_attribute_role_confidential::PcdItemEncAttributeRoleConfidential, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct MetadataRoleConfidential { - pub meta_data: MetaData, -} - -impl MetadataRoleConfidential { - pub fn new(meta_data: MetaData) -> Self { - MetadataRoleConfidential { meta_data } - } - pub fn display_info(&self) { - println!("MetadataRoleConfidential:"); - // Assuming MetaData has a display_info method - self.meta_data.display_info(); // Display information for `meta_data` - } - pub fn enc_list(&self) -> Vec { - let mut enc_attribute_list: Vec = Vec::new(); - - // tag_list - let mut enc_attribute_tag_list_key = - KeyEncryption::new(Some("tag_list".to_owned()), None, None); - if let Ok(_new) = enc_attribute_tag_list_key.key_new_random() { - let enc_attribute_tag_list = PcdItemEncAttributeRoleConfidential::new( - "tag_list".to_owned(), - enc_attribute_tag_list_key.enc_vec_string(self.meta_data.tag_list.clone()), - enc_attribute_tag_list_key, - ); - enc_attribute_list.push(enc_attribute_tag_list); - } - - // zone_list - let mut enc_attribute_zone_list_key = - KeyEncryption::new(Some("zone_list".to_owned()), None, None); - if let Ok(_new) = enc_attribute_zone_list_key.key_new_random() { - let enc_attribute_zone_list = PcdItemEncAttributeRoleConfidential::new( - "zone_list".to_owned(), - enc_attribute_zone_list_key.enc_vec_string(self.meta_data.zone_list.clone()), - enc_attribute_zone_list_key, - ); - enc_attribute_list.push(enc_attribute_zone_list); - } - - // label_list - let mut enc_attribute_label_list_key = - KeyEncryption::new(Some("label_list".to_owned()), None, None); - if let Ok(_new) = enc_attribute_label_list_key.key_new_random() { - let enc_attribute_label_list = PcdItemEncAttributeRoleConfidential::new( - "label_list".to_owned(), - enc_attribute_label_list_key.enc_vec_string(self.meta_data.label_list.clone()), - enc_attribute_label_list_key, - ); - enc_attribute_list.push(enc_attribute_label_list); - } - - // ref_list - let mut enc_attribute_ref_list_key = - KeyEncryption::new(Some("ref_list".to_owned()), None, None); - if let Ok(_new) = enc_attribute_ref_list_key.key_new_random() { - let enc_attribute_ref_list = PcdItemEncAttributeRoleConfidential::new( - "ref_list".to_owned(), - enc_attribute_ref_list_key.enc_vec_string(self.meta_data.ref_list.clone()), - enc_attribute_ref_list_key, - ); - enc_attribute_list.push(enc_attribute_ref_list); - } - - // data_list - let mut enc_attribute_data_list_key = - KeyEncryption::new(Some("data_list".to_owned()), None, None); - if let Ok(_new) = enc_attribute_data_list_key.key_new_random() { - let enc_attribute_data_list = PcdItemEncAttributeRoleConfidential::new( - "data_list".to_owned(), - enc_attribute_data_list_key.enc_vec_string(self.meta_data.data_list.clone()), - enc_attribute_data_list_key, - ); - enc_attribute_list.push(enc_attribute_data_list); - } - - // amount - let mut enc_attribute_amount_key = - KeyEncryption::new(Some("amount".to_owned()), None, None); - if let Ok(_new) = enc_attribute_amount_key.key_new_random() { - let enc_attribute_amount = PcdItemEncAttributeRoleConfidential::new( - "amount".to_owned(), - enc_attribute_amount_key.enc_amount(self.meta_data.amount.clone()), - enc_attribute_amount_key, - ); - enc_attribute_list.push(enc_attribute_amount); - } - - // number - let mut enc_attribute_number_key = - KeyEncryption::new(Some("number".to_owned()), None, None); - if let Ok(_new) = enc_attribute_number_key.key_new_random() { - let enc_attribute_number = PcdItemEncAttributeRoleConfidential::new( - "number".to_owned(), - enc_attribute_number_key.enc_number(self.meta_data.number.clone()), - enc_attribute_number_key, - ); - enc_attribute_list.push(enc_attribute_number); - } - - // render_template_list - let mut enc_attribute_render_template_list_key = - KeyEncryption::new(Some("render_template_list".to_owned()), None, None); - if let Ok(_new) = enc_attribute_render_template_list_key.key_new_random() { - let enc_attribute_render_template_list = PcdItemEncAttributeRoleConfidential::new( - "render_template_list".to_owned(), - enc_attribute_render_template_list_key - .enc_vec_string(self.meta_data.render_template_list.clone()), - enc_attribute_render_template_list_key, - ); - enc_attribute_list.push(enc_attribute_render_template_list); - } - - // legal_text_list - let mut enc_attribute_legal_text_list_key = - KeyEncryption::new(Some("legal_text_list".to_owned()), None, None); - if let Ok(_new) = enc_attribute_legal_text_list_key.key_new_random() { - let enc_attribute_legal_text_list = PcdItemEncAttributeRoleConfidential::new( - "legal_text_list".to_owned(), - enc_attribute_legal_text_list_key - .enc_vec_string(self.meta_data.legal_text_list.clone()), - enc_attribute_legal_text_list_key, - ); - enc_attribute_list.push(enc_attribute_legal_text_list); - } - - // key_list - let mut enc_attribute_key_list_key = - KeyEncryption::new(Some("key_list".to_owned()), None, None); - if let Ok(_new) = enc_attribute_key_list_key.key_new_random() { - let enc_attribute_key_list = PcdItemEncAttributeRoleConfidential::new( - "key_list".to_owned(), - enc_attribute_key_list_key.enc_vec_key_encryption(self.meta_data.key_list.clone()), - enc_attribute_key_list_key, - ); - enc_attribute_list.push(enc_attribute_key_list); - } - - return enc_attribute_list; - } - - // Additional -} diff --git a/src/models/mod.rs b/src/models/mod.rs deleted file mode 100644 index 4e2bf5b..0000000 --- a/src/models/mod.rs +++ /dev/null @@ -1,54 +0,0 @@ -pub mod commit_method; -pub mod condition_cap; -pub mod condition_commit; -pub mod condition_deposit; -pub mod condition_orchestration; -pub mod condition_Payments; -pub mod condition_prd_address_set; -pub mod condition_publish; -pub mod deposit_method; -pub mod item; -pub mod item_artefact; -pub mod item_commit; -pub mod item_deposit; -pub mod item_enum; -pub mod item_Member; -pub mod item_Payments; -pub mod item_peer; -pub mod item_process; -pub mod key_encryption; -pub mod `Envelope` ; -pub mod `Envelope` _client; -pub mod `Envelope` _connect; -pub mod metadata; -pub mod metadata_contract_public; -pub mod metadata_private; -pub mod metadata_role_confidential; -pub mod pagination; -pub mod Payments_method; -pub mod pcd_item_enc; -pub mod pcd_item_enc_attribute_private; -pub mod pcd_item_enc_attribute_public; -pub mod pcd_item_enc_attribute_role_confidential; -pub mod pcd_item_generic_enc; -pub mod request; -pub mod request_pcd; -pub mod request_prd; -pub mod request_prd_confirm; -pub mod request_prd_key_backup; -pub mod request_prd_key_hello; -pub mod request_prd_list; -pub mod request_prd_message; -pub mod request_prd_response; -pub mod request_prd_update; -pub mod role; -pub mod role_artefact; -pub mod role_commit; -pub mod role_deposit; -pub mod role_Member; -pub mod role_Payments; -pub mod role_peer; -pub mod role_process; -pub mod roles_group; -pub mod shared_peer; -pub mod shared_process; diff --git a/src/models/pagination.rs b/src/models/pagination.rs deleted file mode 100644 index 33702b3..0000000 --- a/src/models/pagination.rs +++ /dev/null @@ -1,25 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Pagination { - pub start: usize, - pub number: usize, - pub page_index: usize, -} - -impl Pagination { - pub fn new(start: usize, number: usize, page_index: usize) -> Self { - Pagination { - start, - number, - page_index, - } - } - pub fn display_info(&self) { - println!("Pagination:"); - println!("Start: {}", self.start); - println!("Number: {}", self.number); - println!("Page Index: {}", self.page_index); - } -} diff --git a/src/models/payment_method.rs b/src/models/payment_method.rs deleted file mode 100644 index 438919c..0000000 --- a/src/models/payment_method.rs +++ /dev/null @@ -1,8 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PaymentsMethod { - pub method: String, -} -impl PaymentsMethod {} diff --git a/src/models/pcd_item_enc.rs b/src/models/pcd_item_enc.rs deleted file mode 100644 index 7457c3a..0000000 --- a/src/models/pcd_item_enc.rs +++ /dev/null @@ -1,63 +0,0 @@ -use std::hash::Hash; - -use serde::{Deserialize, Serialize}; - -use super::{ - pcd_item_enc_attribute_private::PcdItemEncAttributePrivate, - pcd_item_enc_attribute_public::PcdItemEncAttributePublic, - pcd_item_enc_attribute_role_confidential::PcdItemEncAttributeRoleConfidential, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PcdItemEnc { - pub version: i64, - pub item_type: String, - pub name: String, - pub pagination_number_per_pcd: u32, - pub pcd_item_enc_attribute_public_list: Vec, - pub pcd_item_enc_attribute_role_confidential_list: Vec, - pub pcd_item_enc_attribute_private_list: Vec, -} - -impl PcdItemEnc { - pub fn new( - version: i64, - item_type: String, - name: String, - pagination_number_per_pcd: u32, - pcd_item_enc_attribute_public_list: Vec, - pcd_item_enc_attribute_role_confidential_list: Vec, - pcd_item_enc_attribute_private_list: Vec, - ) -> Self { - PcdItemEnc { - version, - item_type, - name, - pagination_number_per_pcd, - pcd_item_enc_attribute_public_list, - pcd_item_enc_attribute_role_confidential_list, - pcd_item_enc_attribute_private_list, - } - } - - pub fn display_info(&self) { - println!("PcdItemEnc:"); - println!("Public Attributes:"); - for attr in &self.pcd_item_enc_attribute_public_list { - attr.display_info(); - } - - println!("Role Confidential Attributes:"); - for attr in &self.pcd_item_enc_attribute_role_confidential_list { - attr.display_info(); - } - - println!("Private Attributes:"); - for attr in &self.pcd_item_enc_attribute_private_list { - attr.display_info(); - } - } - - // Additional methods for PcdItemEnc can be added here -} diff --git a/src/models/pcd_item_enc_attribute_private.rs b/src/models/pcd_item_enc_attribute_private.rs deleted file mode 100644 index 974e3a4..0000000 --- a/src/models/pcd_item_enc_attribute_private.rs +++ /dev/null @@ -1,27 +0,0 @@ -use std::hash::Hash; - -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PcdItemEncAttributePrivate { - pub attribute_name: String, - pub data_enc: String, // Assuming the encrypted data is represented as a String -} - -impl PcdItemEncAttributePrivate { - pub fn new(attribute_name: String, data_enc: String) -> Self { - PcdItemEncAttributePrivate { - attribute_name, - data_enc, - } - } - // Method to display information - pub fn display_info(&self) { - println!("PcdItemEncAttributePrivate:"); - println!("Attribute Name: {}", self.attribute_name); - println!("Data Enc: {}", self.data_enc); - } - - // Additional methods for PcdItemEncAttributePrivate can be added here -} diff --git a/src/models/pcd_item_enc_attribute_public.rs b/src/models/pcd_item_enc_attribute_public.rs deleted file mode 100644 index 911cdeb..0000000 --- a/src/models/pcd_item_enc_attribute_public.rs +++ /dev/null @@ -1,25 +0,0 @@ -use std::hash::Hash; - -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PcdItemEncAttributePublic { - pub attribute_name: String, - pub data_enc: String, // Assuming the encrypted data is represented as a String -} -impl PcdItemEncAttributePublic { - pub fn new(attribute_name: String, data_enc: String) -> Self { - PcdItemEncAttributePublic { - attribute_name, - data_enc, - } - } - pub fn display_info(&self) { - println!("PcdItemEncAttributePublic:"); - println!("Attribute Name: {}", self.attribute_name); - println!("Data Enc: {}", self.data_enc); - } - - // Additional methods for PcdItemEncAttributePublic can be added here -} diff --git a/src/models/pcd_item_enc_attribute_role_confidential.rs b/src/models/pcd_item_enc_attribute_role_confidential.rs deleted file mode 100644 index 4d8bebd..0000000 --- a/src/models/pcd_item_enc_attribute_role_confidential.rs +++ /dev/null @@ -1,29 +0,0 @@ -use std::hash::Hash; - -use serde::{Deserialize, Serialize}; - -use super::key_encryption::KeyEncryption; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PcdItemEncAttributeRoleConfidential { - pub attribute_name: String, - pub data_enc: String, // Assuming the encrypted data is represented as a String - pub key: KeyEncryption, // Assuming the encrypted data is represented as a String -} - -impl PcdItemEncAttributeRoleConfidential { - pub fn new(attribute_name: String, data_enc: String, key: KeyEncryption) -> Self { - PcdItemEncAttributeRoleConfidential { - attribute_name, - data_enc, - key, - } - } - pub fn display_info(&self) { - println!("PcdItemEncAttributeRoleConfidential:"); - println!("Attribute Name: {}", self.attribute_name); - println!("Data Enc: {}", self.data_enc); - self.key.display_info(); - } -} diff --git a/src/models/pcd_item_generic_enc.rs b/src/models/pcd_item_generic_enc.rs deleted file mode 100644 index 524e258..0000000 --- a/src/models/pcd_item_generic_enc.rs +++ /dev/null @@ -1,63 +0,0 @@ -use std::hash::Hash; - -use serde::{Deserialize, Serialize}; - -use super::{ - pcd_item_enc::PcdItemEnc, pcd_item_enc_attribute_private::PcdItemEncAttributePrivate, - pcd_item_enc_attribute_public::PcdItemEncAttributePublic, - pcd_item_enc_attribute_role_confidential::PcdItemEncAttributeRoleConfidential, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PcdItemGenericEnc { - pub item_enc: PcdItemEnc, - pub pcd_item_enc_attribute_public_list: Option>, - pub pcd_item_enc_attribute_role_confidential_list: - Option>, - pub pcd_item_enc_attribute_private_list: Option>, -} - -impl PcdItemGenericEnc { - pub fn new( - item_enc: PcdItemEnc, - pcd_item_enc_attribute_public_list: Option>, - pcd_item_enc_attribute_role_confidential_list: Option< - Vec, - >, - pcd_item_enc_attribute_private_list: Option>, - ) -> Self { - PcdItemGenericEnc { - item_enc, - pcd_item_enc_attribute_public_list, - pcd_item_enc_attribute_role_confidential_list, - pcd_item_enc_attribute_private_list, - } - } - - pub fn display_info(&self) { - println!("PcdItemEnc:"); - println!("Public Attributes:"); - for attr in &self.pcd_item_enc_attribute_public_list { - for attr_sub in attr { - attr_sub.display_info(); - } - } - - println!("Role Confidential Attributes:"); - for attr in &self.pcd_item_enc_attribute_role_confidential_list { - for attr_sub in attr { - attr_sub.display_info(); - } - } - - println!("Private Attributes:"); - for attr in &self.pcd_item_enc_attribute_private_list { - for attr_sub in attr { - attr_sub.display_info(); - } - } - } - - // Additional methods for PcdItemEnc can be added here -} diff --git a/src/models/request.rs b/src/models/request.rs deleted file mode 100644 index 45fe701..0000000 --- a/src/models/request.rs +++ /dev/null @@ -1,46 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Request { - pub item_name: Option, - pub request_type: String, // `type` is a reserved keyword in Rust, renamed to `request_type` - pub version: i64, - pub process_hash: String, - pub pcd_reference_hash: Option, - pub item_reference_hash: Option, -} - -impl Request { - pub fn new( - item_name: Option, - request_type: String, - version: i64, - process_hash: String, - pcd_reference_hash: Option, - item_reference_hash: Option, - ) -> Self { - let req = Request { - item_name, - request_type, - version, - process_hash, - pcd_reference_hash, - item_reference_hash, - }; - return req; - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!( - "Item Name: {}, Request Type: {}, Version: {}, Process Hash: {}, PCD Reference Hash: {}, Item Reference Hash: {}", - self.item_name.as_ref().unwrap_or(&"None".to_string()), - self.request_type, - self.version, - self.process_hash, - self.pcd_reference_hash.as_ref().unwrap_or(&"None".to_string()), - self.item_reference_hash.as_ref().unwrap_or(&"None".to_string()), - ) - } -} diff --git a/src/models/request_pcd.rs b/src/models/request_pcd.rs deleted file mode 100644 index 516453a..0000000 --- a/src/models/request_pcd.rs +++ /dev/null @@ -1,143 +0,0 @@ -use std::{ - collections::hash_map::DefaultHasher, - hash::{Hash, Hasher}, -}; - -use serde::{Deserialize, Serialize}; - -use super::{ - item_enum::ItemEnum, key_encryption::KeyEncryption, `Envelope` _client::EnvelopeClient, - pagination::Pagination, pcd_item_generic_enc::PcdItemGenericEnc, request::Request, - shared_peer::Peer, shared_process::Process, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Pcd { - pub request: Request, // Assuming Request is a predefined struct - pub item_list: Vec, - pub pagination: Pagination, // Assuming Pagination is a predefined struct -} - -impl Pcd { - pub const TYPE: &'static str = "pcd"; - pub fn new( - request_item_name: Option, - request_version: i64, - request_process_hash: String, - request_pcd_reference_hash: Option, - request_item_reference_hash: Option, - item_list: Vec, - pagination: Pagination, - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - ) -> Self { - let request = Request::new( - request_item_name, - Self::TYPE.to_string(), - request_version, - request_process_hash, - request_pcd_reference_hash, - request_item_reference_hash, - ); - - // TODO: encrypt item_list - let mut item_enc_list: Vec = Vec::new(); - - item_list.iter().for_each(|item| match item { - ItemEnum::Process(item_process) => { - let item_enc = item_process.enc( - process_public_enc_key.clone(), - Member_private_enc_key.clone(), - ); - item_enc_list.push(item_enc); - } - ItemEnum::Member(item_Member) => { - let item_enc = item_Member.enc( - process_public_enc_key.clone(), - Member_private_enc_key.clone(), - ); - item_enc_list.push(item_enc); - } - ItemEnum::Artefact(item_artefact) => { - let item_enc = item_artefact.enc( - process_public_enc_key.clone(), - Member_private_enc_key.clone(), - ); - item_enc_list.push(item_enc); - } - ItemEnum::Peer(item_peer) => { - let item_enc = item_peer.enc( - process_public_enc_key.clone(), - Member_private_enc_key.clone(), - ); - item_enc_list.push(item_enc); - } - ItemEnum::Payments(item_Payments) => { - let item_enc = item_Payments.enc( - process_public_enc_key.clone(), - Member_private_enc_key.clone(), - ); - item_enc_list.push(item_enc); - } - ItemEnum::Deposit(item_deposit) => { - let item_enc = item_deposit.enc( - process_public_enc_key.clone(), - Member_private_enc_key.clone(), - ); - item_enc_list.push(item_enc); - } - ItemEnum::commit(item_commit) => { - let item_enc = item_commit.enc( - process_public_enc_key.clone(), - Member_private_enc_key.clone(), - ); - item_enc_list.push(item_enc); - } - }); - - Pcd { - request, - item_list: item_enc_list, - pagination, - } - } - pub fn display_info(&self) { - println!("Pcd:"); - println!("Request:"); - self.request.display_info(); - - println!("Item List:"); - for item in &self.item_list { - item.display_info(); - } - - println!("Pagination:"); - self.pagination.display_info(); - } - - pub fn to_message( - &self, - process_public_enc_key: KeyEncryption, - `Envelope` _shared_peer_list: Vec, - `Envelope` _shared_process_list: Vec, - `Envelope` _faucet_sp_address: String, - pow_pathern: String, - pow_difficulty: usize, - ) -> `Envelope` Client { - let mut hasher: DefaultHasher = DefaultHasher::new(); - self.hash(&mut hasher); - let request_hash = hasher.finish().to_string(); - let request_enc: String = process_public_enc_key.enc_pcd(self.clone()).to_string(); - - `Envelope` Client::new( - request_enc, - request_hash, - `Envelope` _shared_peer_list, - `Envelope` _shared_process_list, - `Envelope` _faucet_sp_address, - pow_pathern, - pow_difficulty, - ) - } -} diff --git a/src/models/request_prd.rs b/src/models/request_prd.rs deleted file mode 100644 index 07ce986..0000000 --- a/src/models/request_prd.rs +++ /dev/null @@ -1,108 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::hash::Hash; - -use super::{key_encryption::KeyEncryption, request::Request}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct KeyRoleConfidential { - pub attribute_name: String, - pub key: KeyEncryption, - pub algorithm_name: String, -} - -impl KeyRoleConfidential { - pub fn new(attribute_name: String, key: KeyEncryption, algorithm_name: String) -> Self { - KeyRoleConfidential { - attribute_name, - key, - algorithm_name, - } - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!( - "Attribute Name: {}, Key: {:?}, Algorithm: {}", - self.attribute_name, - self.key, // Utilise {:?} si KeyEncryption implémente Debug - self.algorithm_name - ) - } - - // Additional methods for KeyRoleConfidential can be added here -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct Prd { - pub request: Request, // Assuming Request is a predefined struct - pub pcd_keys_role_confidential_list_confidential: String, - pub `Envelope` _public: Option, - pub `Envelope` _confidential: Option, - pub `Envelope` _private: Option, - pub sp_address_to: String, - pub sp_address_from: String, - pub sp_address_reply: String, - pub timestamp_declared: u64, // Assuming a Unix timestamp - pub role_name_from: String, - pub role_name_to: String, -} - -impl Prd { - pub const TYPE: &'static str = "prd"; - pub fn new( - request_item_name: Option, - request_type: String, - request_version: i64, - request_process_hash: String, - request_pcd_reference_hash: Option, - request_item_reference_hash: Option, - pcd_keys_role_confidential_list_confidential: String, - `Envelope` _public: Option, - `Envelope` _confidential: Option, - `Envelope` _private: Option, - sp_address_to: String, - sp_address_from: String, - sp_address_reply: String, - timestamp_declared: u64, - role_name_from: String, - role_name_to: String, - ) -> Self { - let request = Request::new( - request_item_name, - request_type, - request_version, - request_process_hash, - request_pcd_reference_hash, - request_item_reference_hash, - ); - Prd { - request, - pcd_keys_role_confidential_list_confidential, - `Envelope` _public, - `Envelope` _confidential, - `Envelope` _private, - sp_address_to, - sp_address_from, - sp_address_reply, - timestamp_declared, - role_name_from, - role_name_to, - } - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!( - "Request: {:?}, PCD Keys Role Confidential: {:?}, `Envelope` Public: {}, `Envelope` Confidential: {}, `Envelope` Private: {}, SP Address From: {}, SP Address Reply: {}, Timestamp Declared: {}, Role Name From: {}, Role Name To: {}", - self.request, - self.pcd_keys_role_confidential_list_confidential, - self.message_public.as_ref().unwrap(), - self.message_confidential.as_ref().unwrap(), - self.message_private.as_ref().unwrap(), - self.sp_address_from, - self.sp_address_reply, - self.timestamp_declared, - self.role_name_from, - self.role_name_to, - ) - } -} diff --git a/src/models/request_prd_confirm.rs b/src/models/request_prd_confirm.rs deleted file mode 100644 index fa8da88..0000000 --- a/src/models/request_prd_confirm.rs +++ /dev/null @@ -1,100 +0,0 @@ -use std::{ - collections::hash_map::DefaultHasher, - hash::{Hash, Hasher}, -}; - -use serde::{Deserialize, Serialize}; - -use super::{ - key_encryption::KeyEncryption, `Envelope` _client::EnvelopeClient, request_prd::Prd, - shared_peer::Peer, shared_process::Process, -}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PrdConfirm { - pub prd: Prd, - pub code_confirm_confidential: String, -} - -impl PrdConfirm { - pub const TYPE: &'static str = "prd_confirm"; - pub fn new( - request_item_name: Option, - request_version: i64, - request_process_hash: String, - request_pcd_reference_hash: Option, - request_item_reference_hash: Option, - pcd_keys_role_confidential_list_confidential: String, - `Envelope` _public: Option, - `Envelope` _confidential: Option, - `Envelope` _private: Option, - sp_address_to: String, - sp_address_from: String, - sp_address_reply: String, - timestamp_declared: u64, - role_name_from: String, - role_name_to: String, - code_confirm_confidential: String, - ) -> Self { - let request_type = Self::TYPE.to_string(); - let prd = Prd::new( - request_item_name, - request_type, - request_version, - request_process_hash, - request_pcd_reference_hash, - request_item_reference_hash, - pcd_keys_role_confidential_list_confidential, - `Envelope` _public, - `Envelope` _confidential, - `Envelope` _private, - sp_address_to, - sp_address_from, - sp_address_reply, - timestamp_declared, - role_name_from, - role_name_to, - ); - PrdConfirm { - prd, - code_confirm_confidential, - } - } - - pub fn to_message( - &self, - process_public_enc_key: KeyEncryption, - `Envelope` _shared_peer_list: Vec, - `Envelope` _shared_process_list: Vec, - `Envelope` _faucet_sp_address: String, - pow_pathern: String, - pow_difficulty: usize, - ) -> `Envelope` Client { - let mut hasher: DefaultHasher = DefaultHasher::new(); - self.hash(&mut hasher); - let request_hash = hasher.finish().to_string(); - let request_enc: String = process_public_enc_key - .enc_prd_confirm(self.clone()) - .to_string(); - - `Envelope` Client::new( - request_enc, - request_hash, - `Envelope` _shared_peer_list, - `Envelope` _shared_process_list, - `Envelope` _faucet_sp_address, - pow_pathern, - pow_difficulty, - ) - } - // display_info method - pub fn display_info(&self) { - println!("PrdConfirm:"); - println!("PRD:"); - self.prd.display_info(); // Display information of Prd - println!( - "Code Confirm (Encrypted by Shared Secret): {}", - self.code_confirm_confidential - ); - } -} diff --git a/src/models/request_prd_key_backup.rs b/src/models/request_prd_key_backup.rs deleted file mode 100644 index 98a48e0..0000000 --- a/src/models/request_prd_key_backup.rs +++ /dev/null @@ -1,108 +0,0 @@ -use std::{ - collections::hash_map::DefaultHasher, - hash::{Hash, Hasher}, -}; - -use serde::{Deserialize, Serialize}; - -use super::{ - key_encryption::KeyEncryption, `Envelope` _client::EnvelopeClient, request_prd::Prd, - shared_peer::Peer, shared_process::Process, -}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PrdKeyBackup { - pub prd: Prd, - pub device_footprint_enc_by_sp_shared_secret: String, - pub part_1_enc_hash_enc_by_sp_shared_secret: String, - pub shard_enc_by_sp_shared_secret: String, -} - -impl PrdKeyBackup { - pub const TYPE: &'static str = "prd_key_backup"; - pub fn new( - request_item_name: Option, - request_version: i64, - request_process_hash: String, - request_pcd_reference_hash: Option, - request_item_reference_hash: Option, - pcd_keys_role_confidential_list_confidential: String, - `Envelope` _public: Option, - `Envelope` _confidential: Option, - `Envelope` _private: Option, - sp_address_to: String, - sp_address_from: String, - sp_address_reply: String, - timestamp_declared: u64, - role_name_from: String, - role_name_to: String, - - device_footprint_enc_by_sp_shared_secret: String, - part_1_enc_hash_enc_by_sp_shared_secret: String, - shard_enc_by_sp_shared_secret: String, - ) -> Self { - let request_type = Self::TYPE.to_string(); - let prd = Prd::new( - request_item_name, - request_type, - request_version, - request_process_hash, - request_pcd_reference_hash, - request_item_reference_hash, - pcd_keys_role_confidential_list_confidential, - `Envelope` _public, - `Envelope` _confidential, - `Envelope` _private, - sp_address_to, - sp_address_from, - sp_address_reply, - timestamp_declared, - role_name_from, - role_name_to, - ); - PrdKeyBackup { - prd, - device_footprint_enc_by_sp_shared_secret, - part_1_enc_hash_enc_by_sp_shared_secret, - shard_enc_by_sp_shared_secret, - } - } - - pub fn to_message( - &self, - process_public_enc_key: KeyEncryption, - `Envelope` _shared_peer_list: Vec, - `Envelope` _shared_process_list: Vec, - `Envelope` _faucet_sp_address: String, - pow_pathern: String, - pow_difficulty: usize, - ) -> `Envelope` Client { - let mut hasher: DefaultHasher = DefaultHasher::new(); - self.hash(&mut hasher); - let request_hash = hasher.finish().to_string(); - let request_enc: String = process_public_enc_key - .enc_prd_key_backup(self.clone()) - .to_string(); - - `Envelope` Client::new( - request_enc, - request_hash, - `Envelope` _shared_peer_list, - `Envelope` _shared_process_list, - `Envelope` _faucet_sp_address, - pow_pathern, - pow_difficulty, - ) - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!( - "PRD: {:?}, Device Footprint Encrypted: {}, Part 1 Encrypted Hash: {}, Shard Encrypted: {}", - self.prd, - self.device_footprint_enc_by_sp_shared_secret, - self.part_1_enc_hash_enc_by_sp_shared_secret, - self.shard_enc_by_sp_shared_secret - ) - } -} diff --git a/src/models/request_prd_key_hello.rs b/src/models/request_prd_key_hello.rs deleted file mode 100644 index 45259f5..0000000 --- a/src/models/request_prd_key_hello.rs +++ /dev/null @@ -1,98 +0,0 @@ -use std::{ - collections::hash_map::DefaultHasher, - hash::{Hash, Hasher}, -}; - -use serde::{Deserialize, Serialize}; - -use super::{ - key_encryption::KeyEncryption, `Envelope` _client::EnvelopeClient, request_prd::Prd, - shared_peer::Peer, shared_process::Process, -}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PrdKeyHello { - pub prd: Prd, - pub part_1_enc_hash_enc_by_sp_shared_secret: String, -} - -impl PrdKeyHello { - pub const TYPE: &'static str = "prd_key_hello"; - pub fn new( - request_item_name: Option, - request_version: i64, - request_process_hash: String, - request_pcd_reference_hash: Option, - request_item_reference_hash: Option, - pcd_keys_role_confidential_list_confidential: String, - `Envelope` _public: Option, - `Envelope` _confidential: Option, - `Envelope` _private: Option, - sp_address_to: String, - sp_address_from: String, - sp_address_reply: String, - timestamp_declared: u64, - role_name_from: String, - role_name_to: String, - part_1_enc_hash_enc_by_sp_shared_secret: String, - ) -> Self { - let request_type = Self::TYPE.to_string(); - let prd = Prd::new( - request_item_name, - request_type, - request_version, - request_process_hash, - request_pcd_reference_hash, - request_item_reference_hash, - pcd_keys_role_confidential_list_confidential, - `Envelope` _public, - `Envelope` _confidential, - `Envelope` _private, - sp_address_to, - sp_address_from, - sp_address_reply, - timestamp_declared, - role_name_from, - role_name_to, - ); - PrdKeyHello { - prd, - part_1_enc_hash_enc_by_sp_shared_secret, - } - } - - pub fn to_message( - &self, - process_public_enc_key: KeyEncryption, - `Envelope` _shared_peer_list: Vec, - `Envelope` _shared_process_list: Vec, - `Envelope` _faucet_sp_address: String, - pow_pathern: String, - pow_difficulty: usize, - ) -> `Envelope` Client { - let mut hasher: DefaultHasher = DefaultHasher::new(); - self.hash(&mut hasher); - let request_hash = hasher.finish().to_string(); - let request_enc: String = process_public_enc_key - .enc_prd_key_hello(self.clone()) - .to_string(); - - `Envelope` Client::new( - request_enc, - request_hash, - `Envelope` _shared_peer_list, - `Envelope` _shared_process_list, - `Envelope` _faucet_sp_address, - pow_pathern, - pow_difficulty, - ) - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!( - "PRD: {:?}, Part 1 Encrypted Hash: {}", - self.prd, self.part_1_enc_hash_enc_by_sp_shared_secret - ) - } -} diff --git a/src/models/request_prd_list.rs b/src/models/request_prd_list.rs deleted file mode 100644 index bf94653..0000000 --- a/src/models/request_prd_list.rs +++ /dev/null @@ -1,90 +0,0 @@ -use std::{ - collections::hash_map::DefaultHasher, - hash::{Hash, Hasher}, -}; - -use serde::{Deserialize, Serialize}; - -use super::{ - key_encryption::KeyEncryption, `Envelope` _client::EnvelopeClient, request_prd::Prd, - shared_peer::Peer, shared_process::Process, -}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PrdList { - pub prd: Prd, -} - -impl PrdList { - pub const TYPE: &'static str = "prd_list"; - pub fn new( - request_item_name: Option, - request_version: i64, - request_process_hash: String, - request_pcd_reference_hash: Option, - request_item_reference_hash: Option, - pcd_keys_role_confidential_list_confidential: String, - `Envelope` _public: Option, - `Envelope` _confidential: Option, - `Envelope` _private: Option, - sp_address_to: String, - sp_address_from: String, - sp_address_reply: String, - timestamp_declared: u64, - role_name_from: String, - role_name_to: String, - ) -> Self { - let request_type = Self::TYPE.to_string(); - let prd = Prd::new( - request_item_name, - request_type, - request_version, - request_process_hash, - request_pcd_reference_hash, - request_item_reference_hash, - pcd_keys_role_confidential_list_confidential, - `Envelope` _public, - `Envelope` _confidential, - `Envelope` _private, - sp_address_to, - sp_address_from, - sp_address_reply, - timestamp_declared, - role_name_from, - role_name_to, - ); - PrdList { prd } - } - - pub fn to_message( - &self, - process_public_enc_key: KeyEncryption, - `Envelope` _shared_peer_list: Vec, - `Envelope` _shared_process_list: Vec, - `Envelope` _faucet_sp_address: String, - pow_pathern: String, - pow_difficulty: usize, - ) -> `Envelope` Client { - let mut hasher: DefaultHasher = DefaultHasher::new(); - self.hash(&mut hasher); - let request_hash = hasher.finish().to_string(); - let request_enc: String = process_public_enc_key - .enc_prd_list(self.clone()) - .to_string(); - - `Envelope` Client::new( - request_enc, - request_hash, - `Envelope` _shared_peer_list, - `Envelope` _shared_process_list, - `Envelope` _faucet_sp_address, - pow_pathern, - pow_difficulty, - ) - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!("PRD: {:?}", self.prd) - } -} diff --git a/src/models/request_prd_message.rs b/src/models/request_prd_message.rs deleted file mode 100644 index 0dc50a0..0000000 --- a/src/models/request_prd_message.rs +++ /dev/null @@ -1,89 +0,0 @@ -use std::{ - collections::hash_map::DefaultHasher, - hash::{Hash, Hasher}, -}; - -use serde::{Deserialize, Serialize}; - -use super::{ - key_encryption::KeyEncryption, `Envelope` _client::EnvelopeClient, request_prd::Prd, - shared_peer::Peer, shared_process::Process, -}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PrdMessage { - pub prd: Prd, -} - -impl PrdMessage { - pub const TYPE: &'static str = "prd_message"; - pub fn new( - request_item_name: Option, - request_version: i64, - request_process_hash: String, - request_pcd_reference_hash: Option, - request_item_reference_hash: Option, - pcd_keys_role_confidential_list_confidential: String, - `Envelope` _public: Option, - `Envelope` _confidential: Option, - `Envelope` _private: Option, - sp_address_to: String, - sp_address_from: String, - sp_address_reply: String, - timestamp_declared: u64, - role_name_from: String, - role_name_to: String, - ) -> Self { - let request_type = Self::TYPE.to_string(); - let prd = Prd::new( - request_item_name, - request_type, - request_version, - request_process_hash, - request_pcd_reference_hash, - request_item_reference_hash, - pcd_keys_role_confidential_list_confidential, - `Envelope` _public, - `Envelope` _confidential, - `Envelope` _private, - sp_address_to, - sp_address_from, - sp_address_reply, - timestamp_declared, - role_name_from, - role_name_to, - ); - PrdMessage { prd } - } - - pub fn to_message( - &self, - process_public_enc_key: KeyEncryption, - `Envelope` _shared_peer_list: Vec, - `Envelope` _shared_process_list: Vec, - `Envelope` _faucet_sp_address: String, - pow_pathern: String, - pow_difficulty: usize, - ) -> `Envelope` Client { - let mut hasher: DefaultHasher = DefaultHasher::new(); - self.hash(&mut hasher); - let request_hash = hasher.finish().to_string(); - let request_enc: String = process_public_enc_key - .enc_prd_message(self.clone()) - .to_string(); - - `Envelope` Client::new( - request_enc, - request_hash, - `Envelope` _shared_peer_list, - `Envelope` _shared_process_list, - `Envelope` _faucet_sp_address, - pow_pathern, - pow_difficulty, - ) - } - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!("PRD: {:?}", self.prd) - } -} diff --git a/src/models/request_prd_response.rs b/src/models/request_prd_response.rs deleted file mode 100644 index 40a2e10..0000000 --- a/src/models/request_prd_response.rs +++ /dev/null @@ -1,178 +0,0 @@ -use serde_json::json; -use std::{collections::hash_map::DefaultHasher, hash::Hash, hash::Hasher}; - -use serde::{Deserialize, Serialize}; - -use crate::workflows::workflow_pcd_create_and_send_all::PcdItemEncAttributeRoleConfidentialExportKey; - -use super::{ - commit_method::commitMethod, deposit_method::DepositMethod, - key_encryption::KeyEncryption, `Envelope` _client::EnvelopeClient, Payments_method::PaymentsMethod, - request_prd::Prd, shared_peer::Peer, shared_process::Process, -}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PrdResponse { - pub prd: Prd, - pub sig_value: String, - pub pcd_origin_hash: Option, - pub Payments_method_confidential: Option, - pub deposit_method_confidential: Option, - pub commit_method_confidential: Option, - pub certif_key_confidential: Option, - pub shared_secret_key: Option, -} - -impl PrdResponse { - pub const TYPE: &'static str = "prd_response"; - pub fn new( - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - - request_item_name: Option, - request_version: i64, - request_process_hash: String, - request_pcd_reference_hash: Option, - request_item_reference_hash: Option, - pcd_keys_role_confidential_list: Vec, - - `Envelope` _public_string: Option, - `Envelope` _confidential_string: Option, - `Envelope` _private_string: Option, - - sp_address_to: String, - sp_address_from: String, - sp_address_reply: String, - timestamp_declared: u64, - role_name_from: String, - role_name_to: String, - - sig_value: String, - pcd_origin_hash: Option, - - Payments_method: Option, - deposit_method: Option, - commit_method: Option, - certif_key: Option, - ) -> Self { - let mut shared_secret_key = - KeyEncryption::new(Some("secret_shared".to_owned()), None, None); - - if let Ok(_new) = shared_secret_key.key_new_random() { - let Payments_method_confidential = match Payments_method { - Some(ref _msg) => { - Some(shared_secret_key.enc(serde_json::to_value(Payments_method).unwrap())) - } - None => None, - }; - - let deposit_method_confidential = match deposit_method { - Some(ref _msg) => { - Some(shared_secret_key.enc(serde_json::to_value(deposit_method).unwrap())) - } - None => None, - }; - - let commit_method_confidential = match commit_method { - Some(ref _msg) => { - Some(shared_secret_key.enc(serde_json::to_value(commit_method).unwrap())) - } - None => None, - }; - - let certif_key_confidential = match certif_key { - Some(ref _msg) => { - Some(shared_secret_key.enc(serde_json::to_value(certif_key).unwrap())) - } - None => None, - }; - - let `Envelope` _confidential = `Envelope` _confidential_string - .as_ref() - .map(|msg| shared_secret_key.enc_string(msg.clone())); - let `Envelope` _public = `Envelope` _public_string - .as_ref() - .map(|msg| process_public_enc_key.enc_string(msg.clone())); - let `Envelope` _private = `Envelope` _private_string - .as_ref() - .map(|msg| Member_private_enc_key.enc_string(msg.clone())); - - let pcd_keys_role_confidential_list_confidential = shared_secret_key.enc( - serde_json::to_value(pcd_keys_role_confidential_list).unwrap_or_else(|_| json!({})), - ); - - let request_type = Self::TYPE.to_string(); - let prd = Prd::new( - request_item_name, - request_type, - request_version, - request_process_hash, - request_pcd_reference_hash, - request_item_reference_hash, - pcd_keys_role_confidential_list_confidential, - `Envelope` _public, - `Envelope` _confidential, - `Envelope` _private, - sp_address_to, - sp_address_from, - sp_address_reply, - timestamp_declared, - role_name_from, - role_name_to, - ); - PrdResponse { - prd, - sig_value, - pcd_origin_hash, - Payments_method_confidential, - deposit_method_confidential, - commit_method_confidential, - certif_key_confidential, - shared_secret_key: Some(shared_secret_key), - } - } else { - panic!("Error: Could not create shared secret key"); - } - } - - pub fn to_message( - &self, - process_public_enc_key: KeyEncryption, - `Envelope` _shared_peer_list: Vec, - `Envelope` _shared_process_list: Vec, - `Envelope` _faucet_sp_address: String, - pow_pathern: String, - pow_difficulty: usize, - ) -> `Envelope` Client { - let mut hasher: DefaultHasher = DefaultHasher::new(); - self.hash(&mut hasher); - let request_hash = hasher.finish().to_string(); - let request_enc: String = process_public_enc_key - .enc_prd_response(self.clone()) - .to_string(); - - `Envelope` Client::new( - request_enc, - request_hash, - `Envelope` _shared_peer_list, - `Envelope` _shared_process_list, - `Envelope` _faucet_sp_address, - pow_pathern, - pow_difficulty, - ) - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!( - "PRD: {:?}, Sig Value: {}, PCD Origin Hash: {}, Payments Method Encrypted: {}, Deposit Method Encrypted: {}, commit Method Encrypted: {}, Certification Key Encrypted: {}", - self.prd, - self.sig_value, - self.pcd_origin_hash.as_ref().unwrap(), - self.Payments_method_confidential.as_ref().unwrap(), - self.deposit_method_confidential.as_ref().unwrap(), - self.commit_method_confidential.as_ref().unwrap(), - self.certif_key_confidential.as_ref().unwrap() - ) - } -} diff --git a/src/models/request_prd_update.rs b/src/models/request_prd_update.rs deleted file mode 100644 index c247a05..0000000 --- a/src/models/request_prd_update.rs +++ /dev/null @@ -1,127 +0,0 @@ -use std::{ - collections::hash_map::DefaultHasher, - hash::{Hash, Hasher}, -}; - -use super::{ - key_encryption::KeyEncryption, `Envelope` _client::EnvelopeClient, request_prd::Prd, - shared_peer::Peer, shared_process::Process, -}; -use serde::{Deserialize, Serialize}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PrdUpdate { - pub prd: Prd, - pub pcd_new_version_hash: String, - pub Payments_pcd_hash_list: Vec, - pub cap_pcd_hash_list: Vec, - pub deposit_pcd_hash_list: Vec, - pub commit_pcd_hash_list: Vec, - pub ask_Payments_method: String, - pub ask_deposit_method: String, - pub ask_commit_method: String, -} - -impl PrdUpdate { - pub const TYPE: &'static str = "prd_update"; - pub fn new( - request_item_name: Option, - request_version: i64, - request_process_hash: String, - request_pcd_reference_hash: Option, - request_item_reference_hash: Option, - pcd_keys_role_confidential_list_confidential: String, - `Envelope` _public: Option, - `Envelope` _confidential: Option, - `Envelope` _private: Option, - sp_address_to: String, - sp_address_from: String, - sp_address_reply: String, - timestamp_declared: u64, - role_name_from: String, - role_name_to: String, - - pcd_new_version_hash: String, - Payments_pcd_hash_list: Vec, - cap_pcd_hash_list: Vec, - deposit_pcd_hash_list: Vec, - commit_pcd_hash_list: Vec, - ask_Payments_method: String, - ask_deposit_method: String, - ask_commit_method: String, - ) -> Self { - let request_type = Self::TYPE.to_string(); - let prd = Prd::new( - request_item_name, - request_type, - request_version, - request_process_hash, - request_pcd_reference_hash, - request_item_reference_hash, - pcd_keys_role_confidential_list_confidential, - `Envelope` _public, - `Envelope` _confidential, - `Envelope` _private, - sp_address_to, - sp_address_from, - sp_address_reply, - timestamp_declared, - role_name_from, - role_name_to, - ); - PrdUpdate { - prd, - pcd_new_version_hash, - Payments_pcd_hash_list, - cap_pcd_hash_list, - deposit_pcd_hash_list, - commit_pcd_hash_list, - ask_Payments_method, - ask_deposit_method, - ask_commit_method, - } - } - - pub fn to_message( - &self, - process_public_enc_key: KeyEncryption, - `Envelope` _shared_peer_list: Vec, - `Envelope` _shared_process_list: Vec, - `Envelope` _faucet_sp_address: String, - pow_pathern: String, - pow_difficulty: usize, - ) -> `Envelope` Client { - let mut hasher: DefaultHasher = DefaultHasher::new(); - self.hash(&mut hasher); - let request_hash = hasher.finish().to_string(); - let request_enc: String = process_public_enc_key - .enc_prd_update(self.clone()) - .to_string(); - - `Envelope` Client::new( - request_enc, - request_hash, - `Envelope` _shared_peer_list, - `Envelope` _shared_process_list, - `Envelope` _faucet_sp_address, - pow_pathern, - pow_difficulty, - ) - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!( - "PRD: {:?}, PCD New Version Hash: {}, Payments PCD Hash List: {:?}, Cap PCD Hash List: {:?}, Deposit PCD Hash List: {:?}, commit PCD Hash List: {:?}, Ask Payments Method: {}, Ask Deposit Method: {}, Ask commit Method: {}", - self.prd, - self.pcd_new_version_hash, - self.Payments_pcd_hash_list, - self.cap_pcd_hash_list, - self.deposit_pcd_hash_list, - self.commit_pcd_hash_list, - self.ask_Payments_method, - self.ask_deposit_method, - self.ask_commit_method, - ) - } -} diff --git a/src/models/role.rs b/src/models/role.rs deleted file mode 100644 index 0b99306..0000000 --- a/src/models/role.rs +++ /dev/null @@ -1,201 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::{ - condition_cap::ConditionCap, condition_commit::Conditioncommit, - condition_orchestration::ConditionOrchestration, condition_Payments::ConditionPayments, - condition_prd_address_set::ConditionPrdAddressSet, condition_publish::ConditionPublish, - item::Item, metadata::Amount, -}; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct TransactionModeDistribution { - pub from_prd_update_from: String, - pub from_role_list: Vec, - pub to_role_list: Vec, - pub from_prd_address_list: Vec, - pub to_prd_address_list: Vec, - pub method: String, -} - -impl TransactionModeDistribution { - pub fn new( - from_prd_update_from: String, - from_role_list: Vec, - to_role_list: Vec, - from_prd_address_list: Vec, - to_prd_address_list: Vec, - method: String, - ) -> Self { - TransactionModeDistribution { - from_prd_update_from, - from_role_list, - to_role_list, - from_prd_address_list, - to_prd_address_list, - method, - } - } - // display_info method - pub fn display_info(&self) { - println!("TransactionModeDistribution:"); - println!("From PRD Update From: {}", self.from_prd_update_from); - println!("From Role List: {:?}", self.from_role_list); - println!("To Role List: {:?}", self.to_role_list); - println!("From PRD Address List: {:?}", self.from_prd_address_list); - println!("To PRD Address List: {:?}", self.to_prd_address_list); - println!("Method: {}", self.method); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct TransactionModeDirect { - pub from_prd_update_from: String, - pub to_role_owner: String, -} - -impl TransactionModeDirect { - pub fn new(from_prd_update_from: String, to_role_owner: String) -> Self { - TransactionModeDirect { - from_prd_update_from, - to_role_owner, - } - } - - // display_info method - pub fn display_info(&self) { - println!("TransactionModeDirect:"); - println!("From PRD Update From: {}", self.from_prd_update_from); - println!("To Role Owner: {}", self.to_role_owner); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct TransactionMode { - pub amount: Amount, - pub role_transaction_distribution: TransactionModeDistribution, - pub role_transaction_direct: TransactionModeDirect, -} - -impl TransactionMode { - pub fn new( - amount: Amount, - role_transaction_distribution: TransactionModeDistribution, - role_transaction_direct: TransactionModeDirect, - ) -> Self { - TransactionMode { - amount, - role_transaction_distribution, - role_transaction_direct, - } - } - - // display_info method - pub fn display_info(&self) { - println!("TransactionMode:"); - - println!("Amount:"); - self.amount.display_info(); // Assuming Amount has a display_info method - - println!("Role Transaction Distribution:"); - self.role_transaction_distribution.display_info(); // Assuming TransactionModeDistribution has a display_info method - - println!("Role Transaction Direct:"); - self.role_transaction_direct.display_info(); // Assuming TransactionModeDirect has a display_info method - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Role { - pub item: Item, - pub required_2fa: bool, - pub validation_timeout: u64, - pub condition_prd_address_set_list: Vec, // Assuming ConditionPrdAddressSet is a predefined struct - pub condition_publish: ConditionPublish, // Assuming ConditionPublish is a predefined struct - pub condition_cap_list: Vec, // Assuming ConditionCap is a predefined struct - pub condition_Payments_list: Vec, // Assuming ConditionPayments is a predefined struct - pub condition_commit_list: Vec, // Assuming Conditioncommit is a predefined struct - pub condition_attribute_encryption_list: Vec, - pub condition_orchestration: ConditionOrchestration, // Assuming ConditionOrchestration is a predefined struct - pub role_succession: Option, - pub role_resolve: Option, - pub role_renew: Option, -} - -impl Role { - pub fn new( - item: Item, - required_2fa: bool, - validation_timeout: u64, - condition_prd_address_set_list: Vec, - condition_publish: ConditionPublish, - condition_cap_list: Vec, - condition_Payments_list: Vec, - condition_commit_list: Vec, - condition_attribute_encryption_list: Vec, - condition_orchestration: ConditionOrchestration, - role_succession: Option, - role_resolve: Option, - role_renew: Option, - ) -> Self { - Role { - item, - required_2fa, - validation_timeout, - condition_prd_address_set_list, - condition_publish, - condition_cap_list, - condition_Payments_list, - condition_commit_list, - condition_attribute_encryption_list, - condition_orchestration, - role_succession, - role_resolve, - role_renew, - } - } - // display_info method - pub fn display_info(&self) { - println!("Role:"); - println!("Item: {:?}", self.item); // Assuming `Item` implements Debug trait - println!("Validation Timeout: {}", self.validation_timeout); - - println!("ConditionPrdAddressSet List:"); - for condition in &self.condition_prd_address_set_list { - condition.display_info(); // Assuming `ConditionPrdAddressSet` has a display_info method - } - - println!("ConditionPublish:"); - self.condition_publish.display_info(); // Assuming `ConditionPublish` has a display_info method - - println!("ConditionCap List:"); - for condition in &self.condition_cap_list { - condition.display_info(); // Assuming `ConditionCap` has a display_info method - } - - println!("ConditionPayments List:"); - for condition in &self.condition_Payments_list { - condition.display_info(); // Assuming `ConditionPayments` has a display_info method - } - - println!("Conditioncommit List:"); - for condition in &self.condition_commit_list { - condition.display_info(); // Assuming `Conditioncommit` has a display_info method - } - - println!("ConditionAttributeEncryption:"); - for condition in &self.condition_attribute_encryption_list { - println!("ConditionAttributeEncryption: {:?}", condition); - } - - println!("ConditionOrchestration:"); - self.condition_orchestration.display_info(); // Assuming `ConditionOrchestration` has a display_info method - - println!("Role Succession: {:?}", self.role_succession); - println!("Role Resolve: {:?}", self.role_resolve); - println!("Role Renew: {:?}", self.role_renew); - } - - // Additional methods for Role can be added here -} diff --git a/src/models/role_artefact.rs b/src/models/role_artefact.rs deleted file mode 100644 index 762378d..0000000 --- a/src/models/role_artefact.rs +++ /dev/null @@ -1,20 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::Role; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct RoleArtefact { - pub item_name: String, - pub role: Role, -} - -impl RoleArtefact { - pub fn new(item_name: String, role: Role) -> Self { - RoleArtefact { item_name, role } - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!("Item Name: {}, Role: {:?}", self.item_name, self.role) - } -} diff --git a/src/models/role_commitment.rs b/src/models/role_commitment.rs deleted file mode 100644 index 5df98b3..0000000 --- a/src/models/role_commitment.rs +++ /dev/null @@ -1,20 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::Role; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Rolecommit { - pub item_name: String, - pub role: Role, -} - -impl Rolecommit { - pub fn new(item_name: String, role: Role) -> Self { - Rolecommit { item_name, role } - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!("Item Name: {}, Role: {:?}", self.item_name, self.role) - } -} diff --git a/src/models/role_deposit.rs b/src/models/role_deposit.rs deleted file mode 100644 index acd81ed..0000000 --- a/src/models/role_deposit.rs +++ /dev/null @@ -1,20 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::Role; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct RoleDeposit { - pub item_name: String, - pub role: Role, -} - -impl RoleDeposit { - pub fn new(item_name: String, role: Role) -> Self { - RoleDeposit { item_name, role } - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!("Item Name: {}, Role: {:?}", self.item_name, self.role) - } -} diff --git a/src/models/role_member.rs b/src/models/role_member.rs deleted file mode 100644 index 3fc82e1..0000000 --- a/src/models/role_member.rs +++ /dev/null @@ -1,18 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::Role; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct RoleMember { - pub item_name: String, - pub role: Role, -} - -impl RoleMember { - pub fn new(item_name: String, role: Role) -> Self { - RoleMember { item_name, role } - } - pub fn display_info(&self) -> String { - format!("Item Name: {}, Role: {:?}", self.item_name, self.role) - } -} diff --git a/src/models/role_payment.rs b/src/models/role_payment.rs deleted file mode 100644 index b37737b..0000000 --- a/src/models/role_payment.rs +++ /dev/null @@ -1,20 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::Role; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct RolePayments { - pub item_name: String, - pub role: Role, -} - -impl RolePayments { - pub fn new(item_name: String, role: Role) -> Self { - RolePayments { item_name, role } - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!("Item Name: {}, Role: {:?}", self.item_name, self.role) - } -} diff --git a/src/models/role_peer.rs b/src/models/role_peer.rs deleted file mode 100644 index 8e5bbdc..0000000 --- a/src/models/role_peer.rs +++ /dev/null @@ -1,20 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::Role; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct RolePeer { - pub item_name: String, - pub role: Role, -} - -impl RolePeer { - pub fn new(item_name: String, role: Role) -> Self { - RolePeer { item_name, role } - } - - // Fonction pour afficher ou retourner les informations - pub fn display_info(&self) -> String { - format!("Item Name: {}, Role: {:?}", self.item_name, self.role) - } -} diff --git a/src/models/role_process.rs b/src/models/role_process.rs deleted file mode 100644 index 13d0e1f..0000000 --- a/src/models/role_process.rs +++ /dev/null @@ -1,18 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::role::Role; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct RoleProcess { - pub item_name: String, - pub role: Role, -} - -impl RoleProcess { - pub fn new(item_name: String, role: Role) -> Self { - RoleProcess { item_name, role } - } - pub fn display_info(&self) -> String { - format!("Item Name: {}, Role: {:?}", self.item_name, self.role) - } -} diff --git a/src/models/roles_group.rs b/src/models/roles_group.rs deleted file mode 100644 index 8a74d2d..0000000 --- a/src/models/roles_group.rs +++ /dev/null @@ -1,129 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use crate::workflows::workflow_pcd_create_and_send_all::PcdItemEncAttributeRoleConfidentialExportKey; - -use super::{ - commit_method::commitMethod, deposit_method::DepositMethod, - key_encryption::KeyEncryption, Payments_method::PaymentsMethod, - request_prd_response::PrdResponse, role_artefact::RoleArtefact, role_Member::RoleMember, - role_peer::RolePeer, role_process::RoleProcess, -}; - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct RolesGroup { - pub role_peer: RolePeer, - pub role_Member: RoleMember, - pub role_process: RoleProcess, - pub role_artefact_list: Vec, -} - -impl RolesGroup { - pub fn new( - role_peer: RolePeer, - role_Member: RoleMember, - role_process: RoleProcess, - role_artefact_list: Vec, - ) -> Self { - RolesGroup { - role_peer, - role_Member, - role_process, - role_artefact_list, - } - } - pub fn filter_keys( - condition_attribute_encryption: &Vec, - pcd_keys_role_confidential_list: &mut Vec, - ) { - for key_item in pcd_keys_role_confidential_list.iter_mut() { - if !condition_attribute_encryption.contains(&key_item.attribute_name) { - key_item.key = None; - } - } - } - pub fn to_prd_response_list( - &self, - process_public_enc_key: KeyEncryption, - Member_private_enc_key: KeyEncryption, - request_item_name: Option, - request_version: i64, - request_process_hash: String, - request_pcd_reference_hash: Option, - request_item_reference_hash: Option, - pcd_keys_role_confidential_list: Vec, - `Envelope` _public_string: Option, - `Envelope` _confidential_string: Option, - `Envelope` _private_string: Option, - sp_address_from: String, - sp_address_reply: String, - timestamp_declared: u64, - role_name_from: String, - role_name_to: String, - sig_value: String, - pcd_origin_hash: Option, - - Payments_method: Option, - deposit_method: Option, - commit_method: Option, - certif_key: Option, - ) -> Vec { - let mut request_prd_response_list: Vec = Vec::new(); - - for cond in &self.role_peer.role.condition_prd_address_set_list { - let mut pcd_keys_role_confidential_list_tmp = pcd_keys_role_confidential_list.clone(); - - RolesGroup::filter_keys( - &self.role_peer.role.condition_attribute_encryption_list, - &mut pcd_keys_role_confidential_list_tmp, - ); - - for address in &cond.prd_sp_address_list { - let prd_response = PrdResponse::new( - process_public_enc_key.clone(), - Member_private_enc_key.clone(), - request_item_name.clone(), - request_version.clone(), - request_process_hash.clone(), - request_pcd_reference_hash.clone(), - request_item_reference_hash.clone(), - pcd_keys_role_confidential_list.clone(), - `Envelope` _public_string.clone(), - `Envelope` _confidential_string.clone(), - `Envelope` _private_string.clone(), - address.to_string(), - sp_address_from.clone(), - sp_address_reply.clone(), - timestamp_declared.clone(), - role_name_from.clone(), - role_name_to.clone(), - sig_value.clone(), - pcd_origin_hash.clone(), - Payments_method.clone(), - deposit_method.clone(), - commit_method.clone(), - certif_key.clone(), - ); - request_prd_response_list.push(prd_response); - } - } - request_prd_response_list - } - pub fn display_info(&self) { - println!("RolesGroup:"); - println!("Role Peer:"); - self.role_peer.display_info(); // Affiche les informations de `role_peer` - - println!("Role Member:"); - self.role_Member.display_info(); // Affiche les informations de `role_Member` - - println!("Role Process:"); - self.role_process.display_info(); // Affiche les informations de `role_process` - - println!("Role Artefact List:"); - for (index, role_artefact) in self.role_artefact_list.iter().enumerate() { - println!("Artefact {}: ", index + 1); - role_artefact.display_info(); // Affiche les informations de chaque `role_artefact` - } - } -} diff --git a/src/models/shared_peer.rs b/src/models/shared_peer.rs deleted file mode 100644 index 9ee6197..0000000 --- a/src/models/shared_peer.rs +++ /dev/null @@ -1,221 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::message_client::EnvelopeClient; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Relay { - pub address_port: u16, - pub data_max_size: usize, - pub pow_difficulty: u32, - pub pow_pattern: String, - pub pow_prefix: String, - pub pow_timeout: u32, - pub faucet_address: String, -} - -impl Relay { - pub fn new( - address_port: u16, - data_max_size: usize, - pow_difficulty: u32, - pow_pattern: String, - pow_prefix: String, - pow_timeout: u32, - faucet_address: String, - ) -> Self { - Relay { - address_port, - data_max_size, - pow_difficulty, - pow_pattern, - pow_prefix, - pow_timeout, - faucet_address, - } - } - // display_info method - pub fn display_info(&self) { - println!("Relay:"); - println!("Address Port: {}", self.address_port); - println!("Data Max Size: {}", self.data_max_size); - println!("PoW Difficulty: {}", self.pow_difficulty); - println!("PoW Pattern: {}", self.pow_pattern); - println!("PoW Prefix: {}", self.pow_prefix); - println!("PoW Timeout: {}", self.pow_timeout); - println!("Faucet Address: {}", self.faucet_address); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct L1Node { - pub address_port: u16, - pub explorer_base_url: String, - pub sp_address_anchorage: String, - pub sp_address_reward: String, -} - -impl L1Node { - pub fn new( - address_port: u16, - explorer_base_url: String, - sp_address_anchorage: String, - sp_address_reward: String, - ) -> Self { - L1Node { - address_port, - explorer_base_url, - sp_address_anchorage, - sp_address_reward, - } - } // display_info method - pub fn display_info(&self) { - println!("L1Node:"); - println!("Address Port: {}", self.address_port); - println!("Explorer Base URL: {}", self.explorer_base_url); - println!("SP Address Anchorage: {}", self.sp_address_anchorage); - println!("SP Address Reward: {}", self.sp_address_reward); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct L1Miner { - pub sp_address_rewarder: String, -} - -impl L1Miner { - pub fn new(sp_address_rewarder: String) -> Self { - L1Miner { - sp_address_rewarder, - } - } - - // display_info method - pub fn display_info(&self) { - println!("L1Miner:"); - println!("SP Address Rewarder: {}", self.sp_address_rewarder); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct L2Node { - pub address_port: u16, - pub explorer_base_url: String, - pub sp_address_anchorage: String, - pub sp_address_reward: String, - pub nbits: u32, - pub magic_number: u32, - pub challenge: String, -} - -impl L2Node { - pub fn new( - address_port: u16, - explorer_base_url: String, - sp_address_anchorage: String, - sp_address_reward: String, - nbits: u32, - magic_number: u32, - challenge: String, - ) -> Self { - L2Node { - address_port, - explorer_base_url, - sp_address_anchorage, - sp_address_reward, - nbits, - magic_number, - challenge, - } - } - - // display_info method - pub fn display_info(&self) { - println!("L2Node:"); - println!("Address Port: {}", self.address_port); - println!("Explorer Base URL: {}", self.explorer_base_url); - println!("SP Address Anchorage: {}", self.sp_address_anchorage); - println!("SP Address Reward: {}", self.sp_address_reward); - println!("Nbits: {}", self.nbits); - println!("Magic Number: {}", self.magic_number); - println!("Challenge: {}", self.challenge); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct L2Certif { - pub sp_address_certif: String, -} - -impl L2Certif { - pub fn new(sp_address_certif: String) -> Self { - L2Certif { sp_address_certif } - } - // display_info method - pub fn display_info(&self) { - println!("L2Certif:"); - println!("SP Address Certif: {}", self.sp_address_certif); - } -} - -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Peer { - pub domain: String, - pub address_ip: String, - pub relay: Relay, - pub l1_node: L1Node, - pub l1_miner: L1Miner, - pub l2_node: L2Node, - pub l2_certif: L2Certif, -} - -impl Peer { - pub fn new( - domain: String, - address_ip: String, - relay: Relay, - l1_node: L1Node, - l1_miner: L1Miner, - l2_node: L2Node, - l2_certif: L2Certif, - ) -> Self { - Peer { - domain, - address_ip, - relay, - l1_node, - l1_miner, - l2_node, - l2_certif, - } - } - pub fn send_message_client(&self, _message_client: `Envelope` Client) { - // TODO - } - - // display_info method - pub fn display_info(&self) { - println!("Peer:"); - println!("Domain: {}", self.domain); - println!("IP Address: {}", self.address_ip); - - println!("Relay:"); - self.relay.display_info(); // Assuming Relay has a display_info method - - println!("L1 Node:"); - self.l1_node.display_info(); // Assuming L1Node has a display_info method - - println!("L1 Miner:"); - self.l1_miner.display_info(); // Assuming L1Miner has a display_info method - - println!("L2 Node:"); - self.l2_node.display_info(); // Assuming L2Node has a display_info method - - println!("L2 Certif:"); - self.l2_certif.display_info(); // Assuming L2Certif has a display_info method - } -} diff --git a/src/models/shared_process.rs b/src/models/shared_process.rs deleted file mode 100644 index b4530ce..0000000 --- a/src/models/shared_process.rs +++ /dev/null @@ -1,35 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::key_encryption::KeyEncryption; -#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct Process { - pub hash: String, - pub key: KeyEncryption, - pub role_process_sp_address_list: Vec, -} - -impl Process { - pub fn new( - hash: String, - key: KeyEncryption, - role_process_sp_address_list: Vec, - ) -> Self { - Process { - hash, - key, - role_process_sp_address_list, - } - } - // display_info method - pub fn display_info(&self) { - println!("Process:"); - println!("Hash: {}", self.hash); - println!("Key Encryption:"); - self.key.display_info(); // Assuming KeyEncryption has a display_info method - println!( - "Role Process SP Address List: {:?}", - self.role_process_sp_address_list - ); - } -} diff --git a/src/wallet.rs b/src/wallet.rs deleted file mode 100644 index 5fb91ee..0000000 --- a/src/wallet.rs +++ /dev/null @@ -1,27 +0,0 @@ -// use rand::{rngs::ThreadRng, thread_rng}; -// use silentPayments::secp256k1::{self, Secp256k1, SecretKey}; - -// use sp_backend::SpClient; -/* -pub struct Wallet { - pub client: SpClient, - pub secp: Secp256k1, - pub seckey_spend: SecretKey, - pub seckey_scan: SecretKey, -} - -impl Wallet { - pub fn new() -> Wallet { - let secp: Secp256k1 = Secp256k1::new(); - let mut rng: ThreadRng = thread_rng(); - let seckey_spend: SecretKey = SecretKey::new(rng); - let seckey_scan: SecretKey = SecretKey::new(rng); - Wallet { - client: SpClient::new(), - secp, - seckey_spend, - seckey_scan, - } - } -} -*/ diff --git a/src/workflows/lib.rs b/src/workflows/lib.rs deleted file mode 100644 index e69de29..0000000 diff --git a/src/workflows/mod.rs b/src/workflows/mod.rs deleted file mode 100644 index 60d256c..0000000 --- a/src/workflows/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod workflow_pcd_create_and_send_all; diff --git a/src/workflows/workflow_pcd_create_and_send_all.rs b/src/workflows/workflow_pcd_create_and_send_all.rs deleted file mode 100644 index 8996b99..0000000 --- a/src/workflows/workflow_pcd_create_and_send_all.rs +++ /dev/null @@ -1,253 +0,0 @@ -use crate::models::{ - commit_method::commitMethod, deposit_method::DepositMethod, item_enum::ItemEnum, - `Envelope` _client::EnvelopeClient, Payments_method::PaymentsMethod, roles_group::RolesGroup, -}; - -use serde::{Deserialize, Serialize}; -use std::hash::Hash; - -use crate::models::{ - key_encryption::KeyEncryption, pagination::Pagination, request_pcd::Pcd, - shared_peer::Peer, shared_process::Process, -}; - -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct ProcessRoleSpAddressGroup { - pub sp_address_list: Vec, - pub role_name: String, -} -impl ProcessRoleSpAddressGroup { - pub fn new(sp_address_list: Vec, role_name: String) -> Self { - ProcessRoleSpAddressGroup { - sp_address_list, - role_name, - } - } - pub fn display_info(&self) { - println!("ProcessRoleSpAddressGroup:"); - println!("SP Address List: {:?}", self.sp_address_list); - println!("Role Name: {}", self.role_name); - } -} - -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] - -pub struct PcdItemEncAttributeRoleConfidentialExportKey { - pub attribute_name: String, - pub key: Option, - pub item_index: usize, -} - -pub struct WorkflowPcdCreateAndSendAll { - pub item_name: String, - pub item_list: Vec, - pub pcd_pagination: Pagination, - pub pcd_version: i64, - pub process_hash: String, - pub pcd_reference_hash: Option, - pub pcd_item_reference_hash: Option, - pub Member_private_enc_key: KeyEncryption, - pub process_public_enc_key: KeyEncryption, - pub roles: RolesGroup, - pub pow_pathern: String, - pub pow_difficulty: usize, - pub `Envelope` _shared_peer_list: Vec, - pub `Envelope` _shared_process_list: Vec, - pub `Envelope` _faucet_sp_address: String, - - pub `Envelope` _public_string: Option, - pub `Envelope` _confidential_string: Option, - pub `Envelope` _private_string: Option, - pub sp_address_from: String, - pub sp_address_reply: String, - pub timestamp_declared: u64, - pub role_name_from: String, - pub role_name_to: String, - pub sig_value: String, - pub pcd_origin_hash: Option, - - pub Payments_method: Option, - pub deposit_method: Option, - pub commit_method: Option, - pub certif_key: Option, -} - -impl WorkflowPcdCreateAndSendAll { - pub fn new( - item_name: String, - item_list: Vec, - pcd_pagination: Pagination, - pcd_version: i64, - process_hash: String, - pcd_reference_hash: Option, - pcd_item_reference_hash: Option, - Member_private_enc_key: KeyEncryption, - process_public_enc_key: KeyEncryption, - roles: RolesGroup, - pow_pathern: String, - pow_difficulty: usize, - `Envelope` _shared_peer_list: Vec, - `Envelope` _shared_process_list: Vec, - `Envelope` _faucet_sp_address: String, - `Envelope` _public_string: Option, - `Envelope` _confidential_string: Option, - `Envelope` _private_string: Option, - sp_address_from: String, - sp_address_reply: String, - timestamp_declared: u64, - role_name_from: String, - role_name_to: String, - sig_value: String, - pcd_origin_hash: Option, - - Payments_method: Option, - deposit_method: Option, - commit_method: Option, - certif_key: Option, - ) -> Self { - WorkflowPcdCreateAndSendAll { - item_name, - item_list, - pcd_pagination, - pcd_version, - process_hash, - pcd_reference_hash, - pcd_item_reference_hash, - Member_private_enc_key, - process_public_enc_key, - roles, - pow_pathern, - pow_difficulty, - `Envelope` _shared_peer_list, - `Envelope` _shared_process_list, - `Envelope` _faucet_sp_address, - - `Envelope` _public_string, - `Envelope` _confidential_string, - `Envelope` _private_string, - sp_address_from, - sp_address_reply, - timestamp_declared, - role_name_from, - role_name_to, - sig_value, - pcd_origin_hash, - Payments_method, - deposit_method, - commit_method, - certif_key, - } - } - pub fn run(&self) { - // walk item list and encrypt attributes - - // create pcd - let pcd: Pcd = Pcd::new( - Some(self.item_name.clone()), - self.pcd_version, - self.process_hash.clone(), - self.pcd_reference_hash.clone(), - self.pcd_item_reference_hash.clone(), - self.item_list.clone(), - self.pcd_pagination.clone(), - self.process_public_enc_key.clone(), - self.Member_private_enc_key.clone(), - ); - - let pcd_message: `Envelope` Client = pcd.to_message( - self.process_public_enc_key.clone(), - self.message_shared_peer_list.clone(), - self.message_shared_process_list.clone(), - self.message_faucet_sp_address.clone(), - self.pow_pathern.clone(), - self.pow_difficulty, - ); - - let mut pcd_keys_role_confidential_list: Vec = - Vec::new(); - - let mut item_index = 0; - for item in &pcd.item_list { - for enc_attribute_list in &item.pcd_item_enc_attribute_role_confidential_list { - for enc_attribute in enc_attribute_list { - let exp = PcdItemEncAttributeRoleConfidentialExportKey { - attribute_name: enc_attribute.attribute_name.clone(), - key: Some(enc_attribute.key.clone()), - item_index, - }; - pcd_keys_role_confidential_list.push(exp); - } - } - item_index += 1; - } - - let prd_list = self.roles.to_prd_response_list( - self.process_public_enc_key.clone(), - self.Member_private_enc_key.clone(), - Some(self.item_name.clone()), - 0, - self.process_hash.clone(), - self.pcd_reference_hash.clone(), - self.pcd_item_reference_hash.clone(), - pcd_keys_role_confidential_list.clone(), - self.message_public_string.clone(), - self.message_confidential_string.clone(), - self.message_private_string.clone(), - self.sp_address_from.clone(), - self.sp_address_reply.clone(), - self.timestamp_declared.clone(), - self.role_name_from.clone(), - self.role_name_to.clone(), - self.sig_value.clone(), - Some(pcd_`Envelope`.request_hash), - self.Payments_method.clone(), - self.deposit_method.clone(), - self.commit_method.clone(), - self.certif_key.clone(), - ); - - for prd in prd_list { - let _prd_message_list = prd.to_message( - self.process_public_enc_key.clone(), - self.message_shared_peer_list.clone(), - self.message_shared_process_list.clone(), - self.message_faucet_sp_address.clone(), - self.pow_pathern.clone(), - self.pow_difficulty, - ); - } - // todo - // send - } - pub fn display_info(&self) { - println!("PcdCreateAndSend:"); - println!("Item Name: {}", self.item_name); - println!("Item List: {:?}", self.item_list); - println!("Pagination: {:?}", self.pcd_pagination); - println!("Version: {}", self.pcd_version); - println!("Process Hash: {}", self.process_hash); - println!("Reference Hash: {:?}", self.pcd_reference_hash); - println!("Item Reference Hash: {:?}", self.pcd_item_reference_hash); - println!( - "Member Private Encryption Key: {:?}", - self.Member_private_enc_key - ); - println!( - "Process Public Encryption Key: {:?}", - self.process_public_enc_key - ); - println!("Process roles: {:?}", self.roles); - println!( - "Message Shared Peer List: {:?}", - self.message_shared_peer_list - ); - println!( - "Message Shared Process List: {:?}", - self.message_shared_process_list - ); - println!( - "Message Faucet SP Address: {:?}", - self.message_faucet_sp_address - ); - } -} From 3dff7922187b8647775641d9d9ba1fd1b06ff3c5 Mon Sep 17 00:00:00 2001 From: Sosthene00 <674694@protonmail.ch> Date: Tue, 9 Apr 2024 12:58:41 +0200 Subject: [PATCH 02/30] Add crypto mod --- Cargo.toml | 5 +- src/crypto.rs | 441 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 4 +- 3 files changed, 445 insertions(+), 5 deletions(-) create mode 100644 src/crypto.rs diff --git a/Cargo.toml b/Cargo.toml index 6dcc1a1..1737a6a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,9 +7,10 @@ edition = "2021" crate-type = ["cdylib", "rlib"] [dependencies] +anyhow = "1.0" serde = { version = "1.0.193", features = ["derive"] } serde_json = "1.0.108" -sp_backend = { git = "https://github.com/Sosthene00/sp-backend.git", branch = "master" } +sp_backend = { git = "https://github.com/Sosthene00/sp-backend.git", branch = "sp_client" } uuid = { version = "1.6.1", features = ["serde", "v4"] } aes-gcm = "0.10.3" -aes = "0.8.3" +rand = "0.8.5" diff --git a/src/crypto.rs b/src/crypto.rs new file mode 100644 index 0000000..3873b1d --- /dev/null +++ b/src/crypto.rs @@ -0,0 +1,441 @@ +use std::collections::HashMap; + +use anyhow::{Error, Result}; +use sp_backend::{ + bitcoin::{ + consensus::serde::hex, + hex::DisplayHex, + key::constants::SECRET_KEY_SIZE, + secp256k1::{ecdh::SharedSecret, SecretKey}, + Txid, + }, + silentpayments::sending::SilentPaymentAddress, +}; + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use aes_gcm::{ + aead::{Aead, AeadInPlace, KeyInit, Nonce}, + AeadCore, Aes256Gcm, AesGcm, Key, TagSize, + aes::{Aes256, cipher::{generic_array::GenericArray, consts::{U32, U8}}}, +}; +use rand::thread_rng; + +const HALFKEYSIZE: usize = SECRET_KEY_SIZE / 2; + +const THIRTYTWO: usize = 32; + +pub struct HalfKey([u8; HALFKEYSIZE]); + +impl TryFrom> for HalfKey { + type Error = anyhow::Error; + fn try_from(value: Vec) -> std::prelude::v1::Result { + if value.len() == HALFKEYSIZE { + let mut buf = [0u8; HALFKEYSIZE]; + buf.copy_from_slice(&value); + Ok(HalfKey(buf)) + } else { + Err(Error::msg("Invalid length for HalfKey")) + } + } +} + +impl HalfKey { + pub fn as_slice(&self) -> &[u8] { + &self.0 + } + + pub fn to_inner(&self) -> Vec { + self.0.to_vec() + } +} + +pub enum Purpose { + Login, + ThirtyTwoBytes, +} + +pub type CipherText = Vec; + +pub type EncryptedKey = Vec; + +pub struct Aes256Decryption { + pub purpose: Purpose, + cipher_text: CipherText, + aes_key: [u8; 32], + nonce: [u8; 12], +} + +impl Aes256Decryption { + pub fn new( + purpose: Purpose, + cipher_text: CipherText, + encrypted_aes_key: Vec, // If shared_secret is none this is actually the aes_key + shared_secret: Option, // We don't need that for certain purpose, like Login + ) -> Result { + let mut aes_key = [0u8; 32]; + if let Some(shared_secret) = shared_secret { + if encrypted_aes_key.len() <= 12 { + return Err(Error::msg("encrypted_aes_key is shorter than nonce length")); + } // Actually we could probably test that if the remnant is not a multiple of 32, something's wrong + // take the first 12 bytes form encrypted_aes_key as nonce + let (decrypt_key_nonce, encrypted_key) = encrypted_aes_key.split_at(12); + // decrypt key with shared_secret obtained from transaction + let decrypt_key_cipher = Aes256Gcm::new_from_slice(shared_secret.as_ref()) + .map_err(|e| Error::msg(format!("{}", e)))?; + let aes_key_plain = decrypt_key_cipher + .decrypt(decrypt_key_nonce.into(), encrypted_key) + .map_err(|e| Error::msg(format!("{}", e)))?; + if aes_key_plain.len() != 32 { + return Err(Error::msg("Invalid length for decrypted key")); + } + aes_key.copy_from_slice(&aes_key_plain); + } else { + if encrypted_aes_key.len() != 32 { + return Err(Error::msg("Invalid length for decrypted key")); + } + aes_key.copy_from_slice(&encrypted_aes_key); + } + if cipher_text.len() <= 12 { + return Err(Error::msg("cipher_text is shorter than nonce length")); + } + let (message_nonce, message_cipher) = cipher_text.split_at(12); + let mut nonce = [0u8; 12]; + nonce.copy_from_slice(message_nonce); + Ok(Self { + purpose, + cipher_text: message_cipher.to_vec(), + aes_key, + nonce, + }) + } + + pub fn decrypt_with_key(&self) -> Result> { + match self.purpose { + Purpose::Login => { + let half_key = self.decrypt_login()?; + Ok(half_key.to_inner()) + } + Purpose::ThirtyTwoBytes => { + let thirty_two_buf = self.decrypt_thirty_two()?; + Ok(thirty_two_buf.to_vec()) + } + } + } + + fn decrypt_login(&self) -> Result { + let cipher = Aes256Gcm::new(&self.aes_key.into()); + let plain = cipher + .decrypt(&self.nonce.into(), &*self.cipher_text) + .map_err(|e| Error::msg(format!("{}", e)))?; + if plain.len() != SECRET_KEY_SIZE / 2 { + return Err(Error::msg("Plain text of invalid lenght for a login")); + } + let mut key_half = [0u8; SECRET_KEY_SIZE / 2]; + key_half.copy_from_slice(&plain); + Ok(HalfKey(key_half)) + } + + fn decrypt_thirty_two(&self) -> Result<[u8; THIRTYTWO]> { + let cipher = Aes256Gcm::new(&self.aes_key.into()); + let plain = cipher + .decrypt(&self.nonce.into(), &*self.cipher_text) + .map_err(|e| Error::msg(format!("{}", e)))?; + if plain.len() != THIRTYTWO { + return Err(Error::msg("Plain text of invalid length, should be 32")); + } + let mut thirty_two = [0u8; THIRTYTWO]; + thirty_two.copy_from_slice(&plain); + Ok(thirty_two) + } +} + +pub struct Aes256Encryption { + pub purpose: Purpose, + plaintext: Vec, + aes_key: [u8; 32], + nonce: [u8; 12], + shared_secrets: HashMap>, +} + +impl Aes256Encryption { + pub fn new(purpose: Purpose, plaintext: Vec) -> Result { + let mut rng = thread_rng(); + let aes_key: [u8; 32] = Aes256Gcm::generate_key(&mut rng).into(); + let nonce: [u8; 12] = Aes256Gcm::generate_nonce(&mut rng).into(); + Self::import_key(purpose, plaintext, aes_key, nonce) + } + + pub fn set_shared_secret( + &mut self, + shared_secrets: HashMap>, + ) { + self.shared_secrets = shared_secrets; + } + + pub fn encrypt_keys_with_shared_secrets( + &self, + ) -> Result> { + let mut res = HashMap::new(); + let mut rng = thread_rng(); + + for (_, sp_address2shared_secret) in self.shared_secrets.iter() { + for (sp_address, shared_secret) in sp_address2shared_secret { + let cipher = Aes256Gcm::new_from_slice(shared_secret.as_ref()) + .map_err(|e| Error::msg(format!("{}", e)))?; + let nonce = Aes256Gcm::generate_nonce(&mut rng); + let encrypted_key = cipher + .encrypt(&nonce, self.aes_key.as_slice()) + .map_err(|e| Error::msg(format!("{}", e)))?; + + let mut ciphertext = Vec::::with_capacity(nonce.len() + encrypted_key.len()); + ciphertext.extend(nonce); + ciphertext.extend(encrypted_key); + + res.insert(sp_address.to_owned(), ciphertext); + } + } + Ok(res) + } + + pub fn import_key( + purpose: Purpose, + plaintext: Vec, + aes_key: [u8; 32], + nonce: [u8; 12], + ) -> Result { + if plaintext.len() == 0 { + return Err(Error::msg("Can't create encryption for an empty message")); + } + Ok(Self { + purpose, + plaintext, + aes_key, + nonce, + shared_secrets: HashMap::new(), + }) + } + + pub fn encrypt_with_aes_key(&self) -> Result { + match self.purpose { + Purpose::Login => self.encrypt_login(), + Purpose::ThirtyTwoBytes => self.encrypt_thirty_two(), + } + } + + fn encrypt_login(&self) -> Result { + let half_key: HalfKey = self.plaintext.clone().try_into()?; + let cipher = Aes256Gcm::new(&self.aes_key.into()); + let cipher_text = cipher + .encrypt(&self.nonce.into(), half_key.as_slice()) + .map_err(|e| Error::msg(format!("{}", e)))?; + let mut res = Vec::with_capacity(self.nonce.len() + cipher_text.len()); + res.extend_from_slice(&self.nonce); + res.extend_from_slice(&cipher_text); + Ok(res) + } + + fn encrypt_thirty_two(&self) -> Result { + if self.plaintext.len() != 32 { + return Err(Error::msg("Invalid length, should be 32")); + } + let mut thirty_two = [0u8; 32]; + thirty_two.copy_from_slice(&self.plaintext); + let cipher = Aes256Gcm::new(&self.aes_key.into()); + let cipher_text = cipher + .encrypt(&self.nonce.into(), thirty_two.as_slice()) + .map_err(|e| Error::msg(format!("{}", e)))?; + let mut res = Vec::with_capacity(self.nonce.len() + cipher_text.len()); + res.extend_from_slice(&self.nonce); + res.extend_from_slice(&cipher_text); + Ok(res) + } +} + +#[cfg(test)] +mod tests { + use std::str::FromStr; + + use super::*; + + const ALICE_SP_ADDRESS: &str = "tsp1qqw3lqr6xravz9nf8ntazgwwl0fqv47kfjdxsnxs6eutavqfwyv5q6qk97mmyf6dtkdyzqlu2zv6h9j2ggclk7vn705q5u2phglpq7yw3dg5rwpdz"; + const BOB_SP_ADDRESS: &str = "tsp1qq2hlsgrj0gz8kcfkf9flqw5llz0u2vr04telqndku9mcqm6dl4fhvq60t8r78srrf56w9yr7w9e9dusc2wjqc30up6fjwnh9mw3e3veqegdmtf08"; + const TRANSACTION: &str = "4e6d03dec558e1b6624f813bf2da7cd8d8fb1c2296684c08cf38724dcfd8d10b"; + const ALICE_SHARED_SECRET: &str = + "ccf02d364c2641ca129a3fdf49de57b705896e233f7ba6d738991993ea7e2106"; + const BOB_SHARED_SECRET: &str = + "15ef3e377fb842e81de52dbaaea8ba30aeb051a81043ee19264afd27353da521"; + + #[test] + fn new_aes_empty_plaintext() { + let plaintext = Vec::new(); + let aes_enc = Aes256Encryption::new(Purpose::Login, plaintext); + + assert!(aes_enc.is_err()); + } + + #[test] + fn aes_encrypt_login_invalid_length() { + let plaintext = "example"; + let aes_enc_short = Aes256Encryption::new(Purpose::Login, plaintext.as_bytes().to_vec()); + + assert!(aes_enc_short.is_ok()); + + let cipher = aes_enc_short.unwrap().encrypt_with_aes_key(); + + assert!(cipher.is_err()); + + let plaintext = [1u8; 64]; + let aes_enc_long = Aes256Encryption::new(Purpose::Login, plaintext.to_vec()); + + assert!(aes_enc_long.is_ok()); + + let cipher = aes_enc_long.unwrap().encrypt_with_aes_key(); + + assert!(cipher.is_err()); + } + + #[test] + fn aes_encrypt_login() { + let plaintext = [1u8; HALFKEYSIZE]; + let aes_key = Aes256Gcm::generate_key(&mut thread_rng()); + let nonce = Aes256Gcm::generate_nonce(&mut thread_rng()); + let aes_enc = Aes256Encryption::import_key( + Purpose::Login, + plaintext.to_vec(), + aes_key.into(), + nonce.into(), + ); + + assert!(aes_enc.is_ok()); + + let cipher = aes_enc.unwrap().encrypt_with_aes_key(); + + assert!(cipher.is_ok()); + + let mut plain_key = [0u8; 32]; + plain_key.copy_from_slice(&aes_key.to_vec()); + + let aes_dec = + Aes256Decryption::new(Purpose::Login, cipher.unwrap(), plain_key.to_vec(), None); + + assert!(aes_dec.is_ok()); + } + + #[test] + fn aes_encrypt_key() { + let plaintext = [1u8; HALFKEYSIZE]; + let mut aes_enc = Aes256Encryption::new(Purpose::Login, plaintext.to_vec()).unwrap(); + + let mut shared_secrets: HashMap = HashMap::new(); + let mut sp_address2shared_secrets: HashMap = + HashMap::new(); + sp_address2shared_secrets.insert( + ALICE_SP_ADDRESS.try_into().unwrap(), + SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap(), + ); + shared_secrets.insert( + Txid::from_str(TRANSACTION).unwrap(), + sp_address2shared_secrets, + ); + + aes_enc.set_shared_secret(shared_secrets); + + let sp_address2encrypted_keys = aes_enc.encrypt_keys_with_shared_secrets(); + + assert!(sp_address2encrypted_keys.is_ok()); + + let encrypted_key = sp_address2encrypted_keys + .unwrap() + .get(&ALICE_SP_ADDRESS.try_into().unwrap()) + .cloned(); + + let ciphertext = aes_enc.encrypt_with_aes_key(); + + assert!(ciphertext.is_ok()); + + let aes_dec = Aes256Decryption::new( + Purpose::Login, + ciphertext.unwrap(), + encrypted_key.unwrap(), + Some(SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap()), + ); + + assert!(aes_dec.is_ok()); + + let retrieved_plain = aes_dec.unwrap().decrypt_with_key(); + + assert!(retrieved_plain.is_ok()); + + assert!(retrieved_plain.unwrap() == plaintext); + } + + #[test] + fn aes_encrypt_key_many() { + let plaintext = [1u8; THIRTYTWO]; + let mut aes_enc = + Aes256Encryption::new(Purpose::ThirtyTwoBytes, plaintext.to_vec()).unwrap(); + + let mut shared_secrets: HashMap = HashMap::new(); + let mut sp_address2shared_secrets: HashMap = + HashMap::new(); + sp_address2shared_secrets.insert( + ALICE_SP_ADDRESS.try_into().unwrap(), + SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap(), + ); + sp_address2shared_secrets.insert( + BOB_SP_ADDRESS.try_into().unwrap(), + SharedSecret::from_str(BOB_SHARED_SECRET).unwrap(), + ); + shared_secrets.insert( + Txid::from_str(TRANSACTION).unwrap(), + sp_address2shared_secrets, + ); + + aes_enc.set_shared_secret(shared_secrets); + + let mut sp_address2encrypted_keys = aes_enc.encrypt_keys_with_shared_secrets(); + + assert!(sp_address2encrypted_keys.is_ok()); + + // Alice + let encrypted_key = sp_address2encrypted_keys + .as_mut() + .unwrap() + .get(&ALICE_SP_ADDRESS.try_into().unwrap()) + .cloned(); + + let ciphertext = aes_enc.encrypt_with_aes_key(); + + let aes_dec = Aes256Decryption::new( + Purpose::ThirtyTwoBytes, + ciphertext.unwrap(), + encrypted_key.unwrap(), + Some(SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap()), + ); + + let retrieved_plain = aes_dec.unwrap().decrypt_with_key(); + + assert!(retrieved_plain.unwrap() == plaintext); + + // Bob + let encrypted_key = sp_address2encrypted_keys + .unwrap() + .get(&BOB_SP_ADDRESS.try_into().unwrap()) + .cloned(); + + let ciphertext = aes_enc.encrypt_with_aes_key(); + + let aes_dec = Aes256Decryption::new( + Purpose::ThirtyTwoBytes, + ciphertext.unwrap(), + encrypted_key.unwrap(), + Some(SharedSecret::from_str(BOB_SHARED_SECRET).unwrap()), + ); + + let retrieved_plain = aes_dec.unwrap().decrypt_with_key(); + + assert!(retrieved_plain.unwrap() == plaintext); + } +} diff --git a/src/lib.rs b/src/lib.rs index c21f7c9..274f0ed 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1 @@ -pub mod models; -pub mod wallet; -pub mod workflows; +pub mod crypto; From 76dd12aaac9ac9d83a6ce870d138fb46f26cece3 Mon Sep 17 00:00:00 2001 From: Sosthene00 <674694@protonmail.ch> Date: Wed, 17 Apr 2024 08:27:16 +0200 Subject: [PATCH 03/30] Add network --- Cargo.toml | 2 + src/lib.rs | 1 + src/network.rs | 248 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 251 insertions(+) create mode 100644 src/network.rs diff --git a/Cargo.toml b/Cargo.toml index 1737a6a..6128ce2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,3 +14,5 @@ sp_backend = { git = "https://github.com/Sosthene00/sp-backend.git", branch = "s uuid = { version = "1.6.1", features = ["serde", "v4"] } aes-gcm = "0.10.3" rand = "0.8.5" +tsify = { git = "https://github.com/Sosthene00/tsify", branch = "next" } +wasm-bindgen = "0.2.91" diff --git a/src/lib.rs b/src/lib.rs index 274f0ed..a688c6e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1,2 @@ pub mod crypto; +pub mod network; diff --git a/src/network.rs b/src/network.rs new file mode 100644 index 0000000..274ab04 --- /dev/null +++ b/src/network.rs @@ -0,0 +1,248 @@ +use std::str::FromStr; + +use anyhow::{Error, Result}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sp_backend::bitcoin::key::constants::ZERO; +use sp_backend::bitcoin::{consensus::deserialize, hashes, secp256k1::PublicKey, Transaction}; +use sp_backend::bitcoin::{OutPoint, Txid}; +use sp_backend::silentpayments::bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine}; +use tsify::Tsify; + +use crate::crypto::CipherText; + +const RAWTXTOPIC: &'static str = "rawtx"; +const RAWBLOCKTOPIC: &'static str = "rawblock"; +const ANKMAGIC: [u8; 4] = [0x34, 0x6E, 0x6B, 0x30]; + +#[derive(Debug, Serialize, Deserialize)] +pub enum BitcoinTopic { + RawTx, + RawBlock, +} + +impl BitcoinTopic { + pub fn as_str(&self) -> &str { + match self { + Self::RawTx => RAWTXTOPIC, + Self::RawBlock => RAWBLOCKTOPIC, + } + } +} + +#[derive(Debug, Serialize, Deserialize, Tsify)] +#[tsify(from_wasm_abi, into_wasm_abi)] +pub struct BitcoinNetworkMsg<'a> { + pub topic: BitcoinTopic, + pub data: &'a [u8], + pub sequence: &'a [u8], + pub addon: &'a [u8], +} + +impl<'a> BitcoinNetworkMsg<'a> { + pub fn new(raw_msg: &'a [u8]) -> Result { + let topic: BitcoinTopic; + let data: &[u8]; + let sequence: &[u8]; + let addon: &[u8]; + let addon_len: usize; + let raw_msg_len = raw_msg.len(); + + if raw_msg.starts_with(RAWTXTOPIC.as_bytes()) { + topic = BitcoinTopic::RawTx; + addon_len = 33; + } else if raw_msg.starts_with(RAWBLOCKTOPIC.as_bytes()) { + topic = BitcoinTopic::RawBlock; + addon_len = 0; + } else { + return Err(Error::msg("Unknown prefix")); + } + + data = &raw_msg[topic.as_str().as_bytes().len()..raw_msg_len - 4 - addon_len]; + sequence = &raw_msg[raw_msg_len - 4 - addon_len..]; + addon = &raw_msg[raw_msg_len - addon_len..]; + + Ok(Self { + topic, + data, + sequence, + addon, + }) + } +} + +sha256t_hash_newtype! { + pub struct PcdTag = hash_str("4nk/PCD"); + + #[hash_newtype(forward)] + pub struct PcdHash(_); + + pub struct PrdTag = hash_str("4nk/PRD"); + + #[hash_newtype(forward)] + pub struct PrdHash(_); +} + +impl PcdHash { + pub fn from_pcd(pcd: Pcd) -> Result { + let mut eng = PcdHash::engine(); + eng.input(&serde_json::to_string(&pcd)?.into_bytes()); + Ok(PcdHash::from_engine(eng)) + } +} + +impl PrdHash { + pub fn from_prd(prd: Prd) -> Result { + let mut eng = PrdHash::engine(); + eng.input(&serde_json::to_string(&prd)?.into_bytes()); + Ok(PrdHash::from_engine(eng)) + } +} + +type Item = String; // Is either a stringified json or the hex representation of its cipher + +#[derive(Debug, Serialize, Deserialize)] +pub struct Pcd { + name: String, + items: Item, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Prd { + name: String, + seal: Option, + key: Option>, // encrypted key used to decrypt the linked pcd + pcd: PcdHash, +} + +impl Default for Prd { + fn default() -> Self { + Self { + name: "".to_owned(), + seal: None, + key: None, + pcd: PcdHash::from_byte_array(ZERO), + } + } +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Envelope { + encrypted_prd: CipherText, +} + +impl Envelope { + pub fn new(encrypted_prd: Vec) -> Result { + Ok(Self { encrypted_prd }) + } +} + +#[derive(Debug, Serialize, Deserialize, Tsify)] +#[tsify(into_wasm_abi, from_wasm_abi)] +pub enum AnkFlag { + NewTx, + Faucet, + Error, + Unknown, +} + +impl From<&str> for AnkFlag { + fn from(value: &str) -> Self { + match value { + "NewTx" => Self::NewTx, + "Faucet" => Self::Faucet, + "Error" => Self::Error, + _ => Self::Unknown + } + } +} + +impl From for AnkFlag { + fn from(value: String) -> Self { + (&value[..]).into() + } +} + +impl AnkFlag { + pub fn new_from_byte(byte: u8) -> Self { + match byte { + 0 => Self::NewTx, + 1 => Self::Faucet, + 2 => Self::Error, + _ => Self::Unknown + } + } + + pub fn as_str(&self) -> &str { + match self { + Self::NewTx => "new_tx", + Self::Faucet => "faucet", + Self::Error => "error", + Self::Unknown => "unknown" + } + } +} + +#[derive(Debug, Serialize, Deserialize, Tsify)] +#[tsify(into_wasm_abi, from_wasm_abi)] +pub struct FaucetMessage { + pub sp_address: String, +} + +impl FaucetMessage { + pub fn new(sp_address: String) -> Self { + Self { + sp_address + } + } +} + +#[derive(Debug, Serialize, Deserialize, Tsify)] +#[tsify(into_wasm_abi, from_wasm_abi)] +pub struct NewTxMessage { + pub transaction: String, + pub tweak_data: Option +} + +impl NewTxMessage { + pub fn new(transaction: String, tweak_data: Option) -> Self { + Self { + transaction, + tweak_data + } + } +} + +#[derive(Debug, Serialize, Deserialize, Tsify)] +#[tsify(into_wasm_abi, from_wasm_abi)] +pub struct AnkNetworkMsg { + pub flag: AnkFlag, + pub content: String, +} + +// impl TryFrom<&str> for AnkNetworkMsg { +// type Error = anyhow::Error; +// fn try_from(value: &str) -> std::prelude::v1::Result { +// let parsed: Value = serde_json::from_str(value)?; +// let flag = parsed +// .get("flag") +// .ok_or(Error::msg("Invalid AnkNetworkMsg"))? +// .as_str() +// .ok_or(Error::msg("Invalid AnkNetworkMsg"))?; +// let content = parsed +// .get("content") +// .ok_or(Error::msg("Invalid AnkNetworkMsg"))? +// .as_str() +// .ok_or(Error::msg("Invalid AnkNetworkMsg"))?; +// Ok(Self { flag: flag.into(), content: content.into() }) +// } +// } + +impl AnkNetworkMsg { + pub fn new(flag: AnkFlag, raw: &str) -> Self { + Self { + flag, + content: raw.into() + } + } +} From d24401ada8604dae53c145f6738831adc9362690 Mon Sep 17 00:00:00 2001 From: Sosthene00 <674694@protonmail.ch> Date: Wed, 17 Apr 2024 08:27:46 +0200 Subject: [PATCH 04/30] Add AnkSharedSecret --- src/crypto.rs | 55 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 50 insertions(+), 5 deletions(-) diff --git a/src/crypto.rs b/src/crypto.rs index 3873b1d..71eb324 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -6,26 +6,71 @@ use sp_backend::{ consensus::serde::hex, hex::DisplayHex, key::constants::SECRET_KEY_SIZE, - secp256k1::{ecdh::SharedSecret, SecretKey}, + secp256k1::{ecdh::SharedSecret, PublicKey, SecretKey}, Txid, }, - silentpayments::sending::SilentPaymentAddress, + silentpayments::{ + sending::SilentPaymentAddress, + bitcoin_hashes::{sha256t_hash_newtype, HashEngine, Hash} + }, }; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use aes_gcm::{ - aead::{Aead, AeadInPlace, KeyInit, Nonce}, - AeadCore, Aes256Gcm, AesGcm, Key, TagSize, - aes::{Aes256, cipher::{generic_array::GenericArray, consts::{U32, U8}}}, + aead::{Aead, AeadInPlace, Nonce}, + aes::{ + cipher::{ + consts::{U32, U8}, + generic_array::GenericArray, + }, + Aes256, + }, + AesGcm, Key, TagSize, }; +pub use aes_gcm::{AeadCore, Aes256Gcm, KeyInit}; use rand::thread_rng; const HALFKEYSIZE: usize = SECRET_KEY_SIZE / 2; const THIRTYTWO: usize = 32; +type SharedPublicKey = PublicKey; + +#[derive(Debug)] +pub struct AnkSharedSecret(SharedSecret); + +impl AnkSharedSecret { + pub fn new_from_public_key(public_key: SharedPublicKey) -> Self { + let t_hash = SharedPublicKeyHash::from_shared_pubkey(public_key); + Self(SharedSecret::from_bytes(t_hash.to_byte_array())) + } + + pub fn to_byte_array(&self) -> [u8;SECRET_KEY_SIZE] { + self.0.secret_bytes() + } + + pub fn to_string(&self) -> String { + format!("{}", self.0.display_secret()) + } +} + +sha256t_hash_newtype! { + pub struct SharedPublicKeyTag = hash_str("4nk/SharedPublicKey"); + + #[hash_newtype(forward)] + pub struct SharedPublicKeyHash(_); +} + +impl SharedPublicKeyHash { + pub fn from_shared_pubkey(shared_pubkey: SharedPublicKey) -> Self { + let mut eng = SharedPublicKeyHash::engine(); + eng.input(&shared_pubkey.serialize()); + SharedPublicKeyHash::from_engine(eng) + } +} + pub struct HalfKey([u8; HALFKEYSIZE]); impl TryFrom> for HalfKey { From 8f111119439d0fdc8c4cc3d8bbf3e1a7271713b2 Mon Sep 17 00:00:00 2001 From: Sosthene00 <674694@protonmail.ch> Date: Wed, 17 Apr 2024 21:38:30 +0200 Subject: [PATCH 05/30] replace sp_backend with sp_client --- Cargo.toml | 2 +- src/crypto.rs | 2 +- src/network.rs | 10 +++------- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6128ce2..c63f825 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ crate-type = ["cdylib", "rlib"] anyhow = "1.0" serde = { version = "1.0.193", features = ["derive"] } serde_json = "1.0.108" -sp_backend = { git = "https://github.com/Sosthene00/sp-backend.git", branch = "sp_client" } +sp_client = { git = "https://github.com/Sosthene00/sp-client.git", branch = "sp_client" } uuid = { version = "1.6.1", features = ["serde", "v4"] } aes-gcm = "0.10.3" rand = "0.8.5" diff --git a/src/crypto.rs b/src/crypto.rs index 71eb324..b993983 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use anyhow::{Error, Result}; -use sp_backend::{ +use sp_client::{ bitcoin::{ consensus::serde::hex, hex::DisplayHex, diff --git a/src/network.rs b/src/network.rs index 274ab04..dea07f8 100644 --- a/src/network.rs +++ b/src/network.rs @@ -1,12 +1,8 @@ -use std::str::FromStr; - use anyhow::{Error, Result}; use serde::{Deserialize, Serialize}; -use serde_json::Value; -use sp_backend::bitcoin::key::constants::ZERO; -use sp_backend::bitcoin::{consensus::deserialize, hashes, secp256k1::PublicKey, Transaction}; -use sp_backend::bitcoin::{OutPoint, Txid}; -use sp_backend::silentpayments::bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine}; +use sp_client::bitcoin::key::constants::ZERO; +use sp_client::bitcoin::OutPoint; +use sp_client::silentpayments::bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine}; use tsify::Tsify; use crate::crypto::CipherText; From 9a34a0206309fb02b195c62921e34ed59897b54c Mon Sep 17 00:00:00 2001 From: Sosthene00 Date: Thu, 18 Apr 2024 23:10:18 +0200 Subject: [PATCH 06/30] crypto add arbitrary purpose --- src/crypto.rs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/crypto.rs b/src/crypto.rs index b993983..ac4d4ee 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -10,8 +10,8 @@ use sp_client::{ Txid, }, silentpayments::{ - sending::SilentPaymentAddress, - bitcoin_hashes::{sha256t_hash_newtype, HashEngine, Hash} + bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine}, + sending::SilentPaymentAddress, }, }; @@ -47,7 +47,7 @@ impl AnkSharedSecret { Self(SharedSecret::from_bytes(t_hash.to_byte_array())) } - pub fn to_byte_array(&self) -> [u8;SECRET_KEY_SIZE] { + pub fn to_byte_array(&self) -> [u8; SECRET_KEY_SIZE] { self.0.secret_bytes() } @@ -99,6 +99,7 @@ impl HalfKey { pub enum Purpose { Login, ThirtyTwoBytes, + Arbitrary, } pub type CipherText = Vec; @@ -166,6 +167,10 @@ impl Aes256Decryption { let thirty_two_buf = self.decrypt_thirty_two()?; Ok(thirty_two_buf.to_vec()) } + Purpose::Arbitrary => { + let arbitrary = self.decrypt_arbitrary()?; + Ok(arbitrary) + } } } @@ -194,6 +199,14 @@ impl Aes256Decryption { thirty_two.copy_from_slice(&plain); Ok(thirty_two) } + + fn decrypt_arbitrary(&self) -> Result> { + let cipher = Aes256Gcm::new(&self.aes_key.into()); + let plain = cipher + .decrypt(&self.nonce.into(), &*self.cipher_text) + .map_err(|e| Error::msg(format!("{}", e)))?; + Ok(plain) + } } pub struct Aes256Encryption { @@ -266,6 +279,7 @@ impl Aes256Encryption { match self.purpose { Purpose::Login => self.encrypt_login(), Purpose::ThirtyTwoBytes => self.encrypt_thirty_two(), + Purpose::Arbitrary => self.encrypt_arbitrary(), } } @@ -296,6 +310,17 @@ impl Aes256Encryption { res.extend_from_slice(&cipher_text); Ok(res) } + + fn encrypt_arbitrary(&self) -> Result { + let cipher = Aes256Gcm::new(&self.aes_key.into()); + let cipher_text = cipher + .encrypt(&self.nonce.into(), &*self.plaintext) + .map_err(|e| Error::msg(format!("{}", e)))?; + let mut res = Vec::with_capacity(self.nonce.len() + cipher_text.len()); + res.extend_from_slice(&self.nonce); + res.extend_from_slice(&cipher_text); + Ok(res) + } } #[cfg(test)] From b1bfe0ba220fcd3f5966501b915aec6f7577f74d Mon Sep 17 00:00:00 2001 From: Sosthene00 Date: Wed, 24 Apr 2024 12:10:10 +0200 Subject: [PATCH 07/30] update_meeting --- src/crypto.rs | 81 ++++++++++++++++++------------ src/lib.rs | 1 + src/network.rs | 34 +++++++------ src/silentpayments.rs | 113 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 180 insertions(+), 49 deletions(-) create mode 100644 src/silentpayments.rs diff --git a/src/crypto.rs b/src/crypto.rs index ac4d4ee..df17729 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -1,12 +1,11 @@ use std::collections::HashMap; use anyhow::{Error, Result}; +use serde::{Deserialize, Serialize}; use sp_client::{ bitcoin::{ - consensus::serde::hex, - hex::DisplayHex, key::constants::SECRET_KEY_SIZE, - secp256k1::{ecdh::SharedSecret, PublicKey, SecretKey}, + secp256k1::{ecdh::SharedSecret, PublicKey}, Txid, }, silentpayments::{ @@ -14,9 +13,7 @@ use sp_client::{ sending::SilentPaymentAddress, }, }; - -use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; +use tsify::Tsify; use aes_gcm::{ aead::{Aead, AeadInPlace, Nonce}, @@ -36,38 +33,45 @@ const HALFKEYSIZE: usize = SECRET_KEY_SIZE / 2; const THIRTYTWO: usize = 32; -type SharedPublicKey = PublicKey; - #[derive(Debug)] -pub struct AnkSharedSecret(SharedSecret); +pub struct SharedPoint([u8; 64]); + +impl SharedPoint { + pub fn as_inner(&self) -> &[u8; 64] { + &self.0 + } +} + +#[derive(Debug, Serialize, Deserialize, Tsify, Clone)] +#[tsify(from_wasm_abi, into_wasm_abi)] +pub struct AnkSharedSecret { + secret: [u8; 32], + pub trusted: bool, +} impl AnkSharedSecret { - pub fn new_from_public_key(public_key: SharedPublicKey) -> Self { - let t_hash = SharedPublicKeyHash::from_shared_pubkey(public_key); - Self(SharedSecret::from_bytes(t_hash.to_byte_array())) + pub fn new(shared_point: [u8; 64], trusted: bool) -> Self { + let secret = AnkSharedSecretHash::from_shared_point(shared_point).to_byte_array(); + Self { secret, trusted } } - pub fn to_byte_array(&self) -> [u8; SECRET_KEY_SIZE] { - self.0.secret_bytes() - } - - pub fn to_string(&self) -> String { - format!("{}", self.0.display_secret()) + pub fn to_byte_array(&self) -> [u8; 32] { + self.secret } } sha256t_hash_newtype! { - pub struct SharedPublicKeyTag = hash_str("4nk/SharedPublicKey"); + pub struct AnkSharedSecretTag = hash_str("4nk/AnkSharedSecret"); #[hash_newtype(forward)] - pub struct SharedPublicKeyHash(_); + pub struct AnkSharedSecretHash(_); } -impl SharedPublicKeyHash { - pub fn from_shared_pubkey(shared_pubkey: SharedPublicKey) -> Self { - let mut eng = SharedPublicKeyHash::engine(); - eng.input(&shared_pubkey.serialize()); - SharedPublicKeyHash::from_engine(eng) +impl AnkSharedSecretHash { + pub fn from_shared_point(shared_point: [u8; 64]) -> Self { + let mut eng = AnkSharedSecretHash::engine(); + eng.input(&shared_point); + AnkSharedSecretHash::from_engine(eng) } } @@ -214,7 +218,7 @@ pub struct Aes256Encryption { plaintext: Vec, aes_key: [u8; 32], nonce: [u8; 12], - shared_secrets: HashMap>, + shared_secrets: HashMap>, } impl Aes256Encryption { @@ -227,7 +231,7 @@ impl Aes256Encryption { pub fn set_shared_secret( &mut self, - shared_secrets: HashMap>, + shared_secrets: HashMap>, ) { self.shared_secrets = shared_secrets; } @@ -240,7 +244,7 @@ impl Aes256Encryption { for (_, sp_address2shared_secret) in self.shared_secrets.iter() { for (sp_address, shared_secret) in sp_address2shared_secret { - let cipher = Aes256Gcm::new_from_slice(shared_secret.as_ref()) + let cipher = Aes256Gcm::new_from_slice(&shared_secret.secret) .map_err(|e| Error::msg(format!("{}", e)))?; let nonce = Aes256Gcm::generate_nonce(&mut rng); let encrypted_key = cipher @@ -327,6 +331,8 @@ impl Aes256Encryption { mod tests { use std::str::FromStr; + use sp_client::bitcoin::hex::FromHex; + use super::*; const ALICE_SP_ADDRESS: &str = "tsp1qqw3lqr6xravz9nf8ntazgwwl0fqv47kfjdxsnxs6eutavqfwyv5q6qk97mmyf6dtkdyzqlu2zv6h9j2ggclk7vn705q5u2phglpq7yw3dg5rwpdz"; @@ -399,11 +405,14 @@ mod tests { let mut aes_enc = Aes256Encryption::new(Purpose::Login, plaintext.to_vec()).unwrap(); let mut shared_secrets: HashMap = HashMap::new(); - let mut sp_address2shared_secrets: HashMap = + let mut sp_address2shared_secrets: HashMap = HashMap::new(); + let alice_secret = Vec::from_hex(ALICE_SHARED_SECRET).unwrap(); + let mut buf = [0u8;32]; + buf.copy_from_slice(&alice_secret); sp_address2shared_secrets.insert( ALICE_SP_ADDRESS.try_into().unwrap(), - SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap(), + AnkSharedSecret { secret: buf, trusted: true } ); shared_secrets.insert( Txid::from_str(TRANSACTION).unwrap(), @@ -448,15 +457,21 @@ mod tests { Aes256Encryption::new(Purpose::ThirtyTwoBytes, plaintext.to_vec()).unwrap(); let mut shared_secrets: HashMap = HashMap::new(); - let mut sp_address2shared_secrets: HashMap = + let mut sp_address2shared_secrets: HashMap = HashMap::new(); + let alice_secret = Vec::from_hex(ALICE_SHARED_SECRET).unwrap(); + let mut buf = [0u8;32]; + buf.copy_from_slice(&alice_secret); sp_address2shared_secrets.insert( ALICE_SP_ADDRESS.try_into().unwrap(), - SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap(), + AnkSharedSecret { secret: buf, trusted: true } ); + let bob_secret = Vec::from_hex(BOB_SHARED_SECRET).unwrap(); + let mut buf = [0u8;32]; + buf.copy_from_slice(&bob_secret); sp_address2shared_secrets.insert( BOB_SP_ADDRESS.try_into().unwrap(), - SharedSecret::from_str(BOB_SHARED_SECRET).unwrap(), + AnkSharedSecret { secret: buf, trusted: true } ); shared_secrets.insert( Txid::from_str(TRANSACTION).unwrap(), diff --git a/src/lib.rs b/src/lib.rs index a688c6e..48fa577 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,3 @@ pub mod crypto; pub mod network; +pub mod silentpayments; diff --git a/src/network.rs b/src/network.rs index dea07f8..c4204e6 100644 --- a/src/network.rs +++ b/src/network.rs @@ -138,17 +138,19 @@ impl Envelope { pub enum AnkFlag { NewTx, Faucet, + Prd, Error, Unknown, } impl From<&str> for AnkFlag { - fn from(value: &str) -> Self { + fn from(value: &str) -> Self { match value { "NewTx" => Self::NewTx, "Faucet" => Self::Faucet, + "Prd" => Self::Prd, "Error" => Self::Error, - _ => Self::Unknown + _ => Self::Unknown, } } } @@ -164,8 +166,9 @@ impl AnkFlag { match byte { 0 => Self::NewTx, 1 => Self::Faucet, - 2 => Self::Error, - _ => Self::Unknown + 2 => Self::Prd, + 9 => Self::Error, + _ => Self::Unknown, } } @@ -173,8 +176,9 @@ impl AnkFlag { match self { Self::NewTx => "new_tx", Self::Faucet => "faucet", + Self::Prd => "prd", Self::Error => "error", - Self::Unknown => "unknown" + Self::Unknown => "unknown", } } } @@ -187,9 +191,7 @@ pub struct FaucetMessage { impl FaucetMessage { pub fn new(sp_address: String) -> Self { - Self { - sp_address - } + Self { sp_address } } } @@ -197,14 +199,14 @@ impl FaucetMessage { #[tsify(into_wasm_abi, from_wasm_abi)] pub struct NewTxMessage { pub transaction: String, - pub tweak_data: Option + pub tweak_data: Option, } impl NewTxMessage { pub fn new(transaction: String, tweak_data: Option) -> Self { - Self { - transaction, - tweak_data + Self { + transaction, + tweak_data, } } } @@ -220,17 +222,17 @@ pub struct AnkNetworkMsg { // type Error = anyhow::Error; // fn try_from(value: &str) -> std::prelude::v1::Result { // let parsed: Value = serde_json::from_str(value)?; -// let flag = parsed +// let flag = parsed // .get("flag") // .ok_or(Error::msg("Invalid AnkNetworkMsg"))? // .as_str() // .ok_or(Error::msg("Invalid AnkNetworkMsg"))?; -// let content = parsed +// let content = parsed // .get("content") // .ok_or(Error::msg("Invalid AnkNetworkMsg"))? // .as_str() // .ok_or(Error::msg("Invalid AnkNetworkMsg"))?; -// Ok(Self { flag: flag.into(), content: content.into() }) +// Ok(Self { flag: flag.into(), content: content.into() }) // } // } @@ -238,7 +240,7 @@ impl AnkNetworkMsg { pub fn new(flag: AnkFlag, raw: &str) -> Self { Self { flag, - content: raw.into() + content: raw.into(), } } } diff --git a/src/silentpayments.rs b/src/silentpayments.rs new file mode 100644 index 0000000..51c6c34 --- /dev/null +++ b/src/silentpayments.rs @@ -0,0 +1,113 @@ +use std::collections::HashMap; + +use anyhow::{Error, Result}; + +use rand::Rng; +use serde::{Deserialize, Serialize}; +use sp_client::bitcoin::secp256k1::ecdh::shared_secret_point; +use sp_client::bitcoin::{secp256k1::PublicKey, Transaction}; +use sp_client::bitcoin::{Amount, OutPoint, Txid}; +use sp_client::silentpayments::sending::SilentPaymentAddress; +use sp_client::spclient::{OwnedOutput, Recipient, SpClient, SpWallet}; +use tsify::Tsify; + +use crate::crypto::AnkSharedSecret; + +// #[derive(Debug, Serialize, Deserialize, Tsify)] +// #[tsify(into_wasm_abi, from_wasm_abi)] +// pub struct ScannedTransaction(HashMap>); + +// impl ScannedTransaction { +// pub fn new() -> Self { +// Self(HashMap::new()) +// } + +// pub fn get(&self) -> &HashMap> { +// &self.0 +// } + +// pub fn get_mut(&mut self) -> &mut HashMap> { +// &mut self.0 +// } + +// pub fn to_inner(&self) -> HashMap> { +// self.0.clone() +// } +// } + +pub fn create_transaction_for_address_with_shared_secret( + sp_address: SilentPaymentAddress, + sp_wallet: &SpWallet, + message: String, + fee_rate: Amount, +) -> Result<(Transaction, AnkSharedSecret)> { + let available_outpoints = sp_wallet.get_outputs().to_spendable_list(); + + // Here we need to add more heuristics about which outpoint we spend + // For now let's keep it simple + + let mut inputs: HashMap = HashMap::new(); + + let mut total_available = Amount::from_sat(0); + for (outpoint, output) in available_outpoints { + total_available += output.amount; + inputs.insert(outpoint, output); + if total_available > Amount::from_sat(1000) { + break; + } + } + + if total_available < Amount::from_sat(1000) { + return Err(Error::msg("Not enough available funds")); + } + + let recipient = Recipient { + address: sp_address.into(), + amount: Amount::from_sat(1000), + nb_outputs: 1, + }; + + let mut new_psbt = sp_wallet.get_client().create_new_psbt( + inputs, + vec![recipient], + Some(message.as_bytes()), + )?; + + let change_addr = sp_wallet.get_client().sp_receiver.get_change_address(); + SpClient::set_fees(&mut new_psbt, fee_rate, change_addr)?; + + let partial_secret = sp_wallet + .get_client() + .get_partial_secret_from_psbt(&new_psbt)?; + + // This wouldn't work with many recipients in the same transaction + // each address (or more precisely each scan public key) would have its own point + let shared_point = shared_secret_point(&sp_address.get_scan_key(), &partial_secret); + + sp_wallet + .get_client() + .fill_sp_outputs(&mut new_psbt, partial_secret)?; + let mut aux_rand = [0u8; 32]; + rand::thread_rng().fill(&mut aux_rand); + let mut signed = sp_wallet.get_client().sign_psbt(new_psbt, &aux_rand)?; + SpClient::finalize_psbt(&mut signed)?; + + let final_tx = signed.extract_tx()?; + + Ok((final_tx, AnkSharedSecret::new(shared_point, true))) +} + +// This need to go +pub fn check_transaction( + tx: &Transaction, + sp_wallet: &mut SpWallet, + blockheight: u32, + tweak_data: PublicKey, +) -> Result { + let txid = tx.txid().to_string(); + if sp_wallet.update_wallet_with_transaction(tx, blockheight, tweak_data)? > 0 { + return Ok(txid); + } + + return Err(Error::msg("No new outputs found")); +} From a59c680d0e1b5988764beaa7f15ad232f8db1f79 Mon Sep 17 00:00:00 2001 From: Sosthene00 Date: Tue, 30 Apr 2024 11:23:47 +0200 Subject: [PATCH 08/30] crypto simplification --- src/crypto.rs | 185 +++++++++++++++++++++++--------------------------- 1 file changed, 85 insertions(+), 100 deletions(-) diff --git a/src/crypto.rs b/src/crypto.rs index df17729..c14b7b1 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -4,9 +4,7 @@ use anyhow::{Error, Result}; use serde::{Deserialize, Serialize}; use sp_client::{ bitcoin::{ - key::constants::SECRET_KEY_SIZE, - secp256k1::{ecdh::SharedSecret, PublicKey}, - Txid, + hex::{DisplayHex, FromHex}, key::constants::SECRET_KEY_SIZE, secp256k1::{ecdh::SharedSecret, PublicKey}, Txid }, silentpayments::{ bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine}, @@ -45,18 +43,21 @@ impl SharedPoint { #[derive(Debug, Serialize, Deserialize, Tsify, Clone)] #[tsify(from_wasm_abi, into_wasm_abi)] pub struct AnkSharedSecret { - secret: [u8; 32], + secret: String, pub trusted: bool, } impl AnkSharedSecret { pub fn new(shared_point: [u8; 64], trusted: bool) -> Self { let secret = AnkSharedSecretHash::from_shared_point(shared_point).to_byte_array(); - Self { secret, trusted } + Self { secret: secret.to_lower_hex_string(), trusted } } pub fn to_byte_array(&self) -> [u8; 32] { - self.secret + let bytes = Vec::from_hex(&self.secret).unwrap(); + let mut buf = [0u8;32]; + buf.copy_from_slice(&bytes); + buf } } @@ -121,32 +122,8 @@ impl Aes256Decryption { pub fn new( purpose: Purpose, cipher_text: CipherText, - encrypted_aes_key: Vec, // If shared_secret is none this is actually the aes_key - shared_secret: Option, // We don't need that for certain purpose, like Login + aes_key: [u8;32], ) -> Result { - let mut aes_key = [0u8; 32]; - if let Some(shared_secret) = shared_secret { - if encrypted_aes_key.len() <= 12 { - return Err(Error::msg("encrypted_aes_key is shorter than nonce length")); - } // Actually we could probably test that if the remnant is not a multiple of 32, something's wrong - // take the first 12 bytes form encrypted_aes_key as nonce - let (decrypt_key_nonce, encrypted_key) = encrypted_aes_key.split_at(12); - // decrypt key with shared_secret obtained from transaction - let decrypt_key_cipher = Aes256Gcm::new_from_slice(shared_secret.as_ref()) - .map_err(|e| Error::msg(format!("{}", e)))?; - let aes_key_plain = decrypt_key_cipher - .decrypt(decrypt_key_nonce.into(), encrypted_key) - .map_err(|e| Error::msg(format!("{}", e)))?; - if aes_key_plain.len() != 32 { - return Err(Error::msg("Invalid length for decrypted key")); - } - aes_key.copy_from_slice(&aes_key_plain); - } else { - if encrypted_aes_key.len() != 32 { - return Err(Error::msg("Invalid length for decrypted key")); - } - aes_key.copy_from_slice(&encrypted_aes_key); - } if cipher_text.len() <= 12 { return Err(Error::msg("cipher_text is shorter than nonce length")); } @@ -244,7 +221,7 @@ impl Aes256Encryption { for (_, sp_address2shared_secret) in self.shared_secrets.iter() { for (sp_address, shared_secret) in sp_address2shared_secret { - let cipher = Aes256Gcm::new_from_slice(&shared_secret.secret) + let cipher = Aes256Gcm::new_from_slice(&shared_secret.to_byte_array()) .map_err(|e| Error::msg(format!("{}", e)))?; let nonce = Aes256Gcm::generate_nonce(&mut rng); let encrypted_key = cipher @@ -329,7 +306,7 @@ impl Aes256Encryption { #[cfg(test)] mod tests { - use std::str::FromStr; + use std::{io::Read, str::FromStr}; use sp_client::bitcoin::hex::FromHex; @@ -394,7 +371,7 @@ mod tests { plain_key.copy_from_slice(&aes_key.to_vec()); let aes_dec = - Aes256Decryption::new(Purpose::Login, cipher.unwrap(), plain_key.to_vec(), None); + Aes256Decryption::new(Purpose::Login, cipher.unwrap(), plain_key); assert!(aes_dec.is_ok()); } @@ -412,7 +389,7 @@ mod tests { buf.copy_from_slice(&alice_secret); sp_address2shared_secrets.insert( ALICE_SP_ADDRESS.try_into().unwrap(), - AnkSharedSecret { secret: buf, trusted: true } + AnkSharedSecret { secret: buf.to_lower_hex_string(), trusted: true } ); shared_secrets.insert( Txid::from_str(TRANSACTION).unwrap(), @@ -434,93 +411,101 @@ mod tests { assert!(ciphertext.is_ok()); - let aes_dec = Aes256Decryption::new( - Purpose::Login, - ciphertext.unwrap(), + let decrypt_key = Aes256Decryption::new( + Purpose::Arbitrary, encrypted_key.unwrap(), - Some(SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap()), + SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap().secret_bytes(), ); - assert!(aes_dec.is_ok()); + assert!(decrypt_key.is_ok()); - let retrieved_plain = aes_dec.unwrap().decrypt_with_key(); + let mut retrieved_key = [0u8;32]; + retrieved_key.copy_from_slice(&decrypt_key.unwrap().decrypt_with_key().unwrap()); + + let decrypt_msg = Aes256Decryption::new( + Purpose::Arbitrary, + ciphertext.unwrap(), + retrieved_key + ); + + let retrieved_plain = decrypt_msg.unwrap().decrypt_with_key(); assert!(retrieved_plain.is_ok()); assert!(retrieved_plain.unwrap() == plaintext); } - #[test] - fn aes_encrypt_key_many() { - let plaintext = [1u8; THIRTYTWO]; - let mut aes_enc = - Aes256Encryption::new(Purpose::ThirtyTwoBytes, plaintext.to_vec()).unwrap(); +// #[test] +// fn aes_encrypt_key_many() { +// let plaintext = [1u8; THIRTYTWO]; +// let mut aes_enc = +// Aes256Encryption::new(Purpose::ThirtyTwoBytes, plaintext.to_vec()).unwrap(); - let mut shared_secrets: HashMap = HashMap::new(); - let mut sp_address2shared_secrets: HashMap = - HashMap::new(); - let alice_secret = Vec::from_hex(ALICE_SHARED_SECRET).unwrap(); - let mut buf = [0u8;32]; - buf.copy_from_slice(&alice_secret); - sp_address2shared_secrets.insert( - ALICE_SP_ADDRESS.try_into().unwrap(), - AnkSharedSecret { secret: buf, trusted: true } - ); - let bob_secret = Vec::from_hex(BOB_SHARED_SECRET).unwrap(); - let mut buf = [0u8;32]; - buf.copy_from_slice(&bob_secret); - sp_address2shared_secrets.insert( - BOB_SP_ADDRESS.try_into().unwrap(), - AnkSharedSecret { secret: buf, trusted: true } - ); - shared_secrets.insert( - Txid::from_str(TRANSACTION).unwrap(), - sp_address2shared_secrets, - ); +// let mut shared_secrets: HashMap = HashMap::new(); +// let mut sp_address2shared_secrets: HashMap = +// HashMap::new(); +// let alice_secret = Vec::from_hex(ALICE_SHARED_SECRET).unwrap(); +// let mut buf = [0u8;32]; +// buf.copy_from_slice(&alice_secret); +// sp_address2shared_secrets.insert( +// ALICE_SP_ADDRESS.try_into().unwrap(), +// AnkSharedSecret { secret: buf, trusted: true } +// ); +// let bob_secret = Vec::from_hex(BOB_SHARED_SECRET).unwrap(); +// let mut buf = [0u8;32]; +// buf.copy_from_slice(&bob_secret); +// sp_address2shared_secrets.insert( +// BOB_SP_ADDRESS.try_into().unwrap(), +// AnkSharedSecret { secret: buf, trusted: true } +// ); +// shared_secrets.insert( +// Txid::from_str(TRANSACTION).unwrap(), +// sp_address2shared_secrets, +// ); - aes_enc.set_shared_secret(shared_secrets); +// aes_enc.set_shared_secret(shared_secrets); - let mut sp_address2encrypted_keys = aes_enc.encrypt_keys_with_shared_secrets(); +// let mut sp_address2encrypted_keys = aes_enc.encrypt_keys_with_shared_secrets(); - assert!(sp_address2encrypted_keys.is_ok()); +// assert!(sp_address2encrypted_keys.is_ok()); - // Alice - let encrypted_key = sp_address2encrypted_keys - .as_mut() - .unwrap() - .get(&ALICE_SP_ADDRESS.try_into().unwrap()) - .cloned(); +// // Alice +// let encrypted_key = sp_address2encrypted_keys +// .as_mut() +// .unwrap() +// .get(&ALICE_SP_ADDRESS.try_into().unwrap()) +// .cloned(); - let ciphertext = aes_enc.encrypt_with_aes_key(); +// let ciphertext = aes_enc.encrypt_with_aes_key(); - let aes_dec = Aes256Decryption::new( - Purpose::ThirtyTwoBytes, - ciphertext.unwrap(), - encrypted_key.unwrap(), - Some(SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap()), - ); +// let aes_dec = Aes256Decryption::new( +// Purpose::ThirtyTwoBytes, +// ciphertext.unwrap(), +// encrypted_key.unwrap(), +// Some(SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap()), +// ); - let retrieved_plain = aes_dec.unwrap().decrypt_with_key(); +// let retrieved_plain = aes_dec.unwrap().decrypt_with_key(); - assert!(retrieved_plain.unwrap() == plaintext); +// assert!(retrieved_plain.unwrap() == plaintext); - // Bob - let encrypted_key = sp_address2encrypted_keys - .unwrap() - .get(&BOB_SP_ADDRESS.try_into().unwrap()) - .cloned(); +// // Bob +// let encrypted_key = sp_address2encrypted_keys +// .unwrap() +// .get(&BOB_SP_ADDRESS.try_into().unwrap()) +// .cloned(); - let ciphertext = aes_enc.encrypt_with_aes_key(); +// let ciphertext = aes_enc.encrypt_with_aes_key(); - let aes_dec = Aes256Decryption::new( - Purpose::ThirtyTwoBytes, - ciphertext.unwrap(), - encrypted_key.unwrap(), - Some(SharedSecret::from_str(BOB_SHARED_SECRET).unwrap()), - ); +// let aes_dec = Aes256Decryption::new( +// Purpose::ThirtyTwoBytes, +// ciphertext.unwrap(), +// encrypted_key.unwrap(), +// Some(SharedSecret::from_str(BOB_SHARED_SECRET).unwrap()), +// ); - let retrieved_plain = aes_dec.unwrap().decrypt_with_key(); +// let retrieved_plain = aes_dec.unwrap().decrypt_with_key(); - assert!(retrieved_plain.unwrap() == plaintext); - } +// assert!(retrieved_plain.unwrap() == plaintext); +// } } From 932dc0ba55cc91602d660f3392bd3a5fc9e5d158 Mon Sep 17 00:00:00 2001 From: Sosthene00 Date: Tue, 30 Apr 2024 11:24:05 +0200 Subject: [PATCH 09/30] get_shared_point_from_transaction --- src/silentpayments.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/silentpayments.rs b/src/silentpayments.rs index 51c6c34..d4f815a 100644 --- a/src/silentpayments.rs +++ b/src/silentpayments.rs @@ -97,7 +97,15 @@ pub fn create_transaction_for_address_with_shared_secret( Ok((final_tx, AnkSharedSecret::new(shared_point, true))) } -// This need to go +pub fn get_shared_point_from_transaction(tx: &Transaction, sp_wallet: &SpWallet, tweak_data: PublicKey) -> Result<[u8;64]> { + let b_scan = sp_wallet.get_client().get_scan_key(); + let test = sp_client::bitcoin::secp256k1::ecdh::shared_secret_point(&tweak_data, &b_scan); + let ecdh_shared= sp_client::silentpayments::utils::receiving::calculate_shared_secret(tweak_data, b_scan)?; + let uncompressed = ecdh_shared.serialize_uncompressed(); + assert!(test == uncompressed[1..]); + Ok(test) +} + pub fn check_transaction( tx: &Transaction, sp_wallet: &mut SpWallet, From a55760c9448a613c5120e966beb22e7e0022aef8 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 6 May 2024 15:53:58 +0200 Subject: [PATCH 10/30] Add AAD in encrypted payload --- src/crypto.rs | 163 +++++--------------------------------------------- 1 file changed, 15 insertions(+), 148 deletions(-) diff --git a/src/crypto.rs b/src/crypto.rs index c14b7b1..fc1c853 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -4,7 +4,7 @@ use anyhow::{Error, Result}; use serde::{Deserialize, Serialize}; use sp_client::{ bitcoin::{ - hex::{DisplayHex, FromHex}, key::constants::SECRET_KEY_SIZE, secp256k1::{ecdh::SharedSecret, PublicKey}, Txid + hex::{DisplayHex, FromHex}, key::constants::SECRET_KEY_SIZE, Txid }, silentpayments::{ bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine}, @@ -13,20 +13,12 @@ use sp_client::{ }; use tsify::Tsify; -use aes_gcm::{ - aead::{Aead, AeadInPlace, Nonce}, - aes::{ - cipher::{ - consts::{U32, U8}, - generic_array::GenericArray, - }, - Aes256, - }, - AesGcm, Key, TagSize, -}; +use aes_gcm::aead::{Aead, Payload}; pub use aes_gcm::{AeadCore, Aes256Gcm, KeyInit}; use rand::thread_rng; +const AAD: &[u8] = "4nk".as_bytes(); + const HALFKEYSIZE: usize = SECRET_KEY_SIZE / 2; const THIRTYTWO: usize = 32; @@ -40,7 +32,7 @@ impl SharedPoint { } } -#[derive(Debug, Serialize, Deserialize, Tsify, Clone)] +#[derive(Debug, Serialize, Deserialize, Tsify, Clone, Default, PartialEq)] #[tsify(from_wasm_abi, into_wasm_abi)] pub struct AnkSharedSecret { secret: String, @@ -183,8 +175,12 @@ impl Aes256Decryption { fn decrypt_arbitrary(&self) -> Result> { let cipher = Aes256Gcm::new(&self.aes_key.into()); + let payload = Payload { + msg: &self.cipher_text, + aad: AAD, + }; let plain = cipher - .decrypt(&self.nonce.into(), &*self.cipher_text) + .decrypt(&self.nonce.into(), payload) .map_err(|e| Error::msg(format!("{}", e)))?; Ok(plain) } @@ -294,8 +290,12 @@ impl Aes256Encryption { fn encrypt_arbitrary(&self) -> Result { let cipher = Aes256Gcm::new(&self.aes_key.into()); + let payload = Payload { + msg: &self.plaintext, + aad: AAD, + }; let cipher_text = cipher - .encrypt(&self.nonce.into(), &*self.plaintext) + .encrypt(&self.nonce.into(), payload) .map_err(|e| Error::msg(format!("{}", e)))?; let mut res = Vec::with_capacity(self.nonce.len() + cipher_text.len()); res.extend_from_slice(&self.nonce); @@ -375,137 +375,4 @@ mod tests { assert!(aes_dec.is_ok()); } - - #[test] - fn aes_encrypt_key() { - let plaintext = [1u8; HALFKEYSIZE]; - let mut aes_enc = Aes256Encryption::new(Purpose::Login, plaintext.to_vec()).unwrap(); - - let mut shared_secrets: HashMap = HashMap::new(); - let mut sp_address2shared_secrets: HashMap = - HashMap::new(); - let alice_secret = Vec::from_hex(ALICE_SHARED_SECRET).unwrap(); - let mut buf = [0u8;32]; - buf.copy_from_slice(&alice_secret); - sp_address2shared_secrets.insert( - ALICE_SP_ADDRESS.try_into().unwrap(), - AnkSharedSecret { secret: buf.to_lower_hex_string(), trusted: true } - ); - shared_secrets.insert( - Txid::from_str(TRANSACTION).unwrap(), - sp_address2shared_secrets, - ); - - aes_enc.set_shared_secret(shared_secrets); - - let sp_address2encrypted_keys = aes_enc.encrypt_keys_with_shared_secrets(); - - assert!(sp_address2encrypted_keys.is_ok()); - - let encrypted_key = sp_address2encrypted_keys - .unwrap() - .get(&ALICE_SP_ADDRESS.try_into().unwrap()) - .cloned(); - - let ciphertext = aes_enc.encrypt_with_aes_key(); - - assert!(ciphertext.is_ok()); - - let decrypt_key = Aes256Decryption::new( - Purpose::Arbitrary, - encrypted_key.unwrap(), - SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap().secret_bytes(), - ); - - assert!(decrypt_key.is_ok()); - - let mut retrieved_key = [0u8;32]; - retrieved_key.copy_from_slice(&decrypt_key.unwrap().decrypt_with_key().unwrap()); - - let decrypt_msg = Aes256Decryption::new( - Purpose::Arbitrary, - ciphertext.unwrap(), - retrieved_key - ); - - let retrieved_plain = decrypt_msg.unwrap().decrypt_with_key(); - - assert!(retrieved_plain.is_ok()); - - assert!(retrieved_plain.unwrap() == plaintext); - } - -// #[test] -// fn aes_encrypt_key_many() { -// let plaintext = [1u8; THIRTYTWO]; -// let mut aes_enc = -// Aes256Encryption::new(Purpose::ThirtyTwoBytes, plaintext.to_vec()).unwrap(); - -// let mut shared_secrets: HashMap = HashMap::new(); -// let mut sp_address2shared_secrets: HashMap = -// HashMap::new(); -// let alice_secret = Vec::from_hex(ALICE_SHARED_SECRET).unwrap(); -// let mut buf = [0u8;32]; -// buf.copy_from_slice(&alice_secret); -// sp_address2shared_secrets.insert( -// ALICE_SP_ADDRESS.try_into().unwrap(), -// AnkSharedSecret { secret: buf, trusted: true } -// ); -// let bob_secret = Vec::from_hex(BOB_SHARED_SECRET).unwrap(); -// let mut buf = [0u8;32]; -// buf.copy_from_slice(&bob_secret); -// sp_address2shared_secrets.insert( -// BOB_SP_ADDRESS.try_into().unwrap(), -// AnkSharedSecret { secret: buf, trusted: true } -// ); -// shared_secrets.insert( -// Txid::from_str(TRANSACTION).unwrap(), -// sp_address2shared_secrets, -// ); - -// aes_enc.set_shared_secret(shared_secrets); - -// let mut sp_address2encrypted_keys = aes_enc.encrypt_keys_with_shared_secrets(); - -// assert!(sp_address2encrypted_keys.is_ok()); - -// // Alice -// let encrypted_key = sp_address2encrypted_keys -// .as_mut() -// .unwrap() -// .get(&ALICE_SP_ADDRESS.try_into().unwrap()) -// .cloned(); - -// let ciphertext = aes_enc.encrypt_with_aes_key(); - -// let aes_dec = Aes256Decryption::new( -// Purpose::ThirtyTwoBytes, -// ciphertext.unwrap(), -// encrypted_key.unwrap(), -// Some(SharedSecret::from_str(ALICE_SHARED_SECRET).unwrap()), -// ); - -// let retrieved_plain = aes_dec.unwrap().decrypt_with_key(); - -// assert!(retrieved_plain.unwrap() == plaintext); - -// // Bob -// let encrypted_key = sp_address2encrypted_keys -// .unwrap() -// .get(&BOB_SP_ADDRESS.try_into().unwrap()) -// .cloned(); - -// let ciphertext = aes_enc.encrypt_with_aes_key(); - -// let aes_dec = Aes256Decryption::new( -// Purpose::ThirtyTwoBytes, -// ciphertext.unwrap(), -// encrypted_key.unwrap(), -// Some(SharedSecret::from_str(BOB_SHARED_SECRET).unwrap()), -// ); - -// let retrieved_plain = aes_dec.unwrap().decrypt_with_key(); - -// assert!(retrieved_plain.unwrap() == plaintext); -// } } From 62d135925e4576e860ed32dced045111ba30c643 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Tue, 14 May 2024 22:20:53 +0200 Subject: [PATCH 11/30] Add UnknownMessage struct --- src/network.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/network.rs b/src/network.rs index c4204e6..c34bd04 100644 --- a/src/network.rs +++ b/src/network.rs @@ -211,6 +211,22 @@ impl NewTxMessage { } } +#[derive(Debug, Serialize, Deserialize, Tsify)] +#[tsify(into_wasm_abi, from_wasm_abi)] +pub struct UnknownMessage { + pub sender: String, + pub message: String, +} + +impl UnknownMessage { + pub fn new(sender: String, message: String) -> Self { + Self { + sender, + message, + } + } +} + #[derive(Debug, Serialize, Deserialize, Tsify)] #[tsify(into_wasm_abi, from_wasm_abi)] pub struct AnkNetworkMsg { From 6bf80eb0a53571a3fdf15ad045fb3e3815230b51 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Tue, 14 May 2024 22:22:17 +0200 Subject: [PATCH 12/30] create_transaction_for_address_with_shared_secret takes optional message --- src/silentpayments.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/silentpayments.rs b/src/silentpayments.rs index d4f815a..cb815d3 100644 --- a/src/silentpayments.rs +++ b/src/silentpayments.rs @@ -38,7 +38,7 @@ use crate::crypto::AnkSharedSecret; pub fn create_transaction_for_address_with_shared_secret( sp_address: SilentPaymentAddress, sp_wallet: &SpWallet, - message: String, + message: Option, fee_rate: Amount, ) -> Result<(Transaction, AnkSharedSecret)> { let available_outpoints = sp_wallet.get_outputs().to_spendable_list(); @@ -70,7 +70,7 @@ pub fn create_transaction_for_address_with_shared_secret( let mut new_psbt = sp_wallet.get_client().create_new_psbt( inputs, vec![recipient], - Some(message.as_bytes()), + message.as_ref().map(|m| m.as_bytes()), )?; let change_addr = sp_wallet.get_client().sp_receiver.get_change_address(); From bd09245713c5933c39db3e1ea41cb5c480b55884 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Wed, 15 May 2024 08:32:16 +0200 Subject: [PATCH 13/30] Add create_transaction --- src/silentpayments.rs | 57 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/silentpayments.rs b/src/silentpayments.rs index cb815d3..d7c835e 100644 --- a/src/silentpayments.rs +++ b/src/silentpayments.rs @@ -35,6 +35,63 @@ use crate::crypto::AnkSharedSecret; // } // } +pub fn create_transaction(sp_address: SilentPaymentAddress, sp_wallet: &SpWallet, fee_rate: Amount) -> Result { + let available_outpoints = sp_wallet.get_outputs().to_spendable_list(); + + // Here we need to add more heuristics about which outpoint we spend + // For now let's keep it simple + + let mut inputs: HashMap = HashMap::new(); + + let mut total_available = Amount::from_sat(0); + for (outpoint, output) in available_outpoints { + total_available += output.amount; + inputs.insert(outpoint, output); + if total_available > Amount::from_sat(1000) { + break; + } + } + + if total_available < Amount::from_sat(1000) { + return Err(Error::msg("Not enough available funds")); + } + + let recipient = Recipient { + address: sp_address.into(), + amount: Amount::from_sat(1000), + nb_outputs: 1, + }; + + let mut new_psbt = sp_wallet.get_client().create_new_psbt( + inputs, + vec![recipient], + None, + )?; + + let change_addr = sp_wallet.get_client().sp_receiver.get_change_address(); + SpClient::set_fees(&mut new_psbt, fee_rate, change_addr)?; + + let partial_secret = sp_wallet + .get_client() + .get_partial_secret_from_psbt(&new_psbt)?; + + // This wouldn't work with many recipients in the same transaction + // each address (or more precisely each scan public key) would have its own point + let shared_point = shared_secret_point(&sp_address.get_scan_key(), &partial_secret); + + sp_wallet + .get_client() + .fill_sp_outputs(&mut new_psbt, partial_secret)?; + let mut aux_rand = [0u8; 32]; + rand::thread_rng().fill(&mut aux_rand); + let mut signed = sp_wallet.get_client().sign_psbt(new_psbt, &aux_rand)?; + SpClient::finalize_psbt(&mut signed)?; + + let final_tx = signed.extract_tx()?; + + Ok(final_tx) +} + pub fn create_transaction_for_address_with_shared_secret( sp_address: SilentPaymentAddress, sp_wallet: &SpWallet, From d7daf72da0c3f8d923c3a4e19107d414a5fc533a Mon Sep 17 00:00:00 2001 From: Sosthene Date: Wed, 22 May 2024 10:21:54 +0200 Subject: [PATCH 14/30] Rm trusted in AnkSharedSecret --- src/crypto.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/crypto.rs b/src/crypto.rs index fc1c853..c05fa31 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -36,13 +36,12 @@ impl SharedPoint { #[tsify(from_wasm_abi, into_wasm_abi)] pub struct AnkSharedSecret { secret: String, - pub trusted: bool, } impl AnkSharedSecret { - pub fn new(shared_point: [u8; 64], trusted: bool) -> Self { + pub fn new(shared_point: [u8; 64]) -> Self { let secret = AnkSharedSecretHash::from_shared_point(shared_point).to_byte_array(); - Self { secret: secret.to_lower_hex_string(), trusted } + Self { secret: secret.to_lower_hex_string() } } pub fn to_byte_array(&self) -> [u8; 32] { From 0e88a729c3c43acdd285497281b607477c971732 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Wed, 22 May 2024 10:22:20 +0200 Subject: [PATCH 15/30] Add a dummy commitment in faucet messages --- src/network.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/network.rs b/src/network.rs index c34bd04..385b298 100644 --- a/src/network.rs +++ b/src/network.rs @@ -1,5 +1,7 @@ use anyhow::{Error, Result}; +use rand::{thread_rng, RngCore}; use serde::{Deserialize, Serialize}; +use sp_client::bitcoin::hex::DisplayHex; use sp_client::bitcoin::key::constants::ZERO; use sp_client::bitcoin::OutPoint; use sp_client::silentpayments::bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine}; @@ -9,7 +11,6 @@ use crate::crypto::CipherText; const RAWTXTOPIC: &'static str = "rawtx"; const RAWBLOCKTOPIC: &'static str = "rawblock"; -const ANKMAGIC: [u8; 4] = [0x34, 0x6E, 0x6B, 0x30]; #[derive(Debug, Serialize, Deserialize)] pub enum BitcoinTopic { @@ -187,11 +188,14 @@ impl AnkFlag { #[tsify(into_wasm_abi, from_wasm_abi)] pub struct FaucetMessage { pub sp_address: String, + pub commitment: String, } impl FaucetMessage { pub fn new(sp_address: String) -> Self { - Self { sp_address } + let mut buf = [0u8;64]; + thread_rng().fill_bytes(&mut buf); + Self { sp_address, commitment: buf.to_lower_hex_string() } } } From 1f8da7ea61b86e2d6c167caab8890591af450f5c Mon Sep 17 00:00:00 2001 From: Sosthene Date: Wed, 22 May 2024 10:22:53 +0200 Subject: [PATCH 16/30] Refactor silentpayments --- src/silentpayments.rs | 155 ++++++++++++++++++++++++------------------ 1 file changed, 88 insertions(+), 67 deletions(-) diff --git a/src/silentpayments.rs b/src/silentpayments.rs index d7c835e..b7e2023 100644 --- a/src/silentpayments.rs +++ b/src/silentpayments.rs @@ -1,39 +1,16 @@ use std::collections::HashMap; +use std::str::FromStr; use anyhow::{Error, Result}; -use rand::Rng; -use serde::{Deserialize, Serialize}; -use sp_client::bitcoin::secp256k1::ecdh::shared_secret_point; -use sp_client::bitcoin::{secp256k1::PublicKey, Transaction}; -use sp_client::bitcoin::{Amount, OutPoint, Txid}; +use rand::{thread_rng, Rng, RngCore}; +use sp_client::bitcoin::psbt::raw; +use sp_client::bitcoin::{Psbt, Transaction}; +use sp_client::bitcoin::{Amount, OutPoint}; +use sp_client::bitcoin::consensus::{deserialize, serialize}; use sp_client::silentpayments::sending::SilentPaymentAddress; use sp_client::spclient::{OwnedOutput, Recipient, SpClient, SpWallet}; -use tsify::Tsify; - -use crate::crypto::AnkSharedSecret; - -// #[derive(Debug, Serialize, Deserialize, Tsify)] -// #[tsify(into_wasm_abi, from_wasm_abi)] -// pub struct ScannedTransaction(HashMap>); - -// impl ScannedTransaction { -// pub fn new() -> Self { -// Self(HashMap::new()) -// } - -// pub fn get(&self) -> &HashMap> { -// &self.0 -// } - -// pub fn get_mut(&mut self) -> &mut HashMap> { -// &mut self.0 -// } - -// pub fn to_inner(&self) -> HashMap> { -// self.0.clone() -// } -// } +use sp_client::constants; pub fn create_transaction(sp_address: SilentPaymentAddress, sp_wallet: &SpWallet, fee_rate: Amount) -> Result { let available_outpoints = sp_wallet.get_outputs().to_spendable_list(); @@ -77,7 +54,7 @@ pub fn create_transaction(sp_address: SilentPaymentAddress, sp_wallet: &SpWallet // This wouldn't work with many recipients in the same transaction // each address (or more precisely each scan public key) would have its own point - let shared_point = shared_secret_point(&sp_address.get_scan_key(), &partial_secret); + // let shared_point = shared_secret_point(&sp_address.get_scan_key(), &partial_secret); sp_wallet .get_client() @@ -92,12 +69,66 @@ pub fn create_transaction(sp_address: SilentPaymentAddress, sp_wallet: &SpWallet Ok(final_tx) } -pub fn create_transaction_for_address_with_shared_secret( - sp_address: SilentPaymentAddress, +pub fn create_transaction_spend_outpoint( + outpoint: &OutPoint, sp_wallet: &SpWallet, - message: Option, + recipient: Recipient, + fee_rate: Amount +) -> Result { + let available_outpoints = sp_wallet.get_outputs().to_spendable_list(); + + let mut inputs: HashMap = HashMap::new(); + let mut total_available = Amount::from_sat(0); + let (must_outpoint, must_output) = available_outpoints.get_key_value(outpoint).ok_or_else(|| Error::msg("Mandatory outpoint unknown"))?; + total_available += must_output.amount; + inputs.insert(*must_outpoint, must_output.clone()); + + for (outpoint, output) in available_outpoints { + if total_available > Amount::from_sat(1000) { + break; + } + total_available += output.amount; + inputs.insert(outpoint, output); + } + + if total_available < Amount::from_sat(1000) { + return Err(Error::msg("Not enough available funds")); + } + + // create a dummy commitment + let mut buf = [0u8;64]; + thread_rng().fill_bytes(&mut buf); + + let mut new_psbt = sp_wallet.get_client().create_new_psbt( + inputs, + vec![recipient], + Some(&buf), + )?; + + let change_addr = sp_wallet.get_client().sp_receiver.get_change_address(); + SpClient::set_fees(&mut new_psbt, fee_rate, change_addr)?; + + let partial_secret = sp_wallet + .get_client() + .get_partial_secret_from_psbt(&new_psbt)?; + + sp_wallet + .get_client() + .fill_sp_outputs(&mut new_psbt, partial_secret)?; + let mut aux_rand = [0u8; 32]; + thread_rng().fill(&mut aux_rand); + let mut signed = sp_wallet.get_client().sign_psbt(new_psbt, &aux_rand)?; + SpClient::finalize_psbt(&mut signed)?; + + Ok(signed) +} + +pub fn create_transaction_for_address_with_shared_secret( + recipient: Recipient, + sp_wallet: &SpWallet, + message: Option<&str>, fee_rate: Amount, -) -> Result<(Transaction, AnkSharedSecret)> { +) -> Result { let available_outpoints = sp_wallet.get_outputs().to_spendable_list(); // Here we need to add more heuristics about which outpoint we spend @@ -118,16 +149,10 @@ pub fn create_transaction_for_address_with_shared_secret( return Err(Error::msg("Not enough available funds")); } - let recipient = Recipient { - address: sp_address.into(), - amount: Amount::from_sat(1000), - nb_outputs: 1, - }; - let mut new_psbt = sp_wallet.get_client().create_new_psbt( inputs, vec![recipient], - message.as_ref().map(|m| m.as_bytes()), + message.map(|m| m.as_bytes()), )?; let change_addr = sp_wallet.get_client().sp_receiver.get_change_address(); @@ -137,10 +162,6 @@ pub fn create_transaction_for_address_with_shared_secret( .get_client() .get_partial_secret_from_psbt(&new_psbt)?; - // This wouldn't work with many recipients in the same transaction - // each address (or more precisely each scan public key) would have its own point - let shared_point = shared_secret_point(&sp_address.get_scan_key(), &partial_secret); - sp_wallet .get_client() .fill_sp_outputs(&mut new_psbt, partial_secret)?; @@ -149,30 +170,30 @@ pub fn create_transaction_for_address_with_shared_secret( let mut signed = sp_wallet.get_client().sign_psbt(new_psbt, &aux_rand)?; SpClient::finalize_psbt(&mut signed)?; - let final_tx = signed.extract_tx()?; - - Ok((final_tx, AnkSharedSecret::new(shared_point, true))) + Ok(signed.to_string()) } -pub fn get_shared_point_from_transaction(tx: &Transaction, sp_wallet: &SpWallet, tweak_data: PublicKey) -> Result<[u8;64]> { - let b_scan = sp_wallet.get_client().get_scan_key(); - let test = sp_client::bitcoin::secp256k1::ecdh::shared_secret_point(&tweak_data, &b_scan); - let ecdh_shared= sp_client::silentpayments::utils::receiving::calculate_shared_secret(tweak_data, b_scan)?; - let uncompressed = ecdh_shared.serialize_uncompressed(); - assert!(test == uncompressed[1..]); - Ok(test) -} +pub fn map_outputs_to_sp_address(psbt_str: &str) -> Result>> { + let psbt = Psbt::from_str(&psbt_str)?; -pub fn check_transaction( - tx: &Transaction, - sp_wallet: &mut SpWallet, - blockheight: u32, - tweak_data: PublicKey, -) -> Result { - let txid = tx.txid().to_string(); - if sp_wallet.update_wallet_with_transaction(tx, blockheight, tweak_data)? > 0 { - return Ok(txid); + let mut res: HashMap> = HashMap::new(); + for (i, output) in psbt.outputs.iter().enumerate() { + if let Some(value) = output.proprietary.get(&raw::ProprietaryKey { + prefix: constants::PSBT_SP_PREFIX.as_bytes().to_vec(), + subtype: constants::PSBT_SP_SUBTYPE, + key: constants::PSBT_SP_ADDRESS_KEY.as_bytes().to_vec(), + }) { + let sp_address = SilentPaymentAddress::try_from(deserialize::(value)?)?; + if let Some(vouts) = res.get_mut::(&sp_address.into()) { + vouts.push(i); + } else { + res.insert(sp_address.into(), vec![i]); + } + } else { + // Not a sp output + continue; + } } - return Err(Error::msg("No new outputs found")); + Ok(res) } From f5cdb7e2f14407627402a404fb1675ac53d81340 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Wed, 22 May 2024 20:51:08 +0200 Subject: [PATCH 17/30] [bug] content of the op_return wasn't correctly serialized --- src/silentpayments.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/silentpayments.rs b/src/silentpayments.rs index b7e2023..5688af0 100644 --- a/src/silentpayments.rs +++ b/src/silentpayments.rs @@ -4,6 +4,7 @@ use std::str::FromStr; use anyhow::{Error, Result}; use rand::{thread_rng, Rng, RngCore}; +use sp_client::bitcoin::hex::FromHex; use sp_client::bitcoin::psbt::raw; use sp_client::bitcoin::{Psbt, Transaction}; use sp_client::bitcoin::{Amount, OutPoint}; @@ -149,10 +150,12 @@ pub fn create_transaction_for_address_with_shared_secret( return Err(Error::msg("Not enough available funds")); } + let message_bin = if message.is_some() { Vec::from_hex(message.unwrap())? } else { vec![] }; + let mut new_psbt = sp_wallet.get_client().create_new_psbt( inputs, vec![recipient], - message.map(|m| m.as_bytes()), + if !message_bin.is_empty() { Some(&message_bin) } else { None }, )?; let change_addr = sp_wallet.get_client().sp_receiver.get_change_address(); From 9fe3e7b4996c478f264de59c68a780dad764759b Mon Sep 17 00:00:00 2001 From: Sosthene Date: Wed, 22 May 2024 20:52:16 +0200 Subject: [PATCH 18/30] nit: output value is exactly what's available in the input for confirmation --- src/silentpayments.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/silentpayments.rs b/src/silentpayments.rs index 5688af0..c7e7ba3 100644 --- a/src/silentpayments.rs +++ b/src/silentpayments.rs @@ -73,7 +73,7 @@ pub fn create_transaction(sp_address: SilentPaymentAddress, sp_wallet: &SpWallet pub fn create_transaction_spend_outpoint( outpoint: &OutPoint, sp_wallet: &SpWallet, - recipient: Recipient, + mut recipient: Recipient, fee_rate: Amount ) -> Result { let available_outpoints = sp_wallet.get_outputs().to_spendable_list(); @@ -96,6 +96,9 @@ pub fn create_transaction_spend_outpoint( return Err(Error::msg("Not enough available funds")); } + // update the amount for the recipient + recipient.amount = total_available; + // create a dummy commitment let mut buf = [0u8;64]; thread_rng().fill_bytes(&mut buf); From 87ee8ac40ce663e101c33309a7b740b5597c0177 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Wed, 22 May 2024 20:52:48 +0200 Subject: [PATCH 19/30] Move CachedMessage here from sdk_client --- src/network.rs | 114 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 94 insertions(+), 20 deletions(-) diff --git a/src/network.rs b/src/network.rs index 385b298..04a5cbe 100644 --- a/src/network.rs +++ b/src/network.rs @@ -1,13 +1,13 @@ use anyhow::{Error, Result}; use rand::{thread_rng, RngCore}; use serde::{Deserialize, Serialize}; -use sp_client::bitcoin::hex::DisplayHex; +use sp_client::bitcoin::hex::{DisplayHex, FromHex}; use sp_client::bitcoin::key::constants::ZERO; use sp_client::bitcoin::OutPoint; use sp_client::silentpayments::bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine}; use tsify::Tsify; -use crate::crypto::CipherText; +use crate::crypto::{Aes256Decryption, CipherText, Purpose}; const RAWTXTOPIC: &'static str = "rawtx"; const RAWBLOCKTOPIC: &'static str = "rawblock"; @@ -238,24 +238,6 @@ pub struct AnkNetworkMsg { pub content: String, } -// impl TryFrom<&str> for AnkNetworkMsg { -// type Error = anyhow::Error; -// fn try_from(value: &str) -> std::prelude::v1::Result { -// let parsed: Value = serde_json::from_str(value)?; -// let flag = parsed -// .get("flag") -// .ok_or(Error::msg("Invalid AnkNetworkMsg"))? -// .as_str() -// .ok_or(Error::msg("Invalid AnkNetworkMsg"))?; -// let content = parsed -// .get("content") -// .ok_or(Error::msg("Invalid AnkNetworkMsg"))? -// .as_str() -// .ok_or(Error::msg("Invalid AnkNetworkMsg"))?; -// Ok(Self { flag: flag.into(), content: content.into() }) -// } -// } - impl AnkNetworkMsg { pub fn new(flag: AnkFlag, raw: &str) -> Self { Self { @@ -264,3 +246,95 @@ impl AnkNetworkMsg { } } } + +#[derive(Debug, Serialize, Deserialize, PartialEq, Tsify, Clone)] +pub enum CachedMessageStatus { + NoStatus, // Default + FaucetWaiting, + FaucetComplete, + CipherWaitingTx, + TxWaitingCipher, + SentWaitingConfirmation, + MustSpendConfirmation, + Complete, +} + +impl Default for CachedMessageStatus { + fn default() -> Self { + Self::NoStatus + } +} + +/// Unique struct for both 3nk messages and notification/key exchange, both rust and ts +/// 0. Faucet: commited_in with nothing else, status is NoStatus +/// 1. notification: +/// 0. sender: ciphertext, plaintext, commited_in, sender, recipient, shared_secret, key +/// 1. receiver (without tx): ciphertext +/// 2. receiver (tx without msg): commited_in, commitment, recipient, shared_secret +/// 3. receiver (receive tx after msg): plaintext, key, sender, commited_in, commitment, recipient, shared_secret +/// 4. receiver (msg after tx): ciphertext, key, plaintext, sender +/// 2. confirmation: +/// 0. receiver (spend the smallest vout that pays him in the first tx): confirmed_by +/// 1. sender (detect a transaction that pays him and spend commited_by): confirmed_by +/// 2. sender toggle status to complete when it spent confirmed_by, receiver when it detects the confirmed_by is spent +#[derive(Debug, Default, Serialize, Deserialize, Tsify, Clone)] +#[tsify(into_wasm_abi, from_wasm_abi)] +#[allow(non_camel_case_types)] +pub struct CachedMessage { + pub id: u32, + pub status: CachedMessageStatus, + pub ciphertext: Option, // When we receive message we can't decrypt we only have this and commited_in_tx + pub plaintext: Option, // Never None when message sent + pub commited_in: Option, + pub commitment: Option, // content of the op_return + pub sender: Option, // Never None when message sent + pub recipient: Option, // Never None when message sent + pub shared_secret: Option, // Never None when message sent + pub key: Option, // Never None when message sent + pub confirmed_by: Option, // If this None, Sender keeps sending + pub timestamp: u64, + pub error: Option, +} + +impl CachedMessage { + pub fn new() -> Self { + let mut new = Self::default(); + let mut buf = [0u8;4]; + thread_rng().fill_bytes(&mut buf); + new.id = u32::from_be_bytes(buf); + new + } + + pub fn new_error(error: String) -> Self { + let mut new = Self::default(); + new.error = Some(error); + new + } + + pub fn try_decrypt_cipher(&self, cipher: Vec) -> Result> { + if self.ciphertext.is_some() || self.shared_secret.is_none() { + return Err(Error::msg( + "Can't try decrypt this message, there's already a ciphertext or no shared secret" + )); + } + let mut shared_secret = [0u8; 32]; + shared_secret + .copy_from_slice(&Vec::from_hex(self.shared_secret.as_ref().unwrap())?); + let aes_decrypt = Aes256Decryption::new(Purpose::Arbitrary, cipher, shared_secret)?; + + aes_decrypt.decrypt_with_key() + } + + pub fn try_decrypt_with_shared_secret(&self, shared_secret: [u8; 32]) -> Result> { + if self.ciphertext.is_none() || self.shared_secret.is_some() { + return Err(Error::msg( + "Can't try decrypt this message, ciphertext is none or shared_secret already found" + )); + } + let cipher_bin = Vec::from_hex(self.ciphertext.as_ref().unwrap())?; + let aes_decrypt = + Aes256Decryption::new(Purpose::Arbitrary, cipher_bin, shared_secret)?; + + aes_decrypt.decrypt_with_key() + } +} From c5ff2e2edbd18f68d14a92058aef85b78e7bba3c Mon Sep 17 00:00:00 2001 From: Sosthene Date: Wed, 22 May 2024 23:40:31 +0200 Subject: [PATCH 20/30] add ReceivedMustConfirm status --- src/network.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/network.rs b/src/network.rs index 04a5cbe..7375502 100644 --- a/src/network.rs +++ b/src/network.rs @@ -255,6 +255,7 @@ pub enum CachedMessageStatus { CipherWaitingTx, TxWaitingCipher, SentWaitingConfirmation, + ReceivedMustConfirm, MustSpendConfirmation, Complete, } From 72089b8545a1ca1bbeb6465821f0274bb4bd2527 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 27 May 2024 11:49:53 +0200 Subject: [PATCH 21/30] Rm Error and Prd AnkFlag, Add Cipher, add error field for each message --- src/network.rs | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/network.rs b/src/network.rs index 7375502..a0afe21 100644 --- a/src/network.rs +++ b/src/network.rs @@ -139,8 +139,7 @@ impl Envelope { pub enum AnkFlag { NewTx, Faucet, - Prd, - Error, + Cipher, Unknown, } @@ -149,8 +148,7 @@ impl From<&str> for AnkFlag { match value { "NewTx" => Self::NewTx, "Faucet" => Self::Faucet, - "Prd" => Self::Prd, - "Error" => Self::Error, + "Cipher" => Self::Cipher, _ => Self::Unknown, } } @@ -167,19 +165,17 @@ impl AnkFlag { match byte { 0 => Self::NewTx, 1 => Self::Faucet, - 2 => Self::Prd, - 9 => Self::Error, + 2 => Self::Cipher, _ => Self::Unknown, } } pub fn as_str(&self) -> &str { match self { - Self::NewTx => "new_tx", - Self::Faucet => "faucet", - Self::Prd => "prd", - Self::Error => "error", - Self::Unknown => "unknown", + Self::NewTx => "NewTx", + Self::Faucet => "Faucet", + Self::Cipher => "Cipher", + Self::Unknown => "Unknown", } } } @@ -189,13 +185,14 @@ impl AnkFlag { pub struct FaucetMessage { pub sp_address: String, pub commitment: String, + pub error: Option, } impl FaucetMessage { pub fn new(sp_address: String) -> Self { let mut buf = [0u8;64]; thread_rng().fill_bytes(&mut buf); - Self { sp_address, commitment: buf.to_lower_hex_string() } + Self { sp_address, commitment: buf.to_lower_hex_string(), error: None } } } @@ -204,6 +201,7 @@ impl FaucetMessage { pub struct NewTxMessage { pub transaction: String, pub tweak_data: Option, + pub error: Option, } impl NewTxMessage { @@ -211,22 +209,25 @@ impl NewTxMessage { Self { transaction, tweak_data, + error: None, } } } #[derive(Debug, Serialize, Deserialize, Tsify)] #[tsify(into_wasm_abi, from_wasm_abi)] -pub struct UnknownMessage { +pub struct CipherMessage { pub sender: String, pub message: String, + pub error: Option, } -impl UnknownMessage { +impl CipherMessage { pub fn new(sender: String, message: String) -> Self { Self { sender, message, + error: None, } } } From 6492952dc09fa8e57f644cba8a755df9b876d4c4 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 27 May 2024 11:52:32 +0200 Subject: [PATCH 22/30] Add error mod --- src/error.rs | 41 +++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/network.rs | 1 + 3 files changed, 43 insertions(+) create mode 100644 src/error.rs diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..dcb6304 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,41 @@ +use std::fmt; +use std::error::Error; + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub enum AnkError { + GenericError(String), + FaucetError(String), + NewTxError(String), + CipherError(String), +} + +impl fmt::Display for AnkError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + AnkError::GenericError(msg) => write!(f, "GenericError: {}", msg), + AnkError::FaucetError(msg) => write!(f, "FaucetError: {}", msg), + AnkError::NewTxError(msg) => write!(f, "NewTxError: {}", msg), + AnkError::CipherError(msg) => write!(f, "CipherError: {}", msg), + } + } +} + +impl Error for AnkError {} + +impl From for AnkError { + fn from(error: anyhow::Error) -> Self { + let error_message = error.to_string(); + + if error_message.contains("FaucetError") { + AnkError::FaucetError(error_message) + } else if error_message.contains("NewTxError") { + AnkError::NewTxError(error_message) + } else if error_message.contains("CipherError") { + AnkError::CipherError(error_message) + } else { + AnkError::GenericError(error_message) + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 48fa577..2bdb1ee 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ pub mod crypto; pub mod network; pub mod silentpayments; +pub mod error; diff --git a/src/network.rs b/src/network.rs index a0afe21..8116625 100644 --- a/src/network.rs +++ b/src/network.rs @@ -8,6 +8,7 @@ use sp_client::silentpayments::bitcoin_hashes::{sha256t_hash_newtype, Hash, Hash use tsify::Tsify; use crate::crypto::{Aes256Decryption, CipherText, Purpose}; +use crate::error::AnkError; const RAWTXTOPIC: &'static str = "rawtx"; const RAWBLOCKTOPIC: &'static str = "rawblock"; From 70bc03da9ee44d582df4475a94723515d44a8b6a Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 27 May 2024 11:55:41 +0200 Subject: [PATCH 23/30] error in CachedMessage is AnkError --- src/network.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/network.rs b/src/network.rs index 8116625..beccf59 100644 --- a/src/network.rs +++ b/src/network.rs @@ -296,7 +296,7 @@ pub struct CachedMessage { pub key: Option, // Never None when message sent pub confirmed_by: Option, // If this None, Sender keeps sending pub timestamp: u64, - pub error: Option, + pub error: Option, } impl CachedMessage { From 0c38e24f44cd020bdf0c3cfed13295987ec12c97 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 27 May 2024 11:56:29 +0200 Subject: [PATCH 24/30] AnkSharedSecret new() takes PublicKey --- src/crypto.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/crypto.rs b/src/crypto.rs index c05fa31..ed1eee1 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -9,6 +9,7 @@ use sp_client::{ silentpayments::{ bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine}, sending::SilentPaymentAddress, + secp256k1::PublicKey }, }; use tsify::Tsify; @@ -39,8 +40,10 @@ pub struct AnkSharedSecret { } impl AnkSharedSecret { - pub fn new(shared_point: [u8; 64]) -> Self { - let secret = AnkSharedSecretHash::from_shared_point(shared_point).to_byte_array(); + pub fn new(shared_point: PublicKey) -> Self { + let mut shared_point_bin = [0u8;64]; + shared_point_bin.copy_from_slice(&shared_point.serialize_uncompressed()[1..]); + let secret = AnkSharedSecretHash::from_shared_point(shared_point_bin).to_byte_array(); Self { secret: secret.to_lower_hex_string() } } From f52dca8db7b7ba31ab1740236c2ee88cf4fb2cc8 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 27 May 2024 11:57:23 +0200 Subject: [PATCH 25/30] timestamp new CachedMessage --- src/network.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/network.rs b/src/network.rs index beccf59..705fa03 100644 --- a/src/network.rs +++ b/src/network.rs @@ -1,4 +1,5 @@ use anyhow::{Error, Result}; +use js_sys::Date; use rand::{thread_rng, RngCore}; use serde::{Deserialize, Serialize}; use sp_client::bitcoin::hex::{DisplayHex, FromHex}; @@ -305,12 +306,7 @@ impl CachedMessage { let mut buf = [0u8;4]; thread_rng().fill_bytes(&mut buf); new.id = u32::from_be_bytes(buf); - new - } - - pub fn new_error(error: String) -> Self { - let mut new = Self::default(); - new.error = Some(error); + new.timestamp = Date::now().floor() as u64; new } From d82a1c7624797d419bac046184110d3bc7daf096 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 27 May 2024 11:57:56 +0200 Subject: [PATCH 26/30] Commitment for confirmation transaction is not random --- src/silentpayments.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/silentpayments.rs b/src/silentpayments.rs index c7e7ba3..f98ef00 100644 --- a/src/silentpayments.rs +++ b/src/silentpayments.rs @@ -1,14 +1,16 @@ use std::collections::HashMap; +use std::io::Write; use std::str::FromStr; use anyhow::{Error, Result}; -use rand::{thread_rng, Rng, RngCore}; +use rand::{thread_rng, Rng}; +use sp_client::bitcoin::hashes::{sha256, Hash}; use sp_client::bitcoin::hex::FromHex; use sp_client::bitcoin::psbt::raw; -use sp_client::bitcoin::{Psbt, Transaction}; +use sp_client::bitcoin::{Psbt, Transaction, Txid}; use sp_client::bitcoin::{Amount, OutPoint}; -use sp_client::bitcoin::consensus::{deserialize, serialize}; +use sp_client::bitcoin::consensus::deserialize; use sp_client::silentpayments::sending::SilentPaymentAddress; use sp_client::spclient::{OwnedOutput, Recipient, SpClient, SpWallet}; use sp_client::constants; @@ -74,6 +76,7 @@ pub fn create_transaction_spend_outpoint( outpoint: &OutPoint, sp_wallet: &SpWallet, mut recipient: Recipient, + commited_in_txid: &Txid, fee_rate: Amount ) -> Result { let available_outpoints = sp_wallet.get_outputs().to_spendable_list(); @@ -99,18 +102,25 @@ pub fn create_transaction_spend_outpoint( // update the amount for the recipient recipient.amount = total_available; - // create a dummy commitment + // Take the recipient address + let address = recipient.address.clone(); + + // create a dummy commitment that is H(b_scan | commited_in txid) let mut buf = [0u8;64]; - thread_rng().fill_bytes(&mut buf); + buf[..32].copy_from_slice(commited_in_txid.as_raw_hash().as_byte_array()); + buf[32..].copy_from_slice(&sp_wallet.get_client().get_scan_key().secret_bytes()); + + let mut engine = sha256::HashEngine::default(); + engine.write_all(&buf)?; + let hash = sha256::Hash::from_engine(engine); let mut new_psbt = sp_wallet.get_client().create_new_psbt( inputs, vec![recipient], - Some(&buf), + Some(hash.as_byte_array()), )?; - let change_addr = sp_wallet.get_client().sp_receiver.get_change_address(); - SpClient::set_fees(&mut new_psbt, fee_rate, change_addr)?; + SpClient::set_fees(&mut new_psbt, fee_rate, address)?; let partial_secret = sp_wallet .get_client() From da3829509d1369cc45e0159a2e9ee58cd49ce677 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 27 May 2024 16:04:41 +0200 Subject: [PATCH 27/30] [nit] CachedMessageStatus default Default derivation --- src/network.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/network.rs b/src/network.rs index 705fa03..cd0088b 100644 --- a/src/network.rs +++ b/src/network.rs @@ -250,9 +250,10 @@ impl AnkNetworkMsg { } } -#[derive(Debug, Serialize, Deserialize, PartialEq, Tsify, Clone)] +#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Tsify, Clone)] pub enum CachedMessageStatus { - NoStatus, // Default + #[default] + NoStatus, FaucetWaiting, FaucetComplete, CipherWaitingTx, @@ -263,12 +264,6 @@ pub enum CachedMessageStatus { Complete, } -impl Default for CachedMessageStatus { - fn default() -> Self { - Self::NoStatus - } -} - /// Unique struct for both 3nk messages and notification/key exchange, both rust and ts /// 0. Faucet: commited_in with nothing else, status is NoStatus /// 1. notification: From 71c616cec100f4e0915dcebd6bade947585b2f84 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 27 May 2024 16:05:05 +0200 Subject: [PATCH 28/30] [nit] Add some usefule comment in CachedMessageStatus --- src/network.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/network.rs b/src/network.rs index cd0088b..8efa290 100644 --- a/src/network.rs +++ b/src/network.rs @@ -258,9 +258,9 @@ pub enum CachedMessageStatus { FaucetComplete, CipherWaitingTx, TxWaitingCipher, - SentWaitingConfirmation, - ReceivedMustConfirm, - MustSpendConfirmation, + SentWaitingConfirmation, // we're sender and wait for commited_in to be spent + ReceivedMustConfirm, // we're receiver and we spend commited_in to sender + MustSpendConfirmation, // we're sender and we must spend confirmed_by Complete, } From 77ed38090fb698f3b1512e35b4c4a833afd5f763 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 27 May 2024 21:55:03 +0200 Subject: [PATCH 29/30] rm dead code in network --- src/network.rs | 129 +------------------------------------------------ 1 file changed, 1 insertion(+), 128 deletions(-) diff --git a/src/network.rs b/src/network.rs index 8efa290..c989730 100644 --- a/src/network.rs +++ b/src/network.rs @@ -3,139 +3,12 @@ use js_sys::Date; use rand::{thread_rng, RngCore}; use serde::{Deserialize, Serialize}; use sp_client::bitcoin::hex::{DisplayHex, FromHex}; -use sp_client::bitcoin::key::constants::ZERO; use sp_client::bitcoin::OutPoint; -use sp_client::silentpayments::bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine}; use tsify::Tsify; -use crate::crypto::{Aes256Decryption, CipherText, Purpose}; +use crate::crypto::{Aes256Decryption, Purpose}; use crate::error::AnkError; -const RAWTXTOPIC: &'static str = "rawtx"; -const RAWBLOCKTOPIC: &'static str = "rawblock"; - -#[derive(Debug, Serialize, Deserialize)] -pub enum BitcoinTopic { - RawTx, - RawBlock, -} - -impl BitcoinTopic { - pub fn as_str(&self) -> &str { - match self { - Self::RawTx => RAWTXTOPIC, - Self::RawBlock => RAWBLOCKTOPIC, - } - } -} - -#[derive(Debug, Serialize, Deserialize, Tsify)] -#[tsify(from_wasm_abi, into_wasm_abi)] -pub struct BitcoinNetworkMsg<'a> { - pub topic: BitcoinTopic, - pub data: &'a [u8], - pub sequence: &'a [u8], - pub addon: &'a [u8], -} - -impl<'a> BitcoinNetworkMsg<'a> { - pub fn new(raw_msg: &'a [u8]) -> Result { - let topic: BitcoinTopic; - let data: &[u8]; - let sequence: &[u8]; - let addon: &[u8]; - let addon_len: usize; - let raw_msg_len = raw_msg.len(); - - if raw_msg.starts_with(RAWTXTOPIC.as_bytes()) { - topic = BitcoinTopic::RawTx; - addon_len = 33; - } else if raw_msg.starts_with(RAWBLOCKTOPIC.as_bytes()) { - topic = BitcoinTopic::RawBlock; - addon_len = 0; - } else { - return Err(Error::msg("Unknown prefix")); - } - - data = &raw_msg[topic.as_str().as_bytes().len()..raw_msg_len - 4 - addon_len]; - sequence = &raw_msg[raw_msg_len - 4 - addon_len..]; - addon = &raw_msg[raw_msg_len - addon_len..]; - - Ok(Self { - topic, - data, - sequence, - addon, - }) - } -} - -sha256t_hash_newtype! { - pub struct PcdTag = hash_str("4nk/PCD"); - - #[hash_newtype(forward)] - pub struct PcdHash(_); - - pub struct PrdTag = hash_str("4nk/PRD"); - - #[hash_newtype(forward)] - pub struct PrdHash(_); -} - -impl PcdHash { - pub fn from_pcd(pcd: Pcd) -> Result { - let mut eng = PcdHash::engine(); - eng.input(&serde_json::to_string(&pcd)?.into_bytes()); - Ok(PcdHash::from_engine(eng)) - } -} - -impl PrdHash { - pub fn from_prd(prd: Prd) -> Result { - let mut eng = PrdHash::engine(); - eng.input(&serde_json::to_string(&prd)?.into_bytes()); - Ok(PrdHash::from_engine(eng)) - } -} - -type Item = String; // Is either a stringified json or the hex representation of its cipher - -#[derive(Debug, Serialize, Deserialize)] -pub struct Pcd { - name: String, - items: Item, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct Prd { - name: String, - seal: Option, - key: Option>, // encrypted key used to decrypt the linked pcd - pcd: PcdHash, -} - -impl Default for Prd { - fn default() -> Self { - Self { - name: "".to_owned(), - seal: None, - key: None, - pcd: PcdHash::from_byte_array(ZERO), - } - } -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct Envelope { - encrypted_prd: CipherText, -} - -impl Envelope { - pub fn new(encrypted_prd: Vec) -> Result { - Ok(Self { encrypted_prd }) - } -} - #[derive(Debug, Serialize, Deserialize, Tsify)] #[tsify(into_wasm_abi, from_wasm_abi)] pub enum AnkFlag { From 53b12127ed7955ba7b136f02d94c61fc6db9496e Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 27 May 2024 21:56:12 +0200 Subject: [PATCH 30/30] reorganize dependencies --- Cargo.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c63f825..9e57ef3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,12 +7,12 @@ edition = "2021" crate-type = ["cdylib", "rlib"] [dependencies] +aes-gcm = "0.10.3" anyhow = "1.0" +js-sys = "0.3.69" +rand = "0.8.5" serde = { version = "1.0.193", features = ["derive"] } serde_json = "1.0.108" sp_client = { git = "https://github.com/Sosthene00/sp-client.git", branch = "sp_client" } -uuid = { version = "1.6.1", features = ["serde", "v4"] } -aes-gcm = "0.10.3" -rand = "0.8.5" tsify = { git = "https://github.com/Sosthene00/tsify", branch = "next" } wasm-bindgen = "0.2.91"