forked from openwallet-foundation/credo-ts
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhelpers.ts
223 lines (185 loc) · 8.25 KB
/
helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/* eslint-disable no-console */
import type { SchemaId, Schema, CredDefId, CredDef, Did } from 'indy-sdk';
import path from 'path';
import { Subject } from 'rxjs';
import { Agent, InboundTransporter, OutboundTransporter } from '..';
import { OutboundPackage, WireMessage } from '../types';
import { ConnectionRecord } from '../modules/connections';
import { ProofRecord, ProofState, ProofEventType, ProofStateChangedEvent } from '../modules/proofs';
import { SchemaTemplate, CredDefTemplate } from '../modules/ledger';
import {
CredentialRecord,
CredentialOfferTemplate,
CredentialEventType,
CredentialStateChangedEvent,
CredentialState,
} from '../modules/credentials';
import { BasicMessage, BasicMessageEventType, BasicMessageReceivedEvent } from '../modules/basic-messages';
import testLogger from './logger';
export const genesisPath = process.env.GENESIS_TXN_PATH
? path.resolve(process.env.GENESIS_TXN_PATH)
: path.join(__dirname, '../../../network/genesis/local-genesis.txn');
export const sleep = (ms: number) => new Promise(res => setTimeout(res, ms));
// Custom matchers which can be used to extend Jest matchers via extend, e. g. `expect.extend({ toBeConnectedWith })`.
export function toBeConnectedWith(received: ConnectionRecord, connection: ConnectionRecord) {
const pass = received.theirDid === connection.did && received.theirKey === connection.verkey;
if (pass) {
return {
message: () =>
`expected connection ${received.did}, ${received.verkey} not to be connected to with ${connection.did}, ${connection.verkey}`,
pass: true,
};
} else {
return {
message: () =>
`expected connection ${received.did}, ${received.verkey} to be connected to with ${connection.did}, ${connection.verkey}`,
pass: false,
};
}
}
export async function waitForProofRecord(
agent: Agent,
{ threadId, state, previousState }: { threadId?: string; state?: ProofState; previousState?: ProofState | null }
): Promise<ProofRecord> {
return new Promise(resolve => {
const listener = (event: ProofStateChangedEvent) => {
const previousStateMatches = previousState === undefined || event.previousState === previousState;
const threadIdMatches = threadId === undefined || event.proofRecord.tags.threadId === threadId;
const stateMatches = state === undefined || event.proofRecord.state === state;
if (previousStateMatches && threadIdMatches && stateMatches) {
agent.proofs.events.removeListener(ProofEventType.StateChanged, listener);
resolve(event.proofRecord);
}
};
agent.proofs.events.addListener(ProofEventType.StateChanged, listener);
});
}
export async function waitForCredentialRecord(
agent: Agent,
{
threadId,
state,
previousState,
}: { threadId?: string; state?: CredentialState; previousState?: CredentialState | null }
): Promise<CredentialRecord> {
return new Promise(resolve => {
const listener = (event: CredentialStateChangedEvent) => {
const previousStateMatches = previousState === undefined || event.previousState === previousState;
const threadIdMatches = threadId === undefined || event.credentialRecord.tags.threadId === threadId;
const stateMatches = state === undefined || event.credentialRecord.state === state;
if (previousStateMatches && threadIdMatches && stateMatches) {
agent.credentials.events.removeListener(CredentialEventType.StateChanged, listener);
resolve(event.credentialRecord);
}
};
agent.credentials.events.addListener(CredentialEventType.StateChanged, listener);
});
}
export async function waitForBasicMessage(
agent: Agent,
{ verkey, content }: { verkey?: string; content?: string }
): Promise<BasicMessage> {
return new Promise(resolve => {
const listener = (event: BasicMessageReceivedEvent) => {
const verkeyMatches = verkey === undefined || event.verkey === verkey;
const contentMatches = content === undefined || event.message.content === content;
if (verkeyMatches && contentMatches) {
agent.basicMessages.events.removeListener(BasicMessageEventType.MessageReceived, listener);
resolve(event.message);
}
};
agent.basicMessages.events.addListener(BasicMessageEventType.MessageReceived, listener);
});
}
export class SubjectInboundTransporter implements InboundTransporter {
private subject: Subject<WireMessage>;
public constructor(subject: Subject<WireMessage>) {
this.subject = subject;
}
public start(agent: Agent) {
this.subscribe(agent, this.subject);
}
private subscribe(agent: Agent, subject: Subject<WireMessage>) {
subject.subscribe({
next: (message: WireMessage) => agent.receiveMessage(message),
});
}
}
export class SubjectOutboundTransporter implements OutboundTransporter {
private subject: Subject<WireMessage>;
public constructor(subject: Subject<WireMessage>) {
this.subject = subject;
}
public async sendMessage(outboundPackage: OutboundPackage) {
testLogger.test(`Sending outbound message to connection ${outboundPackage.connection.id}`);
const { payload } = outboundPackage;
this.subject.next(payload);
}
}
export async function makeConnection(agentA: Agent, agentB: Agent) {
// eslint-disable-next-line prefer-const
let { invitation, connectionRecord: agentAConnection } = await agentA.connections.createConnection();
let agentBConnection = await agentB.connections.receiveInvitation(invitation);
agentAConnection = await agentA.connections.returnWhenIsConnected(agentAConnection.id);
agentBConnection = await agentB.connections.returnWhenIsConnected(agentBConnection.id);
return {
agentAConnection,
agentBConnection,
};
}
export async function registerSchema(agent: Agent, schemaTemplate: SchemaTemplate): Promise<[SchemaId, Schema]> {
const [schemaId, ledgerSchema] = await agent.ledger.registerSchema(schemaTemplate);
testLogger.test(`created schema with id ${schemaId}`, ledgerSchema);
return [schemaId, ledgerSchema];
}
export async function registerDefinition(
agent: Agent,
definitionTemplate: CredDefTemplate
): Promise<[CredDefId, CredDef]> {
const [credDefId, ledgerCredDef] = await agent.ledger.registerCredentialDefinition(definitionTemplate);
testLogger.test(`created credential definition with id ${credDefId}`, ledgerCredDef);
return [credDefId, ledgerCredDef];
}
export async function ensurePublicDidIsOnLedger(agent: Agent, publicDid: Did) {
try {
testLogger.test(`Ensure test DID ${publicDid} is written to ledger`);
await agent.ledger.getPublicDid(publicDid);
} catch (error) {
// Unfortunately, this won't prevent from the test suite running because of Jest runner runs all tests
// regardless of thrown errors. We're more explicit about the problem with this error handling.
throw new Error(`Test DID ${publicDid} is not written on ledger or ledger is not available.`);
}
}
export async function issueCredential({
issuerAgent,
issuerConnectionId,
holderAgent,
credentialTemplate,
}: {
issuerAgent: Agent;
issuerConnectionId: string;
holderAgent: Agent;
credentialTemplate: CredentialOfferTemplate;
}) {
let issuerCredentialRecord = await issuerAgent.credentials.offerCredential(issuerConnectionId, credentialTemplate);
let holderCredentialRecord = await waitForCredentialRecord(holderAgent, {
threadId: issuerCredentialRecord.tags.threadId,
state: CredentialState.OfferReceived,
});
holderCredentialRecord = await holderAgent.credentials.acceptOffer(holderCredentialRecord.id);
issuerCredentialRecord = await waitForCredentialRecord(issuerAgent, {
threadId: holderCredentialRecord.tags.threadId,
state: CredentialState.RequestReceived,
});
issuerCredentialRecord = await issuerAgent.credentials.acceptRequest(issuerCredentialRecord.id);
holderCredentialRecord = await waitForCredentialRecord(holderAgent, {
threadId: issuerCredentialRecord.tags.threadId,
state: CredentialState.CredentialReceived,
});
holderCredentialRecord = await holderAgent.credentials.acceptCredential(holderCredentialRecord.id);
issuerCredentialRecord = await waitForCredentialRecord(issuerAgent, {
threadId: issuerCredentialRecord.tags.threadId,
state: CredentialState.Done,
});
return { issuerCredential: issuerCredentialRecord, holderCredential: holderCredentialRecord };
}