diff --git a/README.md b/README.md index 362d32d527..e4f3aeb7e4 100644 --- a/README.md +++ b/README.md @@ -194,16 +194,11 @@ See section "Release channels" for more details. ### MacOS -Pre-built libraries are not provided for MacOS. Please look [here](docs/build-guides/mac-build.md) -for details on building from source for MacOS. - - **Note:** After building `libindy`, add the path containing the library the `LD_LIBRARY_PATH` and -`DYLD_LIBRARY_PATH` environment variables. This is necessary for dynamically linking -your application with `libindy`. The dynamic linker will first check for the library in -`LD_LIBRARY_PATH` if the library in your application doesn't include directory names. -If the library in your application does include any directory name, then dynamic -linker will search for the library in `DYLD_LIBRARY_PATH` (not `LD_LIBRARY_PATH`) -so we recommend you set both variables to be safe. +Pre-built libraries are not provided for MacOS. + +Clone the repo and run `mac.build.sh` in the `libindy` folder. + +Please see [here](docs/build-guides/mac-build.md) for manual build steps. ### RHEL-based distributions (Amazon Linux 2017.03) Pre-built libraries are not provided for RHEL-based distributions. Please look [here](docs/build-guides/rhel-build.md) diff --git a/cli/src/commands/ledger.rs b/cli/src/commands/ledger.rs index 6fa8f25ed0..32da867bd6 100644 --- a/cli/src/commands/ledger.rs +++ b/cli/src/commands/ledger.rs @@ -1230,7 +1230,7 @@ pub mod auth_rule_command { .add_required_param("constraint", r#"Set of constraints required for execution of an action { constraint_id - type of a constraint. Can be either "ROLE" to specify final constraint or "AND"/"OR" to combine constraints. - role - role of a user which satisfy to constrain. + role - role associated value {TRUSTEE: 0, STEWARD: 2, TRUST_ANCHOR: 101, NETWORK_MONITOR: 201, ANY: *}. sig_count - the number of signatures required to execution action. need_to_be_owner - if user must be an owner of transaction. metadata - additional parameters of the constraint. @@ -1241,8 +1241,8 @@ pub mod auth_rule_command { auth_constraints: [, ] } "#) - .add_example(r#"ledger auth-rule txn_type=NYM action=ADD field=role new_value=101 constraint={"sig_count":1,"role":0,"constraint_id":"role","need_to_be_owner":false}"#) - .add_example(r#"ledger auth-rule txn_type=NYM action=EDIT field=role old_value=101 new_value=0 constraint={"sig_count":1,"role":0,"constraint_id":"role","need_to_be_owner":false}"#) + .add_example(r#"ledger auth-rule txn_type=NYM action=ADD field=role new_value=101 constraint="{"sig_count":1,"role":"0","constraint_id":"ROLE","need_to_be_owner":false}""#) + .add_example(r#"ledger auth-rule txn_type=NYM action=EDIT field=role old_value=101 new_value=0 constraint="{"sig_count":1,"role":"0","constraint_id":"ROLE","need_to_be_owner":false}""#) .finalize() ); diff --git a/docs/build-guides/mac-build.md b/docs/build-guides/mac-build.md index bbc1bd2849..5bad3bc0a4 100644 --- a/docs/build-guides/mac-build.md +++ b/docs/build-guides/mac-build.md @@ -1,8 +1,11 @@ -# Setup Indy SDK build environment for MacOS +# MacOS build guide + +Automated build: clone the repo and run `mac.build.sh` in the `libindy` folder. + +## Manual steps 1. Install Rust and rustup (https://www.rust-lang.org/install.html). 2. Install required native libraries and utilities (libsodium is added with URL to homebrew since version<1.0.15 is required) - ``` brew install pkg-config brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/65effd2b617bade68a8a2c5b39e1c3089cc0e945/Formula/libsodium.rb @@ -13,8 +16,6 @@ brew install zeromq brew install zmq ``` - - 3. Setup environment variables: ``` export PKG_CONFIG_ALLOW_CROSS=1 @@ -24,7 +25,10 @@ ``` 4. Setup OPENSSL_DIR variable: path to installed openssl library ``` - export OPENSSL_DIR=/usr/local/Cellar/openssl/1.0.2n # path changes with version number + for version in `ls -t /usr/local/Cellar/openssl/`; do + export OPENSSL_DIR=/usr/local/Cellar/openssl/$version + break + done ``` 5. Checkout and build the library: ``` @@ -38,13 +42,14 @@ cd ../cli cargo build ``` +7. Set your `DYLD_LIBRARY_PATH` and `LD_LIBRARY_PATH` environment variables to the path of `indy-sdk/libindy/target/debug`. You may want to put these in your `.bash_profile` to persist them. -# Note on running local nodes +## Note on running local nodes In order to run local nodes on MacOS, it may be necessary to set up port mapping between the Docker container and local host. Follow the instructions in [Indy SDK README](https://github.com/hyperledger/indy-sdk#how-to-start-local-nodes-pool-with-docker) -# IOError while running of whole set of tests on MacOS +## IOError while running of whole set of tests on MacOS There is a possible case when some tests are failed if whole set of tests is run (`cargo test`). But failed tests will be successful in case of separate runs. diff --git a/docs/getting-started/indy-walkthrough.md b/docs/getting-started/indy-walkthrough.md index 10c40df9e5..97526c75a0 100644 --- a/docs/getting-started/indy-walkthrough.md +++ b/docs/getting-started/indy-walkthrough.md @@ -21,6 +21,7 @@ - [Alice Gets a Transcript](#alice-gets-a-transcript) - [Apply for a Job](#apply-for-a-job) - [Apply for a Loan](#apply-for-a-loan) + - [Alice Quits her Job](#alice-quits-her-job) - [Explore the Code](#explore-the-code) ## What Indy and Libindy are and Why They Matter @@ -246,7 +247,7 @@ By having independent pairwise relationships, you're reducing the ability for ot #### Getting Verinym It is important to understand that earlier created **Faber** DID is not, in and of itself, the same thing as self-sovereign identity. This DID must be used only for secure interaction with the **Steward**. -After the connection is established **Faber** must create new DID record that he will use as Verinym in the Ledger. +After the connection is established **Faber** must create a new DID record that he will use as Verinym in the Ledger. 1. **Faber** creates a new DID in its wallet by calling ``did.create_and_store_my_did``. ```python @@ -415,8 +416,34 @@ The same way **Acme** creates and publishes a **Credential Definition** for the await ledger.sign_and_submit_request(acme['pool'], acme['wallet'], acme['did'], cred_def_request) ``` -At this point we have a **Credential Definition** for the **Job-Certificate** Credential Schema published by **Acme** and a - **Credential Definition** for the **Transcript** Credential Schema published by **Faber**. +**Acme** anticipates revoking **Job-Certificate* credentials. It decides to create a revocation registry. One of Hyperledger Indy's revocation registry types uses cryptographic accumulators for publishing revoked credentials. For details about the inner working of those accumulators see [here](https://github.com/fabienpe/indy-sdk/blob/master/docs/concepts/revocation/cred-revocation.md)). The use of those accumulators requires the publication of "validity tails" outside of the Ledger. For the purpose of this demo, the validity tails are written in a file using a 'blob storage'. + +```python + # Acme Agent + acme['tails_writer_config'] = json.dumps({'base_dir': "/tmp/indy_acme_tails", 'uri_pattern': ''}) + tails_writer = await blob_storage.open_writer('default', acme['tails_writer_config']) +``` +Once the validity tails are configured, **Acme** can create a new revocation registry for the given credential definition. + +```python + # Acme Agent + (acme['revoc_reg_id'], acme['revoc_reg_def'], acme['revoc_reg_entry']) = \ + await anoncreds.issuer_create_and_store_revoc_reg(acme['wallet'], acme['did'], 'CL_ACCUM', 'TAG1', + acme['job_certificate_cred_def_id'], + json.dumps({'max_cred_num': 5, + 'issuance_type': 'ISSUANCE_ON_DEMAND'}), + tails_writer) + + acme['revoc_reg_def_request'] = await ledger.build_revoc_reg_def_request(acme['did'], acme['revoc_reg_def']) + await ledger.sign_and_submit_request(acme['pool'], acme['wallet'], acme['did'], acme['revoc_reg_def_request']) + + acme['revoc_reg_entry_request'] = \ + await ledger.build_revoc_reg_entry_request(acme['did'], acme['revoc_reg_id'], 'CL_ACCUM', + acme['revoc_reg_entry']) + await ledger.sign_and_submit_request(acme['pool'], acme['wallet'], acme['did'], acme['revoc_reg_entry_request']) +``` + +At this point we have a **Credential Definition** (supporting revocation) for the **Job-Certificate** Credential Schema published by **Acme** and a **Credential Definition** for the **Transcript** Credential Schema published by **Faber**. ## Alice Gets a Transcript @@ -529,7 +556,7 @@ In this case, Acme Corp is requesting that Alice provide a **Job Application**. The Job Application requires a name, degree, status, SSN and also the satisfaction of the condition about the average mark or grades. In this case, **Job-Application** Proof Request looks like: -``` +```python # Acme Agent acme['job_application_proof_request'] = json.dumps({ 'nonce': '1432422343242122312411212', @@ -638,7 +665,7 @@ Now Alice has everything to create the Proof for **Acme Job-Application** Proof ``` When **Acme** inspects the received Proof he will see following structure: -``` +```python # Acme Agent { 'requested_proof': { @@ -711,16 +738,49 @@ Alice goes through a familiar sequence of interactions. "salary": {"raw": "2400", "encoded": "2400"}, "experience": {"raw": "10", "encoded": "10"} }) - job_certificate_cred_json, _, _ = \ - await anoncreds.issuer_create_credential(acme['wallet'], acme['job_certificate_cred_offer'],acme['job_certificate_cred_request'], - alice_job_certificate_cred_values_json, None, None) +``` + +One difference with the ussuance of the Transcript by Faber here is that a **Job-Certificate** can be revoked and the credential creation takes the ID of the revocation registry created earlier by **Acme** and a handle to the blob storage containing the validity tails: + + +```python + # Acme Agent + acme['blob_storage_reader_cfg_handle'] = await blob_storage.open_reader('default', acme['tails_writer_config']) + acme['job_certificate_cred'], acme['job_certificate_cred_rev_id'], acme['alice_cert_rev_reg_delta'] = \ + await anoncreds.issuer_create_credential(acme['wallet'], acme['job_certificate_cred_offer'], + acme['job_certificate_cred_request'], + acme['job_certificate_cred_values'], + acme['revoc_reg_id'], + acme['blob_storage_reader_cfg_handle']) +``` + +Furthermore **Acme** must publish a revocation registry entry on the Ledger so other parties can verify later the revocation state of the credential. + +```python + # Acme agent + acme['revoc_reg_entry_req'] = \ + await ledger.build_revoc_reg_entry_request(acme['did'], acme['revoc_reg_id'], 'CL_ACCUM', + acme['alice_cert_rev_reg_delta']) + await ledger.sign_and_submit_request(acme['pool'], acme['wallet'], acme['did'], acme['revoc_reg_entry_req']) +``` + +When **Alice** receives her **Job-Certificate** credential from **Acme**, she should request the revocation registry definition from the Ledger before storing the credential. + +```python + # Alice Agent + alice['acme_revoc_reg_des_req'] = \ + await ledger.build_get_revoc_reg_def_request(alice['did_for_acme'], + alice_job_certificate_cred['rev_reg_id']) + alice['acme_revoc_reg_des_resp'] = await ledger.submit_request(alice['pool'], alice['acme_revoc_reg_des_req']) + (alice['acme_revoc_reg_def_id'], alice['acme_revoc_reg_def_json']) = \ + await ledger.parse_get_revoc_reg_def_response(alice['acme_revoc_reg_des_resp']) ``` Now the **Job-Certificate** Credential has been issued and Alice now has it in her possession. Alice stores **Job-Certificate** Credential in her wallet. ```python # Alice Agent await anoncreds.prover_store_credential(alice['wallet'], None, alice['job_certificate_cred_request_metadata'], - alice['job_certificate_cred'], alice['acme_job_certificate_cred_def'], None) + alice['job_certificate_cred'], alice['acme_job_certificate_cred_def'], alice['acme_revoc_reg_def_json']) ``` She can use it when she applies for her loan, in much the same way that she used her transcript when applying for a job. @@ -755,9 +815,11 @@ Alice gets a **Loan-Application-Basic** Proof Request from Thrift Bank that look 'p_value': 1, 'restrictions': [{'cred_def_id': acme_job_certificate_cred_def_id}] } - } + }, + 'non_revoked': {'to': int(time.time())} }) ``` +The last line indicates that the *Job-Certificate* provided should not be revoked by the application time. Alice has only one credential that meets the proof requirements for this **Loan-Application-Basic** Proof Request. ```python @@ -777,39 +839,45 @@ Alice has only one credential that meets the proof requirements for this **Loan- } ``` -For the **Loan-Application-Basic** Proof Request Alice divided attributes as follows: +For the **Loan-Application-Basic** Proof Request Alice divided attributes as follows. She can get the validity time stamp for each attribute from the revocation states queried from the Ledger: ```python # Alice Agent - alice['apply_loan_requested_creds'] = json.dumps({ - 'self_attested_attributes': {}, - 'requested_attributes': { - 'attr1_referent': {'cred_id': cred_for_attr1['referent'], 'revealed': True} - }, - 'requested_predicates': { - 'predicate1_referent': {'cred_id': cred_for_predicate1['referent']}, - 'predicate2_referent': {'cred_id': cred_for_predicate2['referent']} - } - }) + revoc_states_for_loan_app = json.loads(alice['revoc_states_for_loan_app']) + timestamp_for_attr1 = await get_timestamp_for_attribute(cred_for_attr1, revoc_states_for_loan_app) + timestamp_for_predicate1 = await get_timestamp_for_attribute(cred_for_predicate1, revoc_states_for_loan_app) + timestamp_for_predicate2 = await get_timestamp_for_attribute(cred_for_predicate2, revoc_states_for_loan_app) + alice['apply_loan_requested_creds'] = json.dumps({ + 'self_attested_attributes': {}, + 'requested_attributes': { + 'attr1_referent': {'cred_id': cred_for_attr1['referent'], 'revealed': True, 'timestamp': timestamp_for_attr1} + }, + 'requested_predicates': { + 'predicate1_referent': {'cred_id': cred_for_predicate1['referent'], 'timestamp': timestamp_for_predicate1}, + 'predicate2_referent': {'cred_id': cred_for_predicate2['referent'], 'timestamp': timestamp_for_predicate2} + } + }) ``` Alice creates the Proof for the **Loan-Application-Basic** Proof Request. ```python # Alice Agent alice['apply_loan_proof'] = \ - await anoncreds.prover_create_proof(alice['wallet'], alice['apply_loan_proof_request'], alice['apply_loan_requested_creds'], - alice['master_secret_id'], alice['schemas'], alice['cred_defs'], alice['revoc_states']) + await anoncreds.prover_create_proof(alice['wallet'], alice['apply_loan_proof_request'], + alice['apply_loan_requested_creds'], alice['master_secret_id'], + alice['schemas_for_loan_app'], alice['cred_defs_for_loan_app'], + alice['revoc_states_for_loan_app']) ``` Alice sends just the **Loan-Application-Basic** proof to the bank. This allows her to minimize the PII (personally identifiable information) that she has to share when all she's trying to do right now is prove basic eligibility. When **Thrift** inspects the received Proof he will see following structure: -``` +```python # Thrift Agent { 'requested_proof': { - 'revealed_attributess': { - 'attr1_referent': {'sub_proof_index': 0, 'raw':'Permanent', 'encoded':'2143135425425143112321314321'}, + 'revealed_attrs': { + 'attr1_referent': {'sub_proof_index': 0, 'raw': 'Permanent', 'encoded':'2143135425425143112321314321'}, }, 'self_attested_attrs': {}, 'unrevealed_attrs': {}, @@ -820,10 +888,10 @@ When **Thrift** inspects the received Proof he will see following structure: }, 'proof' : [] # Validity Proof that Thrift can check 'identifiers' : [ # Identifiers of credentials were used for Proof building - 'schema_id': job_certificate_schema_id, - 'cred_def_id': acme_job_certificate_cred_def_id, - 'revoc_reg_seq_no': None, - 'timestamp': None + 'schema_id': acme['job_certificate_schema_id'], + 'cred_def_id': acme['job_certificate_cred_def_id'], + 'rev_reg_id': acme['revoc_reg_id'], + 'timestamp': 1550503925 # A integer timestamp ] } ``` @@ -831,8 +899,12 @@ When **Thrift** inspects the received Proof he will see following structure: **Thrift Bank** successfully verified the **Loan-Application-Basic** Proof from Alice. ```python # Thrift Agent - assert await anoncreds.verifier_verify_proof(thrift['apply_loan_proof_request'], thrift['alice_apply_loan_proof'], - thrift['schemas'], thrift['cred_defs'], thrift['revoc_defs'], thrift['revoc_regs']) + assert await anoncreds.verifier_verify_proof(thrift['apply_loan_proof_request'], + thrift['alice_apply_loan_proof'], + thrift['schemas_for_loan_app'], + thrift['cred_defs_for_loan_app'], + thrift['revoc_defs_for_loan_app'], + thrift['revoc_regs_for_loan_app']) ``` Thrift Bank sends the second Proof Request where Alice needs to share her personal information with the bank. @@ -909,7 +981,7 @@ Alice creates the Proof for **Loan-Application-KYC** Proof Request. ``` When **Thrift** inspects the received Proof he will see following structure: -``` +```python # Thrift Agent { 'requested_proof': { @@ -926,13 +998,13 @@ When **Thrift** inspects the received Proof he will see following structure: 'identifiers' : [ # Identifiers of credentials were used for Proof building { 'schema_id': transcript_schema_id, - 'cred_def_id': faber_transcript_cred_def_id, + 'cred_def_id': faber['transcript_cred_def_id'], 'rev_reg_id': None, 'timestamp': None }, { 'schema_key': job_certificate_schema_id, - 'cred_def_id': acme_job_certificate_cred_def_id, + 'cred_def_id': acme['job_certificate_cred_def_id'], 'rev_reg_id': None, 'timestamp': None } @@ -949,6 +1021,22 @@ When **Thrift** inspects the received Proof he will see following structure: Both of Alice's Proofs have been successfully verified and she got loan from **Thrift Bank**. +## Alice Quits her Job + +Later, **Alice** decides to quit her job so **Acme** revokes the **Job-Certificate** credential: + +```python + # Acme Agent + await anoncreds.issuer_revoke_credential(acme['wallet'], + acme['blob_storage_reader_cfg_handle'], + acme['revoc_reg_id'], + acme['job_certificate_cred_rev_id']) +``` + +**Acme** then just needs to publish the revocation on the ledger calling `ledger.build_revoc_reg_entry_request` and `ledger.sign_and_submit_request`. + +If Alice tries to apply for a loan (**Loan-Application-Basic**) again, the proof verification will then fail. + ## Explore the Code Now that you've had a chance to see how the Libindy implementation works from the outside, perhaps you'd like to see how it works underneath, from code? diff --git a/libindy/benches/wallet.rs b/libindy/benches/wallet.rs index a3355e15b0..2847e46d5d 100644 --- a/libindy/benches/wallet.rs +++ b/libindy/benches/wallet.rs @@ -236,7 +236,7 @@ mod delete { mod get_record { use super::*; - fn get_record(wallet_handle: i32, type_: &str, id: &str) { + fn get_record(wallet_handle: WalletHandle, type_: &str, id: &str) { NonSecretsUtils::get_wallet_record(wallet_handle, type_, id, "{}").unwrap(); } @@ -263,7 +263,7 @@ mod delete_record { } } - fn delete_record(wallet_handle: i32, type_: &str, id: &str) { + fn delete_record(wallet_handle: WalletHandle, type_: &str, id: &str) { NonSecretsUtils::delete_wallet_record(wallet_handle, type_, id).unwrap(); } @@ -290,7 +290,7 @@ mod add_record { } } - fn add_record(wallet_handle: i32, type_: &str, id: &str, value: &str, tags: &str) { + fn add_record(wallet_handle: WalletHandle, type_: &str, id: &str, value: &str, tags: &str) { NonSecretsUtils::add_wallet_record(wallet_handle, type_, id, value, Some(tags)).unwrap(); } @@ -315,7 +315,7 @@ mod add_record_tags { (type_, id, r#"{"tag_1": "value_1", "~tag_2": "value_2"}"#.to_string()) } - fn add_record_tags(wallet_handle: i32, type_: &str, id: &str, tags: &str) { + fn add_record_tags(wallet_handle: WalletHandle, type_: &str, id: &str, tags: &str) { NonSecretsUtils::add_wallet_record_tags(wallet_handle, type_, id, tags).unwrap(); } @@ -340,7 +340,7 @@ mod delete_record_tags { (type_, id, r#"["tag_id_1"]"#.to_string()) } - fn delete_record_tags(wallet_handle: i32, type_: &str, id: &str, tag_names: &str) { + fn delete_record_tags(wallet_handle: WalletHandle, type_: &str, id: &str, tag_names: &str) { NonSecretsUtils::delete_wallet_record_tags(wallet_handle, type_, id, tag_names).unwrap(); } @@ -360,7 +360,7 @@ mod delete_record_tags { mod search_records { use super::*; - fn open_search(wallet_handle: i32, query: &str) { + fn open_search(wallet_handle: WalletHandle, query: &str) { NonSecretsUtils::open_wallet_search(wallet_handle, TYPE_1, query, "{}").unwrap(); } @@ -469,7 +469,7 @@ fn _tags(suffix: usize) -> String { }).to_string() } -fn add_records(wallet_handle: i32) { +fn add_records(wallet_handle: WalletHandle) { for i in 0..COUNT { NonSecretsUtils::add_wallet_record(wallet_handle, &_type(i), diff --git a/libindy/mac.build.sh b/libindy/mac.build.sh new file mode 100644 index 0000000000..829fb5c23d --- /dev/null +++ b/libindy/mac.build.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +onred='\033[41m' +ongreen='\033[42m' +onyellow='\033[43m' +endcolor="\033[0m" + +# Handle errors +set -e +error_report() { + echo -e "${onred}Error: failed on line $1.$endcolor" +} +trap 'error_report $LINENO' ERR + +echo -e "${onyellow}Installing libindy...$endcolor" + +if [[ "$OSTYPE" == "darwin"* ]]; then + xcode-select --version || xcode-select --install + brew --version || yes | /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" + cmake --version || brew install cmake # brew install cmake throws error, not warning if already installed + curl https://sh.rustup.rs -sSf | sh -s -- -y + export PATH="$HOME/.cargo/bin:$PATH" # so can use cargo without relog + brew install pkg-config \ + https://raw.githubusercontent.com/Homebrew/homebrew-core/65effd2b617bade68a8a2c5b39e1c3089cc0e945/Formula/libsodium.rb \ + automake \ + autoconf \ + openssl \ + zeromq \ + zmq + export PKG_CONFIG_ALLOW_CROSS=1 + export CARGO_INCREMENTAL=1 + export RUST_LOG=indy=trace + export RUST_TEST_THREADS=1 + for version in `ls -t /usr/local/Cellar/openssl/`; do + export OPENSSL_DIR=/usr/local/Cellar/openssl/$version + break + done + cargo build + export LIBRARY_PATH=$(pwd)/target/debug + cd ../cli + cargo build + echo 'export DYLD_LIBRARY_PATH='$LIBRARY_PATH' +export LD_LIBRARY_PATH='$LIBRARY_PATH >> ~/.bash_profile + echo -e "${ongreen}Libindy installed.$endcolor" +else + echo -e "${onred}You are not running MacOS. This is a MacOS installer.$endcolor" +fi diff --git a/libindy/src/api/crypto.rs b/libindy/src/api/crypto.rs index 92cb5edabc..90e5b2e64f 100644 --- a/libindy/src/api/crypto.rs +++ b/libindy/src/api/crypto.rs @@ -706,7 +706,7 @@ pub extern fn indy_pack_message( #[no_mangle] pub extern fn indy_unpack_message( command_handle: i32, - wallet_handle: i32, + wallet_handle: WalletHandle, jwe_data: *const u8, jwe_len: u32, cb: Option< diff --git a/libindy/src/api/ledger.rs b/libindy/src/api/ledger.rs index c0d05c7db7..4465b281e4 100644 --- a/libindy/src/api/ledger.rs +++ b/libindy/src/api/ledger.rs @@ -1860,6 +1860,10 @@ pub extern fn indy_get_response_metadata(command_handle: CommandHandle, /// 'auth_constraints': [, ] /// } /// +/// Default ledger auth rules: https://github.com/hyperledger/indy-node/blob/master/docs/source/auth_rules.md +/// +/// More about AUTH_RULE request: https://github.com/hyperledger/indy-node/blob/master/docs/source/requests.md#auth_rule +/// /// cb: Callback that takes command result as parameter. /// /// #Returns diff --git a/libindy/src/api/mod.rs b/libindy/src/api/mod.rs index 241d57d897..4aa583a9c6 100644 --- a/libindy/src/api/mod.rs +++ b/libindy/src/api/mod.rs @@ -19,7 +19,13 @@ use utils::ctypes; pub type IndyHandle = i32; -pub type WalletHandle = i32; +//pub type WalletHandle = i32; +#[repr(transparent)] +#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone)] +pub struct WalletHandle(pub i32); +pub const INVALID_WALLET_HANDLE : WalletHandle = WalletHandle(0); + +pub type CallbackHandle = i32; pub type PoolHandle = i32; pub type CommandHandle = i32; pub type StorageHandle = i32; diff --git a/libindy/src/api/wallet.rs b/libindy/src/api/wallet.rs index eca31552ed..695e16bad7 100644 --- a/libindy/src/api/wallet.rs +++ b/libindy/src/api/wallet.rs @@ -1,6 +1,6 @@ extern crate libc; -use api::{ErrorCode, IndyHandle, CommandHandle, WalletHandle, SearchHandle, StorageHandle}; +use api::{ErrorCode, IndyHandle, CommandHandle, WalletHandle, SearchHandle, StorageHandle, INVALID_WALLET_HANDLE}; use commands::{Command, CommandExecutor}; use commands::wallet::WalletCommand; use domain::wallet::{Config, Credentials, ExportConfig, KeyConfig}; @@ -268,7 +268,7 @@ pub extern fn indy_open_wallet(command_handle: CommandHandle, credentials: *const c_char, cb: Option) -> ErrorCode { + wallet_handle: WalletHandle)>) -> ErrorCode { trace!("indy_open_wallet: >>> command_handle: {:?}, config: {:?}, credentials: {:?}, cb: {:?}", command_handle, config, credentials, cb); @@ -284,7 +284,7 @@ pub extern fn indy_open_wallet(command_handle: CommandHandle, config, credentials, Box::new(move |result| { - let (err, handle) = prepare_result_1!(result, 0); + let (err, handle) = prepare_result_1!(result, INVALID_WALLET_HANDLE); trace!("indy_open_wallet: cb command_handle: {:?} err: {:?}, handle: {:?}", command_handle, err, handle); cb(command_handle, err, handle) diff --git a/libindy/src/commands/anoncreds/issuer.rs b/libindy/src/commands/anoncreds/issuer.rs index f47e43efe1..c67a743fc3 100644 --- a/libindy/src/commands/anoncreds/issuer.rs +++ b/libindy/src/commands/anoncreds/issuer.rs @@ -52,6 +52,7 @@ use services::pool::PoolService; use services::wallet::{RecordOptions, WalletService}; use super::tails::{SDKTailsAccessor, store_tails_from_generator}; +use api::{WalletHandle, CallbackHandle}; pub enum IssuerCommand { CreateSchema( @@ -61,7 +62,7 @@ pub enum IssuerCommand { AttributeNames, // attribute names Box) + Send>), CreateAndStoreCredentialDefinition( - i32, // wallet handle + WalletHandle, String, // issuer did Schema, // schema String, // tag @@ -74,7 +75,7 @@ pub enum IssuerCommand { CredentialPrivateKey, CredentialKeyCorrectnessProof)>) + Send>), CreateAndStoreCredentialDefinitionContinue( - i32, // config + WalletHandle, SchemaV1, // credentials String, String, @@ -85,7 +86,7 @@ pub enum IssuerCommand { CredentialKeyCorrectnessProof)>, i32), CreateAndStoreRevocationRegistry( - i32, // wallet handle + WalletHandle, String, // issuer did Option, // type String, // tag @@ -94,11 +95,11 @@ pub enum IssuerCommand { i32, // tails writer handle Box) + Send>), CreateCredentialOffer( - i32, // wallet handle + WalletHandle, String, // credential definition id Box) + Send>), CreateCredential( - i32, // wallet handle + WalletHandle, CredentialOffer, // credential offer CredentialRequest, // credential request HashMap, // credential values @@ -106,13 +107,13 @@ pub enum IssuerCommand { Option, // blob storage reader config handle Box, Option)>) + Send>), RevokeCredential( - i32, // wallet handle + WalletHandle, i32, // blob storage reader config handle String, //revocation revoc id String, //credential revoc id Box) + Send>), /* RecoverCredential( - i32, // wallet handle + WalletHandle, i32, // blob storage reader config handle String, //revocation revoc id String, //credential revoc id @@ -234,7 +235,7 @@ impl IssuerCommandExecutor { } fn create_and_store_credential_definition(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, issuer_did: &str, schema: &SchemaV1, tag: &str, @@ -289,8 +290,8 @@ impl IssuerCommandExecutor { } fn _create_and_store_credential_definition_continue(&self, - cb_id: i32, - wallet_handle: i32, + cb_id: CallbackHandle, + wallet_handle: WalletHandle, schema: &SchemaV1, schema_id: &str, cred_def_id: &str, @@ -307,7 +308,7 @@ impl IssuerCommandExecutor { } fn _prepare_create_and_store_credential_definition(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, issuer_did: &str, schema: &SchemaV1, tag: &str, @@ -337,7 +338,7 @@ impl IssuerCommandExecutor { } fn _complete_create_and_store_credential_definition(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, schema: &SchemaV1, schema_id: &str, cred_def_id: &str, @@ -377,7 +378,7 @@ impl IssuerCommandExecutor { } fn create_and_store_revocation_registry(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, issuer_did: &str, type_: Option<&str>, tag: &str, @@ -466,7 +467,7 @@ impl IssuerCommandExecutor { } fn create_credential_offer(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, cred_def_id: &str) -> IndyResult { debug!("create_credential_offer >>> wallet_handle: {:?}, cred_def_id: {:?}", wallet_handle, cred_def_id); @@ -493,7 +494,7 @@ impl IssuerCommandExecutor { } fn new_credential(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, cred_offer: &CredentialOffer, cred_request: &CredentialRequest, cred_values: &HashMap, @@ -614,7 +615,7 @@ impl IssuerCommandExecutor { } fn revoke_credential(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, blob_storage_reader_handle: i32, rev_reg_id: &str, cred_revoc_id: &str) -> IndyResult { @@ -673,7 +674,7 @@ impl IssuerCommandExecutor { } fn _recovery_credential(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, blob_storage_reader_handle: i32, rev_reg_id: &str, cred_revoc_id: &str) -> IndyResult { @@ -749,26 +750,26 @@ impl IssuerCommandExecutor { } // TODO: DELETE IT - fn _wallet_set_schema_id(&self, wallet_handle: i32, id: &str, schema_id: &str) -> IndyResult<()> { + fn _wallet_set_schema_id(&self, wallet_handle: WalletHandle, id: &str, schema_id: &str) -> IndyResult<()> { self.wallet_service.add_record(wallet_handle, &self.wallet_service.add_prefix("SchemaId"), id, schema_id, &Tags::new()) } // TODO: DELETE IT - fn _wallet_get_schema_id(&self, wallet_handle: i32, key: &str) -> IndyResult { + fn _wallet_get_schema_id(&self, wallet_handle: WalletHandle, key: &str) -> IndyResult { let schema_id_record = self.wallet_service.get_record(wallet_handle, &self.wallet_service.add_prefix("SchemaId"), &key, &RecordOptions::id_value())?; Ok(schema_id_record.get_value() .ok_or(err_msg(IndyErrorKind::InvalidStructure, format!("SchemaId not found for id: {}", key)))?.to_string()) } - fn _wallet_get_rev_reg_def(&self, wallet_handle: i32, key: &str) -> IndyResult { + fn _wallet_get_rev_reg_def(&self, wallet_handle: WalletHandle, key: &str) -> IndyResult { self.wallet_service.get_indy_object(wallet_handle, &key, &RecordOptions::id_value()) } - fn _wallet_get_rev_reg(&self, wallet_handle: i32, key: &str) -> IndyResult { + fn _wallet_get_rev_reg(&self, wallet_handle: WalletHandle, key: &str) -> IndyResult { self.wallet_service.get_indy_object(wallet_handle, &key, &RecordOptions::id_value()) } - fn _wallet_get_rev_reg_info(&self, wallet_handle: i32, key: &str) -> IndyResult { + fn _wallet_get_rev_reg_info(&self, wallet_handle: WalletHandle, key: &str) -> IndyResult { self.wallet_service.get_indy_object(wallet_handle, &key, &RecordOptions::id_value()) } } diff --git a/libindy/src/commands/anoncreds/prover.rs b/libindy/src/commands/anoncreds/prover.rs index ab2215f84c..19e94adf55 100644 --- a/libindy/src/commands/anoncreds/prover.rs +++ b/libindy/src/commands/anoncreds/prover.rs @@ -25,21 +25,22 @@ use services::wallet::{RecordOptions, SearchOptions, WalletRecord, WalletSearch, use utils::sequence; use super::tails::SDKTailsAccessor; +use api::WalletHandle; pub enum ProverCommand { CreateMasterSecret( - i32, // wallet handle + WalletHandle, Option, // master secret id Box) + Send>), CreateCredentialRequest( - i32, // wallet handle + WalletHandle, String, // prover did CredentialOffer, // credential offer CredentialDefinition, // credential def String, // master secret name Box) + Send>), StoreCredential( - i32, // wallet handle + WalletHandle, Option, // credential id CredentialRequestMetadata, // credential request metadata Credential, // credentials @@ -47,15 +48,15 @@ pub enum ProverCommand { Option, // revocation registry definition Box) + Send>), GetCredentials( - i32, // wallet handle + WalletHandle, Option, // filter json Box) + Send>), GetCredential( - i32, // wallet handle + WalletHandle, String, // credential id Box) + Send>), SearchCredentials( - i32, // wallet handle + WalletHandle, Option, // query json Box) + Send>), FetchCredentials( @@ -66,11 +67,11 @@ pub enum ProverCommand { i32, // search handle Box) + Send>), GetCredentialsForProofReq( - i32, // wallet handle + WalletHandle, ProofRequest, // proof request Box) + Send>), SearchCredentialsForProofReq( - i32, // wallet handle + WalletHandle, ProofRequest, // proof request Option, // extra query Box) + Send>), @@ -83,7 +84,7 @@ pub enum ProverCommand { i32, // search handle Box) + Send>), CreateProof( - i32, // wallet handle + WalletHandle, ProofRequest, // proof request RequestedCredentials, // requested credentials String, // master secret name @@ -225,7 +226,7 @@ impl ProverCommandExecutor { } fn create_master_secret(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, master_secret_id: Option<&str>) -> IndyResult { debug!("create_master_secret >>> wallet_handle: {:?}, master_secret_id: {:?}", wallet_handle, master_secret_id); @@ -249,7 +250,7 @@ impl ProverCommandExecutor { } fn create_credential_request(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, prover_did: &str, cred_offer: &CredentialOffer, cred_def: &CredentialDefinitionV1, @@ -294,7 +295,7 @@ impl ProverCommandExecutor { } fn store_credential(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, cred_id: Option<&str>, cred_req_metadata: &CredentialRequestMetadata, credential: &mut Credential, @@ -325,7 +326,7 @@ impl ProverCommandExecutor { } fn get_credentials(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, filter_json: Option<&str>) -> IndyResult { debug!("get_credentials >>> wallet_handle: {:?}, filter_json: {:?}", wallet_handle, filter_json); @@ -349,7 +350,7 @@ impl ProverCommandExecutor { } fn get_credential(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, cred_id: &str) -> IndyResult { debug!("get_credentials >>> wallet_handle: {:?}, cred_id: {:?}", wallet_handle, cred_id); @@ -366,7 +367,7 @@ impl ProverCommandExecutor { } fn search_credentials(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, query_json: Option<&str>) -> IndyResult<(i32, usize)> { debug!("search_credentials >>> wallet_handle: {:?}, query_json: {:?}", wallet_handle, query_json); @@ -429,7 +430,7 @@ impl ProverCommandExecutor { } fn get_credentials_for_proof_req(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, proof_request: &ProofRequest) -> IndyResult { debug!("get_credentials_for_proof_req >>> wallet_handle: {:?}, proof_request: {:?}", wallet_handle, proof_request); @@ -471,7 +472,7 @@ impl ProverCommandExecutor { } fn search_credentials_for_proof_req(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, proof_request: &ProofRequest, extra_query: Option<&ProofRequestExtraQuery>) -> IndyResult { debug!("search_credentials_for_proof_req >>> wallet_handle: {:?}, proof_request: {:?}, extra_query: {:?}", wallet_handle, proof_request, extra_query); @@ -550,7 +551,7 @@ impl ProverCommandExecutor { } fn create_proof(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, proof_req: &ProofRequest, requested_credentials: &RequestedCredentials, master_secret_id: &str, @@ -701,7 +702,7 @@ impl ProverCommandExecutor { } fn _query_requested_credentials(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, query_json: &str, predicate_info: Option<&PredicateInfo>, interval: &Option) -> IndyResult> { @@ -758,7 +759,7 @@ impl ProverCommandExecutor { } - fn _wallet_get_master_secret(&self, wallet_handle: i32, key: &str) -> IndyResult { + fn _wallet_get_master_secret(&self, wallet_handle: WalletHandle, key: &str) -> IndyResult { self.wallet_service.get_indy_object(wallet_handle, &key, &RecordOptions::id_value()) } } diff --git a/libindy/src/commands/crypto.rs b/libindy/src/commands/crypto.rs index 1045ef6fd6..bd9bf4c175 100644 --- a/libindy/src/commands/crypto.rs +++ b/libindy/src/commands/crypto.rs @@ -15,26 +15,27 @@ use std::str; use utils::crypto::base64; use utils::crypto::chacha20poly1305_ietf; use domain::crypto::combo_box::ComboBox; +use api::WalletHandle; pub enum CryptoCommand { CreateKey( - i32, // wallet handle + WalletHandle, KeyInfo, // key info Box) + Send>, ), SetKeyMetadata( - i32, // wallet handle + WalletHandle, String, // verkey String, // metadata Box) + Send>, ), GetKeyMetadata( - i32, // wallet handle + WalletHandle, String, // verkey Box) + Send>, ), CryptoSign( - i32, // wallet handle + WalletHandle, String, // my vk Vec, // msg Box>) + Send>, @@ -46,14 +47,14 @@ pub enum CryptoCommand { Box) + Send>, ), AuthenticatedEncrypt( - i32, // wallet handle + WalletHandle, String, // my vk String, // their vk Vec, // msg Box>) + Send>, ), AuthenticatedDecrypt( - i32, // wallet handle + WalletHandle, String, // my vk Vec, // encrypted msg Box)>) + Send>, @@ -64,7 +65,7 @@ pub enum CryptoCommand { Box>) + Send>, ), AnonymousDecrypt( - i32, // wallet handle + WalletHandle, String, // my vk Vec, // msg Box>) + Send>, @@ -73,12 +74,12 @@ pub enum CryptoCommand { Vec, // plaintext message String, // list of receiver's keys Option, // senders verkey - i32, //wallet handle + WalletHandle, Box>) + Send>, ), UnpackMessage( Vec, // JWE - i32, // wallet handle + WalletHandle, Box>) + Send>, ), } @@ -148,7 +149,7 @@ impl CryptoCommandExecutor { }; } - fn create_key(&self, wallet_handle: i32, key_info: &KeyInfo) -> IndyResult { + fn create_key(&self, wallet_handle: WalletHandle, key_info: &KeyInfo) -> IndyResult { debug!( "create_key >>> wallet_handle: {:?}, key_info: {:?}", wallet_handle, @@ -164,7 +165,7 @@ impl CryptoCommandExecutor { Ok(res) } - fn crypto_sign(&self, wallet_handle: i32, my_vk: &str, msg: &[u8]) -> IndyResult> { + fn crypto_sign(&self, wallet_handle: WalletHandle, my_vk: &str, msg: &[u8]) -> IndyResult> { trace!( "crypto_sign >>> wallet_handle: {:?}, sender_vk: {:?}, msg: {:?}", wallet_handle, my_vk, msg @@ -206,7 +207,7 @@ impl CryptoCommandExecutor { //TODO begin deprecation process this function. It will be replaced by pack fn authenticated_encrypt( &self, - wallet_handle: i32, + wallet_handle: WalletHandle, my_vk: &str, their_vk: &str, msg: &[u8], @@ -237,7 +238,7 @@ impl CryptoCommandExecutor { //TODO begin deprecation process this function. It will be replaced by unpack fn authenticated_decrypt( &self, - wallet_handle: i32, + wallet_handle: WalletHandle, my_vk: &str, msg: &[u8], ) -> IndyResult<(String, Vec)> { @@ -289,7 +290,7 @@ impl CryptoCommandExecutor { } fn anonymous_decrypt(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, my_vk: &str, encrypted_msg: &[u8]) -> IndyResult> { trace!( @@ -314,7 +315,7 @@ impl CryptoCommandExecutor { Ok(res) } - fn set_key_metadata(&self, wallet_handle: i32, verkey: &str, metadata: &str) -> IndyResult<()> { + fn set_key_metadata(&self, wallet_handle: WalletHandle, verkey: &str, metadata: &str) -> IndyResult<()> { debug!( "set_key_metadata >>> wallet_handle: {:?}, verkey: {:?}, metadata: {:?}", wallet_handle, verkey, metadata @@ -334,7 +335,7 @@ impl CryptoCommandExecutor { Ok(()) } - fn get_key_metadata(&self, wallet_handle: i32, verkey: &str) -> IndyResult { + fn get_key_metadata(&self, wallet_handle: WalletHandle, verkey: &str) -> IndyResult { debug!( "get_key_metadata >>> wallet_handle: {:?}, verkey: {:?}", wallet_handle, verkey @@ -362,7 +363,7 @@ impl CryptoCommandExecutor { message: Vec, receivers: &str, sender_vk: Option, - wallet_handle: i32, + wallet_handle: WalletHandle, ) -> IndyResult> { //parse receivers to structs @@ -427,7 +428,7 @@ impl CryptoCommandExecutor { fn _prepare_protected_authcrypt(&self, cek: &chacha20poly1305_ietf::Key, receiver_list: Vec, sender_vk: &str, - wallet_handle: i32, + wallet_handle: WalletHandle, ) -> IndyResult { let mut encrypted_recipients_struct : Vec = vec![]; @@ -502,7 +503,7 @@ impl CryptoCommandExecutor { }) } - pub fn unpack_msg(&self, jwe_json: Vec, wallet_handle: i32) -> IndyResult> { + pub fn unpack_msg(&self, jwe_json: Vec, wallet_handle: WalletHandle) -> IndyResult> { //serialize JWE to struct let jwe_struct: JWE = serde_json::from_slice(jwe_json.as_slice()).map_err(|err| { err_msg(IndyErrorKind::InvalidStructure, format!( @@ -560,7 +561,7 @@ impl CryptoCommandExecutor { }); } - fn _find_correct_recipient(&self, protected_struct: Protected, wallet_handle: i32) -> IndyResult<(Recipient, bool)>{ + fn _find_correct_recipient(&self, protected_struct: Protected, wallet_handle: WalletHandle) -> IndyResult<(Recipient, bool)>{ for recipient in protected_struct.recipients { let my_key_res = self.wallet_service.get_indy_object::( wallet_handle, @@ -576,7 +577,7 @@ impl CryptoCommandExecutor { return Err(IndyError::from(IndyErrorKind::WalletItemNotFound)); } - fn _unpack_cek_authcrypt(&self, recipient: Recipient, wallet_handle: i32) -> IndyResult<(Option, chacha20poly1305_ietf::Key)> { + fn _unpack_cek_authcrypt(&self, recipient: Recipient, wallet_handle: WalletHandle) -> IndyResult<(Option, chacha20poly1305_ietf::Key)> { let encrypted_key_vec = base64::decode_urlsafe(&recipient.encrypted_key)?; let iv = base64::decode_urlsafe(&recipient.header.iv.unwrap())?; let enc_sender_vk = base64::decode_urlsafe(&recipient.header.sender.unwrap())?; @@ -611,7 +612,7 @@ impl CryptoCommandExecutor { Ok((Some(sender_vk), cek)) } - fn _unpack_cek_anoncrypt(&self, recipient: Recipient, wallet_handle: i32) -> IndyResult<(Option, chacha20poly1305_ietf::Key)> { + fn _unpack_cek_anoncrypt(&self, recipient: Recipient, wallet_handle: WalletHandle) -> IndyResult<(Option, chacha20poly1305_ietf::Key)> { let encrypted_key_vec = base64::decode_urlsafe(&recipient.encrypted_key)?; //get my private key diff --git a/libindy/src/commands/did.rs b/libindy/src/commands/did.rs index 754cb99f7a..6a0a0a3329 100644 --- a/libindy/src/commands/did.rs +++ b/libindy/src/commands/did.rs @@ -18,58 +18,59 @@ use services::ledger::LedgerService; use services::wallet::{RecordOptions, SearchOptions, WalletService}; use utils::crypto::base58; use utils::sequence; +use api::WalletHandle; pub enum DidCommand { CreateAndStoreMyDid( - i32, // wallet handle + WalletHandle, MyDidInfo, // my did info Box) + Send>), ReplaceKeysStart( - i32, // wallet handle + WalletHandle, KeyInfo, // key info String, // did Box) + Send>), ReplaceKeysApply( - i32, // wallet handle + WalletHandle, String, // my did Box) + Send>), StoreTheirDid( - i32, // wallet handle + WalletHandle, TheirDidInfo, // their did info json Box) + Send>), GetMyDidWithMeta( - i32, // wallet handle + WalletHandle, String, // my did Box) + Send>), ListMyDidsWithMeta( - i32, // wallet handle + WalletHandle, Box) + Send>), KeyForDid( i32, // pool handle - i32, // wallet handle + WalletHandle, String, // did (my or their) Box) + Send>), KeyForLocalDid( - i32, // wallet handle + WalletHandle, String, // did (my or their) Box) + Send>), SetEndpointForDid( - i32, // wallet handle + WalletHandle, String, // did Endpoint, // endpoint address and optional verkey Box) + Send>), GetEndpointForDid( - i32, // wallet handle + WalletHandle, i32, // pool handle String, // did Box)>) + Send>), SetDidMetadata( - i32, // wallet handle + WalletHandle, String, // did String, // metadata Box) + Send>), GetDidMetadata( - i32, // wallet handle + WalletHandle, String, // did Box) + Send>), AbbreviateVerkey( @@ -78,13 +79,13 @@ pub enum DidCommand { Box) + Send>), // Internal commands GetNymAck( - i32, // wallet_handle + WalletHandle, IndyResult, // GetNym Result i32, // deferred cmd id ), // Internal commands GetAttribAck( - i32, // wallet_handle + WalletHandle, IndyResult, // GetAttrib Result i32, // deferred cmd id ), @@ -184,7 +185,7 @@ impl DidCommandExecutor { } fn create_and_store_my_did(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, my_did_info: &MyDidInfo) -> IndyResult<(String, String)> { debug!("create_and_store_my_did >>> wallet_handle: {:?}, my_did_info_json: {:?}", wallet_handle, secret!(my_did_info)); @@ -205,7 +206,7 @@ impl DidCommandExecutor { } fn replace_keys_start(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, key_info: &KeyInfo, my_did: &str) -> IndyResult { debug!("replace_keys_start >>> wallet_handle: {:?}, key_info_json: {:?}, my_did: {:?}", wallet_handle, secret!(key_info), my_did); @@ -228,7 +229,7 @@ impl DidCommandExecutor { } fn replace_keys_apply(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, my_did: &str) -> IndyResult<()> { debug!("replace_keys_apply >>> wallet_handle: {:?}, my_did: {:?}", wallet_handle, my_did); @@ -249,7 +250,7 @@ impl DidCommandExecutor { } fn store_their_did(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, their_did_info: &TheirDidInfo) -> IndyResult<()> { debug!("store_their_did >>> wallet_handle: {:?}, their_did_info: {:?}", wallet_handle, their_did_info); @@ -262,7 +263,7 @@ impl DidCommandExecutor { Ok(()) } - fn get_my_did_with_meta(&self, wallet_handle: i32, my_did: &str) -> IndyResult { + fn get_my_did_with_meta(&self, wallet_handle: WalletHandle, my_did: &str) -> IndyResult { debug!("get_my_did_with_meta >>> wallet_handle: {:?}, my_did: {:?}", wallet_handle, my_did); self.crypto_service.validate_did(&my_did)?; @@ -286,7 +287,7 @@ impl DidCommandExecutor { Ok(res) } - fn list_my_dids_with_meta(&self, wallet_handle: i32) -> IndyResult { + fn list_my_dids_with_meta(&self, wallet_handle: WalletHandle) -> IndyResult { debug!("list_my_dids_with_meta >>> wallet_handle: {:?}", wallet_handle); let mut did_search = @@ -325,7 +326,7 @@ impl DidCommandExecutor { fn key_for_did(&self, pool_handle: i32, - wallet_handle: i32, + wallet_handle: WalletHandle, did: String, cb: Box) + Send>) { debug!("key_for_did >>> pool_handle: {:?}, wallet_handle: {:?}, did: {:?}", pool_handle, wallet_handle, did); @@ -359,7 +360,7 @@ impl DidCommandExecutor { } fn key_for_local_did(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, did: &str) -> IndyResult { info!("key_for_local_did >>> wallet_handle: {:?}, did: {:?}", wallet_handle, did); @@ -385,7 +386,7 @@ impl DidCommandExecutor { } fn set_endpoint_for_did(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, did: &str, endpoint: &Endpoint) -> IndyResult<()> { debug!("set_endpoint_for_did >>> wallet_handle: {:?}, did: {:?}, endpoint: {:?}", wallet_handle, did, endpoint); @@ -403,7 +404,7 @@ impl DidCommandExecutor { } fn get_endpoint_for_did(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, pool_handle: i32, did: String, cb: Box)>) + Send>) { @@ -429,7 +430,7 @@ impl DidCommandExecutor { } fn set_did_metadata(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, did: &str, metadata: String) -> IndyResult<()> { debug!("set_did_metadata >>> wallet_handle: {:?}, did: {:?}, metadata: {:?}", wallet_handle, did, metadata); @@ -446,7 +447,7 @@ impl DidCommandExecutor { } fn get_did_metadata(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, did: &str) -> IndyResult { debug!("get_did_metadata >>> wallet_handle: {:?}, did: {:?}", wallet_handle, did); @@ -486,14 +487,14 @@ impl DidCommandExecutor { } fn get_nym_ack(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, get_nym_reply_result: IndyResult, deferred_cmd_id: i32) { let res = self._get_nym_ack(wallet_handle, get_nym_reply_result); self._execute_deferred_command(deferred_cmd_id, res.err()); } - fn _get_nym_ack(&self, wallet_handle: i32, get_nym_reply_result: IndyResult) -> IndyResult<()> { + fn _get_nym_ack(&self, wallet_handle: WalletHandle, get_nym_reply_result: IndyResult) -> IndyResult<()> { trace!("_get_nym_ack >>> wallet_handle: {:?}, get_nym_reply_result: {:?}", wallet_handle, get_nym_reply_result); let get_nym_reply = get_nym_reply_result?; @@ -525,14 +526,14 @@ impl DidCommandExecutor { } fn get_attrib_ack(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, get_attrib_reply_result: IndyResult, deferred_cmd_id: i32) { let res = self._get_attrib_ack(wallet_handle, get_attrib_reply_result); self._execute_deferred_command(deferred_cmd_id, res.err()); } - fn _get_attrib_ack(&self, wallet_handle: i32, get_attrib_reply_result: IndyResult) -> IndyResult<()> { + fn _get_attrib_ack(&self, wallet_handle: WalletHandle, get_attrib_reply_result: IndyResult) -> IndyResult<()> { trace!("_get_attrib_ack >>> wallet_handle: {:?}, get_attrib_reply_result: {:?}", wallet_handle, get_attrib_reply_result); let get_attrib_reply = get_attrib_reply_result?; @@ -600,7 +601,7 @@ impl DidCommandExecutor { } fn _fetch_their_did_from_ledger(&self, - wallet_handle: i32, pool_handle: i32, + wallet_handle: WalletHandle, pool_handle: i32, did: &str, deferred_cmd: DidCommand) { // Defer this command until their did is fetched from ledger. let deferred_cmd_id = self._defer_command(deferred_cmd); @@ -625,7 +626,7 @@ impl DidCommandExecutor { } fn _fetch_attrib_from_ledger(&self, - wallet_handle: i32, pool_handle: i32, + wallet_handle: WalletHandle, pool_handle: i32, did: &str, deferred_cmd: DidCommand) { // Defer this command until their did is fetched from ledger. let deferred_cmd_id = self._defer_command(deferred_cmd); @@ -649,11 +650,11 @@ impl DidCommandExecutor { ))).unwrap(); } - fn _wallet_get_my_did(&self, wallet_handle: i32, my_did: &str) -> IndyResult { + fn _wallet_get_my_did(&self, wallet_handle: WalletHandle, my_did: &str) -> IndyResult { self.wallet_service.get_indy_object(wallet_handle, &my_did, &RecordOptions::id_value()) } - fn _wallet_get_their_did(&self, wallet_handle: i32, their_did: &str) -> IndyResult { + fn _wallet_get_their_did(&self, wallet_handle: WalletHandle, their_did: &str) -> IndyResult { self.wallet_service.get_indy_object(wallet_handle, &their_did, &RecordOptions::id_value()) } } diff --git a/libindy/src/commands/ledger.rs b/libindy/src/commands/ledger.rs index 9818afe5f4..c85e327d50 100644 --- a/libindy/src/commands/ledger.rs +++ b/libindy/src/commands/ledger.rs @@ -23,11 +23,12 @@ use services::pool::{ use services::wallet::{RecordOptions, WalletService}; use utils::crypto::base58; use utils::crypto::signature_serializer::serialize_signature; +use api::WalletHandle; pub enum LedgerCommand { SignAndSubmitRequest( i32, // pool handle - i32, // wallet handle + WalletHandle, String, // submitter did String, // request json Box) + Send>), @@ -46,12 +47,12 @@ pub enum LedgerCommand { Option, // timeout Box) + Send>), SignRequest( - i32, // wallet handle + WalletHandle, String, // submitter did String, // request json Box) + Send>), MultiSignRequest( - i32, // wallet handle + WalletHandle, String, // submitter did String, // request json Box) + Send>), @@ -388,7 +389,7 @@ impl LedgerCommandExecutor { fn sign_and_submit_request(&self, pool_handle: i32, - wallet_handle: i32, + wallet_handle: WalletHandle, submitter_did: &str, request_json: &str, cb: Box) + Send>) { @@ -402,7 +403,7 @@ impl LedgerCommandExecutor { } fn _sign_request(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, submitter_did: &str, request_json: &str, signature_type: SignatureType) -> IndyResult { @@ -476,7 +477,7 @@ impl LedgerCommandExecutor { } fn sign_request(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, submitter_did: &str, request_json: &str) -> IndyResult { debug!("sign_request >>> wallet_handle: {:?}, submitter_did: {:?}, request_json: {:?}", wallet_handle, submitter_did, request_json); @@ -489,7 +490,7 @@ impl LedgerCommandExecutor { } fn multi_sign_request(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, submitter_did: &str, request_json: &str) -> IndyResult { debug!("multi_sign_request >>> wallet_handle: {:?}, submitter_did: {:?}, request_json: {:?}", wallet_handle, submitter_did, request_json); diff --git a/libindy/src/commands/non_secrets.rs b/libindy/src/commands/non_secrets.rs index b0fe7d5812..86dd2f4305 100644 --- a/libindy/src/commands/non_secrets.rs +++ b/libindy/src/commands/non_secrets.rs @@ -6,49 +6,50 @@ use domain::wallet::Tags; use errors::prelude::*; use services::wallet::{RecordOptions, SearchOptions, WalletRecord, WalletSearch, WalletService}; use utils::sequence; +use api::WalletHandle; pub enum NonSecretsCommand { - AddRecord(i32, // handle + AddRecord(WalletHandle, String, // type String, // id String, // value Option, //tags Box) + Send>), - UpdateRecordValue(i32, // handle + UpdateRecordValue(WalletHandle, String, // type String, // id String, // value Box) + Send>), - UpdateRecordTags(i32, // handle + UpdateRecordTags(WalletHandle, String, // type String, // id Tags, //tags Box) + Send>), - AddRecordTags(i32, // handle + AddRecordTags(WalletHandle, String, // type String, // id Tags, //tags Box) + Send>), - DeleteRecordTags(i32, // handle + DeleteRecordTags(WalletHandle, String, // type String, // id String, //tag names json Box) + Send>), - DeleteRecord(i32, // handle + DeleteRecord(WalletHandle, String, // type String, // id Box) + Send>), - GetRecord(i32, // handle + GetRecord(WalletHandle, String, // type String, // id String, // options json Box) + Send>), - OpenSearch(i32, // handle + OpenSearch(WalletHandle, String, // type String, // query json String, // options json Box) + Send>), - FetchSearchNextRecords(i32, // wallet handle + FetchSearchNextRecords(WalletHandle, i32, // wallet search handle usize, // count Box) + Send>), @@ -115,7 +116,7 @@ impl NonSecretsCommandExecutor { } fn add_record(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, type_: &str, id: &str, value: &str, @@ -132,7 +133,7 @@ impl NonSecretsCommandExecutor { } fn update_record_value(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, type_: &str, id: &str, value: &str) -> IndyResult<()> { @@ -148,7 +149,7 @@ impl NonSecretsCommandExecutor { } fn update_record_tags(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, type_: &str, id: &str, tags: &Tags) -> IndyResult<()> { @@ -164,7 +165,7 @@ impl NonSecretsCommandExecutor { } fn add_record_tags(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, type_: &str, id: &str, tags: &Tags) -> IndyResult<()> { @@ -180,7 +181,7 @@ impl NonSecretsCommandExecutor { } fn delete_record_tags(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, type_: &str, id: &str, tag_names_json: &str) -> IndyResult<()> { @@ -199,7 +200,7 @@ impl NonSecretsCommandExecutor { } fn delete_record(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, type_: &str, id: &str) -> IndyResult<()> { trace!("delete_record >>> wallet_handle: {:?}, type_: {:?}, id: {:?}", wallet_handle, type_, id); @@ -214,7 +215,7 @@ impl NonSecretsCommandExecutor { } fn get_record(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, type_: &str, id: &str, options_json: &str) -> IndyResult { @@ -236,7 +237,7 @@ impl NonSecretsCommandExecutor { } fn open_search(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, type_: &str, query_json: &str, options_json: &str) -> IndyResult { @@ -259,7 +260,7 @@ impl NonSecretsCommandExecutor { } fn fetch_search_next_records(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, wallet_search_handle: i32, count: usize) -> IndyResult { trace!("fetch_search_next_records >>> wallet_handle: {:?}, wallet_search_handle: {:?}, count: {:?}", wallet_handle, wallet_search_handle, count); diff --git a/libindy/src/commands/pairwise.rs b/libindy/src/commands/pairwise.rs index e6d64bb5d8..7a401122a7 100644 --- a/libindy/src/commands/pairwise.rs +++ b/libindy/src/commands/pairwise.rs @@ -5,28 +5,29 @@ use services::wallet::{RecordOptions, WalletService}; use std::collections::HashMap; use std::rc::Rc; use std::str; +use api::WalletHandle; pub enum PairwiseCommand { PairwiseExists( - i32, // wallet handle + WalletHandle, String, // their_did Box) + Send>), CreatePairwise( - i32, // wallet handle + WalletHandle, String, // their_did String, // my_did Option, // metadata Box) + Send>), ListPairwise( - i32, // wallet handle + WalletHandle, Box) + Send>), GetPairwise( - i32, // wallet handle + WalletHandle, String, // their_did Box) + Send>), SetPairwiseMetadata( - i32, // wallet handle + WalletHandle, String, // their_did Option, // metadata Box) + Send>) @@ -69,7 +70,7 @@ impl PairwiseCommandExecutor { } fn pairwise_exists(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, their_did: &str) -> IndyResult { debug!("pairwise_exists >>> wallet_handle: {:?}, their_did: {:?}", wallet_handle, their_did); @@ -81,7 +82,7 @@ impl PairwiseCommandExecutor { } fn create_pairwise(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, their_did: &str, my_did: &str, metadata: Option<&str>) -> IndyResult<()> { @@ -104,7 +105,7 @@ impl PairwiseCommandExecutor { } fn list_pairwise(&self, - wallet_handle: i32) -> IndyResult { + wallet_handle: WalletHandle) -> IndyResult { debug!("list_pairwise >>> wallet_handle: {:?}", wallet_handle); let mut pairwise_search = @@ -130,7 +131,7 @@ impl PairwiseCommandExecutor { } fn get_pairwise(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, their_did: &str) -> IndyResult { debug!("get_pairwise >>> wallet_handle: {:?}, their_did: {:?}", wallet_handle, their_did); @@ -148,7 +149,7 @@ impl PairwiseCommandExecutor { fn set_pairwise_metadata(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, their_did: &str, metadata: Option<&str>) -> IndyResult<()> { debug!("set_pairwise_metadata >>> wallet_handle: {:?}, their_did: {:?}, metadata: {:?}", wallet_handle, their_did, metadata); diff --git a/libindy/src/commands/payments.rs b/libindy/src/commands/payments.rs index 18119fbc4a..feb5bab243 100644 --- a/libindy/src/commands/payments.rs +++ b/libindy/src/commands/payments.rs @@ -10,6 +10,7 @@ use errors::prelude::*; use services::crypto::CryptoService; use services::payments::{PaymentsMethodCBs, PaymentsService}; use services::wallet::{RecordOptions, WalletService}; +use api::WalletHandle; pub enum PaymentsCommand { RegisterMethod( @@ -17,19 +18,19 @@ pub enum PaymentsCommand { PaymentsMethodCBs, //method callbacks Box) + Send>), CreateAddress( - i32, //wallet_handle + WalletHandle, String, //type String, //config Box) + Send>), CreateAddressAck( i32, //handle - i32, //wallet handle + WalletHandle, IndyResult), ListAddresses( - i32, //wallet handle + WalletHandle, Box) + Send>), AddRequestFees( - i32, //wallet handle + WalletHandle, Option, //submitter did String, //req String, //inputs @@ -47,7 +48,7 @@ pub enum PaymentsCommand { i32, //handle IndyResult), BuildGetPaymentSourcesRequest( - i32, //wallet_handle + WalletHandle, Option, //submitter did String, //payment address Box) + Send>), @@ -62,7 +63,7 @@ pub enum PaymentsCommand { i32, //cmd_handle IndyResult), BuildPaymentReq( - i32, //wallet_handle + WalletHandle, Option, //submitter did String, //inputs String, //outputs @@ -79,7 +80,7 @@ pub enum PaymentsCommand { i32, IndyResult), BuildMintReq( - i32, //wallet_handle + WalletHandle, Option, //submitter did String, //outputs Option, //extra @@ -88,7 +89,7 @@ pub enum PaymentsCommand { i32, IndyResult), BuildSetTxnFeesReq( - i32, //wallet_handle + WalletHandle, Option, //submitter did String, //method String, //fees @@ -97,7 +98,7 @@ pub enum PaymentsCommand { i32, IndyResult), BuildGetTxnFeesReq( - i32, //wallet_handle + WalletHandle, Option, //submitter did String, //method Box) + Send>), @@ -112,7 +113,7 @@ pub enum PaymentsCommand { i32, IndyResult), BuildVerifyPaymentReq( - i32, //wallet_handle + WalletHandle, Option, //submitter_did String, //receipt Box) + Send>), @@ -273,7 +274,7 @@ impl PaymentsCommandExecutor { res } - fn create_address(&self, wallet_handle: i32, type_: &str, config: &str, cb: Box) + Send>) { + fn create_address(&self, wallet_handle: WalletHandle, type_: &str, config: &str, cb: Box) + Send>) { trace!("create_address >>> wallet_handle: {:?}, type_: {:?}, config: {:?}", wallet_handle, type_, config); match self.wallet_service.check(wallet_handle).map_err(map_err_err!()) { Err(err) => return cb(Err(IndyError::from(err))), @@ -284,7 +285,7 @@ impl PaymentsCommandExecutor { trace!("create_address <<<"); } - fn create_address_ack(&self, handle: i32, wallet_handle: i32, result: IndyResult) { + fn create_address_ack(&self, handle: i32, wallet_handle: WalletHandle, result: IndyResult) { trace!("create_address_ack >>> wallet_handle: {:?}, result: {:?}", wallet_handle, result); let total_result: IndyResult = match result { Ok(res) => { @@ -299,7 +300,7 @@ impl PaymentsCommandExecutor { trace!("create_address_ack <<<"); } - fn list_addresses(&self, wallet_handle: i32, cb: Box) + Send>) { + fn list_addresses(&self, wallet_handle: WalletHandle, cb: Box) + Send>) { trace!("list_addresses >>> wallet_handle: {:?}", wallet_handle); match self.wallet_service.check(wallet_handle).map_err(map_err_err!()) { Err(err) => return cb(Err(IndyError::from(err))), @@ -327,7 +328,7 @@ impl PaymentsCommandExecutor { trace!("list_addresses <<<"); } - fn add_request_fees(&self, wallet_handle: i32, submitter_did: Option<&str>, req: &str, inputs: &str, outputs: &str, extra: Option<&str>, cb: Box) + Send>) { + fn add_request_fees(&self, wallet_handle: WalletHandle, submitter_did: Option<&str>, req: &str, inputs: &str, outputs: &str, extra: Option<&str>, cb: Box) + Send>) { trace!("add_request_fees >>> wallet_handle: {:?}, submitter_did: {:?}, req: {:?}, inputs: {:?}, outputs: {:?}, extra: {:?}", wallet_handle, submitter_did, req, inputs, outputs, extra); if let Some(did) = submitter_did { @@ -383,7 +384,7 @@ impl PaymentsCommandExecutor { trace!("parse_response_with_fees_ack <<<"); } - fn build_get_payment_sources_request(&self, wallet_handle: i32, submitter_did: Option<&str>, payment_address: &str, cb: Box) + Send>) { + fn build_get_payment_sources_request(&self, wallet_handle: WalletHandle, submitter_did: Option<&str>, payment_address: &str, cb: Box) + Send>) { trace!("build_get_payment_sources_request >>> wallet_handle: {:?}, submitter_did: {:?}, payment_address: {:?}", wallet_handle, submitter_did, payment_address); if let Some(did) = submitter_did { match self.crypto_service.validate_did(did).map_err(map_err_err!()) { @@ -430,7 +431,7 @@ impl PaymentsCommandExecutor { trace!("parse_get_payment_sources_response_ack <<<"); } - fn build_payment_req(&self, wallet_handle: i32, submitter_did: Option<&str>, inputs: &str, outputs: &str, extra: Option<&str>, cb: Box) + Send>) { + fn build_payment_req(&self, wallet_handle: WalletHandle, submitter_did: Option<&str>, inputs: &str, outputs: &str, extra: Option<&str>, cb: Box) + Send>) { trace!("build_payment_req >>> wallet_handle: {:?}, submitter_did: {:?}, inputs: {:?}, outputs: {:?}, extra: {:?}", wallet_handle, submitter_did, inputs, outputs, extra); if let Some(did) = submitter_did { match self.crypto_service.validate_did(did).map_err(map_err_err!()) { @@ -481,7 +482,7 @@ impl PaymentsCommandExecutor { trace!("parse_payment_response_ack <<<"); } - fn build_mint_req(&self, wallet_handle: i32, submitter_did: Option<&str>, outputs: &str, extra: Option<&str>, cb: Box) + Send>) { + fn build_mint_req(&self, wallet_handle: WalletHandle, submitter_did: Option<&str>, outputs: &str, extra: Option<&str>, cb: Box) + Send>) { trace!("build_mint_req >>> wallet_handle: {:?}, submitter_did: {:?}, outputs: {:?}, extra: {:?}", wallet_handle, submitter_did, outputs, extra); if let Some(did) = submitter_did { match self.crypto_service.validate_did(did).map_err(map_err_err!()) { @@ -515,7 +516,7 @@ impl PaymentsCommandExecutor { trace!("build_mint_req_ack <<<"); } - fn build_set_txn_fees_req(&self, wallet_handle: i32, submitter_did: Option<&str>, type_: &str, fees: &str, cb: Box) + Send>) { + fn build_set_txn_fees_req(&self, wallet_handle: WalletHandle, submitter_did: Option<&str>, type_: &str, fees: &str, cb: Box) + Send>) { trace!("build_set_txn_fees_req >>> wallet_handle: {:?}, submitter_did: {:?}, type_: {:?}, fees: {:?}", wallet_handle, submitter_did, type_, fees); if let Some(did) = submitter_did { match self.crypto_service.validate_did(did).map_err(map_err_err!()) { @@ -544,7 +545,7 @@ impl PaymentsCommandExecutor { trace!("build_set_txn_fees_req_ack <<<"); } - fn build_get_txn_fees_req(&self, wallet_handle: i32, submitter_did: Option<&str>, type_: &str, cb: Box) + Send>) { + fn build_get_txn_fees_req(&self, wallet_handle: WalletHandle, submitter_did: Option<&str>, type_: &str, cb: Box) + Send>) { trace!("build_get_txn_fees_req >>> wallet_handle: {:?}, submitter_did: {:?}, type_: {:?}", wallet_handle, submitter_did, type_); if let Some(did) = submitter_did { match self.crypto_service.validate_did(did).map_err(map_err_err!()) { @@ -579,7 +580,7 @@ impl PaymentsCommandExecutor { trace!("parse_get_txn_fees_response_ack <<<"); } - fn build_verify_payment_request(&self, wallet_handle: i32, submitter_did: Option<&str>, receipt: &str, cb: Box) + Send>) { + fn build_verify_payment_request(&self, wallet_handle: WalletHandle, submitter_did: Option<&str>, receipt: &str, cb: Box) + Send>) { trace!("build_verify_payment_request >>> wallet_handle: {:?}, submitter_did: {:?}, receipt: {:?}", wallet_handle, submitter_did, receipt); if let Some(did) = submitter_did { match self.crypto_service.validate_did(did).map_err(map_err_err!()) { diff --git a/libindy/src/commands/wallet.rs b/libindy/src/commands/wallet.rs index f9419ce685..85c9ebb00c 100644 --- a/libindy/src/commands/wallet.rs +++ b/libindy/src/commands/wallet.rs @@ -10,6 +10,7 @@ use services::crypto::CryptoService; use services::wallet::{KeyDerivationData, WalletService}; use utils::crypto::{base58, chacha20poly1305_ietf, randombytes}; use utils::crypto::chacha20poly1305_ietf::Key as MasterKey; +use api::{WalletHandle, CallbackHandle}; type DeriveKeyResult = IndyResult; @@ -47,14 +48,14 @@ pub enum WalletCommand { Credentials, // credentials KeyDerivationData, DeriveKeyResult, // derive_key_result - i32), + CallbackHandle), Open(Config, // config Credentials, // credentials - Box) + Send>), - OpenContinue(i32, // wallet handle + Box) + Send>), + OpenContinue(WalletHandle, DeriveKeyResult<(MasterKey, Option)>, // derive_key_result ), - Close(i32, // handle + Close(WalletHandle, Box) + Send>), Delete(Config, // config Credentials, // credentials @@ -63,15 +64,15 @@ pub enum WalletCommand { Credentials, // credentials Metadata, // credentials DeriveKeyResult, - i32), - Export(i32, // wallet_handle + CallbackHandle), + Export(WalletHandle, ExportConfig, // export config Box) + Send>), - ExportContinue(i32, // wallet_handle + ExportContinue(WalletHandle, ExportConfig, // export config KeyDerivationData, DeriveKeyResult, - i32), + CallbackHandle), Import(Config, // config Credentials, // credentials ExportConfig, // import config @@ -79,7 +80,8 @@ pub enum WalletCommand { ImportContinue(Config, // config Credentials, // credentials DeriveKeyResult<(MasterKey, MasterKey)>, // derive_key_result - i32, // handle + WalletHandle, + CallbackHandle ), GenerateKey(Option, // config Box) + Send>), @@ -97,8 +99,8 @@ macro_rules! get_cb { pub struct WalletCommandExecutor { wallet_service: Rc, crypto_service: Rc, - open_callbacks: RefCell) + Send>>>, - pending_callbacks: RefCell) + Send>>> + open_callbacks: RefCell) + Send>>>, + pending_callbacks: RefCell) + Send>>> } impl WalletCommandExecutor { @@ -167,9 +169,9 @@ impl WalletCommandExecutor { debug!(target: "wallet_command_executor", "Import command received"); self._import(&config, &credentials, &import_config, cb); } - WalletCommand::ImportContinue(config, credential, key_result, wallet_handle) => { + WalletCommand::ImportContinue(config, credential, key_result, wallet_handle, cb_id) => { debug!(target: "wallet_command_executor", "ImportContinue command received"); - self._import_continue(wallet_handle, &config, &credential, key_result); + self._import_continue(cb_id, wallet_handle, &config, &credential, key_result); } WalletCommand::GenerateKey(config, cb) => { debug!(target: "wallet_command_executor", "DeriveKey command received"); @@ -231,7 +233,7 @@ impl WalletCommandExecutor { let key_data = KeyDerivationData::from_passphrase_with_new_salt(&credentials.key, &credentials.key_derivation_method); - let cb_id = ::utils::sequence::get_next_id(); + let cb_id : CallbackHandle = ::utils::sequence::get_next_id(); self.pending_callbacks.borrow_mut().insert(cb_id, cb); let config = config.clone(); @@ -248,7 +250,7 @@ impl WalletCommandExecutor { credentials.clone(), key_data.clone(), master_key_res, - cb_id, + cb_id ))).unwrap(); })) )).unwrap(); @@ -257,7 +259,7 @@ impl WalletCommandExecutor { } fn _create_continue(&self, - cb_id: i32, + cb_id: CallbackHandle, config: &Config, credentials: &Credentials, key_data: KeyDerivationData, @@ -270,7 +272,7 @@ impl WalletCommandExecutor { fn _open(&self, config: &Config, credentials: &Credentials, - cb: Box) + Send>) { + cb: Box) + Send>) { trace!("_open >>> config: {:?}, credentials: {:?}", config, secret!(credentials)); let (wallet_handle, key_derivation_data, rekey_data) = try_cb!(self.wallet_service.open_wallet_prepare(config, credentials), cb); @@ -299,7 +301,7 @@ impl WalletCommandExecutor { trace!("_open <<< res: {:?}", res); } - fn _derive_rekey_and_continue(wallet_handle: i32, key_result: MasterKey, rekey_data: KeyDerivationData) { + fn _derive_rekey_and_continue(wallet_handle: WalletHandle, key_result: MasterKey, rekey_data: KeyDerivationData) { CommandExecutor::instance().send( Command::Wallet(WalletCommand::DeriveKey( rekey_data, @@ -312,7 +314,7 @@ impl WalletCommandExecutor { ).unwrap(); } - fn _send_open_continue(wallet_handle: i32, key_result: DeriveKeyResult<(MasterKey, Option)>) { + fn _send_open_continue(wallet_handle: WalletHandle, key_result: DeriveKeyResult<(MasterKey, Option)>) { CommandExecutor::instance().send( Command::Wallet(WalletCommand::OpenContinue( wallet_handle, @@ -322,7 +324,7 @@ impl WalletCommandExecutor { } fn _open_continue(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, key_result: DeriveKeyResult<(MasterKey, Option)>) { let cb = self.open_callbacks.borrow_mut().remove(&wallet_handle).unwrap(); cb(key_result @@ -330,10 +332,10 @@ impl WalletCommandExecutor { } fn _close(&self, - handle: i32) -> IndyResult<()> { - trace!("_close >>> handle: {:?}", handle); + wallet_handle: WalletHandle) -> IndyResult<()> { + trace!("_close >>> handle: {:?}", wallet_handle); - let res = self.wallet_service.close_wallet(handle)?; + let res = self.wallet_service.close_wallet(wallet_handle)?; trace!("_close <<< res: {:?}", res); Ok(res) @@ -347,7 +349,7 @@ impl WalletCommandExecutor { let (metadata, key_derivation_data) = try_cb!(self.wallet_service.delete_wallet_prepare(&config, &credentials), cb); - let cb_id = ::utils::sequence::get_next_id(); + let cb_id: CallbackHandle = ::utils::sequence::get_next_id(); self.pending_callbacks.borrow_mut().insert(cb_id, cb); let config = config.clone(); @@ -374,7 +376,7 @@ impl WalletCommandExecutor { } fn _delete_continue(&self, - cb_id: i32, + cb_id: CallbackHandle, config: &Config, credentials: &Credentials, metadata: &Metadata, @@ -385,7 +387,7 @@ impl WalletCommandExecutor { } fn _export(&self, - wallet_handle: i32, + wallet_handle: WalletHandle, export_config: &ExportConfig, cb: Box) + Send>) { trace!("_export >>> handle: {:?}, export_config: {:?}", wallet_handle, secret!(export_config)); @@ -416,8 +418,8 @@ impl WalletCommandExecutor { } fn _export_continue(&self, - cb_id: i32, - wallet_handle: i32, + cb_id: CallbackHandle, + wallet_handle: WalletHandle, export_config: &ExportConfig, key_data: KeyDerivationData, key_result: DeriveKeyResult) { @@ -436,7 +438,8 @@ impl WalletCommandExecutor { let (wallet_handle, key_data, import_key_data) = try_cb!(self.wallet_service.import_wallet_prepare(&config, &credentials, &import_config), cb); - self.pending_callbacks.borrow_mut().insert(wallet_handle, cb); + let cb_id : CallbackHandle = ::utils::sequence::get_next_id(); + self.pending_callbacks.borrow_mut().insert(cb_id, cb); let config = config.clone(); let credentials = credentials.clone(); @@ -458,6 +461,7 @@ impl WalletCommandExecutor { credentials.clone(), import_key_result.and_then(|import_key| key_result.map(|key| (import_key, key))), wallet_handle, + cb_id ))).unwrap(); }), )) @@ -470,11 +474,12 @@ impl WalletCommandExecutor { } fn _import_continue(&self, - wallet_handle: i32, + cb_id: CallbackHandle, + wallet_handle: WalletHandle, config: &Config, credential: &Credentials, key_result: DeriveKeyResult<(MasterKey, MasterKey)>) { - let cb = get_cb!(self, wallet_handle); + let cb = get_cb!(self, cb_id); cb(key_result .and_then(|key| self.wallet_service.import_wallet_continue(wallet_handle, &config, &credential, key))) } diff --git a/libindy/src/services/payments.rs b/libindy/src/services/payments.rs index bd993b4ae1..3f3bbaaf0c 100644 --- a/libindy/src/services/payments.rs +++ b/libindy/src/services/payments.rs @@ -6,7 +6,7 @@ use std::ptr::null; use serde_json; -use api::ErrorCode; +use api::{ErrorCode, WalletHandle}; use api::payments::*; use errors::prelude::*; use utils::ctypes; @@ -82,7 +82,7 @@ impl PaymentsService { trace!("register_payment_method <<<"); } - pub fn create_address(&self, cmd_handle: i32, wallet_handle: i32, method_type: &str, config: &str) -> IndyResult<()> { + pub fn create_address(&self, cmd_handle: i32, wallet_handle: WalletHandle, method_type: &str, config: &str) -> IndyResult<()> { trace!("create_address >>> wallet_handle: {:?}, method_type: {:?}, config: {:?}", wallet_handle, method_type, config); let create_address: CreatePaymentAddressCB = self.methods.borrow().get(method_type) .ok_or(err_msg(IndyErrorKind::UnknownPaymentMethodType, format!("Unknown payment method {}", method_type)))?.create_address; @@ -96,7 +96,7 @@ impl PaymentsService { res } - pub fn add_request_fees(&self, cmd_handle: i32, method_type: &str, wallet_handle: i32, submitter_did: Option<&str>, req: &str, inputs: &str, outputs: &str, extra: Option<&str>) -> IndyResult<()> { + pub fn add_request_fees(&self, cmd_handle: i32, method_type: &str, wallet_handle: WalletHandle, submitter_did: Option<&str>, req: &str, inputs: &str, outputs: &str, extra: Option<&str>) -> IndyResult<()> { trace!("add_request_fees >>> method_type: {:?}, wallet_handle: {:?}, submitter_did: {:?}, req: {:?}, inputs: {:?}, outputs: {:?}, extra: {:?}", method_type, wallet_handle, submitter_did, req, inputs, outputs, extra); let add_request_fees: AddRequestFeesCB = self.methods.borrow().get(method_type) @@ -135,7 +135,7 @@ impl PaymentsService { res } - pub fn build_get_payment_sources_request(&self, cmd_handle: i32, type_: &str, wallet_handle: i32, submitter_did: Option<&str>, address: &str) -> IndyResult<()> { + pub fn build_get_payment_sources_request(&self, cmd_handle: i32, type_: &str, wallet_handle: WalletHandle, submitter_did: Option<&str>, address: &str) -> IndyResult<()> { trace!("build_get_payment_sources_request >>> type_: {:?}, wallet_handle: {:?}, submitter_did: {:?}, address: {:?}", type_, wallet_handle, submitter_did, address); let build_get_payment_sources_request: BuildGetPaymentSourcesRequestCB = self.methods.borrow().get(type_) .ok_or(err_msg(IndyErrorKind::UnknownPaymentMethodType, format!("Unknown payment method {}", type_)))?.build_get_payment_sources_request; @@ -168,7 +168,7 @@ impl PaymentsService { res } - pub fn build_payment_req(&self, cmd_handle: i32, type_: &str, wallet_handle: i32, submitter_did: Option<&str>, inputs: &str, outputs: &str, extra: Option<&str>) -> IndyResult<()> { + pub fn build_payment_req(&self, cmd_handle: i32, type_: &str, wallet_handle: WalletHandle, submitter_did: Option<&str>, inputs: &str, outputs: &str, extra: Option<&str>) -> IndyResult<()> { trace!("build_payment_req >>> type_: {:?}, wallet_handle: {:?}, submitter_did: {:?}, inputs: {:?}, outputs: {:?}, extra: {:?}", type_, wallet_handle, submitter_did, inputs, outputs, extra); let build_payment_req: BuildPaymentReqCB = self.methods.borrow().get(type_) .ok_or(err_msg(IndyErrorKind::UnknownPaymentMethodType, format!("Unknown payment method {}", type_)))?.build_payment_req; @@ -205,7 +205,7 @@ impl PaymentsService { res } - pub fn build_mint_req(&self, cmd_handle: i32, type_: &str, wallet_handle: i32, submitter_did: Option<&str>, outputs: &str, extra: Option<&str>) -> IndyResult<()> { + pub fn build_mint_req(&self, cmd_handle: i32, type_: &str, wallet_handle: WalletHandle, submitter_did: Option<&str>, outputs: &str, extra: Option<&str>) -> IndyResult<()> { trace!("build_mint_req >>> type_: {:?}, wallet_handle: {:?}, submitter_did: {:?}, outputs: {:?}, extra: {:?}", type_, wallet_handle, submitter_did, outputs, extra); let build_mint_req: BuildMintReqCB = self.methods.borrow().get(type_) .ok_or(err_msg(IndyErrorKind::UnknownPaymentMethodType, format!("Unknown payment method {}", type_)))?.build_mint_req; @@ -226,7 +226,7 @@ impl PaymentsService { res } - pub fn build_set_txn_fees_req(&self, cmd_handle: i32, type_: &str, wallet_handle: i32, submitter_did: Option<&str>, fees: &str) -> IndyResult<()> { + pub fn build_set_txn_fees_req(&self, cmd_handle: i32, type_: &str, wallet_handle: WalletHandle, submitter_did: Option<&str>, fees: &str) -> IndyResult<()> { trace!("build_set_txn_fees_req >>> type_: {:?}, wallet_handle: {:?}, submitter_did: {:?}, fees: {:?}", type_, wallet_handle, submitter_did, fees); let build_set_txn_fees_req: BuildSetTxnFeesReqCB = self.methods.borrow().get(type_) .ok_or(err_msg(IndyErrorKind::UnknownPaymentMethodType, format!("Unknown payment method {}", type_)))?.build_set_txn_fees_req; @@ -245,7 +245,7 @@ impl PaymentsService { res } - pub fn build_get_txn_fees_req(&self, cmd_handle: i32, type_: &str, wallet_handle: i32, submitter_did: Option<&str>) -> IndyResult<()> { + pub fn build_get_txn_fees_req(&self, cmd_handle: i32, type_: &str, wallet_handle: WalletHandle, submitter_did: Option<&str>) -> IndyResult<()> { trace!("build_get_txn_fees_req >>> type_: {:?}, wallet_handle: {:?}, submitter_did: {:?}", type_, wallet_handle, submitter_did); let build_get_txn_fees_req: BuildGetTxnFeesReqCB = self.methods.borrow().get(type_) .ok_or(err_msg(IndyErrorKind::UnknownPaymentMethodType, format!("Unknown payment method {}", type_)))?.build_get_txn_fees_req; @@ -276,7 +276,7 @@ impl PaymentsService { res } - pub fn build_verify_payment_req(&self, cmd_handle: i32, type_: &str, wallet_handle: i32, submitter_did: Option<&str>, receipt: &str) -> IndyResult<()> { + pub fn build_verify_payment_req(&self, cmd_handle: i32, type_: &str, wallet_handle: WalletHandle, submitter_did: Option<&str>, receipt: &str) -> IndyResult<()> { trace!("build_verify_payment_req >>> type_: {:?}, wallet_handle: {:?}, submitter_did: {:?}, receipt: {:?}", type_, wallet_handle, submitter_did, receipt); let build_verify_payment_req: BuildVerifyPaymentReqCB = self.methods.borrow().get(type_) .ok_or(err_msg(IndyErrorKind::UnknownPaymentMethodType, format!("Unknown payment method {}", type_)))?.build_verify_payment_req; @@ -438,7 +438,7 @@ mod cbs { use self::libc::c_char; - pub fn create_address_cb(cmd_handle: i32, wallet_handle: i32) -> Option Option ErrorCode> { send_ack(cmd_handle, Box::new(move |cmd_handle, result| PaymentsCommand::CreateAddressAck(cmd_handle, wallet_handle, result))) diff --git a/libindy/src/services/wallet/mod.rs b/libindy/src/services/wallet/mod.rs index 038f7a35dc..716df35073 100644 --- a/libindy/src/services/wallet/mod.rs +++ b/libindy/src/services/wallet/mod.rs @@ -9,6 +9,7 @@ use named_type::NamedType; use serde_json; use api::wallet::*; + use domain::wallet::{Config, Credentials, ExportConfig, Metadata, MetadataArgon, MetadataRaw, Tags}; use errors::prelude::*; pub use services::wallet::encryption::KeyDerivationData; @@ -21,6 +22,7 @@ use self::storage::{WalletStorage, WalletStorageType}; use self::storage::default::SQLiteStorageType; use self::storage::plugged::PluggedStorageType; use self::wallet::{Keys, Wallet}; +use api::WalletHandle; mod storage; mod encryption; @@ -32,9 +34,9 @@ mod wallet; pub struct WalletService { storage_types: RefCell>>, - wallets: RefCell>>, - pending_for_open: RefCell, Metadata, Option)>>, - pending_for_import: RefCell, chacha20poly1305_ietf::Nonce, usize, Vec, KeyDerivationData)>>, + wallets: RefCell>>, + pending_for_open: RefCell, Metadata, Option)>>, + pending_for_import: RefCell, chacha20poly1305_ietf::Nonce, usize, Vec, KeyDerivationData)>>, } impl WalletService { @@ -177,14 +179,14 @@ impl WalletService { Ok(()) } - pub fn open_wallet_prepare(&self, config: &Config, credentials: &Credentials) -> IndyResult<(i32, KeyDerivationData, Option)> { + pub fn open_wallet_prepare(&self, config: &Config, credentials: &Credentials) -> IndyResult<(WalletHandle, KeyDerivationData, Option)> { trace!("open_wallet >>> config: {:?}, credentials: {:?}", config, secret!(&credentials)); self._is_id_from_config_not_used(config)?; let (storage, metadata, key_derivation_data) = self._open_storage_and_fetch_metadata(config, credentials)?; - let wallet_handle = sequence::get_next_id(); + let wallet_handle = WalletHandle(sequence::get_next_id()); let rekey_data: Option = credentials.rekey.as_ref().map(|ref rekey| KeyDerivationData::from_passphrase_with_new_salt(rekey, &credentials.rekey_derivation_method)); @@ -194,7 +196,7 @@ impl WalletService { Ok((wallet_handle, key_derivation_data, rekey_data)) } - pub fn open_wallet_continue(&self, wallet_handle: i32, master_key: (&MasterKey, Option<&MasterKey>)) -> IndyResult { + pub fn open_wallet_continue(&self, wallet_handle: WalletHandle, master_key: (&MasterKey, Option<&MasterKey>)) -> IndyResult { let (id, storage, metadata, rekey_data) = self.pending_for_open.borrow_mut().remove(&wallet_handle) .ok_or(err_msg(IndyErrorKind::InvalidState, "Open data not found"))?; @@ -227,7 +229,7 @@ impl WalletService { Ok((storage, metadata, key_derivation_data)) } - pub fn close_wallet(&self, handle: i32) -> IndyResult<()> { + pub fn close_wallet(&self, handle: WalletHandle) -> IndyResult<()> { trace!("close_wallet >>> handle: {:?}", handle); match self.wallets.borrow_mut().remove(&handle) { @@ -247,7 +249,7 @@ impl WalletService { } } - pub fn add_record(&self, wallet_handle: i32, type_: &str, name: &str, value: &str, tags: &Tags) -> IndyResult<()> { + pub fn add_record(&self, wallet_handle: WalletHandle, type_: &str, name: &str, value: &str, tags: &Tags) -> IndyResult<()> { match self.wallets.borrow_mut().get_mut(&wallet_handle) { Some(wallet) => wallet.add(type_, name, value, tags) .map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)), @@ -255,7 +257,7 @@ impl WalletService { } } - pub fn add_indy_object(&self, wallet_handle: i32, name: &str, object: &T, tags: &Tags) + pub fn add_indy_object(&self, wallet_handle: WalletHandle, name: &str, object: &T, tags: &Tags) -> IndyResult where T: ::serde::Serialize + Sized, T: NamedType { let type_ = T::short_type_name(); @@ -266,7 +268,7 @@ impl WalletService { Ok(object_json) } - pub fn update_record_value(&self, wallet_handle: i32, type_: &str, name: &str, value: &str) -> IndyResult<()> { + pub fn update_record_value(&self, wallet_handle: WalletHandle, type_: &str, name: &str, value: &str) -> IndyResult<()> { match self.wallets.borrow().get(&wallet_handle) { Some(wallet) => wallet.update(type_, name, value) @@ -275,7 +277,7 @@ impl WalletService { } } - pub fn update_indy_object(&self, wallet_handle: i32, name: &str, object: &T) -> IndyResult where T: ::serde::Serialize + Sized, T: NamedType { + pub fn update_indy_object(&self, wallet_handle: WalletHandle, name: &str, object: &T) -> IndyResult where T: ::serde::Serialize + Sized, T: NamedType { let type_ = T::short_type_name(); match self.wallets.borrow().get(&wallet_handle) { Some(wallet) => { @@ -288,7 +290,7 @@ impl WalletService { } } - pub fn add_record_tags(&self, wallet_handle: i32, type_: &str, name: &str, tags: &Tags) -> IndyResult<()> { + pub fn add_record_tags(&self, wallet_handle: WalletHandle, type_: &str, name: &str, tags: &Tags) -> IndyResult<()> { match self.wallets.borrow_mut().get_mut(&wallet_handle) { Some(wallet) => wallet.add_tags(type_, name, tags) .map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)), @@ -296,7 +298,7 @@ impl WalletService { } } - pub fn update_record_tags(&self, wallet_handle: i32, type_: &str, name: &str, tags: &Tags) -> IndyResult<()> { + pub fn update_record_tags(&self, wallet_handle: WalletHandle, type_: &str, name: &str, tags: &Tags) -> IndyResult<()> { match self.wallets.borrow_mut().get_mut(&wallet_handle) { Some(wallet) => wallet.update_tags(type_, name, tags) .map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)), @@ -304,7 +306,7 @@ impl WalletService { } } - pub fn delete_record_tags(&self, wallet_handle: i32, type_: &str, name: &str, tag_names: &[&str]) -> IndyResult<()> { + pub fn delete_record_tags(&self, wallet_handle: WalletHandle, type_: &str, name: &str, tag_names: &[&str]) -> IndyResult<()> { match self.wallets.borrow().get(&wallet_handle) { Some(wallet) => wallet.delete_tags(type_, name, tag_names) .map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)), @@ -312,7 +314,7 @@ impl WalletService { } } - pub fn delete_record(&self, wallet_handle: i32, type_: &str, name: &str) -> IndyResult<()> { + pub fn delete_record(&self, wallet_handle: WalletHandle, type_: &str, name: &str) -> IndyResult<()> { match self.wallets.borrow().get(&wallet_handle) { Some(wallet) => wallet.delete(type_, name) .map_err(|err| WalletService::_map_wallet_storage_error(err, type_, name)), @@ -320,11 +322,11 @@ impl WalletService { } } - pub fn delete_indy_record(&self, wallet_handle: i32, name: &str) -> IndyResult<()> where T: NamedType { + pub fn delete_indy_record(&self, wallet_handle: WalletHandle, name: &str) -> IndyResult<()> where T: NamedType { self.delete_record(wallet_handle, &self.add_prefix(T::short_type_name()), name) } - pub fn get_record(&self, wallet_handle: i32, type_: &str, name: &str, options_json: &str) -> IndyResult { + pub fn get_record(&self, wallet_handle: WalletHandle, type_: &str, name: &str, options_json: &str) -> IndyResult { match self.wallets.borrow().get(&wallet_handle) { Some(wallet) => wallet.get(type_, name, options_json) @@ -333,12 +335,12 @@ impl WalletService { } } - pub fn get_indy_record(&self, wallet_handle: i32, name: &str, options_json: &str) -> IndyResult where T: NamedType { + pub fn get_indy_record(&self, wallet_handle: WalletHandle, name: &str, options_json: &str) -> IndyResult where T: NamedType { self.get_record(wallet_handle, &self.add_prefix(T::short_type_name()), name, options_json) } // Dirty hack. json must live longer then result T - pub fn get_indy_object(&self, wallet_handle: i32, name: &str, options_json: &str) -> IndyResult where T: ::serde::de::DeserializeOwned, T: NamedType { + pub fn get_indy_object(&self, wallet_handle: WalletHandle, name: &str, options_json: &str) -> IndyResult where T: ::serde::de::DeserializeOwned, T: NamedType { let type_ = T::short_type_name(); let record: WalletRecord = match self.wallets.borrow().get(&wallet_handle) { @@ -354,7 +356,7 @@ impl WalletService { } // Dirty hack. json must live longer then result T - pub fn get_indy_opt_object(&self, wallet_handle: i32, name: &str, options_json: &str) -> IndyResult> where T: ::serde::de::DeserializeOwned, T: NamedType { + pub fn get_indy_opt_object(&self, wallet_handle: WalletHandle, name: &str, options_json: &str) -> IndyResult> where T: ::serde::de::DeserializeOwned, T: NamedType { match self.get_indy_object::(wallet_handle, name, options_json) { Ok(res) => Ok(Some(res)), Err(ref err) if err.kind() == IndyErrorKind::WalletItemNotFound => Ok(None), @@ -362,19 +364,19 @@ impl WalletService { } } - pub fn search_records(&self, wallet_handle: i32, type_: &str, query_json: &str, options_json: &str) -> IndyResult { + pub fn search_records(&self, wallet_handle: WalletHandle, type_: &str, query_json: &str, options_json: &str) -> IndyResult { match self.wallets.borrow().get(&wallet_handle) { Some(wallet) => Ok(WalletSearch { iter: wallet.search(type_, query_json, Some(options_json))? }), None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle")) } } - pub fn search_indy_records(&self, wallet_handle: i32, query_json: &str, options_json: &str) -> IndyResult where T: NamedType { + pub fn search_indy_records(&self, wallet_handle: WalletHandle, query_json: &str, options_json: &str) -> IndyResult where T: NamedType { self.search_records(wallet_handle, &self.add_prefix(T::short_type_name()), query_json, options_json) } #[allow(dead_code)] // TODO: Should we implement getting all records or delete everywhere? - pub fn search_all_records(&self, _wallet_handle: i32) -> IndyResult { + pub fn search_all_records(&self, _wallet_handle: WalletHandle) -> IndyResult { // match self.wallets.borrow().get(&wallet_handle) { // Some(wallet) => wallet.search_all_records(), // None => Err(IndyError::InvalidHandle(wallet_handle.to_string())) @@ -382,7 +384,7 @@ impl WalletService { unimplemented!() } - pub fn upsert_indy_object(&self, wallet_handle: i32, name: &str, object: &T) -> IndyResult + pub fn upsert_indy_object(&self, wallet_handle: WalletHandle, name: &str, object: &T) -> IndyResult where T: ::serde::Serialize + Sized, T: NamedType { if self.record_exists::(wallet_handle, name)? { self.update_indy_object::(wallet_handle, name, object) @@ -391,7 +393,7 @@ impl WalletService { } } - pub fn record_exists(&self, wallet_handle: i32, name: &str) -> IndyResult where T: NamedType { + pub fn record_exists(&self, wallet_handle: WalletHandle, name: &str) -> IndyResult where T: NamedType { match self.wallets.borrow().get(&wallet_handle) { Some(wallet) => match wallet.get(&self.add_prefix(T::short_type_name()), name, &RecordOptions::id()) { @@ -403,14 +405,14 @@ impl WalletService { } } - pub fn check(&self, handle: i32) -> IndyResult<()> { + pub fn check(&self, handle: WalletHandle) -> IndyResult<()> { match self.wallets.borrow().get(&handle) { Some(_) => Ok(()), None => Err(err_msg(IndyErrorKind::InvalidWalletHandle, "Unknown wallet handle")) } } - pub fn export_wallet(&self, wallet_handle: i32, export_config: &ExportConfig, version: u32, key: (&KeyDerivationData, &MasterKey)) -> IndyResult<()> { + pub fn export_wallet(&self, wallet_handle: WalletHandle, export_config: &ExportConfig, version: u32, key: (&KeyDerivationData, &MasterKey)) -> IndyResult<()> { trace!("export_wallet >>> wallet_handle: {:?}, export_config: {:?}, version: {:?}", wallet_handle, secret!(export_config), version); if version != 0 { @@ -448,7 +450,7 @@ impl WalletService { pub fn import_wallet_prepare(&self, config: &Config, credentials: &Credentials, - export_config: &ExportConfig) -> IndyResult<(i32, KeyDerivationData, KeyDerivationData)> { + export_config: &ExportConfig) -> IndyResult<(WalletHandle, KeyDerivationData, KeyDerivationData)> { trace!("import_wallet_prepare >>> config: {:?}, credentials: {:?}, export_config: {:?}", config, secret!(export_config), secret!(export_config)); let exported_file_to_import = @@ -459,7 +461,7 @@ impl WalletService { let (reader, import_key_derivation_data, nonce, chunk_size, header_bytes) = preparse_file_to_import(exported_file_to_import, &export_config.key)?; let key_data = KeyDerivationData::from_passphrase_with_new_salt(&credentials.key, &credentials.key_derivation_method); - let wallet_handle = sequence::get_next_id(); + let wallet_handle = WalletHandle(sequence::get_next_id()); let stashed_key_data = key_data.clone(); @@ -468,7 +470,7 @@ impl WalletService { Ok((wallet_handle, key_data, import_key_derivation_data)) } - pub fn import_wallet_continue(&self, wallet_handle: i32, config: &Config, credentials: &Credentials, key: (MasterKey, MasterKey)) -> IndyResult<()> { + pub fn import_wallet_continue(&self, wallet_handle: WalletHandle, config: &Config, credentials: &Credentials, key: (MasterKey, MasterKey)) -> IndyResult<()> { let (reader, nonce, chunk_size, header_bytes, key_data) = self.pending_for_import.borrow_mut().remove(&wallet_handle).unwrap(); let (import_key, master_key) = key; @@ -735,6 +737,8 @@ mod tests { use std::fs; use std::path::Path; + use api::INVALID_WALLET_HANDLE; + use domain::wallet::KeyDerivationMethod; use utils::environment; use utils::inmem_wallet::InmemWallet; @@ -743,12 +747,12 @@ mod tests { use super::*; impl WalletService { - fn open_wallet(&self, config: &Config, credentials: &Credentials) -> IndyResult { + fn open_wallet(&self, config: &Config, credentials: &Credentials) -> IndyResult { self._is_id_from_config_not_used(config)?; let (storage, metadata, key_derivation_data) = self._open_storage_and_fetch_metadata(config, credentials)?; - let wallet_handle = sequence::get_next_id(); + let wallet_handle = WalletHandle(sequence::get_next_id()); let rekey_data: Option = credentials.rekey.as_ref().map(|ref rekey| KeyDerivationData::from_passphrase_with_new_salt(rekey, &credentials.rekey_derivation_method)); @@ -782,7 +786,7 @@ mod tests { let (reader, import_key_derivation_data, nonce, chunk_size, header_bytes) = preparse_file_to_import(exported_file_to_import, &export_config.key)?; let key_data = KeyDerivationData::from_passphrase_with_new_salt(&credentials.key, &credentials.key_derivation_method); - let wallet_handle = sequence::get_next_id(); + let wallet_handle = WalletHandle(sequence::get_next_id()); let import_key = import_key_derivation_data.calc_master_key()?; let master_key = key_data.calc_master_key()?; @@ -1102,7 +1106,7 @@ mod tests { wallet_service.create_wallet(&_config(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap(); let wallet_handle = wallet_service.open_wallet(&_config(), &RAW_CREDENTIAL).unwrap(); - let res = wallet_service.close_wallet(wallet_handle + 1); + let res = wallet_service.close_wallet(INVALID_WALLET_HANDLE); assert_kind!(IndyErrorKind::InvalidWalletHandle, res); wallet_service.close_wallet(wallet_handle).unwrap(); @@ -1776,10 +1780,10 @@ mod tests { let wallet_service = WalletService::new(); wallet_service.create_wallet(&_config(), &RAW_CREDENTIAL, (&RAW_KDD, &RAW_MASTER_KEY)).unwrap(); - let wallet_handle = wallet_service.open_wallet(&_config(), &RAW_CREDENTIAL).unwrap(); + let _wallet_handle = wallet_service.open_wallet(&_config(), &RAW_CREDENTIAL).unwrap(); let (kdd, master_key) = _export_key_raw(); - let res = wallet_service.export_wallet(wallet_handle + 1, &_export_config_raw(), 0, (&kdd, &master_key)); + let res = wallet_service.export_wallet(INVALID_WALLET_HANDLE, &_export_config_raw(), 0, (&kdd, &master_key)); assert_kind!(IndyErrorKind::InvalidWalletHandle, res); assert!(!_export_file_path().exists()); } diff --git a/samples/python/src/getting_started.py b/samples/python/src/getting_started.py index acd263dd88..6f2956247b 100644 --- a/samples/python/src/getting_started.py +++ b/samples/python/src/getting_started.py @@ -1,6 +1,6 @@ import time -from indy import anoncreds, crypto, did, ledger, pool, wallet +from indy import anoncreds, crypto, did, ledger, pool, wallet, blob_storage import json import logging @@ -8,6 +8,7 @@ import argparse import sys from ctypes import * +from os.path import dirname from indy.error import ErrorCode, IndyError @@ -240,7 +241,7 @@ async def run(): job_certificate_cred_def = { 'tag': 'TAG1', 'type': 'CL', - 'config': {"support_revocation": False} + 'config': {"support_revocation": True} } (acme['job_certificate_cred_def_id'], acme['job_certificate_cred_def']) = \ await anoncreds.issuer_create_and_store_credential_def(acme['wallet'], acme['did'], @@ -252,6 +253,26 @@ async def run(): logger.info("\"Acme\" -> Send \"Acme Job-Certificate\" Credential Definition to Ledger") await send_cred_def(acme['pool'], acme['wallet'], acme['did'], acme['job_certificate_cred_def']) + logger.info("\"Acme\" -> Creates Revocation Registry") + acme['tails_writer_config'] = json.dumps({'base_dir': "/tmp/indy_acme_tails", 'uri_pattern': ''}) + tails_writer = await blob_storage.open_writer('default', acme['tails_writer_config']) + (acme['revoc_reg_id'], acme['revoc_reg_def'], acme['revoc_reg_entry']) = \ + await anoncreds.issuer_create_and_store_revoc_reg(acme['wallet'], acme['did'], 'CL_ACCUM', 'TAG1', + acme['job_certificate_cred_def_id'], + json.dumps({'max_cred_num': 5, + 'issuance_type': 'ISSUANCE_ON_DEMAND'}), + tails_writer) + + logger.info("\"Acme\" -> Post Revocation Registry Definition to Ledger") + acme['revoc_reg_def_request'] = await ledger.build_revoc_reg_def_request(acme['did'], acme['revoc_reg_def']) + await ledger.sign_and_submit_request(acme['pool'], acme['wallet'], acme['did'], acme['revoc_reg_def_request']) + + logger.info("\"Acme\" -> Post Revocation Registry Entry to Ledger") + acme['revoc_reg_entry_request'] = \ + await ledger.build_revoc_reg_entry_request(acme['did'], acme['revoc_reg_id'], 'CL_ACCUM', + acme['revoc_reg_entry']) + await ledger.sign_and_submit_request(acme['pool'], acme['wallet'], acme['did'], acme['revoc_reg_entry_request']) + logger.info("==============================") logger.info("=== Getting Transcript with Faber ==") logger.info("==============================") @@ -276,12 +297,12 @@ async def run(): await anoncreds.issuer_create_credential_offer(faber['wallet'], faber['transcript_cred_def_id']) logger.info("\"Faber\" -> Get key for Alice did") - faber['alic_key_for_faber'] = \ + faber['alice_key_for_faber'] = \ await did.key_for_did(faber['pool'], faber['wallet'], faber['alice_connection_response']['did']) logger.info("\"Faber\" -> Authcrypt \"Transcript\" Credential Offer for Alice") faber['authcrypted_transcript_cred_offer'] = \ - await crypto.auth_crypt(faber['wallet'], faber['key_for_alice'], faber['alic_key_for_faber'], + await crypto.auth_crypt(faber['wallet'], faber['key_for_alice'], faber['alice_key_for_faber'], faber['transcript_cred_offer'].encode('utf-8')) logger.info("\"Faber\" -> Send authcrypted \"Transcript\" Credential Offer to Alice") @@ -298,7 +319,7 @@ async def run(): logger.info("\"Alice\" -> Get \"Faber Transcript\" Credential Definition from Ledger") (alice['faber_transcript_cred_def_id'], alice['faber_transcript_cred_def']) = \ - await get_cred_def(alice['pool'], alice['did_for_faber'], authdecrypted_transcript_cred_offer['cred_def_id']) + await get_cred_def(alice['pool'], alice['did_for_faber'], alice['transcript_cred_def_id']) logger.info("\"Alice\" -> Create \"Transcript\" Credential Request for Faber") (alice['transcript_cred_request'], alice['transcript_cred_request_metadata']) = \ @@ -312,7 +333,14 @@ async def run(): alice['transcript_cred_request'].encode('utf-8')) logger.info("\"Alice\" -> Send authcrypted \"Transcript\" Credential Request to Faber") - alice['transcript_cred_values'] = json.dumps({ + faber['authcrypted_transcript_cred_request'] = alice['authcrypted_transcript_cred_request'] + + logger.info("\"Faber\" -> Authdecrypt \"Transcript\" Credential Request from Alice") + faber['alice_key_for_faber'], faber['transcript_cred_request'], _ = \ + await auth_decrypt(faber['wallet'], faber['key_for_alice'], faber['authcrypted_transcript_cred_request']) + + logger.info("\"Faber\" -> Create \"Transcript\" Credential for Alice") + faber['alice_transcript_cred_values'] = json.dumps({ "first_name": {"raw": "Alice", "encoded": "1139481716457488690172217916278103335"}, "last_name": {"raw": "Garcia", "encoded": "5321642780241790123587902456789123452"}, "degree": {"raw": "Bachelor of Science, Marketing", "encoded": "12434523576212321"}, @@ -321,15 +349,6 @@ async def run(): "year": {"raw": "2015", "encoded": "2015"}, "average": {"raw": "5", "encoded": "5"} }) - faber['authcrypted_transcript_cred_request'] = alice['authcrypted_transcript_cred_request'] - faber['alice_transcript_cred_values'] = alice['transcript_cred_values'] - - logger.info("\"Faber\" -> Authdecrypt \"Transcript\" Credential Request from Alice") - faber['alice_key_for_faber'], faber['transcript_cred_request'], _ = \ - await auth_decrypt(faber['wallet'], faber['key_for_alice'], faber['authcrypted_transcript_cred_request']) - - logger.info("\"Faber\" -> Create \"Transcript\" Credential for Alice") - faber['transcript_cred'], _, _ = \ await anoncreds.issuer_create_credential(faber['wallet'], faber['transcript_cred_offer'], faber['transcript_cred_request'], @@ -444,7 +463,8 @@ async def run(): cred_for_attr5['referent']: cred_for_attr5, cred_for_predicate1['referent']: cred_for_predicate1} - alice['schemas'], alice['cred_defs'], alice['revoc_states'] = \ + alice['schemas_for_job_application'], alice['cred_defs_for_job_application'], \ + alice['revoc_states_for_job_application'] = \ await prover_get_entities_from_ledger(alice['pool'], alice['did_for_acme'], alice['creds_for_job_application_proof'], alice['name']) @@ -466,7 +486,9 @@ async def run(): alice['job_application_proof'] = \ await anoncreds.prover_create_proof(alice['wallet'], alice['job_application_proof_request'], alice['job_application_requested_creds'], alice['master_secret_id'], - alice['schemas'], alice['cred_defs'], alice['revoc_states']) + alice['schemas_for_job_application'], + alice['cred_defs_for_job_application'], + alice['revoc_states_for_job_application']) logger.info("\"Alice\" -> Authcrypt \"Job-Application\" Proof for Acme") alice['authcrypted_job_application_proof'] = \ @@ -480,7 +502,8 @@ async def run(): _, acme['job_application_proof'], decrypted_job_application_proof = \ await auth_decrypt(acme['wallet'], acme['key_for_alice'], acme['authcrypted_job_application_proof']) - acme['schemas'], acme['cred_defs'], acme['revoc_ref_defs'], acme['revoc_regs'] = \ + acme['schemas_for_job_application'], acme['cred_defs_for_job_application'], \ + acme['revoc_ref_defs_for_job_application'], acme['revoc_regs_for_job_application'] = \ await verifier_get_entities_from_ledger(acme['pool'], acme['did'], decrypted_job_application_proof['identifiers'], acme['name']) @@ -497,8 +520,10 @@ async def run(): assert '123-45-6789' == decrypted_job_application_proof['requested_proof']['self_attested_attrs']['attr6_referent'] assert await anoncreds.verifier_verify_proof(acme['job_application_proof_request'], acme['job_application_proof'], - acme['schemas'], acme['cred_defs'], acme['revoc_ref_defs'], - acme['revoc_regs']) + acme['schemas_for_job_application'], + acme['cred_defs_for_job_application'], + acme['revoc_ref_defs_for_job_application'], + acme['revoc_regs_for_job_application']) logger.info("==============================") logger.info("== Apply for the job with Acme - Getting Job-Certificate Credential ==") @@ -555,11 +580,19 @@ async def run(): await auth_decrypt(acme['wallet'], acme['key_for_alice'], acme['authcrypted_job_certificate_cred_request']) logger.info("\"Acme\" -> Create \"Job-Certificate\" Credential for Alice") - - acme['job_certificate_cred'], _, _ = \ + acme['blob_storage_reader_cfg_handle'] = await blob_storage.open_reader('default', acme['tails_writer_config']) + acme['job_certificate_cred'], acme['job_certificate_cred_rev_id'], acme['alice_cert_rev_reg_delta'] = \ await anoncreds.issuer_create_credential(acme['wallet'], acme['job_certificate_cred_offer'], acme['job_certificate_cred_request'], - acme['job_certificate_cred_values'], None, None) + acme['job_certificate_cred_values'], + acme['revoc_reg_id'], + acme['blob_storage_reader_cfg_handle']) + + logger.info("\"Acme\" -> Post Revocation Registry Delta to Ledger") + acme['revoc_reg_entry_req'] = \ + await ledger.build_revoc_reg_entry_request(acme['did'], acme['revoc_reg_id'], 'CL_ACCUM', + acme['alice_cert_rev_reg_delta']) + await ledger.sign_and_submit_request(acme['pool'], acme['wallet'], acme['did'], acme['revoc_reg_entry_req']) logger.info("\"Acme\" -> Authcrypt \"Job-Certificate\" Credential for Alice") acme['authcrypted_job_certificate_cred'] = \ @@ -570,13 +603,21 @@ async def run(): alice['authcrypted_job_certificate_cred'] = acme['authcrypted_job_certificate_cred'] logger.info("\"Alice\" -> Authdecrypted \"Job-Certificate\" Credential from Acme") - _, alice['job_certificate_cred'], _ = \ + _, alice['job_certificate_cred'], alice_job_certificate_cred = \ await auth_decrypt(alice['wallet'], alice['key_for_acme'], alice['authcrypted_job_certificate_cred']) + logger.info("\"Alice\" -> Gets RevocationRegistryDefinition for \"Job-Certificate\" Credential from Acme") + alice['acme_revoc_reg_des_req'] = \ + await ledger.build_get_revoc_reg_def_request(alice['did_for_acme'], + alice_job_certificate_cred['rev_reg_id']) + alice['acme_revoc_reg_des_resp'] = await ledger.submit_request(alice['pool'], alice['acme_revoc_reg_des_req']) + (alice['acme_revoc_reg_def_id'], alice['acme_revoc_reg_def_json']) = \ + await ledger.parse_get_revoc_reg_def_response(alice['acme_revoc_reg_des_resp']) + logger.info("\"Alice\" -> Store \"Job-Certificate\" Credential") await anoncreds.prover_store_credential(alice['wallet'], None, alice['job_certificate_cred_request_metadata'], alice['job_certificate_cred'], - alice['acme_job_certificate_cred_def'], None) + alice['acme_job_certificate_cred_def'], alice['acme_revoc_reg_def_json']) logger.info("==============================") logger.info("=== Apply for the loan with Thrift ==") @@ -587,118 +628,133 @@ async def run(): thrift['did_for_alice'], thrift['key_for_alice'], alice['did_for_thrift'], alice['key_for_thrift'], \ thrift['alice_connection_response'] = await onboarding(thrift, alice) - logger.info("==============================") - logger.info("== Apply for the loan with Thrift - Job-Certificate proving ==") - logger.info("------------------------------") - - logger.info("\"Thrift\" -> Create \"Loan-Application-Basic\" Proof Request") - thrift['apply_loan_proof_request'] = json.dumps({ - 'nonce': '123432421212', - 'name': 'Loan-Application-Basic', - 'version': '0.1', - 'requested_attributes': { - 'attr1_referent': { - 'name': 'employee_status', - 'restrictions': [{'cred_def_id': acme['job_certificate_cred_def_id']}] - } - }, - 'requested_predicates': { - 'predicate1_referent': { - 'name': 'salary', - 'p_type': '>=', - 'p_value': 2000, - 'restrictions': [{'cred_def_id': acme['job_certificate_cred_def_id']}] + async def apply_loan_basic(): + # This method will be called twice: once with a valid Job-Certificate and + # the second time after the Job-Certificate has been revoked. + logger.info("==============================") + logger.info("== Apply for the loan with Thrift - Job-Certificate proving ==") + logger.info("------------------------------") + + logger.info("\"Thrift\" -> Create \"Loan-Application-Basic\" Proof Request") + thrift['apply_loan_proof_request'] = json.dumps({ + 'nonce': '123432421212', + 'name': 'Loan-Application-Basic', + 'version': '0.1', + 'requested_attributes': { + 'attr1_referent': { + 'name': 'employee_status', + 'restrictions': [{'cred_def_id': acme['job_certificate_cred_def_id']}] + } }, - 'predicate2_referent': { - 'name': 'experience', - 'p_type': '>=', - 'p_value': 1, - 'restrictions': [{'cred_def_id': acme['job_certificate_cred_def_id']}] + 'requested_predicates': { + 'predicate1_referent': { + 'name': 'salary', + 'p_type': '>=', + 'p_value': 2000, + 'restrictions': [{'cred_def_id': acme['job_certificate_cred_def_id']}] + }, + 'predicate2_referent': { + 'name': 'experience', + 'p_type': '>=', + 'p_value': 1, + 'restrictions': [{'cred_def_id': acme['job_certificate_cred_def_id']}] + } + }, + 'non_revoked': {'to': int(time.time())} + }) + + logger.info("\"Thrift\" -> Get key for Alice did") + thrift['alice_key_for_thrift'] = \ + await did.key_for_did(thrift['pool'], thrift['wallet'], thrift['alice_connection_response']['did']) + + logger.info("\"Thrift\" -> Authcrypt \"Loan-Application-Basic\" Proof Request for Alice") + thrift['authcrypted_apply_loan_proof_request'] = \ + await crypto.auth_crypt(thrift['wallet'], thrift['key_for_alice'], thrift['alice_key_for_thrift'], + thrift['apply_loan_proof_request'].encode('utf-8')) + + logger.info("\"Thrift\" -> Send authcrypted \"Loan-Application-Basic\" Proof Request to Alice") + alice['authcrypted_apply_loan_proof_request'] = thrift['authcrypted_apply_loan_proof_request'] + + logger.info("\"Alice\" -> Authdecrypt \"Loan-Application-Basic\" Proof Request from Thrift") + alice['thrift_key_for_alice'], alice['apply_loan_proof_request'], _ = \ + await auth_decrypt(alice['wallet'], alice['key_for_thrift'], alice['authcrypted_apply_loan_proof_request']) + + logger.info("\"Alice\" -> Get credentials for \"Loan-Application-Basic\" Proof Request") + + search_for_apply_loan_proof_request = \ + await anoncreds.prover_search_credentials_for_proof_req(alice['wallet'], + alice['apply_loan_proof_request'], None) + + cred_for_attr1 = await get_credential_for_referent(search_for_apply_loan_proof_request, 'attr1_referent') + cred_for_predicate1 = await get_credential_for_referent(search_for_apply_loan_proof_request, 'predicate1_referent') + cred_for_predicate2 = await get_credential_for_referent(search_for_apply_loan_proof_request, 'predicate2_referent') + + await anoncreds.prover_close_credentials_search_for_proof_req(search_for_apply_loan_proof_request) + + alice['creds_for_apply_loan_proof'] = {cred_for_attr1['referent']: cred_for_attr1, + cred_for_predicate1['referent']: cred_for_predicate1, + cred_for_predicate2['referent']: cred_for_predicate2} + + requested_timestamp = int(json.loads(thrift['apply_loan_proof_request'])['non_revoked']['to']) + alice['schemas_for_loan_app'], alice['cred_defs_for_loan_app'], alice['revoc_states_for_loan_app'] = \ + await prover_get_entities_from_ledger(alice['pool'], alice['did_for_thrift'], + alice['creds_for_apply_loan_proof'], + alice['name'], None, requested_timestamp) + + logger.info("\"Alice\" -> Create \"Loan-Application-Basic\" Proof") + revoc_states_for_loan_app = json.loads(alice['revoc_states_for_loan_app']) + timestamp_for_attr1 = get_timestamp_for_attribute(cred_for_attr1, revoc_states_for_loan_app) + timestamp_for_predicate1 = get_timestamp_for_attribute(cred_for_predicate1, revoc_states_for_loan_app) + timestamp_for_predicate2 = get_timestamp_for_attribute(cred_for_predicate2, revoc_states_for_loan_app) + alice['apply_loan_requested_creds'] = json.dumps({ + 'self_attested_attributes': {}, + 'requested_attributes': { + 'attr1_referent': {'cred_id': cred_for_attr1['referent'], 'revealed': True, 'timestamp': timestamp_for_attr1} + }, + 'requested_predicates': { + 'predicate1_referent': {'cred_id': cred_for_predicate1['referent'], 'timestamp': timestamp_for_predicate1}, + 'predicate2_referent': {'cred_id': cred_for_predicate2['referent'], 'timestamp': timestamp_for_predicate2} } - } - }) - - logger.info("\"Thrift\" -> Get key for Alice did") - thrift['alice_key_for_thrift'] = \ - await did.key_for_did(thrift['pool'], thrift['wallet'], thrift['alice_connection_response']['did']) - - logger.info("\"Thrift\" -> Authcrypt \"Loan-Application-Basic\" Proof Request for Alice") - thrift['authcrypted_apply_loan_proof_request'] = \ - await crypto.auth_crypt(thrift['wallet'], thrift['key_for_alice'], thrift['alice_key_for_thrift'], - thrift['apply_loan_proof_request'].encode('utf-8')) - - logger.info("\"Thrift\" -> Send authcrypted \"Loan-Application-Basic\" Proof Request to Alice") - alice['authcrypted_apply_loan_proof_request'] = thrift['authcrypted_apply_loan_proof_request'] - - logger.info("\"Alice\" -> Authdecrypt \"Loan-Application-Basic\" Proof Request from Thrift") - alice['thrift_key_for_alice'], alice['apply_loan_proof_request'], _ = \ - await auth_decrypt(alice['wallet'], alice['key_for_thrift'], alice['authcrypted_apply_loan_proof_request']) - - logger.info("\"Alice\" -> Get credentials for \"Loan-Application-Basic\" Proof Request") - - search_for_apply_loan_proof_request = \ - await anoncreds.prover_search_credentials_for_proof_req(alice['wallet'], - alice['apply_loan_proof_request'], None) - - cred_for_attr1 = await get_credential_for_referent(search_for_apply_loan_proof_request, 'attr1_referent') - cred_for_predicate1 = await get_credential_for_referent(search_for_apply_loan_proof_request, 'predicate1_referent') - cred_for_predicate2 = await get_credential_for_referent(search_for_apply_loan_proof_request, 'predicate2_referent') - - await anoncreds.prover_close_credentials_search_for_proof_req(search_for_apply_loan_proof_request) - - alice['creds_for_apply_loan_proof'] = {cred_for_attr1['referent']: cred_for_attr1, - cred_for_predicate1['referent']: cred_for_predicate1, - cred_for_predicate2['referent']: cred_for_predicate2} - - alice['schemas'], alice['cred_defs'], alice['revoc_states'] = \ - await prover_get_entities_from_ledger(alice['pool'], alice['did_for_thrift'], - alice['creds_for_apply_loan_proof'], - alice['name']) - - logger.info("\"Alice\" -> Create \"Loan-Application-Basic\" Proof") - alice['apply_loan_requested_creds'] = json.dumps({ - 'self_attested_attributes': {}, - 'requested_attributes': { - 'attr1_referent': {'cred_id': cred_for_attr1['referent'], 'revealed': True} - }, - 'requested_predicates': { - 'predicate1_referent': {'cred_id': cred_for_predicate1['referent']}, - 'predicate2_referent': {'cred_id': cred_for_predicate2['referent']} - } - }) - alice['apply_loan_proof'] = \ - await anoncreds.prover_create_proof(alice['wallet'], alice['apply_loan_proof_request'], - alice['apply_loan_requested_creds'], alice['master_secret_id'], - alice['schemas'], alice['cred_defs'], alice['revoc_states']) - - logger.info("\"Alice\" -> Authcrypt \"Loan-Application-Basic\" Proof for Thrift") - alice['authcrypted_alice_apply_loan_proof'] = \ - await crypto.auth_crypt(alice['wallet'], alice['key_for_thrift'], alice['thrift_key_for_alice'], - alice['apply_loan_proof'].encode('utf-8')) - - logger.info("\"Alice\" -> Send authcrypted \"Loan-Application-Basic\" Proof to Thrift") - thrift['authcrypted_alice_apply_loan_proof'] = alice['authcrypted_alice_apply_loan_proof'] - - logger.info("\"Thrift\" -> Authdecrypted \"Loan-Application-Basic\" Proof from Alice") - _, thrift['alice_apply_loan_proof'], authdecrypted_alice_apply_loan_proof = \ - await auth_decrypt(thrift['wallet'], thrift['key_for_alice'], thrift['authcrypted_alice_apply_loan_proof']) - - logger.info("\"Thrift\" -> Get Schemas, Credential Definitions and Revocation Registries from Ledger" - " required for Proof verifying") - - thrift['schemas'], thrift['cred_defs'], thrift['revoc_defs'], thrift['revoc_regs'] = \ - await verifier_get_entities_from_ledger(thrift['pool'], thrift['did'], - authdecrypted_alice_apply_loan_proof['identifiers'], thrift['name']) - - logger.info("\"Thrift\" -> Verify \"Loan-Application-Basic\" Proof from Alice") - assert 'Permanent' == \ - authdecrypted_alice_apply_loan_proof['requested_proof']['revealed_attrs']['attr1_referent']['raw'] - - assert await anoncreds.verifier_verify_proof(thrift['apply_loan_proof_request'], thrift['alice_apply_loan_proof'], - thrift['schemas'], thrift['cred_defs'], thrift['revoc_defs'], - thrift['revoc_regs']) - - logger.info("==============================") + }) + alice['apply_loan_proof'] = \ + await anoncreds.prover_create_proof(alice['wallet'], alice['apply_loan_proof_request'], + alice['apply_loan_requested_creds'], alice['master_secret_id'], + alice['schemas_for_loan_app'], alice['cred_defs_for_loan_app'], + alice['revoc_states_for_loan_app']) + + logger.info("\"Alice\" -> Authcrypt \"Loan-Application-Basic\" Proof for Thrift") + alice['authcrypted_alice_apply_loan_proof'] = \ + await crypto.auth_crypt(alice['wallet'], alice['key_for_thrift'], alice['thrift_key_for_alice'], + alice['apply_loan_proof'].encode('utf-8')) + + logger.info("\"Alice\" -> Send authcrypted \"Loan-Application-Basic\" Proof to Thrift") + thrift['authcrypted_alice_apply_loan_proof'] = alice['authcrypted_alice_apply_loan_proof'] + + logger.info("\"Thrift\" -> Authdecrypted \"Loan-Application-Basic\" Proof from Alice") + _, thrift['alice_apply_loan_proof'], authdecrypted_alice_apply_loan_proof = \ + await auth_decrypt(thrift['wallet'], thrift['key_for_alice'], thrift['authcrypted_alice_apply_loan_proof']) + + logger.info("\"Thrift\" -> Get Schemas, Credential Definitions and Revocation Registries from Ledger" + " required for Proof verifying") + + thrift['schemas_for_loan_app'], thrift['cred_defs_for_loan_app'], thrift['revoc_defs_for_loan_app'], \ + thrift['revoc_regs_for_loan_app'] = \ + await verifier_get_entities_from_ledger(thrift['pool'], thrift['did'], + authdecrypted_alice_apply_loan_proof['identifiers'], + thrift['name'], requested_timestamp) + + logger.info("\"Thrift\" -> Verify \"Loan-Application-Basic\" Proof from Alice") + assert 'Permanent' == \ + authdecrypted_alice_apply_loan_proof['requested_proof']['revealed_attrs']['attr1_referent']['raw'] + + await apply_loan_basic() + + assert await anoncreds.verifier_verify_proof(thrift['apply_loan_proof_request'], + thrift['alice_apply_loan_proof'], + thrift['schemas_for_loan_app'], + thrift['cred_defs_for_loan_app'], + thrift['revoc_defs_for_loan_app'], + thrift['revoc_regs_for_loan_app']) logger.info("==============================") logger.info("== Apply for the loan with Thrift - Transcript and Job-Certificate proving ==") @@ -749,18 +805,21 @@ async def run(): cred_for_attr2['referent']: cred_for_attr2, cred_for_attr3['referent']: cred_for_attr3} - alice['schemas'], alice['cred_defs'], alice['revoc_states'] = \ + alice['schemas_for_loan_kyc_app'], alice['cred_defs_for_loan_kyc_app'], alice['revoc_states_for_loan_kyc_app'] = \ await prover_get_entities_from_ledger(alice['pool'], alice['did_for_thrift'], - alice['creds_for_apply_loan_kyc_proof'], 'Alice') + alice['creds_for_apply_loan_kyc_proof'], alice['name'],) logger.info("\"Alice\" -> Create \"Loan-Application-KYC\" Proof") - + revoc_states_for_loan_app = json.loads(alice['revoc_states_for_loan_kyc_app']) + timestamp_for_attr1 = get_timestamp_for_attribute(cred_for_attr1, revoc_states_for_loan_app) + timestamp_for_attr2 = get_timestamp_for_attribute(cred_for_attr2, revoc_states_for_loan_app) + timestamp_for_attr3 = get_timestamp_for_attribute(cred_for_attr3, revoc_states_for_loan_app) alice['apply_loan_kyc_requested_creds'] = json.dumps({ 'self_attested_attributes': {}, 'requested_attributes': { - 'attr1_referent': {'cred_id': cred_for_attr1['referent'], 'revealed': True}, - 'attr2_referent': {'cred_id': cred_for_attr2['referent'], 'revealed': True}, - 'attr3_referent': {'cred_id': cred_for_attr3['referent'], 'revealed': True} + 'attr1_referent': {'cred_id': cred_for_attr1['referent'], 'revealed': True, 'timestamp': timestamp_for_attr1}, + 'attr2_referent': {'cred_id': cred_for_attr2['referent'], 'revealed': True, 'timestamp': timestamp_for_attr2}, + 'attr3_referent': {'cred_id': cred_for_attr3['referent'], 'revealed': True, 'timestamp': timestamp_for_attr3} }, 'requested_predicates': {} }) @@ -768,7 +827,8 @@ async def run(): alice['apply_loan_kyc_proof'] = \ await anoncreds.prover_create_proof(alice['wallet'], alice['apply_loan_kyc_proof_request'], alice['apply_loan_kyc_requested_creds'], alice['master_secret_id'], - alice['schemas'], alice['cred_defs'], alice['revoc_states']) + alice['schemas_for_loan_kyc_app'], alice['cred_defs_for_loan_kyc_app'], + alice['revoc_states_for_loan_kyc_app']) logger.info("\"Alice\" -> Authcrypt \"Loan-Application-KYC\" Proof for Thrift") alice['authcrypted_alice_apply_loan_kyc_proof'] = \ @@ -785,9 +845,10 @@ async def run(): logger.info("\"Thrift\" -> Get Schemas, Credential Definitions and Revocation Registries from Ledger" " required for Proof verifying") - thrift['schemas'], thrift['cred_defs'], thrift['revoc_defs'], thrift['revoc_regs'] = \ + thrift['schemas_for_loan_kyc_app'], thrift['cred_defs_for_loan_kyc_app'], thrift['revoc_defs_for_loan_kyc_app'], \ + thrift['revoc_regs_for_loan_kyc_app'] = \ await verifier_get_entities_from_ledger(thrift['pool'], thrift['did'], - alice_apply_loan_kyc_proof['identifiers'], 'Thrift') + alice_apply_loan_kyc_proof['identifiers'], thrift['name']) logger.info("\"Thrift\" -> Verify \"Loan-Application-KYC\" Proof from Alice") assert 'Alice' == \ @@ -799,8 +860,43 @@ async def run(): assert await anoncreds.verifier_verify_proof(thrift['apply_loan_kyc_proof_request'], thrift['alice_apply_loan_kyc_proof'], - thrift['schemas'], thrift['cred_defs'], thrift['revoc_defs'], - thrift['revoc_regs']) + thrift['schemas_for_loan_kyc_app'], thrift['cred_defs_for_loan_kyc_app'], + thrift['revoc_defs_for_loan_kyc_app'], + thrift['revoc_regs_for_loan_kyc_app']) + + logger.info("==============================") + + logger.info("==============================") + logger.info("== Credential revocation - Acme revokes Alice's Job-Certificate ==") + logger.info("------------------------------") + + logger.info("\"Acme\" - Revoke credential") + acme['alice_cert_rev_reg_delta'] = \ + await anoncreds.issuer_revoke_credential(acme['wallet'], + acme['blob_storage_reader_cfg_handle'], + acme['revoc_reg_id'], + acme['job_certificate_cred_rev_id']) + + logger.info("\"Acme\" - Post RevocationRegistryDelta to Ledger") + acme['revoc_reg_entry_req'] = \ + await ledger.build_revoc_reg_entry_request(acme['did'], acme['revoc_reg_id'], 'CL_ACCUM', + acme['alice_cert_rev_reg_delta']) + await ledger.sign_and_submit_request(acme['pool'], acme['wallet'], acme['did'], acme['revoc_reg_entry_req']) + + logger.info("==============================") + + logger.info("==============================") + logger.info("== Apply for the loan with Thrift again - Job-Certificate proving ==") + logger.info("------------------------------") + + await apply_loan_basic() + + assert not await anoncreds.verifier_verify_proof(thrift['apply_loan_proof_request'], + thrift['alice_apply_loan_proof'], + thrift['schemas_for_loan_app'], + thrift['cred_defs_for_loan_app'], + thrift['revoc_defs_for_loan_app'], + thrift['revoc_regs_for_loan_app']) logger.info("==============================") @@ -890,6 +986,7 @@ async def onboarding(_from, to): return from_to_did, from_to_key, to_from_did, to_from_key, _from['connection_response'] + def wallet_config(operation, wallet_config_str): if not args.storage_type: return wallet_config_str @@ -900,6 +997,7 @@ def wallet_config(operation, wallet_config_str): #print(operation, json.dumps(wallet_config_json)) return json.dumps(wallet_config_json) + def wallet_credentials(operation, wallet_credentials_str): if not args.storage_type: return wallet_credentials_str @@ -909,6 +1007,7 @@ def wallet_credentials(operation, wallet_credentials_str): #print(operation, json.dumps(wallet_credentials_json)) return json.dumps(wallet_credentials_json) + async def get_verinym(_from, from_to_did, from_to_key, to, to_from_did, to_from_key): logger.info("\"{}\" -> Create and store in Wallet \"{}\" new DID".format(to['name'], to['name'])) (to_did, to_key) = await did.create_and_store_my_did(to['wallet'], "{}") @@ -971,7 +1070,14 @@ async def get_credential_for_referent(search_handle, referent): return credentials[0]['cred_info'] -async def prover_get_entities_from_ledger(pool_handle, _did, identifiers, actor): +def get_timestamp_for_attribute(cred_for_attribute, revoc_states): + if cred_for_attribute['rev_reg_id'] in revoc_states: + return int(next(iter(revoc_states[cred_for_attribute['rev_reg_id']]))) + else: + return None + + +async def prover_get_entities_from_ledger(pool_handle, _did, identifiers, actor, timestamp_from=None, timestamp_to=None): schemas = {} cred_defs = {} rev_states = {} @@ -984,13 +1090,38 @@ async def prover_get_entities_from_ledger(pool_handle, _did, identifiers, actor) (received_cred_def_id, received_cred_def) = await get_cred_def(pool_handle, _did, item['cred_def_id']) cred_defs[received_cred_def_id] = json.loads(received_cred_def) - if 'rev_reg_seq_no' in item: - pass # TODO Create Revocation States + if 'rev_reg_id' in item and item['rev_reg_id'] is not None: + # Create Revocations States + logger.info("\"{}\" -> Get Revocation Registry Definition from Ledger".format(actor)) + get_revoc_reg_def_request = await ledger.build_get_revoc_reg_def_request(_did, item['rev_reg_id']) + + get_revoc_reg_def_response = await ledger.submit_request(pool_handle, get_revoc_reg_def_request) + (rev_reg_id, revoc_reg_def_json) = await ledger.parse_get_revoc_reg_def_response(get_revoc_reg_def_response) + + logger.info("\"{}\" -> Get Revocation Registry Delta from Ledger".format(actor)) + if not timestamp_to: timestamp_to = int(time.time()) + get_revoc_reg_delta_request = \ + await ledger.build_get_revoc_reg_delta_request(_did, item['rev_reg_id'], timestamp_from, timestamp_to) + get_revoc_reg_delta_response = \ + await ledger.submit_request(pool_handle, get_revoc_reg_delta_request) + (rev_reg_id, revoc_reg_delta_json, t) = \ + await ledger.parse_get_revoc_reg_delta_response(get_revoc_reg_delta_response) + + tails_reader_config = json.dumps( + {'base_dir': dirname(json.loads(revoc_reg_def_json)['value']['tailsLocation']), + 'uri_pattern': ''}) + blob_storage_reader_cfg_handle = await blob_storage.open_reader('default', tails_reader_config) + + logger.info('%s - Create Revocation State', actor) + rev_state_json = \ + await anoncreds.create_revocation_state(blob_storage_reader_cfg_handle, revoc_reg_def_json, + revoc_reg_delta_json, t, item['cred_rev_id']) + rev_states[rev_reg_id] = {t: json.loads(rev_state_json)} return json.dumps(schemas), json.dumps(cred_defs), json.dumps(rev_states) -async def verifier_get_entities_from_ledger(pool_handle, _did, identifiers, actor): +async def verifier_get_entities_from_ledger(pool_handle, _did, identifiers, actor, timestamp=None): schemas = {} cred_defs = {} rev_reg_defs = {} @@ -1004,8 +1135,23 @@ async def verifier_get_entities_from_ledger(pool_handle, _did, identifiers, acto (received_cred_def_id, received_cred_def) = await get_cred_def(pool_handle, _did, item['cred_def_id']) cred_defs[received_cred_def_id] = json.loads(received_cred_def) - if 'rev_reg_seq_no' in item: - pass # TODO Get Revocation Definitions and Revocation Registries + if 'rev_reg_id' in item and item['rev_reg_id'] is not None: + # Get Revocation Definitions and Revocation Registries + logger.info("\"{}\" -> Get Revocation Definition from Ledger".format(actor)) + get_revoc_reg_def_request = await ledger.build_get_revoc_reg_def_request(_did, item['rev_reg_id']) + + get_revoc_reg_def_response = await ledger.submit_request(pool_handle, get_revoc_reg_def_request) + (rev_reg_id, revoc_reg_def_json) = await ledger.parse_get_revoc_reg_def_response(get_revoc_reg_def_response) + + logger.info("\"{}\" -> Get Revocation Registry from Ledger".format(actor)) + if not timestamp: timestamp = item['timestamp'] + get_revoc_reg_request = \ + await ledger.build_get_revoc_reg_request(_did, item['rev_reg_id'], timestamp) + get_revoc_reg_response = await ledger.submit_request(pool_handle, get_revoc_reg_request) + (rev_reg_id, rev_reg_json, timestamp2) = await ledger.parse_get_revoc_reg_response(get_revoc_reg_response) + + rev_regs[rev_reg_id] = {timestamp2: json.loads(rev_reg_json)} + rev_reg_defs[rev_reg_id] = json.loads(revoc_reg_def_json) return json.dumps(schemas), json.dumps(cred_defs), json.dumps(rev_reg_defs), json.dumps(rev_regs) diff --git a/vcx/wrappers/ios/vcx/utils/NSError+VcxError.m b/vcx/wrappers/ios/vcx/utils/NSError+VcxError.m index 56095a76fb..9c41e81da4 100644 --- a/vcx/wrappers/ios/vcx/utils/NSError+VcxError.m +++ b/vcx/wrappers/ios/vcx/utils/NSError+VcxError.m @@ -4,6 +4,8 @@ // #import "NSError+VcxError.h" +#import "vcx.h" +#include "vcx.h" static NSString *const VcxErrorDomain = @"VcxErrorDomain"; @@ -13,23 +15,23 @@ + (NSError*) errorFromVcxError:(vcx_error_t) error { NSMutableDictionary *userInfo = [NSMutableDictionary new]; - // if (error != Success) { - // const char * error_json_p; - // indy_get_current_error(&error_json_p); - // - // NSString *errorDetailsJson = [NSString stringWithUTF8String:error_json_p]; - // - // NSError *error; - // NSDictionary *errorDetails = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:[errorDetailsJson UTF8String] - // length:[errorDetailsJson length]] - // options:kNilOptions - // error: &error]; - // - // [userInfo setValue:errorDetails[@"error"] forKey:@"sdk_message"]; - // [userInfo setValue:errorDetails[@"message"] forKey:@"sdk_full_message"]; - // [userInfo setValue:errorDetails[@"cause"] forKey:@"sdk_cause"]; - // [userInfo setValue:errorDetails[@"backtrace"] forKey:@"sdk_backtrace"]; - // } + if (error != Success) { + const char * error_json_p; + vcx_get_current_error(&error_json_p); + + NSString *errorDetailsJson = [NSString stringWithUTF8String:error_json_p]; + + NSError *error; + NSDictionary *errorDetails = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:[errorDetailsJson UTF8String] + length:[errorDetailsJson length]] + options:kNilOptions + error: &error]; + + [userInfo setValue:errorDetails[@"error"] forKey:@"sdk_message"]; + [userInfo setValue:errorDetails[@"message"] forKey:@"sdk_full_message"]; + [userInfo setValue:errorDetails[@"cause"] forKey:@"sdk_cause"]; + [userInfo setValue:errorDetails[@"backtrace"] forKey:@"sdk_backtrace"]; + } return [NSError errorWithDomain:VcxErrorDomain code: error userInfo:userInfo]; } diff --git a/vcx/wrappers/ios/vcx/vcx.framework/Headers/libvcx.h b/vcx/wrappers/ios/vcx/vcx.framework/Headers/libvcx.h index c4c44abc77..9774400399 100644 --- a/vcx/wrappers/ios/vcx/vcx.framework/Headers/libvcx.h +++ b/vcx/wrappers/ios/vcx/vcx.framework/Headers/libvcx.h @@ -68,7 +68,7 @@ vcx_error_t vcx_update_agent_info(vcx_command_handle_t handle, const char *info, const char *vcx_error_c_message(int); const char *vcx_version(); -vcx_error_t vcx_current_error(const char ** error_json_p); +vcx_error_t vcx_get_current_error(const char ** error_json_p); /** * Schema object diff --git a/vcx/wrappers/node/src/vcx.ts b/vcx/wrappers/node/src/vcx.ts index 55e53959ac..8f9aa39fce 100644 --- a/vcx/wrappers/node/src/vcx.ts +++ b/vcx/wrappers/node/src/vcx.ts @@ -1,4 +1,5 @@ import * as ffi from 'ffi' +import * as os from 'os' import * as path from 'path' import { FFIConfiguration, IFFIEntryPoint } from './rustlib' @@ -12,20 +13,28 @@ export interface IVCXRuntimeConfig { // VCXRuntimeConfg is a class that currently only contains a chosen basepath for the .so file // I made it a class just in case we think of more needed configs +const extension = {"darwin": ".dylib", "linux": ".so", "win32": ".dll"} +const libPath = {"darwin": "/usr/local/lib/", "linux": '/usr/lib/', "win32": 'c:\\windows\\system32\\'} + export class VCXRuntime { public readonly ffi: IFFIEntryPoint private _config: IVCXRuntimeConfig constructor (config: IVCXRuntimeConfig = {}) { this._config = config - // initialize FFI + // initialize FFI const libraryPath = this._initializeBasepath() this.ffi = ffi.Library(libraryPath, FFIConfiguration) } private _initializeBasepath = (): string => { - const library = 'libvcx.so' // TODO: FIXME provide better way to resolve library + const platform = os.platform() + // @ts-ignore + const postfix = extension[platform.toLowerCase()] || extension['linux'] + // @ts-ignore + const libDir = libPath[platform.toLowerCase()] || libPath['linux'] + const library = `libvcx${postfix}` const customPath = process.env.LIBVCX_PATH ? process.env.LIBVCX_PATH + library : undefined - return customPath || this._config.basepath || path.resolve(__dirname, '/usr/lib/' + library) + return customPath || this._config.basepath || path.resolve(__dirname, `${libDir}${library}`) } } diff --git a/wrappers/ios/libindy-pod/Indy/Wrapper/IndyLedger.h b/wrappers/ios/libindy-pod/Indy/Wrapper/IndyLedger.h index edafeaaf9f..9a2b09842e 100644 --- a/wrappers/ios/libindy-pod/Indy/Wrapper/IndyLedger.h +++ b/wrappers/ios/libindy-pod/Indy/Wrapper/IndyLedger.h @@ -596,6 +596,10 @@ 'auth_constraints': [, ] } + Default ledger auth rules: https://github.com/hyperledger/indy-node/blob/master/docs/source/auth_rules.md + + More about AUTH_RULE request: https://github.com/hyperledger/indy-node/blob/master/docs/source/requests.md#auth_rule + @param completion Callback that takes command result as parameter. Returns request result as json. */ + (void)buildAuthRuleRequestWithSubmitterDid:(NSString *)submitterDid diff --git a/wrappers/java/src/main/java/org/hyperledger/indy/sdk/ledger/Ledger.java b/wrappers/java/src/main/java/org/hyperledger/indy/sdk/ledger/Ledger.java index a2782e4212..0ff187e3ea 100644 --- a/wrappers/java/src/main/java/org/hyperledger/indy/sdk/ledger/Ledger.java +++ b/wrappers/java/src/main/java/org/hyperledger/indy/sdk/ledger/Ledger.java @@ -1290,7 +1290,11 @@ public static CompletableFuture getResponseMetadata( * 'constraint_id': "AND" or "OR" * 'auth_constraints': [[constraint_1], [constraint_2]] * } - + * + * Default ledger auth rules: https://github.com/hyperledger/indy-node/blob/master/docs/source/auth_rules.md + * + * More about AUTH_RULE request: https://github.com/hyperledger/indy-node/blob/master/docs/source/requests.md#auth_rule + * * @return A future resolving to a request result as json. * @throws IndyException Thrown if an error occurs when calling the underlying SDK. */ diff --git a/wrappers/nodejs/README.md b/wrappers/nodejs/README.md index be942cb166..4c5cdfb010 100644 --- a/wrappers/nodejs/README.md +++ b/wrappers/nodejs/README.md @@ -1776,6 +1776,11 @@ can be combined by 'auth_constraints': [, ] } ``` + +Default ledger auth rules: https://github.com/hyperledger/indy-node/blob/master/docs/source/auth_rules.md + +More about AUTH_RULE request: https://github.com/hyperledger/indy-node/blob/master/docs/source/requests.md#auth_rule + * __->__ `request`: Json Errors: `Common*` diff --git a/wrappers/python/indy/ledger.py b/wrappers/python/indy/ledger.py index 8928d47bd9..d692192462 100644 --- a/wrappers/python/indy/ledger.py +++ b/wrappers/python/indy/ledger.py @@ -1295,6 +1295,10 @@ async def build_auth_rule_request(submitter_did: str, 'auth_constraints': [, ] } + Default ledger auth rules: https://github.com/hyperledger/indy-node/blob/master/docs/source/auth_rules.md + + More about AUTH_RULE request: https://github.com/hyperledger/indy-node/blob/master/docs/source/requests.md#auth_rule + :return: Request result as json. """