Skip to content
This repository has been archived by the owner on Aug 17, 2023. It is now read-only.

Feat/mediator coordination protocol DONT MERGE #20

Draft
wants to merge 16 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

{
"name": "react-native-arnima-sdk",
"version": "1.0.0",
Expand Down
68 changes: 63 additions & 5 deletions src/agent/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ 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 MediatorService from '../protocols/mediator/MediatorService';
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';
import { Connection } from 'react-native-arnima-sdk/src/protocols/connection/ConnectionInterface';

const { ArnimaSdk } = NativeModules;

Expand All @@ -40,8 +41,8 @@ class Agent {

connectWithMediator = async (url: string, apiType: string, apiBody: string) => {
try {
const response = await ConnectWithMediatorService.ConnectWithMediator(url, apiType, apiBody);
this.wallet = await DatabaseServices.getWallet();
const response = await MediatorService.ConnectWithMediator(url, apiType, apiBody);
return response;
}
catch (error) {
Expand All @@ -50,9 +51,49 @@ class Agent {
}
}

connectMediatorWithInvite = async (invitationUrl: string) => {
const connection = await this.acceptInvitation({},invitationUrl,'');

setTimeout(() => {
ConnectionService.connectionStatus(
JSON.parse(this.wallet.walletConfig),
JSON.parse(this.wallet.walletCredentials),
connection.verkey,
)
}, 5000);
connection.state == 'COMPLETE'
}

mediationRequest = async (connection: Connection) => {
try {
await MediatorService.mediationRequest(connection);
} catch (error) {
console.log("Agent - mediationRequest error = ", error);
throw error;
}
}

pickupMessages = async (mediatorConnection: Connection) => {
try {
await MediatorService.pickupMessages(mediatorConnection);
} catch (error) {
console.log("Agent - pickupMessages error = ", error);
throw error;
}
}

sendImplicitMessages = async (mediatorConnection: Connection) => {
try {
await MediatorService.sendImplicitMessages(mediatorConnection);
} catch (error) {
console.log("Agent - pickupMessages error = ", error);
throw error;
}
}

updateMediator = async (url: string, apiType: string, apiBody: string) => {
try {
return await ConnectWithMediatorService.updateMediator(url, apiType, apiBody);
return await MediatorService.updateMediator(url, apiType, apiBody);
}
catch (error) {
console.log("Agent - Update mediator error = ", error);
Expand Down Expand Up @@ -115,10 +156,17 @@ class Agent {
}
}

acceptInvitation = async (didJson: Object, message: any, logo: string,) => {
acceptInvitation = async (didJson: Object, message: any, logo: string) => {
try {
this.wallet = await DatabaseServices.getWallet();
const invitation = decodeInvitationFromUrl(message);
return await ConnectionService.acceptInvitation(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), didJson, invitation, logo);
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);
Expand All @@ -136,6 +184,16 @@ class Agent {
}
}

getMediatorRecord = async (query: Object) => {
try {
return await WalletStorageService.getWalletRecordsFromQuery(JSON.parse(this.wallet.walletConfig), JSON.parse(this.wallet.walletCredentials), RecordType.MediatorAgent, 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));
Expand Down
51 changes: 30 additions & 21 deletions src/network/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Copyright AyanWorks Technology Solutions Pvt. Ltd. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
import InboundMessageService from '../transports';

export const NetworkServices: Function = async (url: string, apiType: string, apiBody: string) => {
try {
Expand All @@ -26,28 +27,36 @@ export const NetworkServices: Function = async (url: string, apiType: string, ap

export const OutboundAgentMessage: Function = async (url: string, apiType: string, apiBody: string) => {
try {
return new Promise(async function (
resolve, reject
) {
const response = await fetch(url, {
method: apiType,
body: apiBody,
headers: {
Accept: 'application/json',
'Content-Type': 'application/ssi-agent-wire',
},
}).then((response) => {
response.json()
})
.then((json) => {
resolve(json);
})
.catch((error) => {
reject('We are not able to communicate with the agent at this moment, Please try again later');
});
console.log("url", url)
const abortController = new AbortController()
const id = setTimeout(() => abortController.abort(), 4000)
const response = await fetch(url, {
method: 'POST',
body: apiBody,
headers: { 'Content-Type': 'application/ssi-agent-wire' },
signal: abortController.signal,
})
clearTimeout(id)
const responseMessage = await response.text()
if (responseMessage) {
console.log(`Response received`)
try {
const wireMessage = JSON.parse(responseMessage)
if (wireMessage.hasOwnProperty('tag')) {
await InboundMessageService.addMessages(wireMessage)
}
} catch (error) {
console.log('Unable to parse response message', error)
}
} else {
console.log(`No response received.`)
}
)
} catch (error) {
throw new Error('We are not able to communicate with the agent at this moment, Please try again later');
console.log('Error OutboundAgentMessage', error)
if (error.name == 'AbortError') {
console.log('Signal aborted')
} else {
throw new Error('We are not able to communicate with the agent at this moment, Please try again later');
}
}
};
68 changes: 48 additions & 20 deletions src/protocols/connection/ConnectionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ 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 WalletStorageService from '../../wallet/WalletStorageService';
import { createTrustPingMessage } from '../trustPing/TrustPingMessages';
import MediatorService from '../mediator/MediatorService';
import { EventInterface } from 'react-native-arnima-sdk/src/agent/EventInterface';
import { EventRegister } from 'react-native-event-listeners';

Expand Down Expand Up @@ -65,7 +65,9 @@ class ConnectionService {
credentialsJson: WalletCredentials,
didJson: Object,
logo: string): Promise<string> {
const connection: Connection = await this.createConnection(configJson, credentialsJson, didJson);

const routing = await MediatorService.getRouting();
const connection: Connection = await this.createConnection(routing, '');

const connectionTags: Object = {
connectionId: connection.verkey,
Expand Down Expand Up @@ -98,20 +100,24 @@ class ConnectionService {
* @return {*} {Promise<Connection>}
* @memberof ConnectionService
*/
async acceptInvitation(configJson: WalletConfig,
async acceptInvitation(
configJson: WalletConfig,
credentialsJson: WalletCredentials,
didJson: Object,
invitation: Message,
logo: string): Promise<Connection> {
logo: string,
): Promise<Connection> {
try {
const connection: Connection = await this.createConnection(configJson, credentialsJson, didJson, invitation.label,
const routing = await MediatorService.getRouting();
const connection: Connection = await this.createConnection(
routing,
invitation.label,
invitation.hasOwnProperty('alias') ? invitation.alias.logoUrl : '',
invitation.hasOwnProperty('alias') ? invitation.alias.organizationId : '');
invitation.hasOwnProperty('alias') ? invitation.alias.organizationId : '',
);
const connectionRequest = createConnectionRequestMessage(connection, DatabaseServices.getLabel(), logo);
connection.state = ConnectionState.REQUESTED;

await sendOutboundMessage(configJson, credentialsJson, connection, connectionRequest, invitation)

const connectionTags: Object = {
connectionId: connection.verkey,
}
Expand All @@ -124,9 +130,10 @@ class ConnectionService {
JSON.stringify(connection),
JSON.stringify(connectionTags)
);
await sendOutboundMessage(configJson, credentialsJson, connection, connectionRequest, invitation)
return connection;
} catch (error) {
console.log('Connection - Create invitation error = ', JSON.stringify(error));
console.log('Connection - Accept invitation error = ', JSON.stringify(error));
throw error;
}
}
Expand Down Expand Up @@ -282,23 +289,22 @@ class ConnectionService {
* @return {*} {Promise<Connection>}
* @memberof ConnectionService
*/
async createConnection(configJson: WalletConfig,
credentialsJson: WalletCredentials,
didJson: Object,
async createConnection(
routing: {
endpoint: string;
routingKeys: string[];
pairwiseDid: string;
verkey: string;
},
label?: string,
logo?: string,
organizationId?: string,
): Promise<Connection> {
try {
const [pairwiseDid, verkey]: string[] = await ArnimaSdk.createAndStoreMyDid(JSON.stringify(configJson), JSON.stringify(credentialsJson), JSON.stringify(didJson), false);
const { endpoint, pairwiseDid, routingKeys, verkey } = routing;

const apiBody = {
publicVerkey: DatabaseServices.getVerKey(),
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');
const service = new Service(`${pairwiseDid};indy`, endpoint, [verkey], routingKeys, 0, 'IndyAgent');
const auth = new Authentication(publicKey);
const did_doc = new DidDoc(pairwiseDid, [auth], [publicKey], [service]);

Expand All @@ -316,14 +322,36 @@ class ConnectionService {
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};

return connection;
}
catch (error) {
console.log('Connection - Create connection error = ', JSON.stringify(error));
throw error;
}
}


async connectionStatus(
configJson: WalletConfig,
credentialsJson: WalletCredentials,
verkey:string,
) {
try {
const query = {
connectionId: verkey
}
const connection: Connection = await WalletStorageService.getWalletRecordFromQuery(configJson, credentialsJson, RecordType.Connection, JSON.stringify(query));
if (!connection) {
throw new Error(`Connection for verkey ${verkey} not found!`);
}
return connection;
}
catch (error) {
console.log('Connection - Connection status error = ', JSON.stringify(error));
throw error;
}
}

}

export default new ConnectionService();
Loading