-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkilt.js
269 lines (221 loc) · 8.02 KB
/
kilt.js
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// config
import { createRequire } from "module";
const require = createRequire(import.meta.url);
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// important imports
import * as Kilt from '@kiltprotocol/sdk-js'
import { mnemonicGenerate, cryptoWaitReady, blake2AsHex, xxhashAsHex, mnemonicToMiniSecret } from '@polkadot/util-crypto';
import { Keyring } from '@polkadot/keyring';
// utility functions
import * as util from "./utility.js";
// set up the samaritan test account
const keyring = new Keyring({ type: 'sr25519' });
let api = undefined;
let sam = undefined;
await cryptoWaitReady().then(() => {
// sam = keyring.createFromUri("shoe urban series connect prize poverty mimic random warm melody fence valid", 'sr25519');
// sam = keyring.createFromUri("yellow obscure salmon affair extra six bubble clutch fly bread away tired", 'sr25519');
sam = keyring.createFromUri("lava couch around wave clog wool old melt delay detail coyote bus", 'sr25519');
});
export async function connect() {
try {
// set up the samaritan test account
// api = await Kilt.connect('wss://peregrine.kilt.io/parachain-public-ws');
await Kilt.connect(`wss://peregrine.kilt.io/parachain-public-ws`);
api = Kilt.ConfigService.get(`api`);
} catch (e) {
return false;
}
return true;
}
export async function getPresentation(
credential,
mnemonic,
selectedAttributes = undefined,
challenge = undefined
) {
// get owner did from credential
const did = credential.claim.owner;
const { authentication, encryption, attestation, delegation } = generateKeypairs(mnemonic);
let signCallback = useSignCallback(did, authentication);
// Create a presentation with only the specified fields revealed, if specified.
return Kilt.Credential.createPresentation({
credential,
signCallback,
selectedAttributes,
challenge,
})
}
export function createClaim(ctype, attr, did) {
try {
// The claimer generates the claim they would like to get attested.
const claim = Kilt.Claim.fromCTypeAndClaimContents(
ctype,
attr,
did
)
const credential = Kilt.Credential.fromClaim(claim);
return credential;
} catch (e) {
return false;
}
}
export async function getKiltLightDID(cid) {
const keyring = new Keyring({ type: 'sr25519' });
const mnemonic = mnemonicGenerate();
const auth = keyring.createFromUri(mnemonic, 'sr25519');
const service = [
{
id: '#claims-repo',
type: ['KiltPublishedCredentialCollectionV1'],
serviceEndpoint: [`http://ipfs.io/ipfs/${cid}`],
},
];
// Create a light DID from the generated authentication key.
const lightDID = Kilt.Did.createLightDidDocument({
authentication: [auth],
service
})
return lightDID
}
export async function createFullDid() {
const mnemonic = mnemonicGenerate()
const { authentication, encryption, attestation, delegation } =
generateKeypairs(mnemonic);
// Get tx that will create the DID on chain and DID-URI that can be used to resolve the DID Document.
const fullDidCreationTx = await Kilt.Did.getStoreTx(
{
authentication: [authentication],
keyAgreement: [encryption],
assertionMethod: [attestation],
capabilityDelegation: [delegation],
},
sam.address,
async ({ data }) => ({
signature: authentication.sign(data),
keyType: authentication.type,
})
)
await Kilt.Blockchain.signAndSubmitTx(fullDidCreationTx, sam)
const didUri = Kilt.Did.getFullDidUriFromKey(authentication);
const encodedFullDid = await api.call.did.query(Kilt.Did.toChain(didUri));
const { document } = Kilt.Did.linkedInfoFromChain(encodedFullDid);
if (!document) {
throw 'Full DID was not successfully created.'
};
return { mnemonic, fullDid: document }
}
export function generateKeypairs(mnemonic = mnemonicGenerate()) {
const authentication = Kilt.Utils.Crypto.makeKeypairFromSeed(
mnemonicToMiniSecret(mnemonic)
)
const encryption = Kilt.Utils.Crypto.makeEncryptionKeypairFromSeed(
mnemonicToMiniSecret(mnemonic)
)
const attestation = authentication.derive('//attestation')
const delegation = authentication.derive('//delegation')
return {
authentication,
encryption,
attestation,
delegation
}
}
export async function mintCType({ title, attr }, did_doc) {
// Create a new CType definition.
const ctObj = util.strToCType(attr);
const assert = keyring.createFromUri(did_doc.mnemonic, 'sr25519');
const { authentication, encryption, attestation, delegation } = generateKeypairs(did_doc.mnemonic);
// create signCallback
let signCallback = useSignCallback(did_doc.fullDid.uri, attestation);
// Create a new CType definition.
const ctype = Kilt.CType.fromProperties(title, ctObj);
// Generate a creation tx.
const ctypeCreationTx = api.tx.ctype.add(Kilt.CType.toChain(ctype));
// Sign it with the right DID key.
const authorizedCtypeCreationTx = await Kilt.Did.authorizeTx(
did_doc.fullDid.uri,
ctypeCreationTx,
signCallback,
sam.address
)
// Submit the creation tx to the KILT blockchain
// using the KILT account specified in the creation operation.
await Kilt.Blockchain.signAndSubmitTx(
authorizedCtypeCreationTx,
sam
);
return ctype;
}
function useSignCallback(keyUri, didSigningKey) {
const signCallback = async ({
data,
// The key relationship specifies which DID key must be used.
keyRelationship,
// The DID URI specifies which DID must be used. We already know which DID
// this will be since we will use this callback just a few lines later (did === didUri).
did,
}) => ({
signature: didSigningKey.sign(data),
keyType: didSigningKey.type,
keyUri,
})
return signCallback
}
export async function verifyPresentation(presentation, challenge = undefined) {
try {
// Verify the presentation with the provided challenge.
let trustedAttesterUris = []
await Kilt.Credential.verifyPresentation(presentation, { challenge });
const attestationChain = await api.query.attestation.attestations(
presentation.rootHash
);
const attestation = Kilt.Attestation.fromChain(
attestationChain,
presentation.rootHash
);
if (attestation.revoked) {
throw new Error("Credential has been revoked and hence it's not valid.")
};
if (!trustedAttesterUris.includes(attestation.owner)) {
throw `Credential was issued by ${attestation.owner} which is not in the provided list of trusted attesters: ${trustedAttesterUris}.`
};
return true;
} catch (e) {
return false;
}
}
export async function createAttestation(
attester,
mnemonic,
credential
) {
try {
const { authentication, encryption, attestation, delegation } = generateKeypairs(mnemonic);
const { cTypeHash, claimHash, delegationId } = Kilt.Attestation.fromCredentialAndDid(credential, attester);
// create signCallback
let signCallback = useSignCallback(attester, attestation);
// Write the attestation info on the chain.
const attestationTx = api.tx.attestation.add(
claimHash,
cTypeHash,
delegationId
)
const authorizedAttestationTx = await Kilt.Did.authorizeTx(
attester,
attestationTx,
signCallback,
sam.address
);
await Kilt.Blockchain.signAndSubmitTx(
authorizedAttestationTx,
sam
);
return true;
} catch (e) {
return false;
}
}