Compare commits

...

272 Commits
main ... dev

Author SHA1 Message Date
Sosthene
e205229e92 Take an optional pairingid as sender instead of Member 2025-09-03 15:13:50 +02:00
Sosthene
dab1a4dd2c More verbose error messages for is_valid() 2025-09-02 12:51:42 +02:00
Sosthene
f65dd126ff Impl insert() in Roles 2025-09-02 12:51:20 +02:00
Sosthene
922cf2aa53 Add Device::get_mut_sp_wallet 2025-08-25 01:03:29 +02:00
Sosthene
aaaec47c23 Add Stream/Sink for wasm 2025-08-23 17:47:32 +02:00
Sosthene
1b885606ae Reexport backend_blindbit_wasm 2025-08-23 13:18:34 +02:00
Sosthene
a4c2fd2090 set sp_client to dev 2025-08-22 13:15:01 +02:00
Sosthene
362d2d6328 Update Cargo file 2025-08-22 10:25:44 +02:00
Sosthene
35cf0285fa Add wasm feature 2025-08-18 12:44:59 +02:00
Sosthene
21fb275739 checkout 4nk sp_client branch 2025-08-18 11:32:02 +02:00
Sosthene
e2369eaf6f Merge branch 'blindbit' into dev 2025-08-18 10:58:31 +02:00
Sosthene
684b71e00c Update tests 2025-07-15 11:26:56 +02:00
Sosthene
1e73a9aa1d Cargo fmt 2025-07-15 11:26:56 +02:00
Sosthene
ab8d556ad7 Update ProcessState implementation with new serialization 2025-07-15 11:26:56 +02:00
Sosthene
9a5ce7f5e2 Add get_sp_wallet to Device 2025-07-15 11:26:56 +02:00
Sosthene
e77d27e0e4 Rm all ciborium code from pcd 2025-07-15 11:26:56 +02:00
Sosthene
a7de9b1107 Add check_inputs 2025-07-15 11:26:56 +02:00
Sosthene
b5ac0584ed Add get_as methods for Pcd 2025-07-15 11:26:56 +02:00
Sosthene
4ce434d642 Add mark_output_spend and update mark_output_mined 2025-07-15 11:26:56 +02:00
Sosthene
e0bc9e9036 Use PcdSerializable in TryFrom impl for Pcd 2025-07-15 11:26:56 +02:00
Sosthene
b14a37a32a Add updates mod 2025-07-15 11:26:56 +02:00
Sosthene
14603debb2 Define and implement PcdSerializable trait 2025-07-15 11:26:56 +02:00
Sosthene
b52468e987 Add mark_output_mined to SpWallet 2025-07-15 11:26:56 +02:00
Sosthene
d55855710d Add const PCD_VERSION and ZSTD_COMPRESSION_LEVEL 2025-07-15 11:26:56 +02:00
Sosthene
af3f1879f9 Add chain_tip to HandshakeMessage and rm SyncMessage 2025-07-15 11:26:56 +02:00
Sosthene
8ab1a7db71 Replace ciborium with zstd 2025-07-15 11:26:56 +02:00
92c777dbef Add sync logic to handshake message 2025-07-15 11:26:56 +02:00
Sosthene
1c159806d9 Don't force ProcessState::public_data type to Record<string, string> 2025-07-15 11:22:05 +02:00
Sosthene
e5802d2855 Add verify_merkle_proof() 2025-06-30 19:41:43 +02:00
Sosthene
3c89b0fb7f Various minor fixes 2025-06-23 17:39:24 +02:00
Sosthene
dd6d93cd34 Make FileBlob pub and reexport js_sys 2025-06-17 15:17:18 +02:00
41b288eed6 Make ciborium serialize generic 2025-06-06 22:45:34 +02:00
58730c48f4 Move hashing into hash mod and refactor hash code 2025-06-06 22:45:17 +02:00
a3cf2517b3 Add const ROLESLABEL 2025-06-06 22:44:24 +02:00
f4baef4145 Add hash mod 2025-06-06 22:44:12 +02:00
d256ac7074 Add is_empty method to Roles 2025-06-06 12:47:55 +02:00
7264e64a4a Separate handling of the files data when encoding pcd 2025-06-06 12:47:34 +02:00
204211f3a3 reexport dependencies 2025-06-03 18:14:49 +02:00
304b1d0cc9 update ProcessState tests 2025-06-03 18:13:16 +02:00
e05929ace1 Update ProcessState 2025-06-03 18:13:06 +02:00
e7df62f9cd Update pcd tests 2025-06-03 18:12:13 +02:00
208449eb72 Add ciborium_serialize helper functions 2025-06-03 18:05:04 +02:00
cded679f4f Pcd is BTreeMap<String, Vec<u8>> 2025-06-03 18:04:27 +02:00
774d675d9c Add ciborium 2025-06-03 18:02:01 +02:00
985e6dcdc9 SpWallet in Device 2025-04-08 16:01:16 +02:00
d69d179439 Add SpWallet 2025-04-08 16:00:39 +02:00
ed78b370fc create_transaction deep refactoring 2025-04-08 16:00:25 +02:00
daff63113a Don't only look last output for commitments 2025-04-08 15:59:49 +02:00
0eaa4497d1 Rm obsolete tests 2025-04-08 15:59:17 +02:00
339b88c785 [bug] actually handle demiurge case 2025-04-05 18:34:55 +02:00
9293a3f5d1 Add TsUnsignedTransaction (wrapper type) 2025-04-04 12:47:42 +02:00
d008101ea9 Add get_balance to Device 2025-04-04 12:47:14 +02:00
f89b79ab5e Add outputs to Device 2025-04-03 15:56:37 +02:00
c3b24b754c Upgrade to latest sp_client 2025-04-03 14:52:18 +02:00
3985896d91 OutPointProcessMap PcdCommitments serialization 2025-04-03 14:52:18 +02:00
a686870e08 Update process tests 2025-03-26 12:38:30 +01:00
0175c793bb ProcessState new slight refactor 2025-03-26 12:38:17 +01:00
78dfebd71a Update dependencies 2025-03-26 12:38:03 +01:00
2d226392dc Add extract_paired_addresses 2025-03-26 12:37:37 +01:00
afc40b4395 Refactor ProcessState validation logic 2025-03-26 12:37:12 +01:00
491f260374 Add handle_pairing 2025-03-26 12:36:26 +01:00
d2a3147120 Refactor handle_obliteration 2025-03-26 12:36:06 +01:00
614849db78 Rm list_modified_states 2025-03-26 12:35:24 +01:00
0ecf627bf8 Update tests 2025-03-26 12:34:52 +01:00
e421b5d7d9 Implement get_mut for Roles 2025-03-26 12:31:22 +01:00
6c65a6d184 More check on quorum for ValidationRule 2025-03-26 12:31:05 +01:00
ee2fddbd4f Implement contains_key for PcdCommitments + change keys() return value 2025-03-26 12:30:44 +01:00
a85551773b derive from_wasm_abi for Pcd 2025-03-26 12:29:22 +01:00
f69fc1587e PcdCommitments new refactor 2025-03-26 12:29:05 +01:00
77618c4061 Add pairing special role + some refactor 2025-03-26 12:27:47 +01:00
f762fb903c Define constants for special roles 2025-03-26 12:27:18 +01:00
f246b5f039 Derive from_wasm_abi for OutPointMemberMap 2025-03-19 15:06:17 +01:00
dd13423c2b Update tests 2025-03-19 11:47:19 +01:00
818e4d2152 Remove dead code 2025-03-19 11:47:00 +01:00
df5d40ce96 Replace Member with Outpoint in RoleDefinition 2025-03-19 11:46:47 +01:00
b71e3f7525 Remove empty member condition 2025-03-19 11:44:59 +01:00
b5bd076f1e Update tests for obliteration 2025-03-13 14:39:33 +01:00
4429564974 Add process obliteration code 2025-03-13 14:39:13 +01:00
786ea94623 Add PcdCommitments::is_empty() 2025-03-13 14:38:20 +01:00
d8f6915a4a Lift restriction on new CommitMessage that couldn't take validation tokens 2025-03-13 14:38:02 +01:00
7babbc2a74 Rename PcdCommitments::emtpy() to new_empty() 2025-03-13 14:28:51 +01:00
4d9b03ff18 Add Apophis special role 2025-03-13 14:28:08 +01:00
6f786c5cc9 Add a special case in ProcessState::is_valid() for demiurge role 2025-03-12 13:03:50 +01:00
e5024ff019 Add SpecialRoles with Demiurge 2025-03-12 13:03:15 +01:00
bd8ae9183a Complete overhaul of the pcd/process logic, with sensible custom types and less serialization 2025-03-12 10:24:20 +01:00
8c5b2701fa Add crypto generate_key function 2025-03-12 10:20:30 +01:00
506d62d1d3 Add serialization hex_array_btree 2025-03-12 10:20:10 +01:00
fe6d78fbb6 Add serialization {de}serialize_hex 2025-03-12 10:19:55 +01:00
978ebd75c1 Rationalize serialization imports 2025-03-12 10:19:36 +01:00
2837fb6939 [bug] don't filter out freezed outputs but ignore them when selecting 2025-03-12 10:18:54 +01:00
f74c9a324b Export serde_json et serde_wasm_bindgen 2025-03-12 10:17:56 +01:00
3cf653c280 Add serde-wasm-bindgen and remove serde-json preserve-order feature 2025-03-12 10:10:36 +01:00
4bcf31d311 Add roles and public_data to prd 2025-03-04 14:43:43 +01:00
dc77482cc6 Add public_data to CommitMsg 2025-03-03 23:19:32 +01:00
131ee8c55b Rename process descriptions to public_data 2025-03-03 23:19:10 +01:00
17ad1a0319 Roles is now part of ProcessState out of the pcd 2025-02-07 23:05:11 +01:00
855cd948ef [bug] update_value also update the state_id 2025-02-07 22:38:18 +01:00
5fc2764bbf Derive Eq, PartialOrd, Ord for Proof 2025-02-07 22:36:21 +01:00
f0db7a1f23 Update to latest CommitMessage 2025-02-04 16:23:00 +01:00
1fe174190f More explicit error in case of Mutex poisoning 2025-02-04 16:22:48 +01:00
4c0a034a16 fee_provision is not a fraction of sent amount but some fixed value 2025-02-04 16:22:25 +01:00
1bc61f9251 filter_keys takes &HashSet 2025-02-04 16:21:58 +01:00
4be53916b0 Replace commitment_tx with process_id 2025-01-29 17:25:36 +01:00
079156d86a [bug] remove_all_concurrent_states won't panic if there's no concurrent states 2025-01-24 16:00:21 +01:00
a4a81f42f1 Replace MemberOutpointMap with OutPointMemberMap 2025-01-21 11:05:18 +01:00
51531a0f44 Add check_tx_for_process_updates 2025-01-17 18:08:18 +01:00
12705aa737 Reduce log verbosity 2025-01-16 18:09:17 +01:00
57a196d3ed Remove the revokation output 2025-01-16 17:12:14 +01:00
b8a3042131 Add serialization mod, with custom serialization logic 2025-01-10 16:24:08 +01:00
c5a00aa845 Implement Display for Member 2025-01-10 16:23:38 +01:00
35a046f7e8 Custom implement of Serialize for HandshakeMessage 2025-01-09 17:54:28 +01:00
0a6bc4e970 Improve Process impl 2025-01-09 17:29:14 +01:00
cd1ab95a94 Update Member 2025-01-09 17:28:48 +01:00
09b0f7a794 Merge branch 'init-message' into dev 2025-01-09 17:27:53 +01:00
228ad8c0ec Replace Init with Handshake 2025-01-09 17:27:03 +01:00
4f9775526e Rm CachedMessage 2025-01-07 09:25:33 +01:00
a628da9e2a All Prd constructors takes sender as a Member 2025-01-07 09:25:33 +01:00
57ce288ca4 Reimplement PartialEq, Eq and Hash for Member 2025-01-07 09:25:33 +01:00
b6ffebf6c0 Add new_request 2025-01-07 09:25:33 +01:00
13957e3e1f Add InitMessage 2025-01-07 09:25:33 +01:00
8f1b4a9071 [bug] correctly handle the case available funds are equal or just above target 2025-01-06 15:35:32 +01:00
326eb56b62 Rename merkle_root to state_id 2025-01-02 12:00:34 +01:00
26495e973e Check if we don't have the roles already in clear when validating a state 2024-12-19 14:06:38 +01:00
Sosthene
ac17d28f08 Various minor fixes 2024-12-17 22:37:47 +01:00
Sosthene
0be1065c5e [bug] Fix get_state_for_commitments_root 2024-12-17 22:37:38 +01:00
Sosthene
27ee79f31d Modify ts type for ProcessState fields 2024-12-17 22:37:15 +01:00
Sosthene
123c6946f2 Remove impending_requests from Process 2024-12-17 22:36:33 +01:00
Sosthene
1e8a51f37a Fix pcd to_sorted_key_values to sort recursively 2024-12-17 22:34:58 +01:00
Sosthene
8a682b0a7c Modify prd update to take the roles map as payload 2024-12-17 22:34:00 +01:00
Sosthene
95451b517e Add Init Flag 2024-12-17 13:26:19 +01:00
Sosthene
58578450f3 Add descriptions field in ProcessState 2024-12-12 16:03:21 +01:00
Sosthene
fff051b12c Add Process::get_process_id() 2024-12-12 15:50:15 +01:00
Sosthene
8a5beeacc7 Update process tests 2024-12-11 23:28:07 +01:00
Sosthene
e0647610db get_state_for_commitments_root mut and immut version 2024-12-11 23:27:52 +01:00
Sosthene
d2d586f996 Update decrypt_pcd to return Map 2024-12-11 23:27:18 +01:00
Sosthene
2db9b29e6b Add merkle_root to ProcessState and update new() 2024-12-11 23:25:11 +01:00
Sosthene
5be3340aad Add Pcd::to_sorted_key_values, and hash values with a counter 2024-12-11 23:23:14 +01:00
Sosthene
1068340c09 AnkPcdHash from_value_with_outpoint takes &[u8] 2024-12-11 23:20:25 +01:00
Sosthene
0f47588e8d Fix process tests 2024-12-06 15:27:53 +01:00
Sosthene
1789f95761 Update some calls 2024-12-06 15:27:44 +01:00
Sosthene
2e8652453d Add new and update_value to ProcessState 2024-12-06 15:27:05 +01:00
Sosthene
adc1fbfabd Fix pcd tests 2024-12-06 15:26:38 +01:00
Sosthene
103586570f Refactor is_hex_string 2024-12-06 15:26:30 +01:00
Sosthene
348e509ddc decrypt_all check is the value is clear or a commitment 2024-12-06 15:26:07 +01:00
Sosthene
adeb5e6537 Encrypt_fields check for existing keys and don't overwrite values 2024-12-06 15:24:54 +01:00
Sosthene
f409671d3a Use commited_in instead of root_commitment as salt 2024-12-06 15:23:54 +01:00
Sosthene
46625984f3 Remove dead code 2024-12-06 15:22:43 +01:00
Sosthene
1619222fb3 Add storages to RoleDefinition 2024-12-06 15:22:00 +01:00
Sosthene
baaee6d31d fix pcd tests 2024-12-03 22:54:03 +01:00
Sosthene
a2b969b72e [bug] correct hash construction 2024-12-03 22:34:36 +01:00
Sosthene
e47059668d [bug] implement a from_merkle_root method for ValidationHash instead of from_byte_array 2024-12-03 22:33:24 +01:00
Sosthene
72a3230952 Add is_hexstring to Pcd trait 2024-12-03 10:36:13 +01:00
Sosthene
a786eb8fe0 Remove is_linked() and is_linking() from device 2024-12-03 10:36:13 +01:00
Sosthene
614bdcedd2 create_merkle_tree() sorts leaves 2024-12-03 10:36:13 +01:00
Sosthene
e2d8e0eb77 Add RoleDefinition is_member_validation_needed() 2024-12-03 10:36:13 +01:00
Sosthene
da4c752df0 Update ValidationRule is_satisfied() 2024-12-03 10:36:10 +01:00
Sosthene
0ad63d347b Add ValidationRule::allows_modification() 2024-11-29 09:10:54 +01:00
Sosthene
b38189beca Make Pcd::decrypt_fields() replace encrypted by commitments 2024-11-29 09:09:54 +01:00
Sosthene
64908496eb Update dependendies in process.rs 2024-11-29 09:09:14 +01:00
Sosthene
2c5ed2c94a Tsify Process 2024-11-29 09:08:55 +01:00
Sosthene
541ad36d13 Add get_fields_to_validate_for_member() 2024-11-29 09:08:19 +01:00
Sosthene
eda2dd687d Refactor ProcessState is_valid() 2024-11-29 09:07:48 +01:00
Sosthene
391ca02186 Refactor decrypt_pcd() 2024-11-29 09:07:15 +01:00
Sosthene
43459fa0bb Rename compute->list_modified_fields, and slight refactor 2024-11-29 08:43:43 +01:00
Sosthene
2fadc2e39c Update create_merkle_tree 2024-11-29 01:11:43 +01:00
Sosthene
d19abaf653 [bug] ProcessState compute_modified_fields compare hashes instead of ciphers 2024-11-26 22:04:31 +01:00
Sosthene
00327b2e46 Add get_state_for_commitment_root 2024-11-25 23:24:05 +01:00
Sosthene
0fc6a2a939 Process::new() creates Process with empty state 2024-11-25 22:27:43 +01:00
Sosthene
d459d608ed Add SecretsStore methods 2024-11-25 22:27:09 +01:00
Sosthene
8845942f32 confirm_secret_for_address returns the previous secret 2024-11-25 22:26:50 +01:00
Sosthene
49c125f085 Change Proof message to byte array 2024-11-25 22:26:09 +01:00
Sosthene
d10382f121 Add env_logger and reexport 2024-11-19 13:08:03 +01:00
Sosthene
06f3485361 Derive into_wasm_abi for SecretsStore 2024-11-13 10:35:50 +01:00
Sosthene
4e7dd4e0b4 Refactor states update 2024-11-12 23:22:20 +01:00
Sosthene
c2fde13e95 Update prd/pcd to keep commitments of each field 2024-11-12 20:52:28 +01:00
Sosthene
4885066bd2 Update device 2024-11-12 20:51:56 +01:00
Sosthene
ae807c3857 Add rs_merkle dependency 2024-11-12 20:51:30 +01:00
Sosthene
12da1740e2 Optimise to_network_msg: no need to clone to_sign 2024-10-29 13:03:03 +01:00
Sosthene
b858c68ae0 PrdConnect takes a secret hash as payload and previous proof 2024-10-29 13:03:03 +01:00
Sosthene
c3a7a3570b Add get_address_for_key to Member 2024-10-29 13:03:03 +01:00
Sosthene
9c9e50bcdb key_is_part_of_member takes PublicKey 2024-10-29 13:03:03 +01:00
Sosthene
c191d53769 Proof keeps the compressed PublicKey, not x only 2024-10-29 13:03:03 +01:00
Sosthene
a84d1d0508 Derive Default for Member 2024-10-29 12:57:25 +01:00
Sosthene
b2ad5ee227 Remove shared_secrets from Process 2024-10-29 12:57:03 +01:00
Sosthene
d275fc5bc0 Add SecretsStore 2024-10-29 12:56:14 +01:00
Sosthene
838149982e Correct error message for prd signed by ourselves 2024-10-28 21:43:45 +01:00
Sosthene
ccd5e398b0 Add Prd Connect 2024-10-28 16:03:13 +01:00
775119cdf6 Check a prd is not signed by ourselves when extracting from message 2024-10-21 13:01:17 +02:00
Sosthene
9fd463b592 Fix bug with set_fees returning insufficient amount 2024-10-12 16:28:50 +02:00
Sosthene
4eda758b64 Add get_latest_commited_state method to Process 2024-10-10 16:57:56 +02:00
Sosthene
ef556fddaa Choice of inputs in create_transaction adds 10% to the amount 2024-10-10 16:57:35 +02:00
Sosthene
aa14c69bdf Prd commitment doesn't take validation_tokens 2024-10-10 16:57:03 +02:00
Sosthene
21dccde051 ProcessState validation tests + bug fixes 2024-10-08 11:02:59 +02:00
Sosthene
4744740303 Update process states validation logic 2024-10-07 11:16:35 +02:00
Sosthene
7a4344608e Modify fields encryption, can selectively encrypt and fields that are not decrypted stay as they are 2024-10-07 11:15:22 +02:00
Sosthene
3c15b41699 Format 2024-10-06 10:40:29 +02:00
Sosthene
4809459da5 Add RoleDefinition tests 2024-10-06 10:38:48 +02:00
Sosthene
3f633cf594 Add ValidationRule tests + some fixes 2024-10-04 11:45:04 +02:00
Sosthene
9ff9176498 Modify create_transaction mandatory_inputs argument 2024-10-04 09:27:38 +02:00
Sosthene
1d9a994543 Add get_message to Proof 2024-10-04 09:27:38 +02:00
Sosthene
3ebf4f7899 Add validation logic to ProcessState 2024-10-04 09:27:38 +02:00
Sosthene
319da6b1a3 New_response takes multiple Proof 2024-10-04 09:27:38 +02:00
Sosthene
70bd927077 Add validation logic to ValidationRules and RuleDefinition 2024-10-04 09:27:38 +02:00
Sosthene
432dc4b8ea Add key_is_part_of_member to Member 2024-10-04 09:27:38 +02:00
Sosthene
185a014de1 Update Device api 2024-10-04 09:27:38 +02:00
Sosthene
9632ef24e3 Update Process api 2024-10-04 09:27:38 +02:00
Sosthene
8d4238f531 Add CommitMessage 2024-10-04 09:27:38 +02:00
Sosthene
bb82a0b760 Simplify CachedMessage 2024-10-04 09:27:38 +02:00
Omar Oughriss
d91a4a67eb Update Cargo.toml 2024-10-02 13:42:26 +00:00
Sosthene
15eda2c4b1 Impl PartialEq for NewTxMessage 2024-09-26 10:46:01 +02:00
Sosthene
f3ab3525a3 Merge branch 'minimal_prd_pcd' into dev 2024-09-25 10:11:29 +02:00
Sosthene
959f8a3058 Rm uuid dependency 2024-09-23 16:14:58 +02:00
Sosthene
f3aa1bc2d0 Functional prd/pcd 2024-09-23 16:12:29 +02:00
Sosthene
62b2137c77 Complete Process implementation 2024-09-23 16:12:29 +02:00
Sosthene
bbc9eaa962 cleanup crypto 2024-09-23 16:12:29 +02:00
Sosthene
3cbe77c143 Add MutexExt trait 2024-09-23 16:12:29 +02:00
Sosthene
97df8ea13d Update prd/pcd 2024-09-02 07:55:35 +02:00
Sosthene
0ea4c5f118 Implement prd/pcd logic 2024-08-28 09:40:19 +02:00
Sosthene
665d95554d Add basic signature 2024-08-21 13:17:34 +02:00
Sosthene
b2c070642e Implement Process 2024-08-20 12:21:15 +02:00
Sosthene
8688b6ed79 Update create_transaction test 2024-08-15 16:24:58 +02:00
Sosthene
dd797bd981 Update Pcd/Prd 2024-08-15 16:15:26 +02:00
Sosthene
95ed1e1f1c Rename AnkNetworkMsg to Envelope 2024-08-13 15:52:54 +02:00
Sosthene
41743ab3e7 Replace CipherMessage with Prd and put data in Pcd 2024-08-13 15:52:54 +02:00
Sosthene
d61b210dda [bug] FaucetMessage commitment is 32B long 2024-08-13 15:04:59 +02:00
Sosthene
38fa6e6239 Add to_string() to Faucet and NewTxMessage 2024-08-13 14:21:07 +02:00
Sosthene
9017f7651b new_login 2024-08-01 12:25:49 +02:00
Sosthene
d871b326c8 Merge branch 'new_login' into dev 2024-07-19 22:51:01 +02:00
Sosthene
b5881d63b0 Add TrustedChannel 2024-07-19 22:48:57 +02:00
Sosthene
f59dc042b6 Update CachedMessage 2024-07-19 22:48:45 +02:00
Sosthene
e1f70cf849 fmt 2024-07-19 22:48:15 +02:00
Sosthene
9087e0a535 Replace silentpayments methods with one create_transaction 2024-07-19 22:47:09 +02:00
Sosthene
207e2d1d73 Add to_string and from_string methods to network types 2024-07-19 22:46:07 +02:00
Sosthene
a1cfba63ff Add optional payload to create_transaction_spend_outpoint 2024-06-27 17:19:04 +02:00
Sosthene
b648ed9ada Add export_key method to Aes256Encryption 2024-06-27 17:16:26 +02:00
Sosthene
3d30eb8ce3 Update sp-client to latest master 2024-06-17 13:40:03 +02:00
Sosthene
cc45650777 import SilentPaymentAddress from utils 2024-06-03 18:16:35 +02:00
e6007ca0a7 path = "../sp-client" } -> sp_client = { git = "https://github.com/Sosthene00/sp-client.git", branch = "sp_client" } 2024-05-29 16:03:47 +02:00
ef55bcea5e Update 2024-05-28 16:33:40 +02:00
Sosthene
c1b95290bf [temp] sp-client temporary branch 2024-05-28 10:42:20 +02:00
Sosthene
b69fbdbd4c Reexport sp_client 2024-05-28 10:41:47 +02:00
Sosthene
31e955677e Merge branch 'demo' into dev 2024-05-27 21:59:08 +02:00
Sosthene
53b12127ed reorganize dependencies 2024-05-27 21:56:12 +02:00
Sosthene
77ed38090f rm dead code in network 2024-05-27 21:55:03 +02:00
Sosthene
71c616cec1 [nit] Add some usefule comment in CachedMessageStatus 2024-05-27 16:05:05 +02:00
Sosthene
da3829509d [nit] CachedMessageStatus default Default derivation 2024-05-27 16:04:41 +02:00
Sosthene
d82a1c7624 Commitment for confirmation transaction is not random 2024-05-27 15:25:57 +02:00
Sosthene
f52dca8db7 timestamp new CachedMessage 2024-05-27 11:57:23 +02:00
Sosthene
0c38e24f44 AnkSharedSecret new() takes PublicKey 2024-05-27 11:56:29 +02:00
Sosthene
70bc03da9e error in CachedMessage is AnkError 2024-05-27 11:55:41 +02:00
Sosthene
6492952dc0 Add error mod 2024-05-27 11:54:19 +02:00
Sosthene
72089b8545 Rm Error and Prd AnkFlag, Add Cipher, add error field for each message 2024-05-27 11:49:53 +02:00
Sosthene
c5ff2e2edb add ReceivedMustConfirm status 2024-05-22 23:40:31 +02:00
Sosthene
87ee8ac40c Move CachedMessage here from sdk_client 2024-05-22 20:52:48 +02:00
Sosthene
9fe3e7b499 nit: output value is exactly what's available in the input for confirmation 2024-05-22 20:52:16 +02:00
Sosthene
f5cdb7e2f1 [bug] content of the op_return wasn't correctly serialized 2024-05-22 20:51:24 +02:00
Sosthene
1f8da7ea61 Refactor silentpayments 2024-05-22 10:22:53 +02:00
Sosthene
0e88a729c3 Add a dummy commitment in faucet messages 2024-05-22 10:22:20 +02:00
Sosthene
d7daf72da0 Rm trusted in AnkSharedSecret 2024-05-22 10:21:54 +02:00
Sosthene
bd09245713 Add create_transaction 2024-05-15 08:32:16 +02:00
Sosthene
6bf80eb0a5 create_transaction_for_address_with_shared_secret takes optional message 2024-05-14 22:22:17 +02:00
Sosthene
62d135925e Add UnknownMessage struct 2024-05-14 22:20:53 +02:00
Sosthene
a55760c944 Add AAD in encrypted payload 2024-05-06 15:53:58 +02:00
Sosthene00
932dc0ba55 get_shared_point_from_transaction 2024-04-30 12:21:42 +02:00
Sosthene00
a59c680d0e crypto simplification 2024-04-30 12:21:42 +02:00
Sosthene00
b1bfe0ba22 update_meeting 2024-04-24 12:10:10 +02:00
Sosthene00
9a34a02063 crypto add arbitrary purpose 2024-04-24 00:10:26 +02:00
Sosthene00
8f11111943 replace sp_backend with sp_client 2024-04-24 00:10:26 +02:00
Sosthene00
d24401ada8 Add AnkSharedSecret 2024-04-17 08:30:01 +02:00
Sosthene00
76dd12aaac Add network 2024-04-17 08:30:01 +02:00
Sosthene00
3dff792218 Add crypto mod 2024-04-17 08:30:01 +02:00
Sosthene00
0a7b289087 tabula rasa 2024-04-17 08:30:01 +02:00
76 changed files with 4610 additions and 5506 deletions

