diff --git a/.prettierrc.js b/.prettierrc.js index 5c4de1a..0c73287 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -1,6 +1,7 @@ module.exports = { - bracketSpacing: false, + bracketSpacing: true, jsxBracketSameLine: true, singleQuote: true, trailingComma: 'all', + semi: false, }; diff --git a/android/src/main/java/com/arnimasdk/ArnimaSdk.java b/android/src/main/java/com/arnimasdk/ArnimaSdk.java index 2ba86f2..188c65e 100644 --- a/android/src/main/java/com/arnimasdk/ArnimaSdk.java +++ b/android/src/main/java/com/arnimasdk/ArnimaSdk.java @@ -50,10 +50,10 @@ public class ArnimaSdk extends ReactContextBaseJavaModule { - private final ReactApplicationContext reactContext; public static final int PROTOCOL_VERSION = 2; + private final ReactApplicationContext reactContext; private final Map walletMap; - private Map credentialSearchMap; + private final Map credentialSearchMap; private int credentialSearchIterator = 0; public ArnimaSdk(ReactApplicationContext reactContext) { @@ -126,7 +126,6 @@ protected void onPreExecute() { } } - @ReactMethod public void openInitWallet(String walletConfig, String walletCredentials, Promise promise) { Wallet wallet = null; @@ -162,6 +161,19 @@ public Wallet openWallet(String walletConfig, String walletCredentials, Promise } } + @ReactMethod + public Wallet getWalletHandle(Promise promise) { + Wallet wallet = null; + try { + wallet = walletMap.get(1); + } catch (Exception e) { + IndySdkRejectResponse rejectResponse = new IndySdkRejectResponse(e); + promise.reject(rejectResponse.getCode(), rejectResponse.toJson(), e); + } finally { + return wallet; + } + } + public Pool openPoolLedger(String poolName, String poolConfig, Promise promise) { Pool pool = null; try { @@ -173,6 +185,7 @@ public Pool openPoolLedger(String poolName, String poolConfig, Promise promise) return null; } } + public void closePoolLedger(Pool pool) { try { pool.closePoolLedger().get(); @@ -187,10 +200,10 @@ public void closePoolLedger(Pool pool) { @ReactMethod public void createAndStoreMyDid(String walletConfig, String walletCredentials, String didJson, - Boolean createMasterSecret, Promise promise) { + Boolean createMasterSecret, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = openWallet(walletConfig, walletCredentials ,promise); if (wallet != null) { DidResults.CreateAndStoreMyDidResult createMyDidResult = Did .createAndStoreMyDid(wallet, didJson).get(); @@ -200,7 +213,7 @@ public void createAndStoreMyDid(String walletConfig, String walletCredentials, S JSONObject config = new JSONObject(walletConfig); response.pushString(myDid); response.pushString(myVerkey); - if ((Boolean) createMasterSecret) { + if (createMasterSecret) { String outputMasterSecretId = Anoncreds .proverCreateMasterSecret(wallet, config.get("id").toString()).get(); response.pushString(outputMasterSecretId); @@ -214,11 +227,11 @@ public void createAndStoreMyDid(String walletConfig, String walletCredentials, S } @ReactMethod - public void addWalletRecord(String walletConfig, String walletCredentials, String recordType, String id, String value, String tags, + public void addWalletRecord(String recordType, String id, String value, String tags, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { WalletRecord.add(wallet, recordType, id, value, tags).get(); promise.resolve("true"); @@ -230,17 +243,17 @@ public void addWalletRecord(String walletConfig, String walletCredentials, Strin } @ReactMethod - public void updateWalletRecord(String walletConfig, String walletCredentials, String recordType, String id, String value, String tags, + public void updateWalletRecord(String recordType, String id, String value, String tags, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { WalletRecord.updateValue(wallet, recordType, id, value) .get(); if (!tags.equalsIgnoreCase("{}")) { - WalletRecord.updateTags(wallet, recordType, id,tags); + WalletRecord.updateTags(wallet, recordType, id, tags); } promise.resolve("true"); } @@ -251,11 +264,11 @@ public void updateWalletRecord(String walletConfig, String walletCredentials, St } @ReactMethod - public void deleteWalletRecord(String walletConfig, String walletCredentials, String recordType, String id, + public void deleteWalletRecord(String recordType, String id, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { WalletRecord.delete(wallet, recordType, id) .get(); @@ -268,11 +281,11 @@ public void deleteWalletRecord(String walletConfig, String walletCredentials, St } @ReactMethod - public void getWalletRecordFromQuery(String walletConfig, String walletCredentials, String recordType, String query, - Promise promise) { + public void getWalletRecordFromQuery(String recordType, String query, + Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { WalletSearch search = WalletSearch.open(wallet, recordType, query, "{\"retrieveTags\":true,\"retrieveType \":true, \"retrieveType\": true }") .get(); @@ -287,15 +300,15 @@ public void getWalletRecordFromQuery(String walletConfig, String walletCredentia } @ReactMethod - public void packMessage(String walletConfig, String walletCredentials, ReadableArray message, + public void packMessage(ReadableArray message, ReadableArray receiverKeyArray, String senderVk, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { - byte[] buffer = readableArrayToBuffer((ReadableArray) message); + byte[] buffer = readableArrayToBuffer(message); - ReadableArray receiverKeys = (ReadableArray) receiverKeyArray; + ReadableArray receiverKeys = receiverKeyArray; String[] keys = new String[receiverKeys.size()]; for (int i = 0; i < receiverKeys.size(); i++) { keys[i] = receiverKeys.getString(i); @@ -318,10 +331,10 @@ public void packMessage(String walletConfig, String walletCredentials, ReadableA } @ReactMethod - public void unpackMessage(String walletConfig, String walletCredentials, ReadableArray jwe, Promise promise) { + public void unpackMessage(ReadableArray jwe, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { byte[] buffer = readableArrayToBuffer(jwe); byte[] res = Crypto.unpackMessage(wallet, buffer).get(); @@ -339,11 +352,11 @@ public void unpackMessage(String walletConfig, String walletCredentials, Readabl } @ReactMethod - public void cryptoSign(String walletConfig, String walletCredentials, String signerVk, ReadableArray messageRaw, + public void cryptoSign(String signerVk, ReadableArray messageRaw, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { byte[] messageBuf = readableArrayToBuffer(messageRaw); byte[] signature = Crypto.cryptoSign(wallet, signerVk, messageBuf).get(); @@ -360,11 +373,11 @@ public void cryptoSign(String walletConfig, String walletCredentials, String sig } @ReactMethod - public void cryptoVerify(String walletConfig, String walletCredentials, String signerVk, ReadableArray messageRaw, + public void cryptoVerify(String signerVk, ReadableArray messageRaw, ReadableArray signatureRaw, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { byte[] messageBuf = readableArrayToBuffer(messageRaw); byte[] sigBuf = readableArrayToBuffer(signatureRaw); @@ -378,11 +391,11 @@ public void cryptoVerify(String walletConfig, String walletCredentials, String s } @ReactMethod - public void proverCreateCredentialReq(String walletConfig, String walletCredentials, String proverDid, + public void proverCreateCredentialReq(String proverDid, String credentialOfferJson, String credentialDefJson, String masterSecret, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { AnoncredsResults.ProverCreateCredentialRequestResult credentialRequestResult = Anoncreds .proverCreateCredentialReq(wallet, proverDid, credentialOfferJson, @@ -400,14 +413,14 @@ public void proverCreateCredentialReq(String walletConfig, String walletCredenti } @ReactMethod - public void proverStoreCredential(String walletConfig, String walletCredentials, String credId, + public void proverStoreCredential(String credId, String credReqMetadataJson, String credJson, String credDefJson, String revRegDefJson, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { - String newCredId = Anoncreds.proverStoreCredential(wallet, credId, credReqMetadataJson, - credJson, credDefJson, revRegDefJson).get(); + String newCredId = Anoncreds.proverStoreCredential(wallet, credId, credReqMetadataJson, + credJson, credDefJson, revRegDefJson).get(); promise.resolve(newCredId); } } catch (Exception e) { @@ -467,10 +480,10 @@ public void verifierVerifyProof(String proofRequest, String proof, } @ReactMethod - public void proverGetCredentials(String walletConfig, String walletCredentials, String filter, Promise promise) { + public void proverGetCredentials(String filter, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { String credentials = Anoncreds.proverGetCredentials(wallet, filter).get(); promise.resolve(credentials); @@ -482,10 +495,10 @@ public void proverGetCredentials(String walletConfig, String walletCredentials, } @ReactMethod - public void proverGetCredential(String walletConfig, String walletCredentials, String credId, Promise promise) { + public void proverGetCredential(String credId, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { String credential = Anoncreds.proverGetCredential(wallet, credId).get(); promise.resolve(credential); @@ -503,7 +516,7 @@ public void getCredDef(String submitterDid, String id, String poolName, String p String credDefRequest = Ledger.buildGetCredDefRequest(submitterDid, id).get(); pool = openPoolLedger(poolName, poolConfig, promise); if (pool != null) { - String credDefResponse = Ledger.submitRequest(pool, credDefRequest).get(); + String credDefResponse = Ledger.submitRequest(pool, credDefRequest).get(); LedgerResults.ParseResponseResult responseResult = Ledger.parseGetCredDefResponse(credDefResponse).get(); promise.resolve(responseResult.getObjectJson()); @@ -577,11 +590,11 @@ public void getSchemasJson(String poolName, String poolConfig, String submitterD } @ReactMethod - public void proverCreateProof(String walletConfig, String walletCredentials, String proofRequest, + public void proverCreateProof(String proofRequest, String requestedCredentials, String masterSecret, String schemas, String credentialDefs, String revocObject, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { String cred_proof = Anoncreds.proverCreateProof(wallet, proofRequest, String.valueOf(requestedCredentials), masterSecret, String.valueOf(schemas), @@ -753,10 +766,10 @@ public void createRevocationStateObject(String poolName, String poolConfig, Stri } @ReactMethod - public void exportWallet(String walletConfig, String walletCredentials, String config, Promise promise) { + public void exportWallet(String config, Promise promise) { Wallet wallet = null; try { - wallet = openWallet(walletConfig, walletCredentials, promise); + wallet = getWalletHandle(promise); if (wallet != null) { Wallet.exportWallet(wallet, config).get(); promise.resolve("true"); diff --git a/ios/RNArnimaSdk.m b/ios/RNArnimaSdk.m index e5fcbf8..aeee72a 100644 --- a/ios/RNArnimaSdk.m +++ b/ios/RNArnimaSdk.m @@ -47,6 +47,11 @@ -(void) openWallet: (NSString *)config } } +-(IndyHandle) getWalletHandle +{ + return WalletHandleNumber; +} + RCT_EXPORT_METHOD(getRequestRedirectionUrl:(NSString *)url resolver: (RCTPromiseResolveBlock) resolve rejecter: (RCTPromiseRejectBlock) reject) @@ -94,16 +99,15 @@ -(void) openWallet: (NSString *)config }]; } -RCT_EXPORT_METHOD(exportWallet: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(exportWallet :(NSString *)config resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { - if (walletHandle > 0) { - [[IndyWallet sharedInstance] exportWalletWithHandle:walletHandle exportConfigJson:config completion:^(NSError *errorWhileExportWallet) { + IndyHandle wallet = [self getWalletHandle]; + + if (wallet > 0) { + [[IndyWallet sharedInstance] exportWalletWithHandle:wallet exportConfigJson:config completion:^(NSError *errorWhileExportWallet) { if(errorWhileExportWallet.code > 1) { [self rejectResult:errorWhileExportWallet reject:reject]; } @@ -112,7 +116,6 @@ -(void) openWallet: (NSString *)config } }]; } - }]; } RCT_EXPORT_METHOD(importWallet: @@ -231,17 +234,15 @@ -(void) openWallet: (NSString *)config }]; } -RCT_EXPORT_METHOD(addWalletRecord: - (NSString *)walletConfig - :(NSString *)walletCredentials - :(NSString *)Type +RCT_EXPORT_METHOD(addWalletRecord:(NSString *)Type :(NSString *)Id :(NSString *)value :(NSString *)tags resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyNonSecrets addRecordInWallet:walletHandle type:Type id:Id value:value tagsJson:tags completion:^(NSError *errorWhileAddRecord) { if(errorWhileAddRecord.code > 1) { @@ -252,22 +253,16 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; } -RCT_EXPORT_METHOD(updateWalletRecord: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(updateWalletRecord :(NSString *)type :(NSString *)Id :(NSString *)value :(NSString *)tag resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - - - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; if (walletHandle > 0) { [IndyNonSecrets updateRecordValueInWallet:walletHandle type:type id:Id value:value completion:^(NSError *errorWhileUpdateRecordValue) { if(errorWhileUpdateRecordValue.code > 1) { @@ -290,19 +285,17 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; + } -RCT_EXPORT_METHOD(deleteWalletRecord: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(deleteWalletRecord :(NSString *)type :(NSString *)Id resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject){ - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyNonSecrets deleteRecordInWallet:walletHandle type:type id:Id completion:^(NSError *errorWhileDeleteREcord) { if(errorWhileDeleteREcord.code > 1) { @@ -313,21 +306,17 @@ -(void) openWallet: (NSString *)config } }]; } - }]; - - } -RCT_EXPORT_METHOD(getWalletRecordFromQuery: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(getWalletRecordFromQuery :(NSString *)type :(NSString *)query resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyNonSecrets openSearchInWallet:walletHandle type:type queryJson:query optionsJson:@"{\"retrieveTags\":true,\"retrieveType \":true, \"retrieveType\": true }" completion:^(NSError *errorOS, IndyHandle searchHandle) { if(errorOS.code > 1) { @@ -345,20 +334,16 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; - } -RCT_EXPORT_METHOD(cryptoSign: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(cryptoSign :(NSString *)signerKey :(NSString *)messageRaw resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { NSData *jsonData = [messageRaw dataUsingEncoding:NSUTF8StringEncoding]; [IndyCrypto signMessage:jsonData key:signerKey walletHandle:walletHandle completion:^(NSError *errorWhileSignMessage, NSData *signature) { @@ -381,20 +366,16 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; - } -RCT_EXPORT_METHOD(packMessage: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(packMessage :(NSString *)message :(NSArray *)receiverKeys :(NSString *)senderVerkey resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyCrypto createKey:@"{}" walletHandle:walletHandle completion:^(NSError *errorWhileCreateKey, NSString *verkey1) { if(errorWhileCreateKey.code > 1) { @@ -419,19 +400,15 @@ -(void) openWallet: (NSString *)config } }]; } - }]; - - } -RCT_EXPORT_METHOD(unpackMessage: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(unpackMessage :(NSString *)message resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding]; [IndyCrypto unpackMessage:messageData walletHandle:walletHandle completion:^(NSError *errorWhileUnpackMessage, NSData *unPackMessageData) { @@ -444,15 +421,9 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; - - } -RCT_EXPORT_METHOD(cryptoVerify: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(cryptoVerify :(NSString *)signVerkey :(NSString *)message :(NSString *)signatureRaw @@ -460,7 +431,8 @@ -(void) openWallet: (NSString *)config reject:(RCTPromiseRejectBlock)reject) { NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding]; - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { NSData *revocRegDefJsonData = [signatureRaw dataUsingEncoding:NSUTF8StringEncoding]; id generatedRevocRegDefJsonData = [NSJSONSerialization JSONObjectWithData:revocRegDefJsonData options:0 error:nil]; @@ -494,8 +466,6 @@ -(void) openWallet: (NSString *)config } }]; } - - }]; } RCT_EXPORT_METHOD(createPoolLedgerConfig: @@ -537,9 +507,7 @@ -(void) openWallet: (NSString *)config -RCT_EXPORT_METHOD(proverCreateCredentialReq: - (NSString *)walletConfig - :(NSString *)credentialsJson +RCT_EXPORT_METHOD(proverCreateCredentialReq :(NSString *)proverDid :(NSString *)credentialOfferJson :(NSString *)credentialDefJson @@ -547,7 +515,8 @@ -(void) openWallet: (NSString *)config resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :credentialsJson completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyAnoncreds proverCreateCredentialReqForCredentialOffer:credentialOfferJson credentialDefJSON:credentialDefJson proverDID:proverDid masterSecretID:masterSecretId walletHandle:walletHandle completion:^(NSError *errorWhileCreateRequest, NSString *credReqJSON, NSString *credReqMetadataJSON) { if(errorWhileCreateRequest.code > 1) { @@ -561,12 +530,9 @@ -(void) openWallet: (NSString *)config } }]; } - }]; } -RCT_EXPORT_METHOD(proverStoreCredential: - (NSString *)walletConfig - :(NSString *)credentialsJson +RCT_EXPORT_METHOD(proverStoreCredential :(NSString *)credId :(NSString *)credReqMetadataJson :(NSString *)credJson @@ -574,7 +540,8 @@ -(void) openWallet: (NSString *)config :(NSString *)revRegDefJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject){ - [self openWallet:walletConfig :credentialsJson completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyAnoncreds proverStoreCredential:credJson credID:credId credReqMetadataJSON:credReqMetadataJson credDefJSON:credDefJson revRegDefJSON:revRegDefJson walletHandle:walletHandle completion:^(NSError *errorWhileStoreCredential, NSString *outCredID) { if(errorWhileStoreCredential.code > 1) { @@ -585,16 +552,14 @@ -(void) openWallet: (NSString *)config } }]; } - }]; } -RCT_EXPORT_METHOD(proverGetCredentials: - (NSString *)walletConfig - :(NSString *)credentialsJson +RCT_EXPORT_METHOD(proverGetCredentials :(NSString *)filter resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject){ - [self openWallet:walletConfig :credentialsJson completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyAnoncreds proverGetCredentialsForFilter:filter walletHandle:walletHandle completion:^(NSError *errorWhileGetCredential, NSString *credentialsJSON) { if(errorWhileGetCredential.code > 1) { @@ -605,8 +570,6 @@ -(void) openWallet: (NSString *)config } }]; } - }]; - } RCT_EXPORT_METHOD(getRevocRegDef: @@ -882,13 +845,12 @@ -(void) openWallet: (NSString *)config } RCT_EXPORT_METHOD(proverGetCredential - :(NSString *) walletConfig - :(NSString *) walletCredentials :(NSString *) credId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; + if (walletHandle > 0) { [IndyAnoncreds proverGetCredentialWithId:credId walletHandle:walletHandle completion:^(NSError *error, NSString *credentialJSON) { if(error.code > 1) { @@ -899,8 +861,6 @@ -(void) openWallet: (NSString *)config } }]; } - }]; - } RCT_EXPORT_METHOD(getSchemasJson @@ -1279,9 +1239,7 @@ -(void) openWallet: (NSString *)config } -RCT_EXPORT_METHOD(proverCreateProof: - (NSString *)walletConfig - :(NSString *)walletCredentials +RCT_EXPORT_METHOD(proverCreateProof :(NSString *)proofRequest :(NSString *)requestedCredentials :(NSString *)masterSecret @@ -1291,7 +1249,7 @@ -(void) openWallet: (NSString *)config resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject){ - [self openWallet:walletConfig :walletCredentials completion:^(IndyHandle walletHandle) { + IndyHandle walletHandle = [self getWalletHandle]; if (walletHandle > 0) { [IndyAnoncreds proverCreateProofForRequest:proofRequest requestedCredentialsJSON:requestedCredentials masterSecretID:masterSecret schemasJSON:schemas credentialDefsJSON:credentialDefs revocStatesJSON:revocObject walletHandle:walletHandle completion:^(NSError *errorWhileCreateProofRequest, NSString *proofJSON) { if(errorWhileCreateProofRequest.code > 1) { @@ -1299,12 +1257,9 @@ -(void) openWallet: (NSString *)config } else { resolve(proofJSON); - } }]; } - }]; - } @end diff --git a/src/agent/index.ts b/src/agent/index.ts index 0cbfdd2..7654ee5 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -3,182 +3,211 @@ SPDX-License-Identifier: Apache-2.0 */ - -import { decodeInvitationFromUrl, RecordType } from '../utils/Helpers'; -import { InboundMessage } from '../utils/Types'; -import { MessageType } from '../utils/MessageType'; -import { NativeModules } from 'react-native'; -import { WalletConfig, WalletCredentials } from '../wallet/WalletInterface'; -import BasicMessageService from '../protocols/basicMessage/BasicMessageService'; -import ConnectionService from '../protocols/connection/ConnectionService'; -import ConnectWithMediatorService from '../protocols/mediator/ConnectWithMediatorService'; -import CredentialService from '../protocols/credential/CredentialService'; -import DatabaseServices from '../storage'; -import InboundMessageService from '../transports'; -import PoolService from '../pool'; -import PresentationService from '../protocols/presentation/PresentationService'; -import WalletService from '../wallet/WalletService'; -import WalletStorageService from '../wallet/WalletStorageService'; - -const { ArnimaSdk } = NativeModules; +import { decodeInvitationFromUrl, RecordType } from '../utils/Helpers' +import { InboundMessage } from '../utils/Types' +import { MessageType } from '../utils/MessageType' +import { NativeModules } from 'react-native' +import { WalletConfig, WalletCredentials } from '../wallet/WalletInterface' +import BasicMessageService from '../protocols/basicMessage/BasicMessageService' +import ConnectionService from '../protocols/connection/ConnectionService' +import ConnectWithMediatorService from '../protocols/mediator/ConnectWithMediatorService' +import CredentialService from '../protocols/credential/CredentialService' +import DatabaseServices from '../storage' +import InboundMessageService from '../transports' +import PoolService from '../pool' +import PresentationService from '../protocols/presentation/PresentationService' +import WalletService from '../wallet/WalletService' +import WalletStorageService from '../wallet/WalletStorageService' + +const { ArnimaSdk } = NativeModules class Agent { - wallet: any = DatabaseServices.getWallet(); + wallet: any = DatabaseServices.getWallet() getRequestRedirectionUrl = async (url: string) => { return await ArnimaSdk.getRequestRedirectionUrl(url) } - createWallet = async (config: WalletConfig, credentials: WalletCredentials, label: string) => { + createWallet = async ( + config: WalletConfig, + credentials: WalletCredentials, + label: string, + ) => { try { - return await WalletService.createWallet(config, credentials, label); + return await WalletService.createWallet(config, credentials, label) } catch (error) { - console.log("Agent - Create wallet error= ", error); - throw error; + console.log('Agent - Create wallet error= ', error) + throw error } } - connectWithMediator = async (url: string, apiType: string, apiBody: string) => { + connectWithMediator = async ( + url: string, + apiType: string, + apiBody: string, + ) => { try { - const response = await ConnectWithMediatorService.ConnectWithMediator(url, apiType, apiBody); - this.wallet = await DatabaseServices.getWallet(); - return response; - } - catch (error) { - console.log("Agent - Connect with mediator error = ", error); - throw error; + const response = await ConnectWithMediatorService.ConnectWithMediator( + url, + apiType, + apiBody, + ) + this.wallet = await DatabaseServices.getWallet() + return response + } catch (error) { + console.log('Agent - Connect with mediator error = ', error) + throw error } } updateMediator = async (url: string, apiType: string, apiBody: string) => { try { - return await ConnectWithMediatorService.updateMediator(url, apiType, apiBody); - } - catch (error) { - console.log("Agent - Update mediator error = ", error); - throw error; + return await ConnectWithMediatorService.updateMediator( + url, + apiType, + apiBody, + ) + } catch (error) { + console.log('Agent - Update mediator error = ', error) + throw error } } getWallet = async () => { try { - return await WalletService.getWallet(); + return await WalletService.getWallet() } catch (error) { - console.log('Agent - Get wallet error = ', error); - throw error; + console.log('Agent - Get wallet error = ', error) + throw error } - } openWallet = async () => { try { - return await WalletService.openWallet(); + return await WalletService.openWallet() } catch (error) { - console.log("Agent - Open wallet error = ", error); - throw error; + console.log('Agent - Open wallet error = ', error) + throw error } - }; + } getAllPool = async () => { try { - return await PoolService.getAllPool(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials)); + return await PoolService.getAllPool() } catch (error) { - console.log("Agent - Get all pool error = ", error); - throw error; + console.log('Agent - Get all pool error = ', error) + throw error } - }; + } - createPool = async (poolName: string, poolConfig: string, defaultPool?: boolean) => { + createPool = async ( + poolName: string, + poolConfig: string, + defaultPool?: boolean, + ) => { try { - return await PoolService.createPool(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), poolName, poolConfig, defaultPool); + return await PoolService.createPool(poolName, poolConfig, defaultPool) } catch (error) { - console.log("Agent - Create pool error = ", error); - throw error; + console.log('Agent - Create pool error = ', error) + throw error } - }; + } selectDefaultPool = async (poolName: string) => { try { - return await PoolService.selectDefaultPool(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), poolName) + return await PoolService.selectDefaultPool(poolName) } catch (error) { - console.log("Agent - Select default pool error = ", error); - throw error; + console.log('Agent - Select default pool error = ', error) + throw error } - }; + } createInvitation = async (didJson: Object, logo: string) => { try { - return await ConnectionService.createInvitation(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), didJson, logo); + return await ConnectionService.createInvitation(didJson, logo) } catch (error) { - console.log("Agent - Create invitation error = ", error); - throw error; + console.log('Agent - Create invitation error = ', error) + throw error } } - acceptInvitation = async (didJson: Object, message: any, logo: string,) => { + acceptInvitation = async (didJson: Object, message: any, logo: string) => { try { - const invitation = decodeInvitationFromUrl(message); - return await ConnectionService.acceptInvitation(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), didJson, invitation, logo); - } - catch (error) { - console.log("Agent - Accept invitation error = ", error); - throw error; + const invitation = decodeInvitationFromUrl(message) + return await ConnectionService.acceptInvitation(didJson, invitation, logo) + } catch (error) { + console.log('Agent - Accept invitation error = ', error) + throw error } } getConnectionRecord = async (query: Object) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Connection, JSON.stringify(query)); - } - catch (error) { - console.log("Agent - Get all connections error = ", error); - throw error; + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Connection, + JSON.stringify(query), + ) + } catch (error) { + console.log('Agent - Get all connections error = ', error) + throw error } } getPresentationRecord = async (query: Object) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Presentation, JSON.stringify(query)); - } - catch (error) { - console.log("Agent - Get all connections error = ", error); - throw error; + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Presentation, + JSON.stringify(query), + ) + } catch (error) { + console.log('Agent - Get all connections error = ', error) + throw error } } basicMessageHistory = async (query: Object) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.BasicMessage, JSON.stringify(query)); - } - catch (error) { - console.log("Agent - Get all connections error = ", error); - throw error; + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.BasicMessage, + JSON.stringify(query), + ) + } catch (error) { + console.log('Agent - Get all connections error = ', error) + throw error } } deleteConnection = async (connectionId: string) => { try { - const records = await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Credential, JSON.stringify({ connectionId: connectionId })); + const records = await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Credential, + JSON.stringify({ connectionId: connectionId }), + ) if (records === null || records.length === 0) { - await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Connection, connectionId); - return true; + await WalletStorageService.deleteWalletRecord( + RecordType.Connection, + connectionId, + ) + return true } else { - return false; + return false } } catch (error) { - console.log('Agent - Delete connection error = ', error); - throw error; + console.log('Agent - Delete connection error = ', error) + throw error } } getAllActionMessages = async () => { try { const query = { autoProcessed: false } - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify(query)); - } - catch (error) { - console.log("Agent - Get all action messages error= ", error); - throw error; + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.SSIMessage, + JSON.stringify(query), + ) + } catch (error) { + console.log('Agent - Get all action messages error= ', error) + throw error } } @@ -188,185 +217,272 @@ class Agent { if (connectionId !== null) { query = { connectionId: connectionId } } - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Credential, JSON.stringify(query)); + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Credential, + JSON.stringify(query), + ) } catch (error) { - console.log('Agent - Get issue credential by connection id error = ', error); - throw error; + console.log( + 'Agent - Get issue credential by connection id error = ', + error, + ) + throw error } } getPresentationByConnectionId = async (connectionId: string) => { try { - return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Presentation, JSON.stringify({ connectionId: connectionId })); + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Presentation, + JSON.stringify({ connectionId: connectionId }), + ) } catch (error) { - console.log('Agent - Get presentation by connection id error = ', error); - throw error; + console.log('Agent - Get presentation by connection id error = ', error) + throw error } } getAllActionMessagesById = async (thId: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify({ thId: thId })); + return await WalletStorageService.getWalletRecordFromQuery( + RecordType.SSIMessage, + JSON.stringify({ thId: thId }), + ) } catch (error) { - console.log('Agent - Get all action messages by id error = ', error); - throw error; + console.log('Agent - Get all action messages by id error = ', error) + throw error } } getIssueCredentialByCredentialsId = async (referent: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Credential, JSON.stringify({ credentialsId: referent })); + return await WalletStorageService.getWalletRecordFromQuery( + RecordType.Credential, + JSON.stringify({ credentialsId: referent }), + ) } catch (error) { - console.log('Agent - Get all issue credential by credentials id error = ', error); - throw error; + console.log( + 'Agent - Get all issue credential by credentials id error = ', + error, + ) + throw error } } - sendCredentialProposal = async (connectionId: object, credentialProposal: string, schemaId: string, credDefId: string, issuerDid: string, comment: string) => { + sendCredentialProposal = async ( + connectionId: object, + credentialProposal: string, + schemaId: string, + credDefId: string, + issuerDid: string, + comment: string, + ) => { try { return await CredentialService.createProposal( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), connectionId, credentialProposal, schemaId, credDefId, issuerDid, - comment - ); + comment, + ) } catch (error) { - console.log('Agent - Send credential proposal error = ', error); - throw error; + console.log('Agent - Send credential proposal error = ', error) + throw error } } - acceptCredentialOffer = async (messageId: string, inboundMessage: InboundMessage) => { + acceptCredentialOffer = async ( + messageId: string, + inboundMessage: InboundMessage, + ) => { try { - let { message }: any = inboundMessage; - message = JSON.stringify(message); - inboundMessage['message'] = message; - const response: Boolean = await CredentialService.createRequest(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), inboundMessage); - if (response) await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, messageId); - return response; + let { message }: any = inboundMessage + message = JSON.stringify(message) + inboundMessage['message'] = message + const response: Boolean = await CredentialService.createRequest( + inboundMessage, + ) + if (response) + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + messageId, + ) + return response } catch (error) { - console.log('Agent - Accept credential offer error = ', error); - throw error; + console.log('Agent - Accept credential offer error = ', error) + throw error } } - storeCredential = async (messageId: string, inboundMessage: InboundMessage) => { + storeCredential = async ( + messageId: string, + inboundMessage: InboundMessage, + ) => { try { - let { message }: any = inboundMessage; - message = JSON.stringify(message); - inboundMessage['message'] = message; - const response: Boolean = await CredentialService.processCredential(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), inboundMessage); - if (response) await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, messageId); - return response; + let { message }: any = inboundMessage + message = JSON.stringify(message) + inboundMessage['message'] = message + const response: Boolean = await CredentialService.processCredential( + inboundMessage, + ) + if (response) + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + messageId, + ) + return response } catch (error) { - console.log('Agent - Store credential error = ', error); - throw error; + console.log('Agent - Store credential error = ', error) + throw error } } getAllCredential = async (filter?: Object) => { try { const getCredentials = await ArnimaSdk.proverGetCredentials( - this.wallet.walletConfig, - this.wallet.walletCredentials, - JSON.stringify(filter) - ); - return JSON.parse(getCredentials); + JSON.stringify(filter), + ) + return JSON.parse(getCredentials) } catch (error) { - console.log("Agent - List all credentials error = ", error); - throw error; + console.log('Agent - List all credentials error = ', error) + throw error } - }; + } sendBasicMessage = async (message: string, connectionId: string) => { try { - return await BasicMessageService.send(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), message, connectionId); + return await BasicMessageService.send(message, connectionId) } catch (error) { - console.log('Agent - Send message error = ', error); - throw error; + console.log('Agent - Send message error = ', error) + throw error } } - sendProposePresentation = async (connectionId: string, + sendProposePresentation = async ( + connectionId: string, presentationProposal: object, - comment: string + comment: string, ) => { try { - presentationProposal["@type"] = MessageType.presentationPreview; + presentationProposal['@type'] = MessageType.presentationPreview return await PresentationService.createProposal( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), connectionId, presentationProposal, - comment - ); + comment, + ) } catch (error) { - console.log('Agent - Send propose presentation error = ', error); - throw error; + console.log('Agent - Send propose presentation error = ', error) + throw error } } - sendOutOfBandProof = async (inboundMessage: InboundMessage, revealAttributes: boolean, presentationObj: object) => { + sendOutOfBandProof = async ( + inboundMessage: InboundMessage, + revealAttributes: boolean, + presentationObj: object, + ) => { try { - const response: Boolean = await PresentationService.createPresentation(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), inboundMessage, revealAttributes, presentationObj); - return response; + const response: Boolean = await PresentationService.createPresentation( + JSON.parse(this.wallet.walletConfig), + JSON.parse(this.wallet.walletCredentials), + inboundMessage, + revealAttributes, + presentationObj, + ) + return response } catch (error) { - console.log('Agent - Send proof error = ', error); - throw error; + console.log('Agent - Send proof error = ', error) + throw error } } - sendProof = async (messageId: string, inboundMessage: InboundMessage, revealAttributes: boolean, presentationObj: object) => { + sendProof = async ( + messageId: string, + inboundMessage: InboundMessage, + revealAttributes: boolean, + presentationObj: object, + ) => { try { - const response: Boolean = await PresentationService.createPresentation(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), inboundMessage, revealAttributes, presentationObj); - if (response) { await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, messageId) } - return response; + const response: Boolean = await PresentationService.createPresentation( + inboundMessage, + revealAttributes, + presentationObj, + ) + if (response) { + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + messageId, + ) + } + return response } catch (error) { - console.log('Agent - Send proof error = ', error); - throw error; + console.log('Agent - Send proof error = ', error) + throw error } } verifyProof = async (messageId: string, inboundMessage: InboundMessage) => { try { - let { message }: any = inboundMessage; - message = JSON.stringify(message); - inboundMessage['message'] = message; - const response = await PresentationService.verifyProof(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), messageId, inboundMessage); - await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, messageId) - return response; + let { message }: any = inboundMessage + message = JSON.stringify(message) + inboundMessage['message'] = message + const response = await PresentationService.verifyProof( + messageId, + inboundMessage, + ) + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + messageId, + ) + return response } catch (error) { - console.log('Agent - Verify proof error = ', error); - throw error; + console.log('Agent - Verify proof error = ', error) + throw error } } - sendPresentProofRequest = async (connectionId: string, proofRequest: object, comment: string) => { + sendPresentProofRequest = async ( + connectionId: string, + proofRequest: object, + comment: string, + ) => { try { - return await PresentationService.createRequest(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), connectionId, proofRequest, comment); + return await PresentationService.createRequest( + connectionId, + proofRequest, + comment, + ) } catch (error) { - console.log('Agent - Send present proof request error = ', error); - throw error; + console.log('Agent - Send present proof request error = ', error) + throw error } } getAllActionMessagesByMessageId = async (messageId: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify({ messageId: messageId })); + return await WalletStorageService.getWalletRecordFromQuery( + RecordType.SSIMessage, + JSON.stringify({ messageId: messageId }), + ) } catch (error) { - console.log('Agent - Get all action messages by message id error = ', error); - throw error; + console.log( + 'Agent - Get all action messages by message id error = ', + error, + ) + throw error } } getConnection = async (connectionId: string) => { try { - return await WalletStorageService.getWalletRecordFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Connection, JSON.stringify({ connectionId: connectionId })); + return await WalletStorageService.getWalletRecordFromQuery( + RecordType.Connection, + JSON.stringify({ connectionId: connectionId }), + ) } catch (error) { - console.log('Agent - Get Connection from connection id error = ', error); - throw error; + console.log('Agent - Get Connection from connection id error = ', error) + throw error } } @@ -378,40 +494,44 @@ class Agent { try { const config = { path: filePath, - key: key + key: key, } - const data = []; + const data = [] - await PoolService.deletePoolRecords(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials)); + await PoolService.deletePoolRecords() - const response = await ArnimaSdk.exportWallet( - this.wallet.walletConfig, - this.wallet.walletCredentials, - JSON.stringify(config), - ); + const response = await ArnimaSdk.exportWallet(JSON.stringify(config)) - return response; + return response } catch (error) { - console.log('Agent - Export wallet error = ', error); - throw error; + console.log('Agent - Export wallet error = ', error) + throw error } } - importWallet = async (config: WalletConfig, credentials: WalletCredentials, filePath: string, key: string) => { + importWallet = async ( + config: WalletConfig, + credentials: WalletCredentials, + filePath: string, + key: string, + ) => { try { const importConfig = { path: filePath, - key: key + key: key, } await ArnimaSdk.importWallet( JSON.stringify(config), JSON.stringify(credentials), JSON.stringify(importConfig), - JSON.stringify([]) - ); + JSON.stringify([]), + ) - const mediatorRecord = await WalletStorageService.getWalletRecordFromQuery(config, credentials, RecordType.MediatorAgent, '{}'); + const mediatorRecord = await WalletStorageService.getWalletRecordFromQuery( + RecordType.MediatorAgent, + '{}', + ) DatabaseServices.storeWallet({ walletConfig: JSON.stringify(config), @@ -422,21 +542,20 @@ class Agent { publicDid: mediatorRecord.publicDid, verKey: mediatorRecord.verKey, masterSecretId: mediatorRecord.masterSecretId, - }); + }) const record = { mediatorRecord, } - this.wallet = await DatabaseServices.getWallet(); + this.wallet = await DatabaseServices.getWallet() - return record; + return record } catch (error) { - console.log('Agent - Import wallet error = ', error); - throw error; + console.log('Agent - Import wallet error = ', error) + throw error } } - } -export default new Agent(); \ No newline at end of file +export default new Agent() diff --git a/src/core/index.ts b/src/core/index.ts index df830f5..ba0dcd4 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -3,10 +3,10 @@ SPDX-License-Identifier: Apache-2.0 */ -import AgentServices from '../agent'; +import AgentServices from '../agent' const ARNIMASDK = { ...AgentServices, } -export default ARNIMASDK; \ No newline at end of file +export default ARNIMASDK diff --git a/src/network/index.ts b/src/network/index.ts index 0bbcb2d..f58ab09 100644 --- a/src/network/index.ts +++ b/src/network/index.ts @@ -3,7 +3,11 @@ SPDX-License-Identifier: Apache-2.0 */ -export const NetworkServices: Function = async (url: string, apiType: string, apiBody: string) => { +export const NetworkServices: Function = async ( + url: string, + apiType: string, + apiBody: string, +) => { try { const response = await fetch(url, { method: apiType, @@ -12,23 +16,25 @@ export const NetworkServices: Function = async (url: string, apiType: string, ap Accept: 'application/json', 'Content-Type': 'application/json', }, - }); - const responseJson = await response.json(); + }) + const responseJson = await response.json() if (responseJson.hasOwnProperty('success')) { - return responseJson; + return responseJson } else { - throw responseJson; + throw responseJson } } catch (error) { - throw error; + throw error } -}; +} -export const OutboundAgentMessage: Function = async (url: string, apiType: string, apiBody: string) => { +export const OutboundAgentMessage: Function = async ( + url: string, + apiType: string, + apiBody: string, +) => { try { - return new Promise(async function ( - resolve, reject - ) { + return new Promise(async function(resolve, reject) { const response = await fetch(url, { method: apiType, body: apiBody, @@ -36,18 +42,22 @@ export const OutboundAgentMessage: Function = async (url: string, apiType: strin Accept: 'application/json', 'Content-Type': 'application/ssi-agent-wire', }, - }).then((response) => { - response.json() }) - .then((json) => { - resolve(json); + .then(response => { + response.json() }) - .catch((error) => { - reject('We are not able to communicate with the agent at this moment, Please try again later'); - }); - } - ) + .then(json => { + resolve(json) + }) + .catch(error => { + reject( + 'We are not able to communicate with the agent at this moment, Please try again later', + ) + }) + }) } catch (error) { - throw new Error('We are not able to communicate with the agent at this moment, Please try again later'); + throw new Error( + 'We are not able to communicate with the agent at this moment, Please try again later', + ) } -}; \ No newline at end of file +} diff --git a/src/pool/index.ts b/src/pool/index.ts index c7ab208..872d494 100644 --- a/src/pool/index.ts +++ b/src/pool/index.ts @@ -3,145 +3,145 @@ SPDX-License-Identifier: Apache-2.0 */ -import { NativeModules } from "react-native"; -import { Pool, PoolTags } from "./PoolInterface"; -import { Record, WalletConfig, WalletCredentials } from "../wallet/WalletInterface"; -import { RecordType } from "../utils/Helpers"; -import WalletStorageService from "../wallet/WalletStorageService"; +import { NativeModules } from 'react-native' +import { Pool, PoolTags } from './PoolInterface' +import { Record } from '../wallet/WalletInterface' +import { RecordType } from '../utils/Helpers' +import WalletStorageService from '../wallet/WalletStorageService' -const { ArnimaSdk } = NativeModules; +const { ArnimaSdk } = NativeModules class PoolService { - /** * Create pool genesis file and set default pool * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} poolName * @param {string} poolConfig * @param {boolean} [defaultPool=false] * @return {*} {Promise} * @memberof PoolService */ - async createPool(configJson: WalletConfig, credentialsJson: WalletCredentials, poolName: string, poolConfig: string, defaultPool: boolean = false): Promise { + async createPool( + poolName: string, + poolConfig: string, + defaultPool: boolean = false, + ): Promise { try { const response: null = await ArnimaSdk.createPoolLedgerConfig( poolName, - poolConfig - ); + poolConfig, + ) if (response === null || response === 'NULL') { const poolRecord: Pool = { poolName: poolName, - poolConfig: poolConfig + poolConfig: poolConfig, } const poolTags: PoolTags = { poolName: poolName, - isSelected: JSON.stringify(defaultPool) + isSelected: JSON.stringify(defaultPool), } await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Pool, poolName, JSON.stringify(poolRecord), - JSON.stringify(poolTags) - ); + JSON.stringify(poolTags), + ) } - return response; + return response } catch (error) { - console.log("Pool - Create pool error = ", error); - throw error; + console.log('Pool - Create pool error = ', error) + throw error } - }; + } /** * Return all the create pool records * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @return {*} {Promise} * @memberof PoolService */ - async getAllPool(configJson: WalletConfig, credentialsJson: WalletCredentials): Promise { + async getAllPool(): Promise { try { - return await WalletStorageService.getWalletRecordsFromQuery(configJson, credentialsJson, RecordType.Pool, '{}'); + return await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Pool, + '{}', + ) } catch (error) { - console.log("Pool - Get all pools error = ", error); - throw error; + console.log('Pool - Get all pools error = ', error) + throw error } } /** - * Update default select pool + * Update default select pool * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} poolName * @return {*} {Promise} * @memberof PoolService */ - async selectDefaultPool(configJson: WalletConfig, credentialsJson: WalletCredentials, poolName: string): Promise { + async selectDefaultPool(poolName: string): Promise { try { - const poolRecords: Array = await WalletStorageService.getWalletRecordsFromQuery(configJson, credentialsJson, RecordType.Pool, '{}'); + const poolRecords: Array< + Record + > = await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Pool, + '{}', + ) for await (let record of poolRecords) { - const pool: Pool = JSON.parse(record.value); + const pool: Pool = JSON.parse(record.value) const poolRecord: Pool = { poolName: pool.poolName, - poolConfig: pool.poolConfig + poolConfig: pool.poolConfig, } const poolTags: PoolTags = { poolName: pool.poolName, - isSelected: JSON.stringify(false) + isSelected: JSON.stringify(false), } if (pool.poolName === poolName) { poolTags.isSelected = JSON.stringify(true) } await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Pool, pool.poolName, JSON.stringify(poolRecord), - JSON.stringify(poolTags) - ); + JSON.stringify(poolTags), + ) } return true } catch (error) { - console.log("Pool - Select default pool error = ", error); - throw error; + console.log('Pool - Select default pool error = ', error) + throw error } } /** * Delete all pool records * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @return {*} {Promise} * @memberof PoolService */ - async deletePoolRecords(configJson: WalletConfig, credentialsJson: WalletCredentials): Promise { + async deletePoolRecords(): Promise { try { - const poolRecords: Array = await WalletStorageService.getWalletRecordsFromQuery(configJson, credentialsJson, RecordType.Pool, '{}'); + const poolRecords: Array< + Record + > = await WalletStorageService.getWalletRecordsFromQuery( + RecordType.Pool, + '{}', + ) for await (let record of poolRecords) { - const pool: Pool = JSON.parse(record.value); - + const pool: Pool = JSON.parse(record.value) await WalletStorageService.deleteWalletRecord( - configJson, - credentialsJson, RecordType.Pool, pool.poolName, - ); + ) } - return true; + return true } catch (error) { - console.log("Pool - Select default pool error = ", error); - throw error; + console.log('Pool - Select default pool error = ', error) + throw error } } - } -export default new PoolService(); \ No newline at end of file +export default new PoolService() diff --git a/src/protocols/basicMessage/BasicMessageMessages.ts b/src/protocols/basicMessage/BasicMessageMessages.ts index 8d0f290..d1caf1a 100644 --- a/src/protocols/basicMessage/BasicMessageMessages.ts +++ b/src/protocols/basicMessage/BasicMessageMessages.ts @@ -3,8 +3,8 @@ SPDX-License-Identifier: Apache-2.0 */ -import { MessageType } from '../../utils/MessageType'; -import { v4 as uuidv4 } from 'uuid'; +import { MessageType } from '../../utils/MessageType' +import { v4 as uuidv4 } from 'uuid' export function createBasicMessage(content: string) { return { @@ -13,5 +13,5 @@ export function createBasicMessage(content: string) { '~l10n': { locale: 'en' }, sent_time: new Date().toISOString(), content, - }; -} \ No newline at end of file + } +} diff --git a/src/protocols/basicMessage/BasicMessageService.ts b/src/protocols/basicMessage/BasicMessageService.ts index 623518f..6aab692 100644 --- a/src/protocols/basicMessage/BasicMessageService.ts +++ b/src/protocols/basicMessage/BasicMessageService.ts @@ -3,132 +3,137 @@ SPDX-License-Identifier: Apache-2.0 */ -import { Connection } from '../connection/ConnectionInterface'; -import { createBasicMessage } from './BasicMessageMessages'; -import { InboundMessage } from '../../utils/Types'; -import { RecordType, sendOutboundMessage } from '../../utils/Helpers'; -import { WalletConfig, WalletCredentials } from '../../wallet/WalletInterface'; -import WalletStorageService from '../../wallet/WalletStorageService'; +import { Connection } from '../connection/ConnectionInterface' +import { createBasicMessage } from './BasicMessageMessages' +import { InboundMessage } from '../../utils/Types' +import { RecordType, sendOutboundMessage } from '../../utils/Helpers' +import WalletStorageService from '../../wallet/WalletStorageService' class BasicMessageService { - /** * @description Send basic message to exiting connection * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} message * @param {string} connectionId * @return {*} {Promise} * @memberof BasicMessageService */ - async send(configJson: WalletConfig, credentialsJson: WalletCredentials, message: string, connectionId: string): Promise { + async send(message: string, connectionId: string): Promise { try { const query = { - connectionId: connectionId + connectionId: connectionId, } - - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); - const basicMessage = createBasicMessage(message); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery( + RecordType.Connection, + JSON.stringify(query), + ) + const basicMessage = createBasicMessage(message) const chatBody = { type: 'sent', message, time: new Date().toISOString(), - }; + } const basicMessageTags: Object = { connectionId: connectionId, - lastUpdatedAt: new Date().toISOString() + lastUpdatedAt: new Date().toISOString(), } - const chatThread: Array = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.BasicMessage, JSON.stringify(query)); + const chatThread: Array< + Object + > = await WalletStorageService.getWalletRecordFromQuery( + RecordType.BasicMessage, + JSON.stringify(query), + ) - if (chatThread === undefined || chatThread === null || chatThread.length == 0) { + if ( + chatThread === undefined || + chatThread === null || + chatThread.length == 0 + ) { await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.BasicMessage, connectionId, JSON.stringify([chatBody]), - JSON.stringify(basicMessageTags) - ); - } - else { - chatThread.push(chatBody); + JSON.stringify(basicMessageTags), + ) + } else { + chatThread.push(chatBody) await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.BasicMessage, connectionId, JSON.stringify(chatThread), - JSON.stringify(basicMessageTags) - ); + JSON.stringify(basicMessageTags), + ) } - setTimeout(async ()=> { - await sendOutboundMessage(configJson, credentialsJson, connection, basicMessage) - },50) - return true; + setTimeout(async () => { + await sendOutboundMessage(connection, basicMessage) + }, 50) + return true } catch (error) { - console.log('Basic message - Send message error = ', error); - throw error; + console.log('Basic message - Send message error = ', error) + throw error } } - /** * @description Process basic message and update the record * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @param {string} connectionId * @return {*} {Promise} * @memberof BasicMessageService */ - async save(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage, connectionId: string): Promise { + async save( + inboundMessage: InboundMessage, + connectionId: string, + ): Promise { try { - const { message } = inboundMessage; + const { message } = inboundMessage const chatBody = { type: 'receive', message: JSON.parse(message).content, time: JSON.parse(message).sent_time, - }; + } const query = { - connectionId: connectionId + connectionId: connectionId, } - const chatThread: Array = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.BasicMessage, JSON.stringify(query)); - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const chatThread: Array< + Object + > = await WalletStorageService.getWalletRecordFromQuery( + RecordType.BasicMessage, + JSON.stringify(query), + ) + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery( + RecordType.Connection, + JSON.stringify(query), + ) const basicMessageTags: Object = { connectionId: connectionId, - lastUpdatedAt: new Date().toISOString() + lastUpdatedAt: new Date().toISOString(), } if (chatThread.length == 0) { await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.BasicMessage, connectionId, JSON.stringify([chatBody]), - JSON.stringify(basicMessageTags) - ); - } - else { - chatThread.push(chatBody); + JSON.stringify(basicMessageTags), + ) + } else { + chatThread.push(chatBody) await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.BasicMessage, connectionId, JSON.stringify(chatThread), - JSON.stringify(basicMessageTags) - ); + JSON.stringify(basicMessageTags), + ) } - return connection; + return connection } catch (error) { - console.log('Basic message - Save message error = ', error); - throw (error); + console.log('Basic message - Save message error = ', error) + throw error } } } -export default new BasicMessageService(); \ No newline at end of file +export default new BasicMessageService() diff --git a/src/protocols/connection/ConnectionService.ts b/src/protocols/connection/ConnectionService.ts index b29afe8..af8be12 100644 --- a/src/protocols/connection/ConnectionService.ts +++ b/src/protocols/connection/ConnectionService.ts @@ -3,42 +3,53 @@ SPDX-License-Identifier: Apache-2.0 */ -import { Authentication, DidDoc, PublicKey, PublicKeyType, Service } from '../../utils/DidDoc'; -import { InboundMessage, Message } from '../../utils/Types'; -import { RecordType, encodeInvitationToUrl, getServiceEndpoint, sendOutboundMessage, sign, verify } from '../../utils/Helpers'; -import { WalletConfig, WalletCredentials } from '../../wallet/WalletInterface'; +import { + Authentication, + DidDoc, + PublicKey, + PublicKeyType, + Service, +} from '../../utils/DidDoc'; +import {InboundMessage, Message} from '../../utils/Types'; +import { + RecordType, + encodeInvitationToUrl, + getServiceEndpoint, + sendOutboundMessage, + sign, + verify, +} from '../../utils/Helpers'; import { createConnectionRequestMessage, createConnectionResponseMessage, - createInvitationMessage + createInvitationMessage, } from './ConnectionMessages'; -import { Connection } from './ConnectionInterface'; -import { ConnectionState } from './ConnectionState'; +import {Connection} from './ConnectionInterface'; +import {ConnectionState} from './ConnectionState'; import DatabaseServices from '../../storage'; -import { NativeModules } from "react-native"; -import { NetworkServices } from "../../network"; -import { TrustPing } from "../trustPing/TrustPingInterface"; -import { TrustPingState } from '../trustPing/TrustPingState'; +import {NativeModules} from 'react-native'; +import {NetworkServices} from '../../network'; +import {TrustPing} from '../trustPing/TrustPingInterface'; +import {TrustPingState} from '../trustPing/TrustPingState'; import WalletStorageService from '../../wallet/WalletStorageService'; -import { createTrustPingMessage } from '../trustPing/TrustPingMessages'; -import { EventInterface } from 'react-native-arnima-sdk/src/agent/EventInterface'; -import { EventRegister } from 'react-native-event-listeners'; +import {createTrustPingMessage} from '../trustPing/TrustPingMessages'; +import {EventInterface} from 'react-native-arnima-sdk/src/agent/EventInterface'; +import {EventRegister} from 'react-native-event-listeners'; -const { ArnimaSdk } = NativeModules; +const {ArnimaSdk} = NativeModules; class ConnectionService { - /** * @description Create invitation with details * * @private * @param {Connection} connection * @param {string} logo - * @return {*} + * @return {*} * @memberof ConnectionService */ private createInvitationDetails(connection: Connection, logo: string) { - const { didDoc } = connection; + const {didDoc} = connection; return { label: DatabaseServices.getLabel(), recipientKeys: didDoc.service[0].recipientKeys, @@ -46,37 +57,30 @@ class ConnectionService { routingKeys: didDoc.service[0].routingKeys, alias: { logo, - organizationId: '' - } + organizationId: '', + }, }; } /** * @description Create a new connection record containing a connection invitation message * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {Object} didJson * @param {string} logo * @return {*} {Promise} * @memberof ConnectionService */ - async createInvitation(configJson: WalletConfig, - credentialsJson: WalletCredentials, - didJson: Object, - logo: string): Promise { - const connection: Connection = await this.createConnection(configJson, credentialsJson, didJson); + async createInvitation(didJson: Object, logo: string): Promise { + const connection: Connection = await this.createConnection(didJson); const connectionTags: Object = { connectionId: connection.verkey, - } + }; await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Connection, connection.verkey, JSON.stringify(connection), - JSON.stringify(connectionTags) + JSON.stringify(connectionTags), ); const invitationDetails = this.createInvitationDetails(connection, logo); @@ -90,43 +94,51 @@ class ConnectionService { /** * @description Process a received invitation message. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {Object} didJson * @param {Message} invitation * @param {string} logo * @return {*} {Promise} * @memberof ConnectionService */ - async acceptInvitation(configJson: WalletConfig, - credentialsJson: WalletCredentials, + async acceptInvitation( didJson: Object, invitation: Message, - logo: string): Promise { + logo: string, + ): Promise { try { - const connection: Connection = await this.createConnection(configJson, credentialsJson, didJson, invitation.label, + const connection: Connection = await this.createConnection( + didJson, + invitation.label, invitation.hasOwnProperty('alias') ? invitation.alias.logoUrl : '', - invitation.hasOwnProperty('alias') ? invitation.alias.organizationId : ''); - const connectionRequest = createConnectionRequestMessage(connection, DatabaseServices.getLabel(), logo); + invitation.hasOwnProperty('alias') + ? invitation.alias.organizationId + : '', + ); + const connectionRequest = createConnectionRequestMessage( + connection, + DatabaseServices.getLabel(), + logo, + ); connection.state = ConnectionState.REQUESTED; - await sendOutboundMessage(configJson, credentialsJson, connection, connectionRequest, invitation) + await sendOutboundMessage(connection, connectionRequest, invitation); const connectionTags: Object = { connectionId: connection.verkey, - } + }; await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Connection, connection.verkey, JSON.stringify(connection), - JSON.stringify(connectionTags) + JSON.stringify(connectionTags), ); return connection; } catch (error) { - console.log('Connection - Create invitation error = ', JSON.stringify(error)); + console.log( + 'Connection - Create invitation error = ', + JSON.stringify(error), + ); throw error; } } @@ -134,19 +146,20 @@ class ConnectionService { /** * @description Process a received connection request message. This will not accept the connection request * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage - * @return {*} + * @return {*} * @memberof ConnectionService */ - async processRequest(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage) { - const { message, recipient_verkey } = inboundMessage; + async processRequest(inboundMessage: InboundMessage) { + const {message, recipient_verkey} = inboundMessage; const query = { - connectionId: recipient_verkey - } + connectionId: recipient_verkey, + }; - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery( + RecordType.Connection, + JSON.stringify(query), + ); if (!connection) { throw new Error(`Connection for verkey ${recipient_verkey} not found!`); @@ -156,11 +169,13 @@ class ConnectionService { throw new Error('Invalid message'); } try { - const receivedMessage: Message = await verify(configJson, credentialsJson, typeMessage, 'connection'); + const receivedMessage: Message = await verify(typeMessage, 'connection'); connection.theirDid = receivedMessage.connection.DID; connection.theirDidDoc = receivedMessage.connection.DIDDoc; if (!connection.theirDidDoc.service[0].recipientKeys[0]) { - throw new Error(`Connection with verkey ${connection.verkey} has no recipient keys.`); + throw new Error( + `Connection with verkey ${connection.verkey} has no recipient keys.`, + ); } const trustPingMessage = createTrustPingMessage(); connection.state = ConnectionState.COMPLETE; @@ -173,42 +188,41 @@ class ConnectionService { status: TrustPingState.SENT, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), - } + }; const trustPingTags = { connectionId: recipient_verkey, trustPingId: trustPingMessage['@id'], status: TrustPingState.SENT, - } + }; - await sendOutboundMessage(configJson, credentialsJson, connection, trustPingMessage) + await sendOutboundMessage(connection, trustPingMessage); await WalletStorageService.updateWalletRecord( - configJson, credentialsJson, RecordType.Connection, connection.verkey, JSON.stringify(connection), - '{}' + '{}', ); await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.TrustPing, recipient_verkey, JSON.stringify(trustPing), - JSON.stringify(trustPingTags) + JSON.stringify(trustPingTags), ); const event: EventInterface = { message: `You are now connected with ${connection.theirLabel}`, type: 'Connection', - messageData: JSON.stringify({ connection }), - } + messageData: JSON.stringify({connection}), + }; EventRegister.emit('SDKEvent', event); return true; - } - catch (error) { - console.log('Connection - Accept response error = ', JSON.stringify(error)); + } catch (error) { + console.log( + 'Connection - Accept response error = ', + JSON.stringify(error), + ); throw error; } } @@ -216,21 +230,20 @@ class ConnectionService { /** * @description Create a connection response message for the connection with the specified connection id. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage - * @return {*} + * @return {*} * @memberof ConnectionService */ - async createResponse(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage) { + async createResponse(inboundMessage: InboundMessage) { try { - - const { message, recipient_verkey } = inboundMessage; + const {message, recipient_verkey} = inboundMessage; const query = { - connectionId: recipient_verkey - } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); - + connectionId: recipient_verkey, + }; + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery( + RecordType.Connection, + JSON.stringify(query), + ); if (!connection) { throw new Error(`Connection for verkey ${recipient_verkey} not found!`); @@ -248,24 +261,35 @@ class ConnectionService { connection.updatedAt = new Date().toISOString(); if (!connection.theirDidDoc.service[0].recipientKeys[0]) { - throw new Error(`Connection with verkey ${connection.verkey} has no recipient keys.`); + throw new Error( + `Connection with verkey ${connection.verkey} has no recipient keys.`, + ); } - const connectionResponse = createConnectionResponseMessage(connection, typeMessage['@id']); - const signedConnectionResponse = await sign(configJson, credentialsJson, connection.verkey, connectionResponse, 'connection'); + const connectionResponse = createConnectionResponseMessage( + connection, + typeMessage['@id'], + ); + const signedConnectionResponse = await sign( + connection.verkey, + connectionResponse, + 'connection', + ); - await sendOutboundMessage(configJson, credentialsJson, connection, signedConnectionResponse) + await sendOutboundMessage(connection, signedConnectionResponse); await WalletStorageService.updateWalletRecord( - configJson, credentialsJson, RecordType.Connection, connection.verkey, JSON.stringify(connection), - '{}' + '{}', ); return true; } catch (error) { - console.log('Connection - Accept request error = ', JSON.stringify(error)); + console.log( + 'Connection - Accept request error = ', + JSON.stringify(error), + ); throw error; } } @@ -273,8 +297,6 @@ class ConnectionService { /** * @description Create connection and DidDoc. Also register the verkey on mediator agent * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {Object} didJson * @param {string} [label] * @param {string} [logo] @@ -282,23 +304,48 @@ class ConnectionService { * @return {*} {Promise} * @memberof ConnectionService */ - async createConnection(configJson: WalletConfig, - credentialsJson: WalletCredentials, + async createConnection( didJson: Object, label?: string, logo?: string, organizationId?: string, ): Promise { try { - const [pairwiseDid, verkey]: string[] = await ArnimaSdk.createAndStoreMyDid(JSON.stringify(configJson), JSON.stringify(credentialsJson), JSON.stringify(didJson), false); + const wallet: any = await DatabaseServices.getWallet(); + + const [ + pairwiseDid, + verkey, + ]: string[] = await ArnimaSdk.createAndStoreMyDid( + wallet.walletConfig, + wallet.walletCredentials, + JSON.stringify(didJson), + false, + ); const apiBody = { publicVerkey: DatabaseServices.getVerKey(), - verkey: verkey + verkey: verkey, }; - await NetworkServices(getServiceEndpoint() + 'verkey', 'POST', JSON.stringify(apiBody)); - const publicKey = new PublicKey(`${pairwiseDid}#1`, PublicKeyType.ED25519_SIG_2018, pairwiseDid, verkey); - const service = new Service(`${pairwiseDid};indy`, DatabaseServices.getServiceEndpoint(), [verkey], [DatabaseServices.getRoutingKeys()], 0, 'IndyAgent'); + await NetworkServices( + getServiceEndpoint() + 'verkey', + 'POST', + JSON.stringify(apiBody), + ); + const publicKey = new PublicKey( + `${pairwiseDid}#1`, + PublicKeyType.ED25519_SIG_2018, + pairwiseDid, + verkey, + ); + const service = new Service( + `${pairwiseDid};indy`, + DatabaseServices.getServiceEndpoint(), + [verkey], + [DatabaseServices.getRoutingKeys()], + 0, + 'IndyAgent', + ); const auth = new Authentication(publicKey); const did_doc = new DidDoc(pairwiseDid, [auth], [publicKey], [service]); @@ -318,12 +365,14 @@ class ConnectionService { }; return connection; - } - catch (error) { - console.log('Connection - Create connection error = ', JSON.stringify(error)); + } catch (error) { + console.log( + 'Connection - Create connection error = ', + JSON.stringify(error), + ); throw error; } } } -export default new ConnectionService(); \ No newline at end of file +export default new ConnectionService(); diff --git a/src/protocols/credential/CredentialService.ts b/src/protocols/credential/CredentialService.ts index ce963f1..2afcf1b 100644 --- a/src/protocols/credential/CredentialService.ts +++ b/src/protocols/credential/CredentialService.ts @@ -13,7 +13,6 @@ import { InboundMessage, Message } from '../../utils/Types'; import { NativeModules } from 'react-native'; import { Pool } from '../../pool/PoolInterface'; import { RecordType, decodeBase64, sendOutboundMessage } from '../../utils/Helpers'; -import { WalletConfig, WalletCredentials } from '../../wallet/WalletInterface'; import DatabaseServices from '../../storage'; import WalletStorageService from '../../wallet/WalletStorageService'; @@ -23,21 +22,19 @@ class CredentialService { /** * @description Process a received offer message, This will only store credential record. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @param {string} messageId * @return {*} {Promise} * @memberof CredentialService */ - async requestReceived(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage, messageId: string): Promise { + async requestReceived(inboundMessage: InboundMessage, messageId: string): Promise { try { const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = (inboundMessage.message); const offersAttach = message['offers~attach']; @@ -61,8 +58,6 @@ class CredentialService { if (message.hasOwnProperty('~thread') && Object.keys(message['~thread']).length > 0) { await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Credential, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(issueCredential), @@ -71,8 +66,6 @@ class CredentialService { } else { issueCredential.createdAt = new Date().toISOString() await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Credential, message['@id'], JSON.stringify(issueCredential), @@ -90,8 +83,6 @@ class CredentialService { /** * @description Create a credential proposal and send to particular connection not bound to an existing credential exchange. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {object} connectionId * @param {string} proposeCredential * @param {string} schemaId @@ -101,7 +92,7 @@ class CredentialService { * @return {*} {Promise} * @memberof CredentialService */ - async createProposal(configJson: WalletConfig, credentialsJson: WalletCredentials, + async createProposal( connectionId: object, proposeCredential: string, schemaId: string, @@ -113,7 +104,7 @@ class CredentialService { try { const query = { connectionId: connectionId } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const credentialPreview = await credentialPreviewMessage(proposeCredential); const credentialProposal = await credentialProposalMessage(credentialPreview, @@ -130,7 +121,7 @@ class CredentialService { } if (proposeCredential !== '') { - await sendOutboundMessage(configJson, credentialsJson, connection, credentialProposal) + await sendOutboundMessage(connection, credentialProposal) const issueCredentialTags: Object = { connectionId: connection.verkey, @@ -138,8 +129,6 @@ class CredentialService { } await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Credential, credentialProposal["@id"], JSON.stringify(issueCredential), @@ -160,19 +149,17 @@ class CredentialService { /** * @description Create a request credential message as response to a received credential offer. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof CredentialService */ - async createRequest(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage): Promise { + async createRequest(inboundMessage: InboundMessage): Promise { try { const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = JSON.parse(inboundMessage.message); const offersAttach = message['offers~attach']; @@ -182,7 +169,7 @@ class CredentialService { isSelected: JSON.stringify(true) } - const poolRecord: Pool = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Pool, JSON.stringify(queryPool)); + const poolRecord: Pool = await WalletStorageService.getWalletRecordFromQuery(RecordType.Pool, JSON.stringify(queryPool)); const credDefJson: string = await ArnimaSdk.getCredDef( connection.did, credOfferJson.cred_def_id, @@ -191,8 +178,6 @@ class CredentialService { ); const credentialRequest = await ArnimaSdk.proverCreateCredentialReq( - JSON.stringify(configJson), - JSON.stringify(credentialsJson), connection.did, JSON.stringify(credOfferJson), credDefJson, @@ -219,7 +204,7 @@ class CredentialService { message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], ); - await sendOutboundMessage(configJson, credentialsJson, connection, credentialRequestMessage) + await sendOutboundMessage(connection, credentialRequestMessage) const issueCredentialTags: Object = { issueCredentialId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], @@ -228,8 +213,6 @@ class CredentialService { issueCredential.updatedAt = new Date().toISOString() await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Credential, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(issueCredential), @@ -246,13 +229,11 @@ class CredentialService { /** * @description Process a received credential message. This will store the credential and send a credential acknowledgement. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof CredentialService */ - async processCredential(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage): Promise { + async processCredential(inboundMessage: InboundMessage): Promise { try { const { recipient_verkey } = inboundMessage; const message: Message = JSON.parse(inboundMessage.message); @@ -260,12 +241,12 @@ class CredentialService { const issueCredentialQuery = { issueCredentialId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'] } - const issueCredentialRecord: Credential = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Credential, JSON.stringify(issueCredentialQuery)); + const issueCredentialRecord: Credential = await WalletStorageService.getWalletRecordFromQuery(RecordType.Credential, JSON.stringify(issueCredentialQuery)); const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const credentialsAttach = message['credentials~attach']; const credCertificate = await decodeBase64(credentialsAttach[0].data.base64); @@ -275,7 +256,7 @@ class CredentialService { isSelected: JSON.stringify(true) } - const poolRecord: Pool = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Pool, JSON.stringify(queryPool)); + const poolRecord: Pool = await WalletStorageService.getWalletRecordFromQuery(RecordType.Pool, JSON.stringify(queryPool)); if (credCertificate.rev_reg_id !== null) { revocRegDefJson = await ArnimaSdk.getRevocRegDef( connection.did, @@ -285,8 +266,6 @@ class CredentialService { ); } const storedCredentialId = await ArnimaSdk.proverStoreCredential( - JSON.stringify(configJson), - JSON.stringify(credentialsJson), null, JSON.stringify(issueCredentialRecord.credentialRequestMetadata), JSON.stringify(credCertificate), @@ -297,7 +276,7 @@ class CredentialService { if (storedCredentialId.length !== '') { issueCredentialRecord.state = CredentialState.STATE_ACKED; issueCredentialRecord.revocRegId = credCertificate.rev_reg_id; - issueCredentialRecord.revocRegDefJson = revocRegDefJson === null ? {} : JSON.parse(revocRegDefJson); + issueCredentialRecord.revocRegDefJson = revocRegDefJson === null ? { } : JSON.parse(revocRegDefJson); issueCredentialRecord.updatedAt = new Date().toISOString(); issueCredentialRecord.credentialId = storedCredentialId; } else { @@ -308,7 +287,7 @@ class CredentialService { message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'] ); - await sendOutboundMessage(configJson, credentialsJson, connection, credentialRequestMessage) + await sendOutboundMessage(connection, credentialRequestMessage) const issueCredentialTags: Object = { issueCredentialId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], @@ -316,8 +295,6 @@ class CredentialService { credentialsId: storedCredentialId, } await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Credential, message['~thread'].thid, JSON.stringify(issueCredentialRecord), diff --git a/src/protocols/mediator/ConnectWithMediatorService.ts b/src/protocols/mediator/ConnectWithMediatorService.ts index 8df37c6..c92203a 100644 --- a/src/protocols/mediator/ConnectWithMediatorService.ts +++ b/src/protocols/mediator/ConnectWithMediatorService.ts @@ -51,8 +51,6 @@ class MediatorService { } await WalletStorageService.updateWalletRecord( - myWallet.walletConfig, - myWallet.walletConfig, RecordType.MediatorAgent, '1', JSON.stringify(walletRecord), diff --git a/src/protocols/presentation/PresentationService.ts b/src/protocols/presentation/PresentationService.ts index fd25676..a88e3fd 100644 --- a/src/protocols/presentation/PresentationService.ts +++ b/src/protocols/presentation/PresentationService.ts @@ -11,7 +11,6 @@ import { Pool } from '../../pool/PoolInterface'; import { Presentation } from './PresentationInterface'; import { PresentationState } from './PresentationState'; import { RecordType, decodeBase64, sendOutboundMessage } from '../../utils/Helpers'; -import { WalletConfig, WalletCredentials } from '../../wallet/WalletInterface'; import DatabaseServices from '../../storage'; import WalletStorageService from '../../wallet/WalletStorageService'; @@ -20,25 +19,23 @@ class PresentationService { /** * @description Process a received presentation message, This will only store record. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} messageId * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof PresentationService */ - async requestReceived(configJson: WalletConfig, credentialsJson: WalletCredentials, messageId: string, inboundMessage: InboundMessage): Promise { + async requestReceived(messageId: string, inboundMessage: InboundMessage): Promise { try { const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = (inboundMessage.message); const presentationQuery = { presentationId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'] } - const presentation: Presentation = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Presentation, JSON.stringify(presentationQuery)); + const presentation: Presentation = await WalletStorageService.getWalletRecordFromQuery(RecordType.Presentation, JSON.stringify(presentationQuery)); const presentationsAttach = message['presentations~attach']; const presentationJson = await decodeBase64(presentationsAttach[0].data.base64); const presentProofRecord: Presentation = { @@ -59,8 +56,6 @@ class PresentationService { if (message.hasOwnProperty('~thread') && Object.keys(message['~thread']).length > 0) { await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(presentProofRecord), @@ -69,8 +64,6 @@ class PresentationService { } else { presentProofRecord.createdAt = new Date().toISOString(); await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message['@id'], JSON.stringify(presentProofRecord), @@ -87,25 +80,19 @@ class PresentationService { /** * @description Create a propose presentation message not bound to an existing presentation exchange. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} connectionId * @param {object} proposePresentation * @param {string} comment * @return {*} {Promise} * @memberof PresentationService */ - async createProposal(configJson: WalletConfig, credentialsJson: WalletCredentials, - connectionId: string, - proposePresentation: object, - comment: string): Promise { - + async createProposal(connectionId: string, proposePresentation: object, comment: string): Promise { try { const query = { connectionId: connectionId } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const presentationProposal = await presentationProposalMessage(proposePresentation, comment); const presentProofRecord: Presentation = await { @@ -124,11 +111,9 @@ class PresentationService { if (presentProofRecord) { - await sendOutboundMessage(configJson, credentialsJson, connection, presentationProposal) + await sendOutboundMessage(connection, presentationProposal) await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, presentationProposal['@id'], JSON.stringify(presentationProposal), @@ -148,23 +133,21 @@ class PresentationService { /** * @description Process a received request presentation message.It will only create a new, or update the existing proof record * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} messageId * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof PresentationService */ - async processRequest(configJson: WalletConfig, credentialsJson: WalletCredentials, messageId: string, inboundMessage: InboundMessage): Promise { + async processRequest(messageId: string, inboundMessage: InboundMessage): Promise { try { const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = inboundMessage.message; if (message.hasOwnProperty('comment') && message.comment.includes(':::auto:::')) { - const response = await this.createPresentation(configJson, credentialsJson, inboundMessage, true); - if (response) { await WalletStorageService.deleteWalletRecord(configJson, credentialsJson, RecordType.SSIMessage, messageId) } + const response = await this.createPresentation(inboundMessage, true); + if (response) { await WalletStorageService.deleteWalletRecord(RecordType.SSIMessage, messageId) } return connection; } else { @@ -186,8 +169,6 @@ class PresentationService { if (message.hasOwnProperty('~thread') && Object.keys(message['~thread']).length > 0) { await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(presentProofRecord), @@ -196,8 +177,6 @@ class PresentationService { } else { presentProofRecord.createdAt = new Date().toISOString(); await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(presentProofRecord), @@ -216,14 +195,12 @@ class PresentationService { /** * @description Create a presentation message as response to a received presentation request. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @param {boolean} [revealAttributes=true] * @return {*} {Promise} * @memberof PresentationService */ - async createPresentation(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage, revealAttributes: boolean = true, presentationObj?: object): Promise { + async createPresentation(inboundMessage: InboundMessage, revealAttributes: boolean = true, presentationObj?: object): Promise { try { // TODO : Need to find a way for realm db typing const sdkDB: any = DatabaseServices.getWallet(); @@ -233,7 +210,7 @@ class PresentationService { } let connection: Connection; if (recipient_verkey !== null) { - connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); } const message: Message = inboundMessage.message; const presentationRequest = message['request_presentations~attach']; @@ -241,7 +218,7 @@ class PresentationService { const queryPool = { isSelected: JSON.stringify(true) } - const { poolName, poolConfig }: Pool = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Pool, JSON.stringify(queryPool)); + const { poolName, poolConfig }: Pool = await WalletStorageService.getWalletRecordFromQuery(RecordType.Pool, JSON.stringify(queryPool)); const [requestedCredentials, revocStates] = await this.getRequestedCredentialsForProofRequest(proofRequest, presentationObj, poolName, poolConfig, sdkDB.publicDid, revealAttributes) const credentialObjects: Array = [] const credIds = [] @@ -256,11 +233,7 @@ class PresentationService { } for (const credentialId of new Set(credIds)) { - const credentialInfo = await ArnimaSdk.proverGetCredential( - JSON.stringify(configJson), - JSON.stringify(credentialsJson), - credentialId - ) + const credentialInfo = await ArnimaSdk.proverGetCredential(credentialId) credentialObjects.push(JSON.parse(credentialInfo)) } const [schemas, credDefs] = await Promise.all([ @@ -269,8 +242,6 @@ class PresentationService { ); const presentation = await ArnimaSdk.proverCreateProof( - JSON.stringify(configJson), - JSON.stringify(credentialsJson), JSON.stringify(proofRequest), JSON.stringify(requestedCredentials), sdkDB.masterSecretId, @@ -297,12 +268,10 @@ class PresentationService { message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], ); - await sendOutboundMessage(configJson, credentialsJson, connection, creatPresentationMessageObject, undefined, message['~service']) + await sendOutboundMessage(connection, creatPresentationMessageObject, undefined, message['~service']) if (recipient_verkey !== null) { await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(presentProofRecord), @@ -319,7 +288,7 @@ class PresentationService { public async generateSchemaJson(credentialObjects: any[], poolName: string, poolConfig: string, publicDid: string): Promise { try { - let schemas = {}; + let schemas = { }; const schemaIds = credentialObjects.map((c) => c.schema_id) for (const schemaId of schemaIds) { const schema = await ArnimaSdk.getSchemasJson(poolName, poolConfig, publicDid, schemaId) @@ -333,7 +302,7 @@ class PresentationService { public async generateCredDefJson(credentialObjects: any[], poolName: string, poolConfig: string, publicDid: string): Promise { try { - let credDefs = {}; + let credDefs = { }; const credDefIds = credentialObjects.map((c) => c.cred_def_id) for (const credDefId of credDefIds) { const credDef = await ArnimaSdk.getCredDef(publicDid, credDefId, poolName, poolConfig) @@ -371,11 +340,11 @@ class PresentationService { revealAttributes?: boolean, ): Promise { try { - const revocStates: Object = {} + const revocStates: Object = { } const requestedCredentials = { - self_attested_attributes: {}, - requested_attributes: {}, - requested_predicates: {}, + self_attested_attributes: { }, + requested_attributes: { }, + requested_predicates: { }, } let revRegIdMatcher: string = ''; let revRegIdJsonMatcher: Object = {}; @@ -449,7 +418,7 @@ class PresentationService { if (value.restrictions) { let timestampObj: { timestamp?: number - } = {}; + } = { }; if (credentialMatch.cred_info.rev_reg_id !== null) { if (credentialMatch.cred_info.rev_reg_id !== revRegIdMatcher) { @@ -544,7 +513,7 @@ class PresentationService { if (value.restrictions) { let timestampObj: { timestamp?: number - } = {}; + } = { }; if (credMatch.cred_info.rev_reg_id !== null) { if (credMatch.cred_info.rev_reg_id !== revRegIdMatcher) { @@ -628,18 +597,16 @@ class PresentationService { /** * @description Create a request presentation message not bound to an existing presentation exchange. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} connectionId * @param {object} proofRequest * @param {string} comment * @return {*} {Promise} * @memberof PresentationService */ - async createRequest(configJson: WalletConfig, credentialsJson: WalletCredentials, connectionId: string, proofRequest: object, comment: string): Promise { + async createRequest(connectionId: string, proofRequest: object, comment: string): Promise { try { const query = { connectionId: connectionId } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const requestPresentation = await requestPresentationMessage( JSON.stringify(proofRequest), comment, @@ -654,15 +621,13 @@ class PresentationService { updatedAt: new Date().toISOString(), } - await sendOutboundMessage(configJson, credentialsJson, connection, requestPresentation) + await sendOutboundMessage(connection, requestPresentation) const presentationProofTags: Object = { presentationId: requestPresentation['@id'], connectionId: connection.verkey, } await WalletStorageService.addWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, requestPresentation['@id'], JSON.stringify(presentProofRecord), @@ -680,37 +645,35 @@ class PresentationService { /** * @description Verify an indy proof object. Will also ack to sender. * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {string} messageId * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof PresentationService */ - async verifyProof(configJson: WalletConfig, credentialsJson: WalletCredentials, messageId: string, inboundMessage: InboundMessage): Promise { + async verifyProof(messageId: string, inboundMessage: InboundMessage): Promise { try { // TODO : Need to find a way for realm db typing const sdkDB: any = DatabaseServices.getWallet(); const message: Message = JSON.parse(inboundMessage.message); const presentationQuery = { messageId: messageId } - const presentationRecord = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Presentation, JSON.stringify(presentationQuery)); + const presentationRecord = await WalletStorageService.getWalletRecordFromQuery(RecordType.Presentation, JSON.stringify(presentationQuery)); const presentProofRecord = presentationRecord.presentation; const presentationRequest = presentationRecord.presentationRequest; const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const queryPool = { isSelected: JSON.stringify(true) } - const { poolName, poolConfig }: Pool = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Pool, JSON.stringify(queryPool)); + const { poolName, poolConfig }: Pool = await WalletStorageService.getWalletRecordFromQuery(RecordType.Pool, JSON.stringify(queryPool)); - const schemas: Object = {} - const credDefs: Object = {} - const revRegDefs: Object = {} - const revRegsObj: Object = {} + const schemas: Object = { } + const credDefs: Object = { } + const revRegDefs: Object = { } + const revRegsObj: Object = { } const identifiers = JSON.parse(presentationRequest).identifiers for (const identifier of new Set(identifiers)) { @@ -753,11 +716,9 @@ class PresentationService { message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'] ); - await sendOutboundMessage(configJson, credentialsJson, connection, presentationAcknowledgeMessage) + await sendOutboundMessage(connection, presentationAcknowledgeMessage) await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Presentation, message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], JSON.stringify(presentationRecord), diff --git a/src/protocols/trustPing/TrustPingService.ts b/src/protocols/trustPing/TrustPingService.ts index 50a9148..43e7150 100644 --- a/src/protocols/trustPing/TrustPingService.ts +++ b/src/protocols/trustPing/TrustPingService.ts @@ -9,7 +9,6 @@ import { createTrustPingResponseMessage } from './TrustPingMessages'; import { InboundMessage, Message } from '../../utils/Types'; import { RecordType, sendOutboundMessage } from '../../utils/Helpers'; import { TrustPingState } from './TrustPingState'; -import { WalletConfig, WalletCredentials } from '../../wallet/WalletInterface'; import WalletStorageService from '../../wallet/WalletStorageService'; class TrustPingService { @@ -17,17 +16,15 @@ class TrustPingService { /** * @description Process trust ping response message and update the status * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof TrustPingService */ - async saveTrustPingResponse(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage): Promise { + async saveTrustPingResponse(inboundMessage: InboundMessage): Promise { try { const { recipient_verkey } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const message: Message = JSON.parse(inboundMessage.message); const trustPingId = message['~thread'].thid; const trustPingTags = { @@ -37,8 +34,6 @@ class TrustPingService { } await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.TrustPing, recipient_verkey, JSON.stringify(message), @@ -54,19 +49,17 @@ class TrustPingService { /** * @description Process trust ping message * - * @param {WalletConfig} configJson - * @param {WalletCredentials} credentialsJson * @param {InboundMessage} inboundMessage * @return {*} {Promise} * @memberof TrustPingService */ - async processPing(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage): Promise { + async processPing(inboundMessage: InboundMessage): Promise { try { const { recipient_verkey, message } = inboundMessage; const query = { connectionId: recipient_verkey } - const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query)); + const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(RecordType.Connection, JSON.stringify(query)); const parseMessage: Message = JSON.parse(message); if (connection.state != ConnectionState.COMPLETE) { @@ -77,11 +70,9 @@ class TrustPingService { if (parseMessage['responseRequested']) { const reply = createTrustPingResponseMessage(parseMessage['@id']); - await sendOutboundMessage(configJson, credentialsJson, connection, reply) + await sendOutboundMessage(connection, reply) await WalletStorageService.updateWalletRecord( - configJson, - credentialsJson, RecordType.Connection, connection.verkey, JSON.stringify(connection), diff --git a/src/storage/index.ts b/src/storage/index.ts index 72860de..a878e1e 100644 --- a/src/storage/index.ts +++ b/src/storage/index.ts @@ -2,7 +2,7 @@ Copyright AyanWorks Technology Solutions Pvt. Ltd. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ -import Realm from 'realm'; +import Realm from 'realm' const agentDB = new Realm({ schemaVersion: 1, @@ -21,56 +21,52 @@ const agentDB = new Realm({ verKey: 'string', masterSecretId: 'string', }, - }] -}); + }, + ], +}) const DBServices = { storeWallet(data) { agentDB.write(() => { - agentDB.create( - 'wallet', - data, - true, - ); - }); + agentDB.create('wallet', data, true) + }) }, getWallet() { - const query = agentDB.objects('wallet'); - const wallet = Array.from(query)[0]; - return wallet; + const query = agentDB.objects('wallet') + const wallet = Array.from(query)[0] + return wallet }, getServiceEndpoint() { - const query = agentDB.objects('wallet'); - const wallet: any = Array.from(query)[0]; + const query = agentDB.objects('wallet') + const wallet: any = Array.from(query)[0] return wallet.serviceEndpoint }, getLabel() { - const query = agentDB.objects('wallet'); - const wallet: any = Array.from(query)[0]; + const query = agentDB.objects('wallet') + const wallet: any = Array.from(query)[0] return wallet.label }, getMasterSecretId() { - const query = agentDB.objects('wallet'); - const wallet: any = Array.from(query)[0]; + const query = agentDB.objects('wallet') + const wallet: any = Array.from(query)[0] return wallet.masterSecretId }, getRoutingKeys() { - const query = agentDB.objects('wallet'); - const wallet: any = Array.from(query)[0]; + const query = agentDB.objects('wallet') + const wallet: any = Array.from(query)[0] return wallet.routingKey }, getVerKey() { - const query = agentDB.objects('wallet'); - const wallet: any = Array.from(query)[0]; + const query = agentDB.objects('wallet') + const wallet: any = Array.from(query)[0] return wallet.verKey - }, -}; +} -export default DBServices; \ No newline at end of file +export default DBServices diff --git a/src/transports/index.ts b/src/transports/index.ts index 1ab8608..08d0336 100644 --- a/src/transports/index.ts +++ b/src/transports/index.ts @@ -3,45 +3,52 @@ SPDX-License-Identifier: Apache-2.0 */ -import { Connection } from "../protocols/connection/ConnectionInterface"; -import { EventInterface } from "../agent/EventInterface"; +import { Connection } from '../protocols/connection/ConnectionInterface'; +import { EventInterface } from '../agent/EventInterface'; import { EventRegister } from 'react-native-event-listeners'; -import { MessageType } from "../utils/MessageType"; -import { Record } from "../wallet/WalletInterface"; -import { RecordType, getServiceEndpoint, unpackMessage } from "../utils/Helpers"; -import BasicMessageService from "../protocols/basicMessage/BasicMessageService"; -import ConnectionService from "../protocols/connection/ConnectionService"; -import CredentialService from "../protocols/credential/CredentialService"; -import DatabaseServices from "../storage"; -import io from "socket.io-client"; -import PresentationService from "../protocols/presentation/PresentationService"; -import TrustPingService from "../protocols/trustPing/TrustPingService"; -import WalletStorageService from "../wallet/WalletStorageService"; +import { MessageType } from '../utils/MessageType'; +import { Record } from '../wallet/WalletInterface'; +import { + RecordType, + getServiceEndpoint, + unpackMessage, +} from '../utils/Helpers'; +import BasicMessageService from '../protocols/basicMessage/BasicMessageService'; +import ConnectionService from '../protocols/connection/ConnectionService'; +import CredentialService from '../protocols/credential/CredentialService'; +import DatabaseServices from '../storage'; +import io from 'socket.io-client'; +import PresentationService from '../protocols/presentation/PresentationService'; +import TrustPingService from '../protocols/trustPing/TrustPingService'; +import WalletStorageService from '../wallet/WalletStorageService'; class InboundMessageHandler { - isProcess: boolean = false; - socket: any + socket: any; wallet: any = DatabaseServices.getWallet(); initializeSocket = async () => { // TODO :Refactor the get wallet condition - this.wallet = await DatabaseServices.getWallet() - if (this.socket === undefined || (this.socket !== undefined && this.socket.disconnected)) { + this.wallet = await DatabaseServices.getWallet(); + if ( + this.socket === undefined || + (this.socket !== undefined && this.socket.disconnected) + ) { this.socket = io(getServiceEndpoint(), { - reconnection: true, reconnectionDelay: 500, + reconnection: true, + reconnectionDelay: 500, jsonp: false, reconnectionAttempts: Infinity, autoConnect: true, - transports: ['websocket'] + transports: ['websocket'], }); this.socketMessageListener(); this.socketEmitMessage(); } else if (this.socket !== undefined) { this.socketEmitMessage(); } - this.socket.on('disconnect', (reason) => { - console.log("reason-----", reason); + this.socket.on('disconnect', reason => { + console.log('reason-----', reason); if (reason === 'io server disconnect') { } this.socket.connect(); @@ -49,30 +56,37 @@ class InboundMessageHandler { }; socketEmitMessage = () => { - this.socket.emit("message", DatabaseServices.getVerKey()); + this.socket.emit('message', DatabaseServices.getVerKey()); }; socketMessageListener = async () => { - this.socket.on("message", async (msg) => { + this.socket.on('message', async msg => { let inboxId: string = ''; if (msg.length > 0) { for await (let message of msg) { - inboxId = inboxId + message.id + "," + inboxId = inboxId + message.id + ','; const ssiMessageTags = { messageId: message.id + '', autoProcessed: JSON.stringify(true), isProcessed: JSON.stringify(false), - message: typeof message.message == 'string' ? message.message : JSON.stringify(message.message) - } - const walletRecords = await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify({ 'messageId': message.id + '' })); + message: + typeof message.message == 'string' + ? message.message + : JSON.stringify(message.message), + }; + const walletRecords = await WalletStorageService.getWalletRecordsFromQuery( + RecordType.SSIMessage, + JSON.stringify({ messageId: message.id + '' }), + ); if (walletRecords.length === 0) { await WalletStorageService.addWalletRecord( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, message.id + '', - typeof message.message == 'string' ? message.message : JSON.stringify(message.message), - JSON.stringify(ssiMessageTags) + typeof message.message == 'string' + ? message.message + : JSON.stringify(message.message), + JSON.stringify(ssiMessageTags), ); } } @@ -87,74 +101,121 @@ class InboundMessageHandler { inboxId = inboxId.substring(0, inboxId.length - 1); const apiBody = { publicKey: DatabaseServices.getVerKey(), - inboxId: inboxId + inboxId: inboxId, }; this.socket.emit('receiveAcknowledgement', apiBody); - EventRegister.emit('inboundMessageStatusListener', `inboundMessageStatusListener`); + EventRegister.emit( + 'inboundMessageStatusListener', + `inboundMessageStatusListener`, + ); } } - inboundMessageStatusListener = EventRegister.addEventListener('inboundMessageStatusListener', async () => { - const query: Object = { isProcessed: JSON.stringify(false) } - const unprocessedMessages: Array = await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify(query)); - if (this.isProcess === false && unprocessedMessages.length > 0) { - await this.proceedInboundMessage(); - } - }); + inboundMessageStatusListener = EventRegister.addEventListener( + 'inboundMessageStatusListener', + async () => { + const query: Object = { isProcessed: JSON.stringify(false) }; + const unprocessedMessages: Array< + Record + > = await WalletStorageService.getWalletRecordsFromQuery( + RecordType.SSIMessage, + JSON.stringify(query), + ); + if (this.isProcess === false && unprocessedMessages.length > 0) { + await this.proceedInboundMessage(); + } + }, + ); proceedInboundMessage = async () => { - try { - const query: Object = { isProcessed: JSON.stringify(false) } - let unprocessedMessages: Array = await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, JSON.stringify(query)); + const query: Object = { isProcessed: JSON.stringify(false) }; + let unprocessedMessages: Array< + Record + > = await WalletStorageService.getWalletRecordsFromQuery( + RecordType.SSIMessage, + JSON.stringify(query), + ); if (unprocessedMessages === null) { - unprocessedMessages = [] + unprocessedMessages = []; } for (let i = 0; i < unprocessedMessages.length; i++) { this.isProcess = true; if (unprocessedMessages[i].tags.autoProcessed === 'true') { const messageRecord = JSON.parse(unprocessedMessages[i].value); - const unpackMessageResponse = await unpackMessage(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), messageRecord.msg); + const unpackMessageResponse = await unpackMessage(messageRecord.msg); const message = JSON.parse(unpackMessageResponse.message); const query = { - connectionId: unpackMessageResponse.recipient_verkey - } + connectionId: unpackMessageResponse.recipient_verkey, + }; - const connection = await WalletStorageService.getWalletRecordFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.Connection, JSON.stringify(query)); - console.log('connection', typeof connection) + const connection = await WalletStorageService.getWalletRecordFromQuery( + RecordType.Connection, + JSON.stringify(query), + ); + console.log('connection', typeof connection); if (connection.length === 0 || connection.verkey === '') { - console.log('Connection not found') - await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id); + console.log('Connection not found'); + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + unprocessedMessages[i].id, + ); this.isProcess = false; return; } switch (message['@type']) { case MessageType.ConnectionResponse: { - const isCompleted = await ConnectionService.processRequest(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse); - if (isCompleted === true) await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id); + const isCompleted = await ConnectionService.processRequest( + unpackMessageResponse, + ); + if (isCompleted === true) + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + unprocessedMessages[i].id, + ); break; } case MessageType.ConnectionRequest: { - const isCompleted = await ConnectionService.createResponse(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse); - if (isCompleted === true) await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id); + const isCompleted = await ConnectionService.createResponse( + unpackMessageResponse, + ); + if (isCompleted === true) + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + unprocessedMessages[i].id, + ); break; } case MessageType.TrustPingMessage: { - const connection: Connection = await TrustPingService.processPing(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse); - if (connection !== null) { await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) } + const connection: Connection = await TrustPingService.processPing( + unpackMessageResponse, + ); + if (connection !== null) { + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + unprocessedMessages[i].id, + ); + } const event: EventInterface = { message: `You are now connected with ${connection.theirLabel}`, type: 'Connection', - } + }; EventRegister.emit('SDKEvent', event); - console.log("Connected by scanning the QR code ..."); + console.log('Connected by scanning the QR code ...'); break; } case MessageType.TrustPingResponseMessage: { - const connection: Connection = await TrustPingService.saveTrustPingResponse(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse); - if (connection !== null) { await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) } + const connection: Connection = await TrustPingService.saveTrustPingResponse( + unpackMessageResponse, + ); + if (connection !== null) { + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + unprocessedMessages[i].id, + ); + } break; } case MessageType.OfferCredential: { @@ -164,28 +225,43 @@ class InboundMessageHandler { const ssiMessageTags = { messageId: unprocessedMessages[i].id + '', autoProcessed: JSON.stringify(false), - thId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], + thId: message.hasOwnProperty('~thread') + ? Object.keys(message['~thread']).length > 0 === false + ? message['@id'] + : message['~thread'].thid + : message['@id'], isProcessed: JSON.stringify(true), - } + }; await WalletStorageService.updateWalletRecord( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id + '', JSON.stringify(unpackMessageResponse), - JSON.stringify(ssiMessageTags) + JSON.stringify(ssiMessageTags), + ); + const connection = await CredentialService.requestReceived( + unpackMessageResponse, + unprocessedMessages[i].id, ); - const connection = await CredentialService.requestReceived(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse, unprocessedMessages[i].id); const event: EventInterface = { - message: `You have received a credential from ${connection.theirLabel}`, + message: `You have received a credential from ${ + connection.theirLabel + }`, type: 'Credential', - messageData: JSON.stringify({ connection }) - } + messageData: JSON.stringify({ connection }), + }; EventRegister.emit('SDKEvent', event); break; } case MessageType.IssueCredential: { - const isCompleted = await CredentialService.processCredential(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse); - if (isCompleted) { await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) } + const isCompleted = await CredentialService.processCredential( + unpackMessageResponse, + ); + if (isCompleted) { + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + unprocessedMessages[i].id, + ); + } break; } case MessageType.RequestPresentation: { @@ -195,33 +271,44 @@ class InboundMessageHandler { const ssiMessageTags = { messageId: unprocessedMessages[i].id + '', autoProcessed: JSON.stringify(false), - thId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], + thId: message.hasOwnProperty('~thread') + ? Object.keys(message['~thread']).length > 0 === false + ? message['@id'] + : message['~thread'].thid + : message['@id'], isProcessed: JSON.stringify(true), - } + }; await WalletStorageService.updateWalletRecord( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id + '', JSON.stringify(unpackMessageResponse), - JSON.stringify(ssiMessageTags) + JSON.stringify(ssiMessageTags), + ); + const connection = await PresentationService.processRequest( + unprocessedMessages[i].id, + unpackMessageResponse, ); - const connection = await PresentationService.processRequest(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unprocessedMessages[i].id, unpackMessageResponse); const event: EventInterface = { - message: `You have received a proof request from ${connection.theirLabel}`, + message: `You have received a proof request from ${ + connection.theirLabel + }`, type: 'Proof Request', - messageData: JSON.stringify({ connection }) - } + messageData: JSON.stringify({ connection }), + }; EventRegister.emit('SDKEvent', event); break; } case MessageType.PresentationAck: { - await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + unprocessedMessages[i].id, + ); const event: EventInterface = { message: 'Your proof is verified successfully', type: 'Proof Status', - messageData: JSON.stringify({ connection }) - } + messageData: JSON.stringify({ connection }), + }; EventRegister.emit('SDKEvent', event); break; } @@ -232,40 +319,60 @@ class InboundMessageHandler { const ssiMessageTags = { messageId: unprocessedMessages[i].id + '', autoProcessed: JSON.stringify(false), - thId: message.hasOwnProperty('~thread') ? Object.keys(message['~thread']).length > 0 === false ? message['@id'] : message['~thread'].thid : message['@id'], + thId: message.hasOwnProperty('~thread') + ? Object.keys(message['~thread']).length > 0 === false + ? message['@id'] + : message['~thread'].thid + : message['@id'], isProcessed: JSON.stringify(true), - } + }; await WalletStorageService.updateWalletRecord( - JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id + '', JSON.stringify(unpackMessageResponse), - JSON.stringify(ssiMessageTags) + JSON.stringify(ssiMessageTags), + ); + const connection = await PresentationService.requestReceived( + unprocessedMessages[i].id, + unpackMessageResponse, ); - const connection = await PresentationService.requestReceived(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unprocessedMessages[i].id, unpackMessageResponse); const event: EventInterface = { - message: `You have received a proof request to verify from ${connection.theirLabel}`, + message: `You have received a proof request to verify from ${ + connection.theirLabel + }`, type: 'Verify Proof', - messageData: JSON.stringify({ connection }) - } + messageData: JSON.stringify({ connection }), + }; EventRegister.emit('SDKEvent', event); break; } case MessageType.problemReport: { - await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + unprocessedMessages[i].id, + ); break; } case MessageType.BasicMessage: { - const connection = await BasicMessageService.save(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), unpackMessageResponse, unpackMessageResponse.recipient_verkey); - if (connection) { await WalletStorageService.deleteWalletRecord(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.SSIMessage, unprocessedMessages[i].id) } - + const connection = await BasicMessageService.save( + unpackMessageResponse, + unpackMessageResponse.recipient_verkey, + ); + if (connection) { + await WalletStorageService.deleteWalletRecord( + RecordType.SSIMessage, + unprocessedMessages[i].id, + ); + } const event: EventInterface = { - message: `You have received a message from ${connection.theirLabel}`, + message: `You have received a message from ${ + connection.theirLabel + }`, type: 'Message', connectionId: connection.verkey, - messageData: JSON.stringify({ connection }) - } + messageData: JSON.stringify({ connection }), + }; EventRegister.emit('SDKEvent', event); break; } @@ -276,17 +383,21 @@ class InboundMessageHandler { } } this.isProcess = false; - EventRegister.emit('inboundMessageStatusListener', `inboundMessageStatusListener`); + EventRegister.emit( + 'inboundMessageStatusListener', + `inboundMessageStatusListener`, + ); return true; - } - catch (error) { - console.warn('Agent - Proceed inbound message error = ', error) + } catch (error) { + console.warn('Agent - Proceed inbound message error = ', error); this.isProcess = false; - EventRegister.emit('inboundMessageStatusListener', `inboundMessageStatusListener`); + EventRegister.emit( + 'inboundMessageStatusListener', + `inboundMessageStatusListener`, + ); throw error; } - } - + }; } -export default new InboundMessageHandler(); \ No newline at end of file +export default new InboundMessageHandler(); diff --git a/src/utils/Helpers.ts b/src/utils/Helpers.ts index a6ba5f7..2a2f706 100644 --- a/src/utils/Helpers.ts +++ b/src/utils/Helpers.ts @@ -3,20 +3,19 @@ SPDX-License-Identifier: Apache-2.0 */ -import { Connection } from '../protocols/connection/ConnectionInterface'; -import { createForwardMessage } from '../protocols/connection/ConnectionMessages'; -import { InboundMessage, OutboundMessage } from './Types'; -import { InvitationDetails } from '../protocols/connection/InvitationInterface'; -import { Message } from './Types'; -import { NativeModules, Platform } from "react-native"; -import { OutboundAgentMessage } from '../network'; -import { WalletConfig, WalletCredentials } from '../wallet/WalletInterface'; -import base64url from 'base64url'; -import DatabaseServices from '../storage'; +import { Connection } from '../protocols/connection/ConnectionInterface' +import { createForwardMessage } from '../protocols/connection/ConnectionMessages' +import { InboundMessage, OutboundMessage } from './Types' +import { InvitationDetails } from '../protocols/connection/InvitationInterface' +import { Message } from './Types' +import { NativeModules, Platform } from 'react-native' +import { OutboundAgentMessage } from '../network' +import base64url from 'base64url' +import DatabaseServices from '../storage' -const Buffer = require('buffer').Buffer; +const Buffer = require('buffer').Buffer -const { ArnimaSdk } = NativeModules; +const { ArnimaSdk } = NativeModules export enum RecordType { Connection = 'Connection', @@ -26,43 +25,42 @@ export enum RecordType { Presentation = 'Presentation', MediatorAgent = 'MediatorAgent', SSIMessage = 'SSIMessage', - Pool = 'Pool' + Pool = 'Pool', } function timestamp(): Uint8Array { - let time = Date.now(); - const bytes = []; + let time = Date.now() + const bytes = [] for (let i = 0; i < 8; i++) { - const byte = time & 0xff; - bytes.push(byte); - time = (time - byte) / 256; // Javascript right shift (>>>) only works on 32 bit integers + const byte = time & 0xff + bytes.push(byte) + time = (time - byte) / 256 // Javascript right shift (>>>) only works on 32 bit integers } - return Uint8Array.from(bytes).reverse(); + return Uint8Array.from(bytes).reverse() } -export async function verify(configJson: WalletConfig, credentialsJson: WalletCredentials, message: Message, field: string) { +export async function verify(message: Message, field: string) { try { const fieldKey = `${field}~sig` - const { [fieldKey]: data, ...signedMessage } = message; + const { [fieldKey]: data, ...signedMessage } = message - const signerVerkey = data.signer; - const signedData = base64url.toBuffer(data.sig_data); - const signature = base64url.toBuffer(data.signature); + const signerVerkey = data.signer + const signedData = base64url.toBuffer(data.sig_data) + const signature = base64url.toBuffer(data.signature) - let valid; + let valid if (Platform.OS == 'android') { - valid = await ArnimaSdk.cryptoVerify(JSON.stringify(configJson), - JSON.stringify(credentialsJson), + valid = await ArnimaSdk.cryptoVerify( signerVerkey, Array.from(signedData), - Array.from(signature)); - } - else { - valid = await ArnimaSdk.cryptoVerify(JSON.stringify(configJson), - JSON.stringify(credentialsJson), + Array.from(signature), + ) + } else { + valid = await ArnimaSdk.cryptoVerify( signerVerkey, data.sig_data, - JSON.stringify(Array.from(signature))); + JSON.stringify(Array.from(signature)), + ) } // if (!valid) { @@ -73,33 +71,39 @@ export async function verify(configJson: WalletConfig, credentialsJson: WalletCr '@id': message['@id'], ...signedMessage, [`${field}`]: JSON.parse(signedData.slice(8).toString('utf-8')), - }; + } - return originalMessage; + return originalMessage } catch (error) { - console.log("verify = ", error); - throw error; + console.log('verify = ', error) + throw error } } -export async function sign(configJson: WalletConfig, credentialsJson: WalletCredentials, signerVerkey: string, message: Message, field: string) { +export async function sign( + signerVerkey: string, + message: Message, + field: string, +) { try { + const { [field]: data, ...originalMessage } = message - const { [field]: data, ...originalMessage } = message; - - const dataBuffer = Buffer.concat([timestamp(), Buffer.from(JSON.stringify(data), 'utf8')]); - let signatureBuffer; + const dataBuffer = Buffer.concat([ + timestamp(), + Buffer.from(JSON.stringify(data), 'utf8'), + ]) + let signatureBuffer if (Platform.OS === 'ios') { - signatureBuffer = await ArnimaSdk.cryptoSign(JSON.stringify(configJson), - JSON.stringify(credentialsJson), + signatureBuffer = await ArnimaSdk.cryptoSign( signerVerkey, - JSON.stringify(data)); + JSON.stringify(data), + ) } else { - signatureBuffer = await ArnimaSdk.cryptoSign(JSON.stringify(configJson), - JSON.stringify(credentialsJson), + signatureBuffer = await ArnimaSdk.cryptoSign( signerVerkey, - Array.from(dataBuffer)); + Array.from(dataBuffer), + ) } const signedMessage = { @@ -107,104 +111,134 @@ export async function sign(configJson: WalletConfig, credentialsJson: WalletCred '@id': message['@id'], ...originalMessage, [`${field}~sig`]: { - '@type': 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/signature/1.0/ed25519Sha512_single', + '@type': + 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/signature/1.0/ed25519Sha512_single', signature: base64url.encode(signatureBuffer), sig_data: base64url.encode(dataBuffer), signer: signerVerkey, }, - }; + } - return signedMessage; + return signedMessage } catch (error) { - console.log("sign message = ", error); - throw error; + console.log('sign message = ', error) + throw error } } -export async function unpackMessage(configJson: WalletConfig, credentialsJson: WalletCredentials, inboundMessage: InboundMessage) { +export async function unpackMessage(inboundMessage: InboundMessage) { try { - const buf = Buffer.from(JSON.stringify(inboundMessage)); - let unpackedBufferMessage; + const buf = Buffer.from(JSON.stringify(inboundMessage)) + let unpackedBufferMessage if (Platform.OS === 'ios') { - unpackedBufferMessage = await ArnimaSdk.unpackMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), JSON.stringify(inboundMessage)) - } - else { - unpackedBufferMessage = await ArnimaSdk.unpackMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), Array.from(buf)) + unpackedBufferMessage = await ArnimaSdk.unpackMessage( + JSON.stringify(inboundMessage), + ) + } else { + unpackedBufferMessage = await ArnimaSdk.unpackMessage(Array.from(buf)) } - const unpackedMessage = Buffer.from(unpackedBufferMessage); - return JSON.parse(unpackedMessage.toString('utf-8')); + const unpackedMessage = Buffer.from(unpackedBufferMessage) + return JSON.parse(unpackedMessage.toString('utf-8')) } catch (error) { - console.log("unpackMessage = ", error); - throw error; + console.log('unpackMessage = ', error) + throw error } } -export async function packMessage(configJson: WalletConfig, credentialsJson: WalletCredentials, outboundMessage: OutboundMessage) { +export async function packMessage(outboundMessage: OutboundMessage) { try { - const { routingKeys, recipientKeys, senderVk, payload } = outboundMessage; - const buf = Buffer.from(JSON.stringify(payload)); - let packedBufferMessage; + const { routingKeys, recipientKeys, senderVk, payload } = outboundMessage + const buf = Buffer.from(JSON.stringify(payload)) + let packedBufferMessage if (Platform.OS === 'ios') { - packedBufferMessage = await ArnimaSdk.packMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), JSON.stringify(payload), recipientKeys, senderVk) - } - else { - packedBufferMessage = await ArnimaSdk.packMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), Array.from(buf), recipientKeys, senderVk) + packedBufferMessage = await ArnimaSdk.packMessage( + JSON.stringify(payload), + recipientKeys, + senderVk, + ) + } else { + packedBufferMessage = await ArnimaSdk.packMessage( + Array.from(buf), + recipientKeys, + senderVk, + ) } - const packedMessage = Buffer.from(packedBufferMessage); - const outboundPackedMessage = JSON.parse(packedMessage.toString('utf-8')); + const packedMessage = Buffer.from(packedBufferMessage) + const outboundPackedMessage = JSON.parse(packedMessage.toString('utf-8')) - let message = outboundPackedMessage; + let message = outboundPackedMessage if (routingKeys && routingKeys.length > 0) { for (const routingKey of routingKeys) { - const [recipientKey] = recipientKeys; - const forwardMessage = createForwardMessage(recipientKey, message); - const forwardMessageBuffer = Buffer.from(JSON.stringify(forwardMessage)); - let forwardBufferMessage; + const [recipientKey] = recipientKeys + const forwardMessage = createForwardMessage(recipientKey, message) + const forwardMessageBuffer = Buffer.from(JSON.stringify(forwardMessage)) + let forwardBufferMessage if (Platform.OS === 'ios') { - forwardBufferMessage = await ArnimaSdk.packMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), JSON.stringify(forwardMessage), [routingKey], senderVk) + forwardBufferMessage = await ArnimaSdk.packMessage( + JSON.stringify(forwardMessage), + [routingKey], + senderVk, + ) + } else { + forwardBufferMessage = await ArnimaSdk.packMessage( + Array.from(forwardMessageBuffer), + [routingKey], + senderVk, + ) } - else { - forwardBufferMessage = await ArnimaSdk.packMessage(JSON.stringify(configJson), JSON.stringify(credentialsJson), Array.from(forwardMessageBuffer), [routingKey], senderVk) - } - const forwardPackedMessage = Buffer.from(forwardBufferMessage); - message = JSON.parse(forwardPackedMessage.toString('utf-8')); + const forwardPackedMessage = Buffer.from(forwardBufferMessage) + message = JSON.parse(forwardPackedMessage.toString('utf-8')) } } - return message; - } - catch (error) { - console.log("packMessage = ", error); - throw error; + return message + } catch (error) { + console.log('packMessage = ', error) + throw error } } export function getServiceEndpoint() { // TODO : Need to find a way for realm db typing - const sdkDB: any = DatabaseServices.getWallet(); - return `${sdkDB.serviceEndpoint.split("/")[0] + "/" + sdkDB.serviceEndpoint.split("/")[1] + "/" + sdkDB.serviceEndpoint.split("/")[2]}/`; + const sdkDB: any = DatabaseServices.getWallet() + return `${sdkDB.serviceEndpoint.split('/')[0] + + '/' + + sdkDB.serviceEndpoint.split('/')[1] + + '/' + + sdkDB.serviceEndpoint.split('/')[2]}/` } export function decodeInvitationFromUrl(invitationUrl: string) { - const [, encodedInvitation] = invitationUrl.split('c_i='); - return JSON.parse(Buffer.from(encodedInvitation, 'base64').toString()); + const [, encodedInvitation] = invitationUrl.split('c_i=') + return JSON.parse(Buffer.from(encodedInvitation, 'base64').toString()) } export function encodeInvitationToUrl(invitation: InvitationDetails): string { - const encodedInvitation = Buffer.from(JSON.stringify(invitation)).toString('base64'); + const encodedInvitation = Buffer.from(JSON.stringify(invitation)).toString( + 'base64', + ) // TODO : Need to find a way for realm db typing - const sdkDB: any = DatabaseServices.getWallet(); - return `${sdkDB.serviceEndpoint.split("/")[0] + "/" + sdkDB.serviceEndpoint.split("/")[1] + "/" + sdkDB.serviceEndpoint.split("/")[2]}/ssi?c_i=${encodedInvitation}`; + const sdkDB: any = DatabaseServices.getWallet() + return `${sdkDB.serviceEndpoint.split('/')[0] + + '/' + + sdkDB.serviceEndpoint.split('/')[1] + + '/' + + sdkDB.serviceEndpoint.split('/')[2]}/ssi?c_i=${encodedInvitation}` } export function decodeBase64(base64Data: string) { - return JSON.parse(Buffer.from(base64Data, 'base64').toString()); + return JSON.parse(Buffer.from(base64Data, 'base64').toString()) } export function encodeBase64(data: string) { - return Buffer.from(JSON.stringify(data)).toString('base64'); + return Buffer.from(JSON.stringify(data)).toString('base64') } -export async function createOutboundMessage(connection: Connection, payload: Object, invitation?: Message, oobService?: object) { +export async function createOutboundMessage( + connection: Connection, + payload: Object, + invitation?: Message, + oobService?: object, +) { if (connection) { if (invitation) { const { recipientKeys, routingKeys, serviceEndpoint } = invitation @@ -215,13 +249,15 @@ export async function createOutboundMessage(connection: Connection, payload: Obj recipientKeys: recipientKeys, routingKeys: routingKeys || [], senderVk: connection.verkey, - }; + } } - const { theirDidDoc } = connection; + const { theirDidDoc } = connection if (!theirDidDoc) { - throw new Error(`DidDoc for connection with verkey ${connection.verkey} not found!`); + throw new Error( + `DidDoc for connection with verkey ${connection.verkey} not found!`, + ) } const { service } = theirDidDoc return { @@ -231,12 +267,16 @@ export async function createOutboundMessage(connection: Connection, payload: Obj recipientKeys: service[0].recipientKeys, routingKeys: service[0].routingKeys, senderVk: connection.verkey, - }; + } } else { - const wallet = await DatabaseServices.getWallet(); + const wallet = await DatabaseServices.getWallet() const [pairwiseDid, verkey]: string[] = await ArnimaSdk.createAndStoreMyDid( - wallet.walletConfig, wallet.walletCredentials, JSON.stringify({}), false); - const { recipientKeys, routingKeys, serviceEndpoint } = oobService; + wallet.walletConfig, + wallet.walletCredentials, + JSON.stringify({}), + false, + ) + const { recipientKeys, routingKeys, serviceEndpoint } = oobService return { payload, recipientKeys, @@ -247,8 +287,22 @@ export async function createOutboundMessage(connection: Connection, payload: Obj } } -export async function sendOutboundMessage(configJson: WalletConfig, credentialsJson: WalletCredentials, connection: Connection, message: Object, invitation?: Message, oobService?: object) { - const outboundMessage = await createOutboundMessage(connection, message, invitation, oobService); - const outboundPackMessage = await packMessage(configJson, credentialsJson, outboundMessage); - await OutboundAgentMessage(outboundMessage.endpoint, 'POST', JSON.stringify(outboundPackMessage)); +export async function sendOutboundMessage( + connection: Connection, + message: Object, + invitation?: Message, + oobService?: object, +) { + const outboundMessage = await createOutboundMessage( + connection, + message, + invitation, + oobService, + ) + const outboundPackMessage = await packMessage(outboundMessage) + await OutboundAgentMessage( + outboundMessage.endpoint, + 'POST', + JSON.stringify(outboundPackMessage), + ) } diff --git a/src/utils/MessageType.ts b/src/utils/MessageType.ts index 4a58385..82bc097 100644 --- a/src/utils/MessageType.ts +++ b/src/utils/MessageType.ts @@ -10,7 +10,7 @@ export enum MessageType { TrustPingMessage = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping', TrustPingResponseMessage = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping_response', - + ProposeCredential = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/propose-credential', OfferCredential = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/offer-credential', RequestCredential = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/request-credential', @@ -22,13 +22,13 @@ export enum MessageType { RequestPresentation = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0/request-presentation', Presentation = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0/presentation', PresentationAck = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0/ack', - presentationPreview = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0/presentation-preview", - + presentationPreview = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0/presentation-preview', + BasicMessage = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message', - + ForwardMessage = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/routing/1.0/forward', - + Ack = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/notification/1.0/ack', - problemReport = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/notification/1.0/problem-report" + problemReport = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/notification/1.0/problem-report', } diff --git a/src/wallet/WalletService.ts b/src/wallet/WalletService.ts index a61fbc8..7a08554 100644 --- a/src/wallet/WalletService.ts +++ b/src/wallet/WalletService.ts @@ -3,41 +3,56 @@ SPDX-License-Identifier: Apache-2.0 */ -import { DidJson, WalletConfig, WalletCredentials, WalletRecord } from "./WalletInterface"; -import { NativeModules } from "react-native"; -import { RecordType } from "../utils/Helpers"; -import DatabaseServices from '../storage'; -import WalletStorageService from "./WalletStorageService"; +import { + DidJson, + WalletConfig, + WalletCredentials, + WalletRecord, +} from './WalletInterface' +import { NativeModules } from 'react-native' +import { RecordType } from '../utils/Helpers' +import DatabaseServices from '../storage' +import WalletStorageService from './WalletStorageService' -const { ArnimaSdk } = NativeModules; +const { ArnimaSdk } = NativeModules class WalletService { - - async createWallet(config: WalletConfig, credentials: WalletCredentials, label: string): Promise { + async createWallet( + config: WalletConfig, + credentials: WalletCredentials, + label: string, + ): Promise { try { await ArnimaSdk.createWallet( JSON.stringify(config), - JSON.stringify(credentials) - ); - return await this.createWalletDidStore(config, credentials, {}, true, label); + JSON.stringify(credentials), + ) + return await this.createWalletDidStore( + config, + credentials, + {}, + true, + label, + ) } catch (error) { - console.log('WalletService - Create wallet error = ', error); - throw (error); + console.log('WalletService - Create wallet error = ', error) + throw error } } - async createWalletDidStore(config: WalletConfig, + async createWalletDidStore( + config: WalletConfig, credentials: WalletCredentials, didJson: DidJson, createMasterSecret: boolean, - label: string): Promise { - + label: string, + ): Promise { const response: string[] = await ArnimaSdk.createAndStoreMyDid( JSON.stringify(config), JSON.stringify(credentials), JSON.stringify(didJson), - createMasterSecret - ); + createMasterSecret, + ) if (response.length > 0) { const [did, verkey, masterSecretId] = response @@ -46,19 +61,19 @@ class WalletService { walletConfig: JSON.stringify(config), walletCredentials: JSON.stringify(credentials), label: label, - serviceEndpoint: "", - routingKey: "", + serviceEndpoint: '', + routingKey: '', publicDid: did, verKey: verkey, masterSecretId: masterSecretId, - }); + }) const walletRecord: WalletRecord = { walletConfig: config, walletCredentials: credentials, label: label, - serviceEndpoint: "", - routingKey: "", + serviceEndpoint: '', + routingKey: '', publicDid: did, verKey: verkey, masterSecretId: masterSecretId, @@ -71,43 +86,39 @@ class WalletService { } await WalletStorageService.addWalletRecord( - config, - credentials, RecordType.MediatorAgent, '1', JSON.stringify(walletRecord), - JSON.stringify(walletRecordTags) - ); + JSON.stringify(walletRecordTags), + ) } - return response; + return response } async getWallet(): Promise { try { // TODO : Need to find a way for realm db typing - const response: any = await DatabaseServices.getWallet(); + const response: any = await DatabaseServices.getWallet() return response } catch (error) { - console.log('WalletService - Get wallet error = ', error); - throw error; + console.log('WalletService - Get wallet error = ', error) + throw error } - } async openWallet(): Promise { try { // TODO : Need to find a way for realm db typing - const sdkDB: any = DatabaseServices.getWallet(); + const sdkDB: any = DatabaseServices.getWallet() const response: boolean = await ArnimaSdk.openInitWallet( sdkDB.walletConfig, - sdkDB.walletCredentials - ); - return response; + sdkDB.walletCredentials, + ) + return response } catch (error) { - console.log('WalletService - Open wallet error = ', error); - throw error; + console.log('WalletService - Open wallet error = ', error) + throw error } - }; - + } } -export default new WalletService(); \ No newline at end of file +export default new WalletService() diff --git a/src/wallet/WalletStorageService.ts b/src/wallet/WalletStorageService.ts index c78dc69..b1e27d1 100644 --- a/src/wallet/WalletStorageService.ts +++ b/src/wallet/WalletStorageService.ts @@ -3,75 +3,95 @@ SPDX-License-Identifier: Apache-2.0 */ -import { NativeModules } from "react-native"; -import { Record, WalletConfig, WalletCredentials, WalletStorageRecord } from "./WalletInterface"; +import { NativeModules } from 'react-native' +import { Record, WalletStorageRecord } from './WalletInterface' -const { ArnimaSdk } = NativeModules; +const { ArnimaSdk } = NativeModules class WalletStorageService { - - async addWalletRecord(config: WalletConfig, credentials: WalletCredentials, type: string, id: string, - value: string, tags: string) { - + async addWalletRecord(type: string, id: string, value: string, tags: string) { try { - return await ArnimaSdk.addWalletRecord(JSON.stringify(config), JSON.stringify(credentials), - type, id, value, tags); + return await ArnimaSdk.addWalletRecord(type, id, value, tags) } catch (error) { - console.log('WalletStorageService - ' + type + ' - Add wallet record = ', error); - throw error; + console.log( + 'WalletStorageService - ' + type + ' - Add wallet record = ', + error, + ) + throw error } } - async updateWalletRecord(config: WalletConfig, credentials: WalletCredentials, type: string, id: string, - value: string, tags: string) { - + async updateWalletRecord( + type: string, + id: string, + value: string, + tags: string, + ) { try { - return await ArnimaSdk.updateWalletRecord(JSON.stringify(config), JSON.stringify(credentials), - type, id, value, tags); + return await ArnimaSdk.updateWalletRecord(type, id, value, tags) } catch (error) { - console.log('WalletStorageService - ' + type + ' - Update wallet record = ', error); - throw error; + console.log( + 'WalletStorageService - ' + type + ' - Update wallet record = ', + error, + ) + throw error } } - async deleteWalletRecord(config: WalletConfig, credentials: WalletCredentials, type: string, id: string) { - + async deleteWalletRecord(type: string, id: string) { try { - return await ArnimaSdk.deleteWalletRecord(JSON.stringify(config), JSON.stringify(credentials), - type, id); + return await ArnimaSdk.deleteWalletRecord(type, id) } catch (error) { - console.log('WalletStorageService - ' + type + ' - Delete wallet record = ', error); - throw error; + console.log( + 'WalletStorageService - ' + type + ' - Delete wallet record = ', + error, + ) + throw error } } - async getWalletRecordFromQuery(config: WalletConfig, credentials: WalletCredentials, type: string, query: string) { - + async getWalletRecordFromQuery(type: string, query: string) { try { - const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery(JSON.stringify(config), JSON.stringify(credentials), type, query); + const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery( + type, + query, + ) - const walletRecord: WalletStorageRecord = JSON.parse(queryResponse); + const walletRecord: WalletStorageRecord = JSON.parse(queryResponse) if (walletRecord.records !== null) { - return JSON.parse(walletRecord.records[0].value); + return JSON.parse(walletRecord.records[0].value) } else { // For basic message history, I am returning the empty object return [] } - } catch (error) { - console.log('WalletStorageService - ' + type + ' - Get wallet record from query = ', error); - throw error; + console.log( + 'WalletStorageService - ' + type + ' - Get wallet record from query = ', + error, + ) + throw error } } - async getWalletRecordsFromQuery(config: WalletConfig, credentials: WalletCredentials, type: string, query: string): Promise> { + async getWalletRecordsFromQuery( + type: string, + query: string, + ): Promise> { try { - const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery(JSON.stringify(config), JSON.stringify(credentials), type, query); - const walletRecord: WalletStorageRecord = JSON.parse(queryResponse); - return walletRecord.records === null ? [] : walletRecord.records; + const queryResponse: string = await ArnimaSdk.getWalletRecordFromQuery( + type, + query, + ) + const walletRecord: WalletStorageRecord = JSON.parse(queryResponse) + return walletRecord.records === null ? [] : walletRecord.records } catch (error) { - console.log('WalletStorageService - ' + type + ' - Get wallet records from query = ', error); - throw error; + console.log( + 'WalletStorageService - ' + + type + + ' - Get wallet records from query = ', + error, + ) + throw error } } } -export default new WalletStorageService(); \ No newline at end of file +export default new WalletStorageService()