View File

@ -6,18 +6,31 @@ edition = "2021"
[lib]
crate-type = ["cdylib", "rlib"]
[features]
default = []
parallel = ["sp-client/parallel"]
blindbit-backend = ["backend-blindbit-native"]
blindbit-wasm = ["backend-blindbit-wasm", "dep:js-sys", "dep:serde-wasm-bindgen", "dep:futures"]
[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"
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"] }
anyhow = "1.0"
env_logger = "0.9"
log = "0.4.6"
rand = "0.8.5"
serde = { version = "1.0.193", features = ["derive"] }
serde_json = { version = "1.0.108" }
rs_merkle = "1.4.2"
zstd = "0.13.3"
getrandom = { version = "0.2", features = ["js"] }
sp-client = { git = "https://github.com/Sosthene00/sp-client.git", branch = "dev", default-features = false }
backend-blindbit-native = { git = "https://github.com/Sosthene00/sp-client.git", branch = "dev", optional = true }
backend-blindbit-wasm = { git = "https://github.com/Sosthene00/sp-client.git", branch = "dev", optional = true }
tsify = { git = "https://github.com/Sosthene00/tsify", branch = "next" }
wasm-bindgen = "0.2.91"
# WASM-specific dependencies (optional)
js-sys = { version = "0.3.69", optional = true }
serde-wasm-bindgen = { version = "0.6.5", optional = true }
futures = { version = "0.3", optional = true }

View File

69
src/crypto.rs Normal file
View File

@ -0,0 +1,69 @@
use anyhow::Result;
use rs_merkle::{algorithms::Sha256, MerkleProof};
use sp_client::silentpayments::{
bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine},
secp256k1::PublicKey,
};
use aes_gcm::aead::{Aead, Payload};
pub use aes_gcm::{AeadCore, Aes256Gcm, KeyInit};
use rand::{thread_rng, CryptoRng, RngCore};
pub const AAD: &[u8] = "4nk".as_bytes();
sha256t_hash_newtype! {
pub struct AnkSharedSecretTag = hash_str("4nk/AnkSharedSecret");
#[hash_newtype(forward)]
pub struct AnkSharedSecretHash(_);
}
impl AnkSharedSecretHash {
pub fn from_shared_point(shared_point: PublicKey) -> Self {
let mut eng = AnkSharedSecretHash::engine();
eng.input(&shared_point.serialize_uncompressed()[1..]);
AnkSharedSecretHash::from_engine(eng)
}
}
pub fn generate_key(rng: &mut (impl CryptoRng + RngCore)) -> [u8; 32] {
let key = Aes256Gcm::generate_key(rng);
key.into()
}
pub fn encrypt_with_key(key: &[u8; 32], plaintext: &[u8]) -> Result<Vec<u8>> {
let encryption_eng = Aes256Gcm::new(key.into());
let nonce = Aes256Gcm::generate_nonce(&mut thread_rng());
let payload = Payload {
msg: plaintext,
aad: AAD,
};
let ciphertext = encryption_eng
.encrypt(&nonce, payload)
.map_err(|e| anyhow::anyhow!(e))?;
let mut res: Vec<u8> = Vec::with_capacity(nonce.len() + ciphertext.len());
res.extend_from_slice(&nonce);
res.extend_from_slice(&ciphertext);
Ok(res)
}
pub fn decrypt_with_key(key: &[u8; 32], ciphertext: &[u8]) -> Result<Vec<u8>> {
let decryption_eng = Aes256Gcm::new(key.into());
let nonce = &ciphertext[..12];
let payload = Payload {
msg: &ciphertext[12..],
aad: AAD,
};
let plaintext = decryption_eng
.decrypt(nonce.into(), payload)
.map_err(|e| anyhow::anyhow!(e))?;
Ok(plaintext)
}
pub fn verify_merkle_proof(proof: &[u8], root: &[u8; 32], index: usize, hash: &[u8; 32], total_leaves_count: usize) -> Result<bool> {
let proof = MerkleProof::<Sha256>::from_bytes(proof)?;
Ok(proof.verify(*root, &[index], &[*hash], total_leaves_count))
}

185
src/device.rs Normal file
View File

@ -0,0 +1,185 @@
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use tsify::Tsify;
use wasm_bindgen::prelude::*;
use sp_client::{
bitcoin::{
absolute::Height, hashes::Hash, secp256k1::PublicKey, Amount, OutPoint, Transaction,
XOnlyPublicKey,
},
silentpayments::{utils::receiving::calculate_ecdh_shared_secret, SilentPaymentAddress},
OutputSpendStatus, OwnedOutput, SpClient,
};
use crate::{pcd::Member, silentpayments::SpWallet};
#[derive(Debug, Serialize, Deserialize, Clone, Default, Tsify)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub struct Device {
sp_wallet: SpWallet,
pairing_process_commitment: Option<OutPoint>,
paired_member: Member,
}
impl Device {
pub fn new(sp_client: SpClient) -> Self {
let local_address = sp_client.get_receiving_address();
let member = Member::new(vec![SilentPaymentAddress::try_from(local_address).unwrap()]);
Self {
sp_wallet: SpWallet::new(sp_client),
pairing_process_commitment: None,
paired_member: member,
}
}
pub fn get_sp_wallet(&self) -> &SpWallet {
&self.sp_wallet
}
pub fn get_mut_sp_wallet(&mut self) -> &mut SpWallet {
&mut self.sp_wallet
}
pub fn get_sp_client(&self) -> &SpClient {
self.sp_wallet.get_sp_client()
}
pub fn get_outputs(&self) -> &HashMap<OutPoint, OwnedOutput> {
self.sp_wallet.get_outputs()
}
pub fn get_mut_outputs(&mut self) -> &mut HashMap<OutPoint, OwnedOutput> {
self.sp_wallet.get_mut_outputs()
}
pub fn get_balance(&self) -> Amount {
self.sp_wallet
.get_outputs()
.values()
.filter(|output| output.spend_status == OutputSpendStatus::Unspent)
.fold(Amount::ZERO, |acc, x| acc + x.amount)
}
pub fn update_outputs_with_transaction(
&mut self,
tx: &Transaction,
blockheight: u32,
partial_tweak: PublicKey,
) -> anyhow::Result<HashMap<OutPoint, OwnedOutput>> {
// First check that we haven't already scanned this transaction
let txid = tx.txid();
for i in 0..tx.output.len() {
if self.sp_wallet.get_outputs().contains_key(&OutPoint {
txid,
vout: i as u32,
}) {
return Err(anyhow::Error::msg("Transaction already scanned"));
}
}
for input in tx.input.iter() {
if let Some(output) = self.sp_wallet.get_outputs().get(&input.previous_output) {
match &output.spend_status {
OutputSpendStatus::Spent(tx) => {
if *tx == txid.as_raw_hash().to_byte_array() {
return Err(anyhow::Error::msg("Transaction already scanned"));
}
}
OutputSpendStatus::Mined(_) => {
return Err(anyhow::Error::msg("Transaction already scanned"))
}
_ => continue,
}
}
}
let shared_secret = calculate_ecdh_shared_secret(
&partial_tweak,
&self.sp_wallet.get_sp_client().get_scan_key(),
);
let mut pubkeys_to_check: HashMap<XOnlyPublicKey, u32> = HashMap::new();
for (vout, output) in (0u32..).zip(tx.output.iter()) {
if output.script_pubkey.is_p2tr() {
let xonly = XOnlyPublicKey::from_slice(&output.script_pubkey.as_bytes()[2..])?;
pubkeys_to_check.insert(xonly, vout);
}
}
let ours = self
.sp_wallet
.get_sp_client()
.sp_receiver
.scan_transaction(&shared_secret, pubkeys_to_check.keys().cloned().collect())?;
let mut new_outputs: HashMap<OutPoint, OwnedOutput> = HashMap::new();
for (label, map) in ours.iter() {
for (key, scalar) in map {
let vout = pubkeys_to_check.get(&key).unwrap().to_owned();
let txout = tx.output.get(vout as usize).unwrap();
let outpoint = OutPoint::new(tx.txid(), vout);
let owned = OwnedOutput {
blockheight: Height::from_consensus(blockheight)?,
tweak: scalar.to_be_bytes(),
amount: txout.value,
script: txout.script_pubkey.to_bytes().try_into()?,
label: label.clone(),
spend_status: OutputSpendStatus::Unspent,
};
new_outputs.insert(outpoint, owned);
}
}
let mut res = new_outputs.clone();
self.sp_wallet.get_mut_outputs().extend(new_outputs);
let txid = tx.txid();
// update outputs that we own and that are spent
for input in tx.input.iter() {
if let Some(prevout) = self
.sp_wallet
.get_mut_outputs()
.get_mut(&input.previous_output)
{
// This is spent by this tx
prevout.spend_status = OutputSpendStatus::Spent(*txid.as_byte_array());
res.insert(input.previous_output, prevout.clone());
}
}
Ok(res)
}
pub fn get_pairing_commitment(&self) -> Option<OutPoint> {
self.pairing_process_commitment.clone()
}
pub fn pair(&mut self, commitment_outpoint: OutPoint, member: Member) {
self.pairing_process_commitment = Some(commitment_outpoint);
self.paired_member = member;
}
pub fn unpair(&mut self) {
let local_address = self.get_sp_client().get_receiving_address();
let member = Member::new(vec![SilentPaymentAddress::try_from(local_address).unwrap()]);
self.paired_member = member;
self.pairing_process_commitment = None;
}
pub fn to_member(&self) -> Member {
self.paired_member.clone()
}
pub fn get_address(&self) -> SilentPaymentAddress {
self.get_sp_client().get_receiving_address()
}
pub fn get_other_addresses(&self) -> Vec<String> {
let our_address: String = self.get_sp_client().get_receiving_address().into();
self.to_member()
.get_addresses()
.into_iter()
.filter(|a| *a != our_address)
.collect()
}
}

41
src/error.rs Normal file
View File

@ -0,0 +1,41 @@
use std::error::Error;
use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, 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<anyhow::Error> 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)
}
}
}

24
src/hash.rs Normal file
View File

@ -0,0 +1,24 @@
use sp_client::bitcoin::{
consensus::{serialize, Encodable},
hashes::{sha256t_hash_newtype, Hash, HashEngine},
OutPoint,
};
sha256t_hash_newtype! {
pub struct AnkPcdTag = hash_str("4nk/Pcd");
#[hash_newtype(forward)]
pub struct AnkPcdHash(_);
}
impl AnkPcdHash {
pub fn from_pcd_value(value: &[u8], label: &[u8], outpoint: &OutPoint) -> Self {
let mut eng = AnkPcdHash::engine();
eng.input(value);
eng.input(label);
serialize(outpoint)
.consensus_encode(&mut eng)
.expect("hash engine don't return errors");
AnkPcdHash::from_engine(eng)
}
}

View File

@ -1,3 +1,132 @@
pub mod models;
pub mod wallet;
pub mod workflows;
use std::fmt::Debug;
use std::str::FromStr;
use std::sync::{Mutex, MutexGuard};
pub use aes_gcm;
pub use env_logger;
pub use log;
pub use rand;
pub use serde;
pub use serde_json;
pub use sp_client;
pub use tsify;
pub use wasm_bindgen;
pub use zstd;
#[cfg(feature = "blindbit-wasm")]
pub use js_sys;
#[cfg(feature = "blindbit-wasm")]
pub use serde_wasm_bindgen;
#[cfg(feature = "blindbit-backend")]
pub use backend_blindbit_native;
#[cfg(feature = "blindbit-wasm")]
pub use backend_blindbit_wasm;
pub mod crypto;
pub mod device;
pub mod error;
pub mod hash;
pub mod network;
pub mod pcd;
pub mod prd;
pub mod process;
pub mod secrets;
pub mod serialization;
pub mod signature;
pub mod silentpayments;
pub mod updates;
pub const MAX_PRD_PAYLOAD_SIZE: usize = u16::MAX as usize; // 64KiB sounds reasonable for now
const DEMIURGE: &str = "demiurge";
const PAIRING: &str = "pairing";
const APOPHIS: &str = "apophis";
const MEMBERPUBLICNAME: &str = "memberPublicName";
const PAIREDADDRESSES: &str = "pairedAddresses";
const ROLESLABEL: &str = "roles";
#[derive(Debug, PartialEq, Eq)]
pub enum SpecialRoles {
Demiurge, // Only valid for the first state of a process
Pairing, // Special validation rules for pairing process
Apophis, // Users in this role have the power to destroy the process
}
impl std::fmt::Display for SpecialRoles {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", <&Self as Into<&str>>::into(self))
}
}
impl From<&SpecialRoles> for &str {
fn from(value: &SpecialRoles) -> Self {
match value {
SpecialRoles::Demiurge => DEMIURGE,
SpecialRoles::Pairing => PAIRING,
SpecialRoles::Apophis => APOPHIS,
}
}
}
impl FromStr for SpecialRoles {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
DEMIURGE => Ok(SpecialRoles::Demiurge),
PAIRING => Ok(SpecialRoles::Pairing),
APOPHIS => Ok(SpecialRoles::Apophis),
_ => Err(format!("Invalid special role: {}", s)),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum ReservedFields {
PairedAddresses,
MemberPublicName,
}
impl From<&ReservedFields> for &str {
fn from(value: &ReservedFields) -> Self {
match value {
ReservedFields::MemberPublicName => MEMBERPUBLICNAME,
ReservedFields::PairedAddresses => PAIREDADDRESSES,
}
}
}
impl FromStr for ReservedFields {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
MEMBERPUBLICNAME => Ok(ReservedFields::MemberPublicName),
PAIREDADDRESSES => Ok(ReservedFields::PairedAddresses),
_ => Err(format!("Invalid field name: {}", s)),
}
}
}
pub trait MutexExt<T> {
fn lock_anyhow(&self) -> Result<MutexGuard<T>, anyhow::Error>;
}
impl<T: Debug> MutexExt<T> for Mutex<T> {
fn lock_anyhow(&self) -> Result<MutexGuard<T>, anyhow::Error> {
match self.lock() {
Ok(guard) => Ok(guard),
Err(poison_error) => {
let data = poison_error.into_inner();
log::debug!("Failed to lock Mutex (poisoned). Data was: {:?}", data);
Err(anyhow::anyhow!("Failed to lock Mutex (poisoned)"))
}
}
}
}

View File

@ -1,5 +0,0 @@
use sdk_common::models;
use sdk_common::wallet;
use sdk_common::workflows;
fn main() {}

View File

@ -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 }
}
}

View File

@ -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
}
}

View File

@ -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
}
}

View File

@ -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
}
}

View File

@ -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);
}
}

View File

@ -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
}
}

View File

@ -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<String>,
pub prd_sp_address_required_list: Vec<String>,
pub prd_sp_address_quota: i32,
pub prd_prd_value_ok_list: Vec<String>,
pub prd_value_ko_list: Vec<String>,
pub prd_value_none_list: Vec<String>,
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<String>,
prd_sp_address_required_list: Vec<String>,
prd_sp_address_quota: i32,
prd_prd_value_ok_list: Vec<String>,
prd_value_ko_list: Vec<String>,
prd_value_none_list: Vec<String>,
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.
}

View File

@ -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);
}
}

View File

@ -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 {}

View File

@ -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<String>,
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
}

View File

@ -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<String>, // Assuming list of attributes
pub role_confidential_attribute_group: Vec<String>,
pub private_attribute_group: Vec<String>,
}
impl Artefact {
pub fn new(
item: Item,
public_attribute_group: Vec<String>,
role_confidential_attribute_group: Vec<String>,
private_attribute_group: Vec<String>,
) -> 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<PcdItemEncAttributePublic> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePublic> = 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<PcdItemEncAttributeRoleConfidential> {
let mut enc_attribute_list: Vec<PcdItemEncAttributeRoleConfidential> = 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<PcdItemEncAttributePrivate> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePrivate> = 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
);
}
}

View File

@ -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<String>,
pub goal_list: Vec<String>,
pub provider_type: String,
pub commit_pcd_hash_list: Vec<String>,
pub ref_item_hash_list: Vec<String>,
pub ref_pcd_hash_list: Vec<String>,
pub payload_public_list: Vec<String>,
}
impl CommitPublicAttributeGroup {
pub fn new(
for_sp_address_list: Vec<String>,
goal_list: Vec<String>,
provider_type: String,
commit_pcd_hash_list: Vec<String>,
ref_item_hash_list: Vec<String>,
ref_pcd_hash_list: Vec<String>,
payload_public_list: Vec<String>,
) -> 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<PcdItemEncAttributePublic> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePublic> = 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<String>,
}
impl CommitRoleConfidentialAttributeGroup {
pub fn new(payload_list_confidential: Vec<String>) -> Self {
CommitRoleConfidentialAttributeGroup {
payload_list_confidential,
}
}
pub fn enc_group(&self) -> Vec<PcdItemEncAttributeRoleConfidential> {
let mut enc_attribute_list: Vec<PcdItemEncAttributeRoleConfidential> = 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<String>,
}
impl CommitPrivateAttributeGroup {
pub fn new(payload_list_private: Vec<String>) -> Self {
CommitPrivateAttributeGroup {
payload_list_private,
}
}
pub fn enc_group(&self, Member_enc_key: KeyEncryption) -> Vec<PcdItemEncAttributePrivate> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePrivate> = 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`
}
}

View File

@ -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<String>,
pub for_address_list: Vec<String>,
pub goal_list: Vec<String>,
pub provider_type: String,
pub ref_item_hash_list: Vec<String>,
pub ref_pcd_hash_list: Vec<String>,
pub payload_list_public: Vec<String>,
pub audit_code_list_public: Vec<String>,
}
impl DepositPublicAttributeGroup {
pub fn new(
for_sp_address_list: Vec<String>,
for_address_list: Vec<String>,
goal_list: Vec<String>,
provider_type: String,
ref_item_hash_list: Vec<String>,
ref_pcd_hash_list: Vec<String>,
payload_list_public: Vec<String>,
audit_code_list_public: Vec<String>,
) -> 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<PcdItemEncAttributePublic> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePublic> = 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<String>,
pub audit_code_list_confidential: Vec<String>,
}
impl DepositRoleConfidentialAttributeGroup {
pub fn new(
payload_list_confidential: Vec<String>,
audit_code_list_confidential: Vec<String>,
) -> Self {
DepositRoleConfidentialAttributeGroup {
payload_list_confidential,
audit_code_list_confidential,
}
}
pub fn enc_group(&self) -> Vec<PcdItemEncAttributeRoleConfidential> {
let mut enc_attribute_list: Vec<PcdItemEncAttributeRoleConfidential> = 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<String>,
pub audit_code_private: String,
}
impl DepositPrivateAttributeGroup {
pub fn new(payload_list_private: Vec<String>, audit_code_private: String) -> Self {
DepositPrivateAttributeGroup {
payload_list_private,
audit_code_private,
}
}
pub fn enc_group(&self, Member_enc_key: KeyEncryption) -> Vec<PcdItemEncAttributePrivate> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePrivate> = 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
}
}

View File

@ -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),
}

View File

@ -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<String>,
pub data_size_max: i64,
pub Payments_method_list_public: Vec<String>,
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<String>,
data_size_max: i64,
Payments_method_list_public: Vec<String>,
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<PcdItemEncAttributePublic> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePublic> = 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<String>,
pub id_shard_info: String,
}
impl MemberRoleConfidentialAttributeGroup {
pub fn new(Payments_method_list_confidential: Vec<String>, id_shard_info: String) -> Self {
MemberRoleConfidentialAttributeGroup {
Payments_method_list_confidential,
id_shard_info,
}
}
pub fn enc_group(&self) -> Vec<PcdItemEncAttributeRoleConfidential> {
let mut enc_attribute_list: Vec<PcdItemEncAttributeRoleConfidential> = 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<String>,
pub pcd_list: Vec<String>, // Assuming this is a list of strings
pub prd_list_list: Vec<String>,
pub prd_update_list: Vec<String>,
pub prd_response_list: Vec<String>,
pub prd_message_list: Vec<String>,
pub prd_confirm_list: Vec<String>,
pub prd_key_backup_list: Vec<String>,
pub prd_key_hello_list: Vec<String>,
pub tx_sp_list: Vec<String>,
}
impl MemberPrivateAttributeGroup {
pub fn new(
Payments_method_list_private: Vec<String>,
pcd_list: Vec<String>,
prd_list_list: Vec<String>,
prd_update_list: Vec<String>,
prd_response_list: Vec<String>,
prd_message_list: Vec<String>,
prd_confirm_list: Vec<String>,
prd_key_backup_list: Vec<String>,
prd_key_hello_list: Vec<String>,
tx_sp_list: Vec<String>,
) -> 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<PcdItemEncAttributePrivate> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePrivate> = 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
}
}

View File

@ -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<String>,
pub goal_list: Vec<String>,
pub provider_type: String,
pub commit_pcd_hash_list: Vec<String>,
pub order_pcd_hash_list: Vec<String>,
pub invoice_pcd_hash_list: Vec<String>,
pub pay_pcd_hash_list: Vec<String>,
pub ref_item_hash_list: Vec<String>,
pub ref_pcd_hash_list: Vec<String>,
pub payload_list_public: Vec<String>,
pub audit_code_list_public: Vec<String>,
}
impl PaymentsPublicAttributeGroup {
pub fn new(
for_sp_address_list: Vec<String>,
goal_list: Vec<String>,
provider_type: String,
commit_pcd_hash_list: Vec<String>,
order_pcd_hash_list: Vec<String>,
invoice_pcd_hash_list: Vec<String>,
pay_pcd_hash_list: Vec<String>,
ref_item_hash_list: Vec<String>,
ref_pcd_hash_list: Vec<String>,
payload_list_public: Vec<String>,
audit_code_list_public: Vec<String>,
) -> 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<PcdItemEncAttributePublic> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePublic> = 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<String>,
pub audit_code_list_confidential: Vec<String>,
}
impl PaymentsRoleConfidentialAttributeGroup {
pub fn new(
payload_list_confidential: Vec<String>,
audit_code_list_confidential: Vec<String>,
) -> 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<PcdItemEncAttributeRoleConfidential> {
let mut enc_attribute_list: Vec<PcdItemEncAttributeRoleConfidential> = 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<String>,
pub audit_code_private: String,
}
impl PaymentsPrivateAttributeGroup {
pub fn new(payload_list_private: Vec<String>, 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<PcdItemEncAttributePrivate> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePrivate> = 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
}
}

View File

@ -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<String>,
pub daily_sp_tx_mine_list: Vec<String>,
pub daily_sp_tx_mine_reward_list: Vec<String>,
}
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<String>,
daily_sp_tx_mine_list: Vec<String>,
daily_sp_tx_mine_reward_list: Vec<String>,
) -> 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<PcdItemEncAttributePublic> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePublic> = 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<PcdItemEncAttributePrivate> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePrivate> = 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<String>,
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<String>,
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
}
}

View File

@ -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<PcdItemEncAttributePublic> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePublic> = 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
}

View File

@ -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<u8, U32>,
}
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<Vec<u8>, 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<Vec<u8>, 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<String, String> {
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<String, String> {
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<Self, String> {
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<String>,
pub key: Option<String>,
pub algorithm: Option<String>,
}
impl KeyEncryption {
pub fn new(
attribute_name: Option<String>,
key: Option<String>,
algorithm: Option<String>,
) -> Self {
KeyEncryption {
attribute_name,
key,
algorithm,
}
}
pub fn key_new_random(&mut self) -> CoreResult<String, String> {
let new_key = Aes256GcmIv96Bit::new().export_key();
self.key = Some(new_key.clone());
Ok(new_key)
}
pub fn encode(&self, data: String) -> CoreResult<String, String> {
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<String, String> {
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>) -> String {
self.enc(Value::Array(list.into_iter().map(Value::String).collect()))
}
pub fn enc_vec_key_encryption(&self, list: Vec<KeyEncryption>) -> String {
// Utilisez `serde_json::to_value` pour convertir chaque `KeyEncryption` en `Value`
let json_list: Vec<Value> = 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<u32>) -> String {
let number_list: Vec<Value> = 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<i64>) -> String {
let number_list: Vec<Value> = 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<bool>) -> 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)
}
}

View File

@ -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<u64>,
pub nonce: Option<u64>,
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<Peer>,
pub shared_process_list: Vec<Process>,
pub faucet_sp_address: String,
pub pow: Pow, // Assuming Pow is a predefined struct
}
impl `Envelope` {
pub fn new(
shared_peer_list: Vec<Peer>,
shared_process_list: Vec<Process>,
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
}
}

View File

@ -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<Peer>,
`Envelope` _shared_process_list: Vec<Process>,
`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);
}
}

View File

@ -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
}
}

View File

@ -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<String>,
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<String>,
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<String>,
pub zone_list: Vec<String>,
pub label_list: Vec<String>,
pub ref_list: Vec<String>,
pub data_list: Vec<String>,
pub amount: Amount,
pub number: Number,
pub render_template_list: Vec<String>,
pub legal_text_list: Vec<String>,
pub key_list: Vec<KeyEncryption>,
}
impl MetaData {
pub fn new(
tag_list: Vec<String>,
zone_list: Vec<String>,
label_list: Vec<String>,
ref_list: Vec<String>,
data_list: Vec<String>,
amount: Amount,
number: Number,
render_template_list: Vec<String>,
legal_text_list: Vec<String>,
key_list: Vec<KeyEncryption>,
) -> 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.
}

View File

@ -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<PcdItemEncAttributePublic> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePublic> = 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;
}
}

View File

@ -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<PcdItemEncAttributePrivate> {
let mut enc_attribute_list: Vec<PcdItemEncAttributePrivate> = 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;
}
}

View File

@ -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<PcdItemEncAttributeRoleConfidential> {
let mut enc_attribute_list: Vec<PcdItemEncAttributeRoleConfidential> = 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
}

View File

@ -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;

View File

@ -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);
}
}

View File

@ -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 {}

View File

@ -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<PcdItemEncAttributePublic>,
pub pcd_item_enc_attribute_role_confidential_list: Vec<PcdItemEncAttributeRoleConfidential>,
pub pcd_item_enc_attribute_private_list: Vec<PcdItemEncAttributePrivate>,
}
impl PcdItemEnc {
pub fn new(
version: i64,
item_type: String,
name: String,
pagination_number_per_pcd: u32,
pcd_item_enc_attribute_public_list: Vec<PcdItemEncAttributePublic>,
pcd_item_enc_attribute_role_confidential_list: Vec<PcdItemEncAttributeRoleConfidential>,
pcd_item_enc_attribute_private_list: Vec<PcdItemEncAttributePrivate>,
) -> 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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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();
}
}

View File

@ -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<Vec<PcdItemEncAttributePublic>>,
pub pcd_item_enc_attribute_role_confidential_list:
Option<Vec<PcdItemEncAttributeRoleConfidential>>,
pub pcd_item_enc_attribute_private_list: Option<Vec<PcdItemEncAttributePrivate>>,
}
impl PcdItemGenericEnc {
pub fn new(
item_enc: PcdItemEnc,
pcd_item_enc_attribute_public_list: Option<Vec<PcdItemEncAttributePublic>>,
pcd_item_enc_attribute_role_confidential_list: Option<
Vec<PcdItemEncAttributeRoleConfidential>,
>,
pcd_item_enc_attribute_private_list: Option<Vec<PcdItemEncAttributePrivate>>,
) -> 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
}

View File

@ -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<String>,
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<String>,
pub item_reference_hash: Option<String>,
}
impl Request {
pub fn new(
item_name: Option<String>,
request_type: String,
version: i64,
process_hash: String,
pcd_reference_hash: Option<String>,
item_reference_hash: Option<String>,
) -> 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()),
)
}
}

View File

@ -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<PcdItemGenericEnc>,
pub pagination: Pagination, // Assuming Pagination is a predefined struct
}
impl Pcd {
pub const TYPE: &'static str = "pcd";
pub fn new(
request_item_name: Option<String>,
request_version: i64,
request_process_hash: String,
request_pcd_reference_hash: Option<String>,
request_item_reference_hash: Option<String>,
item_list: Vec<ItemEnum>,
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<PcdItemGenericEnc> = 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<Peer>,
`Envelope` _shared_process_list: Vec<Process>,
`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,
)
}
}

View File

@ -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<String>,
pub `Envelope` _confidential: Option<String>,
pub `Envelope` _private: Option<String>,
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<String>,
request_type: String,
request_version: i64,
request_process_hash: String,
request_pcd_reference_hash: Option<String>,
request_item_reference_hash: Option<String>,
pcd_keys_role_confidential_list_confidential: String,
`Envelope` _public: Option<String>,
`Envelope` _confidential: Option<String>,
`Envelope` _private: Option<String>,
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,
)
}
}

View File

@ -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<String>,
request_version: i64,
request_process_hash: String,
request_pcd_reference_hash: Option<String>,
request_item_reference_hash: Option<String>,
pcd_keys_role_confidential_list_confidential: String,
`Envelope` _public: Option<String>,
`Envelope` _confidential: Option<String>,
`Envelope` _private: Option<String>,
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<Peer>,
`Envelope` _shared_process_list: Vec<Process>,
`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
);
}
}

View File

@ -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<String>,
request_version: i64,
request_process_hash: String,
request_pcd_reference_hash: Option<String>,
request_item_reference_hash: Option<String>,
pcd_keys_role_confidential_list_confidential: String,
`Envelope` _public: Option<String>,
`Envelope` _confidential: Option<String>,
`Envelope` _private: Option<String>,
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<Peer>,
`Envelope` _shared_process_list: Vec<Process>,
`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
)
}
}

View File

@ -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<String>,
request_version: i64,
request_process_hash: String,
request_pcd_reference_hash: Option<String>,
request_item_reference_hash: Option<String>,
pcd_keys_role_confidential_list_confidential: String,
`Envelope` _public: Option<String>,
`Envelope` _confidential: Option<String>,
`Envelope` _private: Option<String>,
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<Peer>,
`Envelope` _shared_process_list: Vec<Process>,
`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
)
}
}

View File

@ -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<String>,
request_version: i64,
request_process_hash: String,
request_pcd_reference_hash: Option<String>,
request_item_reference_hash: Option<String>,
pcd_keys_role_confidential_list_confidential: String,
`Envelope` _public: Option<String>,
`Envelope` _confidential: Option<String>,
`Envelope` _private: Option<String>,
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<Peer>,
`Envelope` _shared_process_list: Vec<Process>,
`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)
}
}

View File

@ -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<String>,
request_version: i64,
request_process_hash: String,
request_pcd_reference_hash: Option<String>,
request_item_reference_hash: Option<String>,
pcd_keys_role_confidential_list_confidential: String,
`Envelope` _public: Option<String>,
`Envelope` _confidential: Option<String>,
`Envelope` _private: Option<String>,
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<Peer>,
`Envelope` _shared_process_list: Vec<Process>,
`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)
}
}

View File

@ -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<String>,
pub Payments_method_confidential: Option<String>,
pub deposit_method_confidential: Option<String>,
pub commit_method_confidential: Option<String>,
pub certif_key_confidential: Option<String>,
pub shared_secret_key: Option<KeyEncryption>,
}
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<String>,
request_version: i64,
request_process_hash: String,
request_pcd_reference_hash: Option<String>,
request_item_reference_hash: Option<String>,
pcd_keys_role_confidential_list: Vec<PcdItemEncAttributeRoleConfidentialExportKey>,
`Envelope` _public_string: Option<String>,
`Envelope` _confidential_string: Option<String>,
`Envelope` _private_string: Option<String>,
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<String>,
Payments_method: Option<PaymentsMethod>,
deposit_method: Option<DepositMethod>,
commit_method: Option<commitMethod>,
certif_key: Option<String>,
) -> 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<Peer>,
`Envelope` _shared_process_list: Vec<Process>,
`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()
)
}
}

View File

@ -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<String>,
pub cap_pcd_hash_list: Vec<String>,
pub deposit_pcd_hash_list: Vec<String>,
pub commit_pcd_hash_list: Vec<String>,
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<String>,
request_version: i64,
request_process_hash: String,
request_pcd_reference_hash: Option<String>,
request_item_reference_hash: Option<String>,
pcd_keys_role_confidential_list_confidential: String,
`Envelope` _public: Option<String>,
`Envelope` _confidential: Option<String>,
`Envelope` _private: Option<String>,
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<String>,
cap_pcd_hash_list: Vec<String>,
deposit_pcd_hash_list: Vec<String>,
commit_pcd_hash_list: Vec<String>,
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<Peer>,
`Envelope` _shared_process_list: Vec<Process>,
`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,
)
}
}

View File

@ -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<String>,
pub to_role_list: Vec<String>,
pub from_prd_address_list: Vec<String>,
pub to_prd_address_list: Vec<String>,
pub method: String,
}
impl TransactionModeDistribution {
pub fn new(
from_prd_update_from: String,
from_role_list: Vec<String>,
to_role_list: Vec<String>,
from_prd_address_list: Vec<String>,
to_prd_address_list: Vec<String>,
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<ConditionPrdAddressSet>, // Assuming ConditionPrdAddressSet is a predefined struct
pub condition_publish: ConditionPublish, // Assuming ConditionPublish is a predefined struct
pub condition_cap_list: Vec<ConditionCap>, // Assuming ConditionCap is a predefined struct
pub condition_Payments_list: Vec<ConditionPayments>, // Assuming ConditionPayments is a predefined struct
pub condition_commit_list: Vec<Conditioncommit>, // Assuming Conditioncommit is a predefined struct
pub condition_attribute_encryption_list: Vec<String>,
pub condition_orchestration: ConditionOrchestration, // Assuming ConditionOrchestration is a predefined struct
pub role_succession: Option<String>,
pub role_resolve: Option<String>,
pub role_renew: Option<String>,
}
impl Role {
pub fn new(
item: Item,
required_2fa: bool,
validation_timeout: u64,
condition_prd_address_set_list: Vec<ConditionPrdAddressSet>,
condition_publish: ConditionPublish,
condition_cap_list: Vec<ConditionCap>,
condition_Payments_list: Vec<ConditionPayments>,
condition_commit_list: Vec<Conditioncommit>,
condition_attribute_encryption_list: Vec<String>,
condition_orchestration: ConditionOrchestration,
role_succession: Option<String>,
role_resolve: Option<String>,
role_renew: Option<String>,
) -> 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
}

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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<RoleArtefact>,
}
impl RolesGroup {
pub fn new(
role_peer: RolePeer,
role_Member: RoleMember,
role_process: RoleProcess,
role_artefact_list: Vec<RoleArtefact>,
) -> Self {
RolesGroup {
role_peer,
role_Member,
role_process,
role_artefact_list,
}
}
pub fn filter_keys(
condition_attribute_encryption: &Vec<String>,
pcd_keys_role_confidential_list: &mut Vec<PcdItemEncAttributeRoleConfidentialExportKey>,
) {
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<String>,
request_version: i64,
request_process_hash: String,
request_pcd_reference_hash: Option<String>,
request_item_reference_hash: Option<String>,
pcd_keys_role_confidential_list: Vec<PcdItemEncAttributeRoleConfidentialExportKey>,
`Envelope` _public_string: Option<String>,
`Envelope` _confidential_string: Option<String>,
`Envelope` _private_string: Option<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<String>,
Payments_method: Option<PaymentsMethod>,
deposit_method: Option<DepositMethod>,
commit_method: Option<commitMethod>,
certif_key: Option<String>,
) -> Vec<PrdResponse> {
let mut request_prd_response_list: Vec<PrdResponse> = 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`
}
}
}

View File

@ -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
}
}

View File

@ -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<String>,
}
impl Process {
pub fn new(
hash: String,
key: KeyEncryption,
role_process_sp_address_list: Vec<String>,
) -> 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
);
}
}

216
src/network.rs Normal file
View File

@ -0,0 +1,216 @@
use anyhow::Result;
use rand::{thread_rng, RngCore};
use serde::{Deserialize, Serialize};
use sp_client::bitcoin::hex::DisplayHex;
use sp_client::bitcoin::OutPoint;
use tsify::Tsify;
use crate::error::AnkError;
use crate::pcd::{Pcd, PcdCommitments, Roles};
use crate::serialization::{OutPointMemberMap, OutPointProcessMap};
use crate::signature::Proof;
#[derive(Debug, Serialize, Deserialize, Tsify)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub enum AnkFlag {
NewTx,
Faucet,
Cipher,
Commit,
Handshake,
Sync,
Unknown,
}
impl From<&str> for AnkFlag {
fn from(value: &str) -> Self {
match value {
"NewTx" => Self::NewTx,
"Faucet" => Self::Faucet,
"Cipher" => Self::Cipher,
"Commit" => Self::Commit,
"Handshake" => Self::Handshake,
"Sync" => Self::Sync,
_ => Self::Unknown,
}
}
}
impl From<String> 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::Cipher,
3 => Self::Commit,
4 => Self::Handshake,
5 => Self::Sync,
_ => Self::Unknown,
}
}
pub fn as_str(&self) -> &str {
match self {
Self::NewTx => "NewTx",
Self::Faucet => "Faucet",
Self::Cipher => "Cipher",
Self::Commit => "Commit",
Self::Handshake => "Handshake",
Self::Sync => "Sync",
Self::Unknown => "Unknown",
}
}
}
/// Message sent to the server to commit some state in a transaction
/// Client must first send a commit message with empty validation_tokens
/// Relay will ignore a commit message for an update he's not aware of that also bears validation_tokens
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Tsify)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub struct CommitMessage {
pub process_id: OutPoint,
pub pcd_commitment: PcdCommitments, // map of field <=> hash of the clear value
pub roles: Roles,
pub public_data: Pcd,
pub validation_tokens: Vec<Proof>,
pub error: Option<AnkError>,
}
impl CommitMessage {
/// Create a new commitment message for a creation/update transaction
pub fn new(
process_id: OutPoint,
pcd_commitment: PcdCommitments,
roles: Roles,
public_data: Pcd,
validation_tokens: Vec<Proof>,
) -> Self {
Self {
process_id,
pcd_commitment,
roles,
public_data,
validation_tokens,
error: None,
}
}
/// Add validation tokens for a pending commitment
pub fn add_validation_tokens(&mut self, validation_tokens: Vec<Proof>) {
self.validation_tokens.extend_from_slice(&validation_tokens);
self.validation_tokens.sort_unstable();
self.validation_tokens.dedup();
}
/// Remove all validation tokens
/// This should rarely be useful, and we'd rather let caller copy all he needs, sorts on its own
/// and clear here
pub fn clear_validation_tokens(&mut self) {
self.validation_tokens = vec![];
}
}
#[derive(Debug, Serialize, Deserialize, Tsify)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub struct FaucetMessage {
pub sp_address: String,
pub commitment: String,
pub error: Option<AnkError>,
}
impl FaucetMessage {
pub fn new(sp_address: String) -> Self {
let mut buf = [0u8; 32];
thread_rng().fill_bytes(&mut buf);
Self {
sp_address,
commitment: buf.to_lower_hex_string(),
error: None,
}
}
pub fn to_string(&self) -> String {
serde_json::to_string(self).unwrap()
}
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Tsify)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub struct NewTxMessage {
pub transaction: String,
pub tweak_data: Option<String>,
pub error: Option<AnkError>,
}
impl NewTxMessage {
pub fn new(transaction: String, tweak_data: Option<String>) -> Self {
Self {
transaction,
tweak_data,
error: None,
}
}
pub fn to_string(&self) -> String {
serde_json::to_string(self).unwrap()
}
}
#[derive(Debug, Serialize, Deserialize, Tsify)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub struct HandshakeMessage {
pub sp_address: String,
pub peers_list: OutPointMemberMap,
pub processes_list: OutPointProcessMap,
pub chain_tip: u32,
}
impl HandshakeMessage {
pub fn new(
sp_address: String,
peers_list: OutPointMemberMap,
processes_list: OutPointProcessMap,
chain_tip: u32,
) -> Self {
Self {
sp_address,
peers_list,
processes_list,
chain_tip,
}
}
pub fn to_string(&self) -> String {
serde_json::to_string(self).unwrap()
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Envelope {
pub flag: AnkFlag,
pub content: String,
}
impl Envelope {
pub fn new(flag: AnkFlag, raw: &str) -> Self {
Self {
flag,
content: raw.into(),
}
}
pub fn from_string(json: &str) -> Result<Self> {
let res: Self = serde_json::from_str(json)?;
Ok(res)
}
pub fn to_string(&self) -> String {
serde_json::to_string(self).unwrap()
}
}

1294
src/pcd.rs Normal file

File diff suppressed because it is too large Load Diff

236
src/prd.rs Normal file
View File

@ -0,0 +1,236 @@
use std::collections::{BTreeMap, HashSet};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use sp_client::bitcoin::hashes::{sha256t_hash_newtype, Hash, HashEngine};
use sp_client::bitcoin::secp256k1::{PublicKey, SecretKey};
use sp_client::bitcoin::OutPoint;
use sp_client::silentpayments::SilentPaymentAddress;
use sp_client::SpClient;
use tsify::Tsify;
use crate::pcd::{Pcd, PcdCommitments, Roles};
use crate::serialization::OutPointMemberMap;
use crate::signature::{AnkHash, AnkMessageHash, Proof};
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, Tsify)]
#[tsify(into_wasm_abi, from_wasm_abi)]
#[allow(non_camel_case_types)]
pub enum PrdType {
#[default]
None,
Connect,
Message,
Update, // Update an existing process
List, // request a list of items
Response, // Validate (or disagree) with a prd update
Confirm, // Confirm we received an update
TxProposal, // Send a psbt asking for recipient signature
Request, // asks for the prd update for some state,
}
sha256t_hash_newtype! {
pub struct AnkPrdTag = hash_str("4nk/Prd");
#[hash_newtype(forward)]
pub struct AnkPrdHash(_);
}
impl AnkPrdHash {
pub fn from_value(value: &Value) -> Self {
let mut eng = AnkPrdHash::engine();
eng.input(value.to_string().as_bytes());
AnkPrdHash::from_engine(eng)
}
pub fn from_map(map: &Map<String, Value>) -> Self {
let value = Value::Object(map.clone());
let mut eng = AnkPrdHash::engine();
eng.input(value.to_string().as_bytes());
AnkPrdHash::from_engine(eng)
}
}
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, Tsify)]
#[tsify(into_wasm_abi, from_wasm_abi)]
#[allow(non_camel_case_types)]
pub struct Prd {
pub prd_type: PrdType,
pub process_id: OutPoint,
pub sender: Option<OutPoint>,
pub keys: BTreeMap<String, [u8; 32]>, // key is a key in pcd, value is the key to decrypt it
pub pcd_commitments: PcdCommitments,
pub validation_tokens: Vec<Proof>,
pub roles: Roles,
pub public_data: Pcd,
pub payload: String, // Additional information depending on the type
pub proof: Option<Proof>, // This must be None up to the creation of the network message
}
impl Prd {
/// We answer to ack we received a transaction and got the shared_secret
/// If validation_tokens is empty we put the proof into it and return it
/// If validation_tokens contains a valid proof signed by ourselves of empty prd,
/// we confirm the secret if necessary and don't return anything
pub fn new_connect(
sender: Option<OutPoint>,
secret_hash: AnkMessageHash,
previous_proof: Option<Proof>,
) -> Self {
let validation_tokens = if let Some(proof) = previous_proof {
vec![proof]
} else {
vec![]
};
Self {
prd_type: PrdType::Connect,
process_id: OutPoint::null(),
pcd_commitments: PcdCommitments::new_empty(),
sender,
validation_tokens,
keys: BTreeMap::new(),
payload: secret_hash.to_string(),
proof: None,
..Default::default()
}
}
pub fn new_update(
process_id: OutPoint,
sender: OutPoint,
roles: Roles,
public_data: Pcd,
keys: BTreeMap<String, [u8; 32]>,
pcd_commitments: PcdCommitments,
) -> Self {
Self {
prd_type: PrdType::Update,
process_id,
sender: Some(sender),
validation_tokens: vec![],
keys,
pcd_commitments,
payload: String::new(),
proof: None,
roles,
public_data,
}
}
pub fn new_response(
process_id: OutPoint,
sender: OutPoint,
validation_tokens: Vec<Proof>,
pcd_commitments: PcdCommitments,
) -> Self {
Self {
prd_type: PrdType::Response,
process_id,
sender: Some(sender),
validation_tokens,
pcd_commitments,
..Default::default()
}
}
pub fn new_confirm(
process_id: OutPoint,
sender: OutPoint,
pcd_commitments: PcdCommitments,
) -> Self {
Self {
prd_type: PrdType::Confirm,
process_id,
pcd_commitments,
sender: Some(sender),
..Default::default()
}
}
pub fn new_request(process_id: OutPoint, sender: OutPoint, state_ids: Vec<[u8; 32]>) -> Self {
Self {
prd_type: PrdType::Request,
process_id,
sender: Some(sender),
payload: serde_json::to_string(&state_ids).unwrap(),
..Default::default()
}
}
pub fn extract_from_message(plain: &[u8], local_address: SilentPaymentAddress, members: &OutPointMemberMap) -> Result<Self> {
let prd: Prd = serde_json::from_slice(plain)?;
// check that the proof is consistent
if let Some(proof) = prd.proof {
let proof_key = proof.get_key();
let local_spend_key = local_address.get_spend_key();
// If it's our own device key we abort
if proof_key == local_spend_key {
return Err(anyhow::Error::msg(
"Proof signed by ourselves, we are parsing our own message",
));
}
proof.verify()?;
if let Some(sender) = prd.sender {
// take the spending keys in sender
let addresses = members.0.get(&sender).ok_or(anyhow::Error::msg("Unknown sender"))?.get_addresses();
let mut spend_keys: Vec<PublicKey> = vec![];
for address in addresses {
spend_keys.push(<SilentPaymentAddress>::try_from(address)?.get_spend_key());
}
// The key in proof must be one of the sender keys
let mut known_key = false;
for key in spend_keys {
if key == proof_key {
known_key = true;
break;
}
}
if !known_key {
log::warn!("Proof signed with a key that doesn't match declared sender");
}
} else {
log::warn!("No declared sender");
}
} else {
log::warn!("No proof for prd with process_id {}", prd.process_id);
}
Ok(prd)
}
pub fn filter_keys(&mut self, to_keep: &HashSet<String>) {
let current_keys = self.keys.clone();
let filtered_keys: BTreeMap<String, [u8; 32]> = current_keys
.into_iter()
.filter(|(field, _)| to_keep.contains(field))
.collect();
self.keys = filtered_keys;
}
/// Generate the signed proof and serialize to send over the network
pub fn to_network_msg(&self, sp_wallet: &SpClient) -> Result<String> {
let spend_sk: SecretKey = sp_wallet.get_spend_key().try_into()?;
let mut to_sign = self.clone(); // we sign the whole prd, incl the keys, for each recipient
let message_hash =
AnkHash::Message(AnkMessageHash::from_message(to_sign.to_string().as_bytes()));
let proof = Proof::new(message_hash, spend_sk);
to_sign.proof = Some(proof);
Ok(to_sign.to_string())
}
pub fn to_string(&self) -> String {
serde_json::to_string(self).unwrap()
}
pub fn to_value(&self) -> Value {
serde_json::to_value(self).unwrap()
}
}

1471
src/process.rs Normal file

File diff suppressed because it is too large Load Diff

181
src/secrets.rs Normal file
View File

@ -0,0 +1,181 @@
use crate::aes_gcm::aead::{Aead, Payload};
use crate::aes_gcm::Nonce;
use crate::crypto::{Aes256Gcm, AnkSharedSecretHash, KeyInit, AAD};
use crate::sp_client::bitcoin::hashes::Hash;
use crate::sp_client::silentpayments::SilentPaymentAddress;
use anyhow::{Error, Result};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::str::FromStr;
use tsify::Tsify;
#[derive(Debug, Clone, Default, PartialEq, Tsify)]
#[tsify(into_wasm_abi)]
pub struct SecretsStore {
shared_secrets: HashMap<SilentPaymentAddress, AnkSharedSecretHash>,
unconfirmed_secrets: Vec<AnkSharedSecretHash>,
}
impl Serialize for SecretsStore {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut temp_map = HashMap::with_capacity(self.shared_secrets.len());
for (key, value) in &self.shared_secrets {
let key_str = key.to_string();
let value_str = value.to_string();
temp_map.insert(key_str, value_str);
}
let mut state = serializer.serialize_struct("SecretsStore", 2)?;
state.serialize_field("shared_secrets", &temp_map)?;
let unconfirmed_secrets_hex: Vec<String> = self
.unconfirmed_secrets
.iter()
.map(|secret| secret.to_string())
.collect();
state.serialize_field("unconfirmed_secrets", &unconfirmed_secrets_hex)?;
state.end()
}
}
impl<'de> Deserialize<'de> for SecretsStore {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Deserialize the structure as a map
#[derive(Deserialize)]
struct SecretsStoreHelper {
shared_secrets: HashMap<String, String>,
unconfirmed_secrets: Vec<String>,
}
let helper = SecretsStoreHelper::deserialize(deserializer)?;
let mut shared_secrets = HashMap::with_capacity(helper.shared_secrets.len());
for (key_str, value_str) in helper.shared_secrets {
let key = SilentPaymentAddress::try_from(key_str).map_err(serde::de::Error::custom)?; // Convert String to SilentPaymentAddress
let value =
AnkSharedSecretHash::from_str(&value_str).map_err(serde::de::Error::custom)?; // Convert hex string back to Vec<u8>
shared_secrets.insert(key, value);
}
let mut unconfirmed_secrets = Vec::with_capacity(helper.unconfirmed_secrets.len());
for secret_str in helper.unconfirmed_secrets {
let secret_bytes =
AnkSharedSecretHash::from_str(&secret_str).map_err(serde::de::Error::custom)?;
unconfirmed_secrets.push(secret_bytes);
}
Ok(SecretsStore {
shared_secrets,
unconfirmed_secrets,
})
}
}
impl SecretsStore {
pub fn new() -> Self {
Self {
shared_secrets: HashMap::new(),
unconfirmed_secrets: Vec::new(),
}
}
pub fn add_unconfirmed_secret(&mut self, new_secret: AnkSharedSecretHash) {
self.unconfirmed_secrets.push(new_secret);
}
/// Returns the previous secret for this address, if any
pub fn confirm_secret_for_address(
&mut self,
secret: AnkSharedSecretHash,
address: SilentPaymentAddress,
) -> Option<AnkSharedSecretHash> {
if let Some(pos) = self.unconfirmed_secrets.iter().position(|s| *s == secret) {
self.shared_secrets
.insert(address, self.unconfirmed_secrets.swap_remove(pos))
} else {
// We didn't know about that secret, just add it
// TODO if we already had a secret for this address we just replace it for now
self.shared_secrets.insert(address, secret)
}
}
pub fn get_secret_for_address(
&self,
address: SilentPaymentAddress,
) -> Option<&AnkSharedSecretHash> {
self.shared_secrets.get(&address)
}
pub fn get_all_confirmed_secrets(&self) -> HashMap<SilentPaymentAddress, AnkSharedSecretHash> {
self.shared_secrets.clone()
}
pub fn get_all_unconfirmed_secrets(&self) -> Vec<AnkSharedSecretHash> {
self.unconfirmed_secrets.clone()
}
pub fn remove_secret_for_address(
&mut self,
address: SilentPaymentAddress,
) -> Result<(SilentPaymentAddress, AnkSharedSecretHash)> {
if let Some(removed_secret) = self.shared_secrets.remove(&address) {
return Ok((address, removed_secret));
} else {
return Err(Error::msg("Secret doesn't exist"));
}
}
pub fn remove_unconfirmed_secret(&mut self, secret: AnkSharedSecretHash) -> Result<()> {
if let Some(i) = self.unconfirmed_secrets.iter().position(|s| *s == secret) {
self.unconfirmed_secrets.swap_remove(i);
Ok(())
} else {
Err(Error::msg("Unknown secret"))
}
}
pub fn try_decrypt(&self, cipher: &[u8]) -> Result<(AnkSharedSecretHash, Vec<u8>)> {
let nonce = Nonce::from_slice(&cipher[..12]);
for (_, secret) in self.shared_secrets.iter() {
let engine = Aes256Gcm::new(secret.as_byte_array().into());
if let Ok(plain) = engine.decrypt(
&nonce,
Payload {
msg: &cipher[12..],
aad: AAD,
},
) {
return Ok((*secret, plain));
}
}
// We try unconfirmed secrets
for secret in self.unconfirmed_secrets.iter() {
let engine = Aes256Gcm::new(secret.as_byte_array().into());
if let Ok(plain) = engine.decrypt(
&nonce,
Payload {
msg: &cipher[12..],
aad: AAD,
},
) {
return Ok((*secret, plain));
}
}
Err(Error::msg("Failed to decrypt message"))
}
}

139
src/serialization.rs Normal file
View File

@ -0,0 +1,139 @@
use crate::{pcd::Member, process::Process};
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sp_client::bitcoin::hex::{DisplayHex, FromHex};
use sp_client::bitcoin::OutPoint;
use std::collections::{BTreeMap, HashMap};
use tsify::Tsify;
#[derive(Debug, Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
pub struct OutPointMemberMap(#[serde(with = "members_map")] pub HashMap<OutPoint, Member>);
#[derive(Debug, Serialize, Deserialize, Tsify)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub struct OutPointProcessMap(#[serde(with = "outpoint_map")] pub HashMap<OutPoint, Process>);
// These helper functions convert a [u8; 32] to/from a hex string.
pub(crate) fn serialize_hex<S>(bytes: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let hex_str = bytes.to_lower_hex_string();
serializer.serialize_str(&hex_str)
}
pub(crate) fn deserialize_hex<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let bytes = Vec::from_hex(&s).map_err(D::Error::custom)?;
if bytes.len() != 32 {
return Err(D::Error::custom("Invalid length for [u8;32]"));
}
let mut arr = [0u8; 32];
arr.copy_from_slice(&bytes);
Ok(arr)
}
pub mod members_map {
use super::*;
use crate::pcd::Member;
pub fn serialize<S>(map: &HashMap<OutPoint, Member>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let map: HashMap<OutPoint, Member> = map.iter().map(|(k, v)| (*k, v.to_owned())).collect();
map.serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<OutPoint, Member>, D::Error>
where
D: Deserializer<'de>,
{
let map: HashMap<OutPoint, Member> = HashMap::deserialize(deserializer)?;
Ok(map)
}
}
pub mod outpoint_map {
use super::*;
use crate::process::Process;
pub fn serialize<S>(map: &HashMap<OutPoint, Process>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// Convert OutPoint keys to Strings
let map: HashMap<String, Process> = map
.into_iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect();
// Serialize as HashMap<String, Process>
map.serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<OutPoint, Process>, D::Error>
where
D: Deserializer<'de>,
{
// Deserialize as HashMap<String, Process>
let map: HashMap<String, Process> = HashMap::deserialize(deserializer)?;
// Convert String keys back to OutPoint
let result: Result<HashMap<OutPoint, Process>, D::Error> = map
.into_iter()
.map(|(k, v)| {
let outpoint = k.parse().map_err(serde::de::Error::custom)?;
Ok((outpoint, v))
})
.collect();
result
}
}
// Custom module for converting a BTreeMap<String, [u8;32]> using hex conversion.
pub mod hex_array_btree {
use super::*;
// Serializes a BTreeMap<String, [u8; 32]> as a BTreeMap<String, String>
// where the value is a hex-encoded string.
pub fn serialize<S>(map: &BTreeMap<String, [u8; 32]>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// Convert each [u8; 32] to a hex string.
let hex_map: BTreeMap<String, String> = map
.iter()
.map(|(k, v)| (k.clone(), v.to_lower_hex_string()))
.collect();
hex_map.serialize(serializer)
}
// Deserializes a BTreeMap<String, [u8; 32]> from a BTreeMap<String, String>
// where the value is expected to be a hex-encoded string.
pub fn deserialize<'de, D>(deserializer: D) -> Result<BTreeMap<String, [u8; 32]>, D::Error>
where
D: Deserializer<'de>,
{
// Deserialize into a temporary map with hex string values.
let hex_map: BTreeMap<String, String> = BTreeMap::deserialize(deserializer)?;
let mut map = BTreeMap::new();
// Convert each hex string back into a [u8; 32].
for (key, hex_str) in hex_map {
let bytes = Vec::from_hex(&hex_str).map_err(D::Error::custom)?;
if bytes.len() != 32 {
return Err(D::Error::custom("Invalid length for [u8;32]"));
}
let mut array = [0u8; 32];
array.copy_from_slice(&bytes);
map.insert(key, array);
}
Ok(map)
}
}

119
src/signature.rs Normal file
View File

@ -0,0 +1,119 @@
use anyhow::Result;
use rand::{thread_rng, RngCore};
use serde::{Deserialize, Serialize};
use sp_client::bitcoin::hashes::{sha256t_hash_newtype, Hash, HashEngine};
use sp_client::bitcoin::key::Secp256k1;
use sp_client::bitcoin::secp256k1::schnorr::Signature;
use sp_client::bitcoin::secp256k1::{Keypair, Message, PublicKey, SecretKey};
sha256t_hash_newtype! {
pub struct AnkMessageTag = hash_str("4nk/Message");
#[hash_newtype(forward)]
pub struct AnkMessageHash(_);
pub struct AnkValidationYesTag = hash_str("4nk/yes");
#[hash_newtype(forward)]
pub struct AnkValidationYesHash(_);
pub struct AnkValidationNoTag = hash_str("4nk/no");
#[hash_newtype(forward)]
pub struct AnkValidationNoHash(_);
}
impl AnkMessageHash {
pub fn from_message(message: &[u8]) -> Self {
let mut eng = AnkMessageHash::engine();
eng.input(&message);
AnkMessageHash::from_engine(eng)
}
}
impl AnkValidationYesHash {
pub fn from_merkle_root(merkle_root: [u8; 32]) -> Self {
let mut eng = AnkValidationYesHash::engine();
eng.input(&merkle_root);
AnkValidationYesHash::from_engine(eng)
}
}
impl AnkValidationNoHash {
pub fn from_merkle_root(merkle_root: [u8; 32]) -> Self {
let mut eng = AnkValidationNoHash::engine();
eng.input(&merkle_root);
AnkValidationNoHash::from_engine(eng)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum AnkHash {
Message(AnkMessageHash),
ValidationYes(AnkValidationYesHash),
ValidationNo(AnkValidationNoHash),
}
impl AnkHash {
pub fn to_byte_array(&self) -> [u8; 32] {
match self {
AnkHash::Message(hash) => hash.to_byte_array(),
AnkHash::ValidationYes(hash) => hash.to_byte_array(),
AnkHash::ValidationNo(hash) => hash.to_byte_array(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Proof {
signature: Signature,
message: [u8; 32],
key: PublicKey,
}
impl Proof {
pub fn new(message_hash: AnkHash, signing_key: SecretKey) -> Self {
let secp = Secp256k1::signing_only();
let keypair = Keypair::from_secret_key(&secp, &signing_key);
let mut aux_rand = [0u8; 32];
thread_rng().fill_bytes(&mut aux_rand);
let sig = secp.sign_schnorr_with_aux_rand(
&Message::from_digest(message_hash.to_byte_array()),
&keypair,
&aux_rand,
);
Self {
signature: sig,
message: message_hash.to_byte_array(),
key: keypair.public_key(),
}
}
pub fn get_key(&self) -> PublicKey {
self.key
}
pub fn get_message(&self) -> [u8; 32] {
self.message
}
pub fn verify(&self) -> Result<()> {
let secp = Secp256k1::verification_only();
secp.verify_schnorr(
&self.signature,
&Message::from_digest(self.message),
&self.key.x_only_public_key().0,
)?;
Ok(())
}
pub fn to_string(&self) -> String {
serde_json::to_string(self).unwrap()
}
}

230
src/silentpayments.rs Normal file
View File

@ -0,0 +1,230 @@
use std::collections::HashMap;
use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};
use sp_client::bitcoin::absolute::Height;
use sp_client::bitcoin::hashes::Hash;
use sp_client::bitcoin::secp256k1::{PublicKey, SecretKey};
use tsify::Tsify;
use rand::{thread_rng, Rng};
use sp_client::bitcoin::{Amount, BlockHash, OutPoint, Transaction, TxOut, Txid, XOnlyPublicKey};
use sp_client::silentpayments::utils::receiving::calculate_ecdh_shared_secret;
use sp_client::{
FeeRate, OutputSpendStatus, OwnedOutput, Recipient, SilentPaymentUnsignedTransaction, SpClient,
};
#[derive(Debug, Default, Deserialize, Serialize, Clone)]
pub struct SpWallet {
sp_client: SpClient,
outputs: HashMap<OutPoint, OwnedOutput>,
birthday: u32,
last_scan: u32,
}
impl SpWallet {
pub fn new(sp_client: SpClient) -> Self {
Self {
sp_client,
..Default::default()
}
}
pub fn get_sp_client(&self) -> &SpClient {
&self.sp_client
}
pub fn get_outputs(&self) -> &HashMap<OutPoint, OwnedOutput> {
&self.outputs
}
pub fn get_mut_outputs(&mut self) -> &mut HashMap<OutPoint, OwnedOutput> {
&mut self.outputs
}
pub fn get_unspent_outputs(&self) -> HashMap<OutPoint, OwnedOutput> {
self.outputs
.iter()
.filter(|(_, output)| output.spend_status == OutputSpendStatus::Unspent)
.map(|(outpoint, output)| (*outpoint, output.clone()))
.collect()
}
pub fn get_balance(&self) -> Amount {
self.outputs
.values()
.filter(|output| output.spend_status == OutputSpendStatus::Unspent)
.fold(Amount::ZERO, |acc, x| acc + x.amount)
}
pub fn get_birthday(&self) -> u32 {
self.birthday
}
pub fn set_birthday(&mut self, birthday: u32) {
self.birthday = birthday;
}
pub fn get_last_scan(&self) -> u32 {
self.last_scan
}
pub fn set_last_scan(&mut self, last_scan: u32) {
self.last_scan = last_scan;
}
pub fn mark_output_spent(&mut self, outpoint: &OutPoint, txid: &Txid) {
if let Some(output) = self.outputs.get_mut(outpoint) {
output.spend_status = OutputSpendStatus::Spent(txid.to_byte_array());
}
}
pub fn mark_output_mined(&mut self, outpoint: &OutPoint, blk_hash: BlockHash) {
if let Some(output) = self.outputs.get_mut(outpoint) {
output.spend_status = OutputSpendStatus::Mined(blk_hash.to_byte_array());
}
}
fn check_inputs(&mut self, tx: &Transaction) {
for input in &tx.input {
if let Some(output) = self.outputs.get(&input.previous_output) {
if output.spend_status != OutputSpendStatus::Unspent {
log::debug!("Input is already spent: {:?}", input.previous_output);
continue;
} else {
self.mark_output_spent(&input.previous_output, &tx.txid());
}
}
}
}
pub fn update_with_transaction(
&mut self,
tx: &Transaction,
public_tweak: &PublicKey,
height: u32,
) -> Result<HashMap<OutPoint, OwnedOutput>> {
// Check if we have outputs that are spent by this transaction
self.check_inputs(tx);
let receiver = &self.get_sp_client().sp_receiver;
let p2tr_outs: Vec<(usize, &TxOut)> = tx
.output
.iter()
.enumerate()
.filter(|(_, o)| o.script_pubkey.is_p2tr())
.collect();
if p2tr_outs.is_empty() {
return Err(Error::msg("No taproot outputs"));
}; // That should never happen since we have a tweak_data, but anyway
// Now we can just run sp_receiver on all the p2tr outputs
let xonlykeys: Result<Vec<XOnlyPublicKey>> = p2tr_outs
.iter()
.map(|(_, o)| {
XOnlyPublicKey::from_slice(&o.script_pubkey.as_bytes()[2..]).map_err(Error::new)
})
.collect();
let tweak_data = calculate_ecdh_shared_secret(public_tweak, &self.sp_client.get_scan_key());
let ours = receiver.scan_transaction(&tweak_data, xonlykeys?)?;
let txid = tx.txid();
let height = Height::from_consensus(height)?;
let mut res = HashMap::new();
for (label, map) in ours.iter() {
res.extend(p2tr_outs.iter().filter_map(|(i, o)| {
match XOnlyPublicKey::from_slice(&o.script_pubkey.as_bytes()[2..]) {
Ok(key) => {
if let Some(scalar) = map.get(&key) {
match SecretKey::from_slice(&scalar.to_be_bytes()) {
Ok(tweak) => {
let outpoint = OutPoint {
txid,
vout: *i as u32,
};
return Some((
outpoint,
OwnedOutput {
blockheight: height,
tweak: tweak.secret_bytes(),
amount: o.value,
script: o.script_pubkey.clone(),
label: label.clone(),
spend_status: OutputSpendStatus::Unspent,
},
));
}
Err(_) => {
return None;
}
}
}
None
}
Err(_) => None,
}
}));
}
self.get_mut_outputs().extend(res.clone());
Ok(res)
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Tsify)]
#[tsify(from_wasm_abi)]
pub struct TsUnsignedTransaction(SilentPaymentUnsignedTransaction);
impl TsUnsignedTransaction {
pub fn new(unsigned_tx: SilentPaymentUnsignedTransaction) -> Self {
Self(unsigned_tx)
}
pub fn as_inner(&self) -> &SilentPaymentUnsignedTransaction {
&self.0
}
pub fn to_inner(self) -> SilentPaymentUnsignedTransaction {
self.0
}
}
pub fn create_transaction(
available_outpoints: Vec<(OutPoint, OwnedOutput)>,
sp_client: &SpClient,
mut recipients: Vec<Recipient>,
payload: Option<Vec<u8>>,
fee_rate: FeeRate,
) -> Result<SilentPaymentUnsignedTransaction> {
let mut commitment = [0u8; 32];
if let Some(ref p) = payload {
commitment.copy_from_slice(&p);
} else {
thread_rng().fill(&mut commitment);
}
recipients.push(Recipient {
address: sp_client::RecipientAddress::Data(commitment.to_vec()),
amount: Amount::ZERO,
});
let new_transaction = sp_client.create_new_transaction(
available_outpoints,
recipients,
fee_rate,
sp_client.get_network(),
)?;
let finalized_transaction = SpClient::finalize_transaction(new_transaction)?;
Ok(finalized_transaction)
}
pub fn sign_transaction(
sp_client: &SpClient,
unsigned_transaction: SilentPaymentUnsignedTransaction,
) -> Result<Transaction> {
let mut aux_rand = [0u8; 32];
thread_rng().fill(&mut aux_rand);
sp_client.sign_transaction(unsigned_transaction, &aux_rand)
}

247
src/updates.rs Normal file
View File

@ -0,0 +1,247 @@
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::mem;
use sp_client::{
bitcoin::{absolute::Height, BlockHash, OutPoint},
OwnedOutput, Updater,
};
use std::collections::{HashMap, HashSet};
#[derive(Debug, Serialize, Deserialize)]
pub struct ScanProgress {
pub start: u32,
pub current: u32,
pub end: u32,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum StateUpdate {
NoUpdate {
blkheight: Height,
},
Update {
blkheight: Height,
blkhash: BlockHash,
found_outputs: HashMap<OutPoint, OwnedOutput>,
found_inputs: HashSet<OutPoint>,
},
}
#[cfg(all(not(target_arch = "wasm32"), not(feature = "blindbit-wasm")))]
use std::sync::{mpsc::{self, Receiver, Sender}};
#[cfg(all(not(target_arch = "wasm32"), not(feature = "blindbit-wasm")))]
pub trait UpdateSink: Send + Sync {
fn send_scan_progress(&self, progress: ScanProgress) -> Result<()>;
fn send_state_update(&self, update: StateUpdate) -> Result<()>;
}
#[cfg(all(target_arch = "wasm32", feature = "blindbit-wasm"))]
pub trait UpdateSink {
fn send_scan_progress(&self, progress: ScanProgress) -> Result<()>;
fn send_state_update(&self, update: StateUpdate) -> Result<()>;
}
#[cfg(all(not(target_arch = "wasm32"), not(feature = "blindbit-wasm")))]
pub struct NativeUpdateSink {
scan_tx: Sender<ScanProgress>,
state_tx: Sender<StateUpdate>,
}
#[cfg(all(not(target_arch = "wasm32"), not(feature = "blindbit-wasm")))]
impl NativeUpdateSink {
pub fn new() -> (Self, Receiver<ScanProgress>, Receiver<StateUpdate>) {
let (scan_tx, scan_rx) = mpsc::channel();
let (state_tx, state_rx) = mpsc::channel();
(Self { scan_tx, state_tx }, scan_rx, state_rx)
}
}
#[cfg(all(not(target_arch = "wasm32"), not(feature = "blindbit-wasm")))]
impl UpdateSink for NativeUpdateSink {
fn send_scan_progress(&self, progress: ScanProgress) -> Result<()> {
self.scan_tx.send(progress)?;
Ok(())
}
fn send_state_update(&self, update: StateUpdate) -> Result<()> {
self.state_tx.send(update)?;
Ok(())
}
}
#[cfg(all(target_arch = "wasm32", feature = "blindbit-wasm"))]
use futures::channel::mpsc::{unbounded, UnboundedSender, UnboundedReceiver};
#[cfg(all(target_arch = "wasm32", feature = "blindbit-wasm"))]
pub struct WasmUpdateSink {
scan_tx: UnboundedSender<ScanProgress>,
state_tx: UnboundedSender<StateUpdate>,
}
#[cfg(all(target_arch = "wasm32", feature = "blindbit-wasm"))]
impl WasmUpdateSink {
pub fn new() -> (Rc<Self>, UnboundedReceiver<ScanProgress>, UnboundedReceiver<StateUpdate>) {
let (scan_tx, scan_rx) = unbounded();
let (state_tx, state_rx) = unbounded();
(Rc::new(Self { scan_tx, state_tx }), scan_rx, state_rx)
}
}
#[cfg(all(target_arch = "wasm32", feature = "blindbit-wasm"))]
impl UpdateSink for WasmUpdateSink {
fn send_scan_progress(&self, progress: ScanProgress) -> Result<()> {
self.scan_tx.unbounded_send(progress)
.map_err(|e| anyhow::Error::msg(format!("Failed to send scan progress: {}", e)))?;
Ok(())
}
fn send_state_update(&self, update: StateUpdate) -> Result<()> {
self.state_tx.unbounded_send(update)
.map_err(|e| anyhow::Error::msg(format!("Failed to send state update: {}", e)))?;
Ok(())
}
}
#[cfg(all(not(target_arch = "wasm32"), not(feature = "blindbit-wasm")))]
use std::sync::{Arc, RwLock};
#[cfg(all(not(target_arch = "wasm32"), not(feature = "blindbit-wasm")))]
// Global sink instance
static UPDATE_SINK: RwLock<Option<Arc<dyn UpdateSink>>> = RwLock::new(None);
#[cfg(all(target_arch = "wasm32", feature = "blindbit-wasm"))]
use std::cell::RefCell;
use std::rc::Rc;
#[cfg(all(target_arch = "wasm32", feature = "blindbit-wasm"))]
thread_local! {
static UPDATE_SINK: RefCell<Option<Rc<dyn UpdateSink>>> = RefCell::new(None);
}
#[cfg(all(not(target_arch = "wasm32"), not(feature = "blindbit-wasm")))]
pub fn init_update_sink(sink: Arc<dyn UpdateSink>) {
let mut sink_guard = UPDATE_SINK.write().unwrap();
*sink_guard = Some(sink);
}
#[cfg(all(not(target_arch = "wasm32"), not(feature = "blindbit-wasm")))]
pub fn get_update_sink() -> Option<Arc<dyn UpdateSink>> {
UPDATE_SINK.read().unwrap().clone()
}
#[cfg(all(target_arch = "wasm32", feature = "blindbit-wasm"))]
pub fn init_update_sink(sink: Rc<dyn UpdateSink>) {
UPDATE_SINK.with(|cell| {
*cell.borrow_mut() = Some(sink);
});
}
#[cfg(all(target_arch = "wasm32", feature = "blindbit-wasm"))]
pub fn get_update_sink() -> Option<Rc<dyn UpdateSink>> {
UPDATE_SINK.with(|cell| cell.borrow().clone())
}
#[derive(Debug)]
pub struct StateUpdater {
update: bool,
blkhash: Option<BlockHash>,
blkheight: Option<Height>,
found_outputs: HashMap<OutPoint, OwnedOutput>,
found_inputs: HashSet<OutPoint>,
}
impl StateUpdater {
pub fn new() -> Self {
Self {
update: false,
blkheight: None,
blkhash: None,
found_outputs: HashMap::new(),
found_inputs: HashSet::new(),
}
}
pub fn to_update(&mut self) -> Result<StateUpdate> {
let blkheight = self
.blkheight
.ok_or(anyhow::Error::msg("blkheight not filled"))?;
if self.update {
self.update = false;
let blkhash = self.blkhash.ok_or(anyhow::Error::msg("blkhash not set"))?;
self.blkheight = None;
self.blkhash = None;
// take results, and insert new empty values
let found_inputs = mem::take(&mut self.found_inputs);
let found_outputs = mem::take(&mut self.found_outputs);
Ok(StateUpdate::Update {
blkheight,
blkhash,
found_outputs,
found_inputs,
})
} else {
Ok(StateUpdate::NoUpdate { blkheight })
}
}
}
impl Updater for StateUpdater {
fn record_scan_progress(&mut self, start: Height, current: Height, end: Height) -> Result<()> {
self.blkheight = Some(current);
if let Some(sink) = get_update_sink() {
sink.send_scan_progress(ScanProgress {
start: start.to_consensus_u32(),
current: current.to_consensus_u32(),
end: end.to_consensus_u32(),
})?;
}
Ok(())
}
fn record_block_outputs(
&mut self,
height: Height,
blkhash: BlockHash,
found_outputs: HashMap<OutPoint, OwnedOutput>,
) -> Result<()> {
// may have already been written by record_block_inputs
self.update = true;
self.found_outputs = found_outputs;
self.blkhash = Some(blkhash);
self.blkheight = Some(height);
Ok(())
}
fn record_block_inputs(
&mut self,
blkheight: Height,
blkhash: BlockHash,
found_inputs: HashSet<OutPoint>,
) -> Result<()> {
self.update = true;
self.blkheight = Some(blkheight);
self.blkhash = Some(blkhash);
self.found_inputs = found_inputs;
Ok(())
}
fn save_to_persistent_storage(&mut self) -> Result<()> {
if let Some(sink) = get_update_sink() {
sink.send_state_update(self.to_update()?)?;
}
Ok(())
}
}

View File

@ -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<secp256k1::All>,
pub seckey_spend: SecretKey,
pub seckey_scan: SecretKey,
}
impl Wallet {
pub fn new() -> Wallet {
let secp: Secp256k1<secp256k1::All> = 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,
}
}
}
*/

View File

View File

@ -1 +0,0 @@
pub mod workflow_pcd_create_and_send_all;

View File

@ -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<String>,
pub role_name: String,
}
impl ProcessRoleSpAddressGroup {
pub fn new(sp_address_list: Vec<String>, 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<KeyEncryption>,
pub item_index: usize,
}
pub struct WorkflowPcdCreateAndSendAll {
pub item_name: String,
pub item_list: Vec<ItemEnum>,
pub pcd_pagination: Pagination,
pub pcd_version: i64,
pub process_hash: String,
pub pcd_reference_hash: Option<String>,
pub pcd_item_reference_hash: Option<String>,
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<Peer>,
pub `Envelope` _shared_process_list: Vec<Process>,
pub `Envelope` _faucet_sp_address: String,
pub `Envelope` _public_string: Option<String>,
pub `Envelope` _confidential_string: Option<String>,
pub `Envelope` _private_string: Option<String>,
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<String>,
pub Payments_method: Option<PaymentsMethod>,
pub deposit_method: Option<DepositMethod>,
pub commit_method: Option<commitMethod>,
pub certif_key: Option<String>,
}
impl WorkflowPcdCreateAndSendAll {
pub fn new(
item_name: String,
item_list: Vec<ItemEnum>,
pcd_pagination: Pagination,
pcd_version: i64,
process_hash: String,
pcd_reference_hash: Option<String>,
pcd_item_reference_hash: Option<String>,
Member_private_enc_key: KeyEncryption,
process_public_enc_key: KeyEncryption,
roles: RolesGroup,
pow_pathern: String,
pow_difficulty: usize,
`Envelope` _shared_peer_list: Vec<Peer>,
`Envelope` _shared_process_list: Vec<Process>,
`Envelope` _faucet_sp_address: String,
`Envelope` _public_string: Option<String>,
`Envelope` _confidential_string: Option<String>,
`Envelope` _private_string: Option<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<String>,
Payments_method: Option<PaymentsMethod>,
deposit_method: Option<DepositMethod>,
commit_method: Option<commitMethod>,
certif_key: Option<String>,
) -> 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<PcdItemEncAttributeRoleConfidentialExportKey> =
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
);
}
}