From 309e419f3d6a0ab2fe7857fdf7709287356cbe6b Mon Sep 17 00:00:00 2001 From: olegnn Date: Thu, 26 Oct 2023 23:03:23 +0200 Subject: [PATCH 01/32] WIP --- src/modules/WithParamsAndPublicKeys.js | 6 +- src/modules/accumulator.js | 116 +++--- src/modules/blob.js | 17 +- src/modules/did/did.js | 4 +- src/modules/offchain-signatures.js | 6 +- src/modules/revocation.js | 30 +- src/modules/status-list-credential.js | 4 +- src/modules/trust-registry.js | 344 ++++++++++++++++++ .../status-list2021-credential.js | 52 +-- src/utils/codec.js | 99 +++-- src/utils/did.js | 13 + src/utils/misc.js | 5 +- tests/integration/custom-nonce.test.js | 16 +- 13 files changed, 552 insertions(+), 160 deletions(-) create mode 100644 src/modules/trust-registry.js diff --git a/src/modules/WithParamsAndPublicKeys.js b/src/modules/WithParamsAndPublicKeys.js index 2289607ef..b2af491b0 100644 --- a/src/modules/WithParamsAndPublicKeys.js +++ b/src/modules/WithParamsAndPublicKeys.js @@ -2,7 +2,7 @@ import { u8aToHex } from '@polkadot/util'; import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; -import { getNonce } from '../utils/misc'; +import { getDidNonce } from '../utils/misc'; /** * Class with logic for public keys and corresponding setup parameters. @@ -225,7 +225,7 @@ export default class WithParamsAndPublicKeys { { nonce = undefined, didModule = undefined }, ) { // eslint-disable-next-line no-param-reassign - nonce = await getNonce(hexDid, nonce, didModule); + nonce = await getDidNonce(hexDid, nonce, didModule); const addParams = { params, nonce }; const signature = this.signAddParams(keyPair, addParams); const didSig = createDidSig(hexDid, keyId, signature); @@ -240,7 +240,7 @@ export default class WithParamsAndPublicKeys { { nonce = undefined, didModule = undefined }, ) { // eslint-disable-next-line no-param-reassign - nonce = await getNonce(hexDid, nonce, didModule); + nonce = await getDidNonce(hexDid, nonce, didModule); const removeParams = { paramsRef: [hexDid, index], nonce }; const signature = this.signRemoveParams(keyPair, removeParams); const didSig = createDidSig(hexDid, keyId, signature); diff --git a/src/modules/accumulator.js b/src/modules/accumulator.js index 45e492f29..f6147f804 100644 --- a/src/modules/accumulator.js +++ b/src/modules/accumulator.js @@ -1,7 +1,7 @@ /* eslint-disable camelcase */ import { isHex, u8aToHex } from '@polkadot/util'; -import { getNonce, getSignatureFromKeyringPair, getStateChange } from '../utils/misc'; +import { getDidNonce, getSignatureFromKeyringPair, getStateChange } from '../utils/misc'; import WithParamsAndPublicKeys from './WithParamsAndPublicKeys'; import { getAllExtrinsicsFromBlock } from '../utils/chain-ops'; import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; @@ -84,9 +84,9 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * using this * @returns {Promise<*>} */ - async createAddPublicKeyTx(publicKey, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { - const signerHexDid = getHexIdentifierFromDID(signerDid); - const [addPk, signature] = await this.createSignedAddPublicKey(publicKey, signerHexDid, keyPair, keyId, { nonce, didModule }); + async createAddPublicKeyTx(publicKey, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { + const signerHexDid = getHexIdentifierFromDID(); + const [addPk, signature] = await this.createSignedAddPublicKey(publicKey, signerDid, signingKeyRef, { nonce, didModule }); return this.module.addPublicKey(addPk, signature); } @@ -101,9 +101,9 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * using this * @returns {Promise<*>} */ - async createRemovePublicKeyTx(removeKeyId, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createRemovePublicKeyTx(removeKeyId, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { const signerHexDid = getHexIdentifierFromDID(signerDid); - const [remPk, signature] = await this.createSignedRemovePublicKey(removeKeyId, signerHexDid, keyPair, keyId, { nonce, didModule }); + const [remPk, signature] = await this.createSignedRemovePublicKey(removeKeyId, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.removePublicKey(remPk, signature); } @@ -120,9 +120,9 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * using this * @returns {Promise<*>} */ - async createAddPositiveAccumulatorTx(id, accumulated, publicKeyRef, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createAddPositiveAccumulatorTx(id, accumulated, publicKeyRef, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { const signerHexDid = getHexIdentifierFromDID(signerDid); - const [addAccumulator, signature] = await this.createSignedAddPositiveAccumulator(id, accumulated, publicKeyRef, signerHexDid, keyPair, keyId, { nonce, didModule }); + const [addAccumulator, signature] = await this.createSignedAddPositiveAccumulator(id, accumulated, publicKeyRef, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addAccumulator(addAccumulator, signature); } @@ -140,9 +140,9 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * using this * @returns {Promise<*>} */ - async createAddUniversalAccumulatorTx(id, accumulated, publicKeyRef, maxSize, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createAddUniversalAccumulatorTx(id, accumulated, publicKeyRef, maxSize, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { const signerHexDid = getHexIdentifierFromDID(signerDid); - const [addAccumulator, signature] = await this.createSignedAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize, signerHexDid, keyPair, keyId, { nonce, didModule }); + const [addAccumulator, signature] = await this.createSignedAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addAccumulator(addAccumulator, signature); } @@ -163,11 +163,11 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { */ async updateAccumulatorTx( id, newAccumulated, - { additions = undefined, removals = undefined, witnessUpdateInfo = undefined }, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }, + { additions = undefined, removals = undefined, witnessUpdateInfo = undefined }, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, ) { const signerHexDid = getHexIdentifierFromDID(signerDid); const [update, signature] = await this.createSignedUpdateAccumulator(id, newAccumulated, - { additions, removals, witnessUpdateInfo }, signerHexDid, keyPair, keyId, { nonce, didModule }); + { additions, removals, witnessUpdateInfo }, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.updateAccumulator(update, signature); } @@ -182,9 +182,9 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * using this * @returns {Promise} */ - async removeAccumulatorTx(id, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async removeAccumulatorTx(id, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { const signerHexDid = getHexIdentifierFromDID(signerDid); - const [removal, signature] = await this.createSignedRemoveAccumulator(id, signerHexDid, keyPair, keyId, { nonce, didModule }); + const [removal, signature] = await this.createSignedRemoveAccumulator(id, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.removeAccumulator(removal, signature); } @@ -201,8 +201,8 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param params * @returns {Promise<*>} */ - async addPublicKey(publicKey, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { - const tx = await this.createAddPublicKeyTx(publicKey, signerDid, keyPair, keyId, { nonce, didModule }); + async addPublicKey(publicKey, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { + const tx = await this.createAddPublicKeyTx(publicKey, signerDid, signingKeyRef, { nonce, didModule }); return this.signAndSend(tx, waitForFinalization, params); } @@ -219,8 +219,8 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param params * @returns {Promise<*>} */ - async removePublicKey(removeKeyId, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { - const tx = await this.createRemovePublicKeyTx(removeKeyId, signerDid, keyPair, keyId, { nonce, didModule }); + async removePublicKey(removeKeyId, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { + const tx = await this.createRemovePublicKeyTx(removeKeyId, signerDid, signingKeyRef, { nonce, didModule }); return this.signAndSend(tx, waitForFinalization, params); } @@ -239,8 +239,8 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param params * @returns {Promise<*>} */ - async addPositiveAccumulator(id, accumulated, publicKeyRef, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { - const tx = await this.createAddPositiveAccumulatorTx(id, accumulated, publicKeyRef, signerDid, keyPair, keyId, { nonce, didModule }); + async addPositiveAccumulator(id, accumulated, publicKeyRef, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { + const tx = await this.createAddPositiveAccumulatorTx(id, accumulated, publicKeyRef, signerDid, signingKeyRef, { nonce, didModule }); return this.signAndSend(tx, waitForFinalization, params); } @@ -260,8 +260,8 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param params * @returns {Promise<*>} */ - async addUniversalAccumulator(id, accumulated, publicKeyRef, maxSize, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { - const tx = await this.createAddUniversalAccumulatorTx(id, accumulated, publicKeyRef, maxSize, signerDid, keyPair, keyId, { nonce, didModule }); + async addUniversalAccumulator(id, accumulated, publicKeyRef, maxSize, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { + const tx = await this.createAddUniversalAccumulatorTx(id, accumulated, publicKeyRef, maxSize, signerDid, signingKeyRef, { nonce, didModule }); return this.signAndSend(tx, waitForFinalization, params); } @@ -283,9 +283,9 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise< object>} */ async updateAccumulator(id, newAccumulated, - { additions = undefined, removals = undefined, witnessUpdateInfo = undefined }, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { + { additions = undefined, removals = undefined, witnessUpdateInfo = undefined }, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { const tx = await this.updateAccumulatorTx(id, newAccumulated, - { additions, removals, witnessUpdateInfo }, signerDid, keyPair, keyId, { nonce, didModule }); + { additions, removals, witnessUpdateInfo }, signerDid, signingKeyRef, { nonce, didModule }); return this.signAndSend(tx, waitForFinalization, params); } @@ -303,53 +303,53 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param params * @returns {Promise<*>} */ - async removeAccumulator(id, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { - const tx = await this.removeAccumulatorTx(id, signerDid, keyPair, keyId, { nonce, didModule }); + async removeAccumulator(id, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { + const tx = await this.removeAccumulatorTx(id, signerDid, signingKeyRef, { nonce, didModule }); return this.signAndSend(tx, waitForFinalization, params); } - async createSignedAddPublicKey(publicKey, signerHexDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createSignedAddPublicKey(publicKey, signerHexDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { // eslint-disable-next-line no-param-reassign - nonce = await getNonce(signerHexDid, nonce, didModule); + nonce = await getDidNonce(signerHexDid, nonce, didModule); const addPk = { publicKey, nonce }; - const signature = this.signAddPublicKey(keyPair, addPk); + const signature = this.signAddPublicKey(signingKeyRef, addPk); const didSig = createDidSig(signerHexDid, keyId, signature); return [addPk, didSig]; } - async createSignedRemovePublicKey(removeKeyId, signerHexDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createSignedRemovePublicKey(removeKeyId, signerHexDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { // eslint-disable-next-line no-param-reassign - nonce = await getNonce(signerHexDid, nonce, didModule); + nonce = await getDidNonce(signerHexDid, nonce, didModule); const removeKey = { keyRef: [signerHexDid, removeKeyId], nonce }; - const signature = this.signRemovePublicKey(keyPair, removeKey); + const signature = this.signRemovePublicKey(signingKeyRef, removeKey); const didSig = createDidSig(signerHexDid, keyId, signature); return [removeKey, didSig]; } - async createSignedAddPositiveAccumulator(id, accumulated, publicKeyRef, signerHexDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createSignedAddPositiveAccumulator(id, accumulated, publicKeyRef, signerHexDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { // eslint-disable-next-line no-param-reassign - nonce = await getNonce(signerHexDid, nonce, didModule); + nonce = await getDidNonce(signerHexDid, nonce, didModule); const accum = AccumulatorModule.prepareAddPositiveAccumulator(id, accumulated, publicKeyRef); const addAccum = { ...accum, nonce }; - const signature = this.signAddAccumulator(keyPair, addAccum); + const signature = this.signAddAccumulator(signingKeyRef, addAccum); const didSig = createDidSig(signerHexDid, keyId, signature); return [addAccum, didSig]; } - async createSignedAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize, signerHexDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createSignedAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize, signerHexDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { // eslint-disable-next-line no-param-reassign - nonce = await getNonce(signerHexDid, nonce, didModule); + nonce = await getDidNonce(signerHexDid, nonce, didModule); const accum = AccumulatorModule.prepareAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize); const addAccum = { ...accum, nonce }; - const signature = this.signAddAccumulator(keyPair, addAccum); + const signature = this.signAddAccumulator(signingKeyRef, addAccum); const didSig = createDidSig(signerHexDid, keyId, signature); return [addAccum, didSig]; } async createSignedUpdateAccumulator(id, newAccumulated, - { additions = undefined, removals = undefined, witnessUpdateInfo = undefined }, signerHexDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + { additions = undefined, removals = undefined, witnessUpdateInfo = undefined }, signerHexDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { // eslint-disable-next-line no-param-reassign - nonce = await getNonce(signerHexDid, nonce, didModule); + nonce = await getDidNonce(signerHexDid, nonce, didModule); if (additions !== undefined) { AccumulatorModule.ensureArrayOfBytearrays(additions); } @@ -367,16 +367,16 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { witness_update_info: witnessUpdateInfo, nonce, }; - const signature = this.signUpdateAccumulator(keyPair, updateAccum); + const signature = this.signUpdateAccumulator(signingKeyRef, updateAccum); const didSig = createDidSig(signerHexDid, keyId, signature); return [updateAccum, didSig]; } - async createSignedRemoveAccumulator(id, signerHexDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createSignedRemoveAccumulator(id, signerHexDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { // eslint-disable-next-line no-param-reassign - nonce = await getNonce(signerHexDid, nonce, didModule); + nonce = await getDidNonce(signerHexDid, nonce, didModule); const remAccum = { id, nonce }; - const signature = this.signRemoveAccumulator(keyPair, remAccum); + const signature = this.signRemoveAccumulator(signingKeyRef, remAccum); const didSig = createDidSig(signerHexDid, keyId, signature); return [remAccum, didSig]; } @@ -558,46 +558,46 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { } } - signAddParams(keyPair, params) { + signAddParams(signingKeyRef, params) { const serialized = getStateChange(this.api, 'AddAccumulatorParams', params); - return getSignatureFromKeyringPair(keyPair, serialized); + return getSignatureFromKeyringPair(signingKeyRef, serialized); } - signAddPublicKey(keyPair, pk) { + signAddPublicKey(signingKeyRef, pk) { const serialized = getStateChange(this.api, 'AddAccumulatorPublicKey', pk); - return getSignatureFromKeyringPair(keyPair, serialized); + return getSignatureFromKeyringPair(signingKeyRef, serialized); } - signRemoveParams(keyPair, ref) { + signRemoveParams(signingKeyRef, ref) { const serialized = getStateChange(this.api, 'RemoveAccumulatorParams', ref); - return getSignatureFromKeyringPair(keyPair, serialized); + return getSignatureFromKeyringPair(signingKeyRef, serialized); } - signRemovePublicKey(keyPair, ref) { + signRemovePublicKey(signingKeyRef, ref) { const serialized = getStateChange( this.api, 'RemoveAccumulatorPublicKey', ref, ); - return getSignatureFromKeyringPair(keyPair, serialized); + return getSignatureFromKeyringPair(signingKeyRef, serialized); } - signAddAccumulator(keyPair, addAccumulator) { + signAddAccumulator(signingKeyRef, addAccumulator) { const serialized = getStateChange( this.api, 'AddAccumulator', addAccumulator, ); - return getSignatureFromKeyringPair(keyPair, serialized); + return getSignatureFromKeyringPair(signingKeyRef, serialized); } - signUpdateAccumulator(keyPair, update) { + signUpdateAccumulator(signingKeyRef, update) { const serialized = getStateChange(this.api, 'UpdateAccumulator', update); - return getSignatureFromKeyringPair(keyPair, serialized); + return getSignatureFromKeyringPair(signingKeyRef, serialized); } - signRemoveAccumulator(keyPair, removal) { + signRemoveAccumulator(signingKeyRef, removal) { const serialized = getStateChange(this.api, 'RemoveAccumulator', removal); - return getSignatureFromKeyringPair(keyPair, serialized); + return getSignatureFromKeyringPair(signingKeyRef, serialized); } } diff --git a/src/modules/blob.js b/src/modules/blob.js index 8fd87803a..cf9e2965d 100644 --- a/src/modules/blob.js +++ b/src/modules/blob.js @@ -3,7 +3,7 @@ import { u8aToString, stringToHex, bufferToU8a, u8aToHex, } from '@polkadot/util'; -import { getNonce, getSignatureFromKeyringPair, getStateChange } from '../utils/misc'; +import { getDidNonce, getSignatureFromKeyringPair, getStateChange } from '../utils/misc'; import { isHexWithGivenByteSize, getHexIdentifier } from '../utils/codec'; import NoBlobError from '../utils/errors/no-blob-error'; import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; @@ -80,9 +80,8 @@ class BlobModule { * using this * @returns {Promise<*>} */ - async createNewTx(blob, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { - const hexDid = getHexIdentifierFromDID(signerDid); - const [addBlob, didSig] = await this.createSignedAddBlob(blob, hexDid, keyPair, keyId, { nonce, didModule }); + async createNewTx(blob, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { + const [addBlob, didSig] = await this.createSignedAddBlob(blob, signerDid, signingKeyRef, { nonce, didModule }); return this.module.new(addBlob, didSig); } @@ -99,9 +98,9 @@ class BlobModule { * @param params * @returns {Promise<*>} */ - async new(blob, signerDid, keyPair, keyId, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { + async new(blob, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { return this.signAndSend( - (await this.createNewTx(blob, signerDid, keyPair, keyId, { nonce, didModule })), waitForFinalization, params, + (await this.createNewTx(blob, signerDid, signingKeyRef, { nonce, didModule })), waitForFinalization, params, ); } @@ -147,12 +146,12 @@ class BlobModule { * using this * @returns {Promise} */ - async createSignedAddBlob(blob, hexDid, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createSignedAddBlob(blob, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { if (!blob.blob) { throw new Error('Blob must have a value!'); } // eslint-disable-next-line no-param-reassign - nonce = await getNonce(hexDid, nonce, didModule); + nonce = await getDidNonce(signerDid, nonce, didModule); const blobObj = { ...blob, @@ -164,7 +163,7 @@ class BlobModule { }; const serializedAddBlob = this.getSerializedBlob(addBlob); const signature = getSignatureFromKeyringPair(keyPair, serializedAddBlob); - const didSig = createDidSig(hexDid, keyId, signature); + const didSig = createDidSig(signerDid, keyId, signature); return [addBlob, didSig]; } diff --git a/src/modules/did/did.js b/src/modules/did/did.js index 71f17a6ae..2268650c6 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -1035,7 +1035,7 @@ class DIDModule { * methods are used internally * @return {Promise} */ - async getNonceForDID(didIdentifier) { + async getDidNonceForDID(didIdentifier) { return (await this.getOnchainDidDetail(didIdentifier)).nonce; } @@ -1045,7 +1045,7 @@ class DIDModule { * @returns {Promise<*>} */ async getNextNonceForDID(didIdentifier) { - return (await this.getNonceForDID(didIdentifier)) + 1; + return (await this.getDidNonceForDID(didIdentifier)) + 1; } /** diff --git a/src/modules/offchain-signatures.js b/src/modules/offchain-signatures.js index dea0c68dd..a9bae5214 100644 --- a/src/modules/offchain-signatures.js +++ b/src/modules/offchain-signatures.js @@ -1,7 +1,7 @@ /* eslint-disable camelcase */ import { - getNonce, + getDidNonce, getSignatureFromKeyringPair, getStateChange, } from '../utils/misc'; @@ -254,7 +254,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { { nonce = undefined, didModule = undefined }, ) { // eslint-disable-next-line no-param-reassign - nonce = await getNonce(signerHexDid, nonce, didModule); + nonce = await getDidNonce(signerHexDid, nonce, didModule); const addPk = { key: publicKey, did: targetHexDid, nonce }; const signature = this.signAddPublicKey(keyPair, addPk); const didSig = createDidSig(signerHexDid, keyId, signature); @@ -270,7 +270,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { { nonce = undefined, didModule = undefined }, ) { // eslint-disable-next-line no-param-reassign - nonce = await getNonce(signerHexDid, nonce, didModule); + nonce = await getDidNonce(signerHexDid, nonce, didModule); const removeKey = { keyRef: [targetHexDid, removeKeyId], did: targetHexDid, diff --git a/src/modules/revocation.js b/src/modules/revocation.js index acebd31cc..c5d627b7c 100644 --- a/src/modules/revocation.js +++ b/src/modules/revocation.js @@ -1,5 +1,5 @@ import { - getNonce, + getDidNonce, getSignatureFromKeyringPair, getStateChange, } from '../utils/misc'; @@ -187,8 +187,8 @@ class RevocationModule { * @param params * @returns {Promise} */ - async revokeCredentialWithOneOfPolicy(registryId, revId, did, keyPair, keyId, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { - const [revoke, sig, sigNonce] = await this.createSignedRevoke(registryId, [revId], did, keyPair, keyId, { nonce, didModule }); + async revokeCredentialWithOneOfPolicy(registryId, revId, did, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { + const [revoke, sig, sigNonce] = await this.createSignedRevoke(registryId, [revId], did, signingKeyRef, { nonce, didModule }); return this.revoke(revoke, [[sig, sigNonce]], waitForFinalization, params); } @@ -205,20 +205,20 @@ class RevocationModule { * @param params * @returns {Promise} */ - async unrevokeCredentialWithOneOfPolicy(registryId, revId, did, keyPair, keyId, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { - const [revoke, sig, sigNonce] = await this.createSignedUnRevoke(registryId, [revId], did, keyPair, keyId, { nonce, didModule }); + async unrevokeCredentialWithOneOfPolicy(registryId, revId, did, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { + const [revoke, sig, sigNonce] = await this.createSignedUnRevoke(registryId, [revId], did, signingKeyRef, { nonce, didModule }); return this.unrevoke(revoke, [[sig, sigNonce]], waitForFinalization, params); } - async removeRegistryWithOneOfPolicy(registryId, did, keyPair, keyId, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { - const [removal, sig, sigNonce] = await this.createSignedRemove(registryId, did, keyPair, keyId, { nonce, didModule }); + async removeRegistryWithOneOfPolicy(registryId, did, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { + const [removal, sig, sigNonce] = await this.createSignedRemove(registryId, did, signingKeyRef, { nonce, didModule }); return this.removeRegistry(removal, [[sig, sigNonce]], waitForFinalization, params); } - async createSignedUpdate(updateFunc, registryId, [...revokeIds], did, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createSignedUpdate(updateFunc, registryId, [...revokeIds], did, signingKeyRef, { nonce = undefined, didModule = undefined }) { const hexDid = getHexIdentifierFromDID(did); // eslint-disable-next-line no-param-reassign - nonce = await getNonce(hexDid, nonce, didModule); + nonce = await getDidNonce(hexDid, nonce, didModule); const update = { data: { @@ -233,18 +233,18 @@ class RevocationModule { return [{ registryId, revokeIds }, didSig, nonce]; } - async createSignedRevoke(registryId, revokeIds, did, keyPair, keyId, { nonce = undefined, didModule = undefined }) { - return this.createSignedUpdate(this.getSerializedRevoke, registryId, revokeIds, did, keyPair, keyId, { nonce, didModule }); + async createSignedRevoke(registryId, revokeIds, did, signingKeyRef, { nonce = undefined, didModule = undefined }) { + return this.createSignedUpdate(this.getSerializedRevoke, registryId, revokeIds, did, signingKeyRef, { nonce, didModule }); } - async createSignedUnRevoke(registryId, revokeIds, did, keyPair, keyId, { nonce = undefined, didModule = undefined }) { - return this.createSignedUpdate(this.getSerializedUnrevoke, registryId, revokeIds, did, keyPair, keyId, { nonce, didModule }); + async createSignedUnRevoke(registryId, revokeIds, did, signingKeyRef, { nonce = undefined, didModule = undefined }) { + return this.createSignedUpdate(this.getSerializedUnrevoke, registryId, revokeIds, did, signingKeyRef, { nonce, didModule }); } - async createSignedRemove(registryId, did, keyPair, keyId, { nonce = undefined, didModule = undefined }) { + async createSignedRemove(registryId, did, signingKeyRef, { nonce = undefined, didModule = undefined }) { const hexDid = getHexIdentifierFromDID(did); // eslint-disable-next-line no-param-reassign - nonce = await getNonce(hexDid, nonce, didModule); + nonce = await getDidNonce(hexDid, nonce, didModule); const remove = { data: { registryId }, diff --git a/src/modules/status-list-credential.js b/src/modules/status-list-credential.js index c3b3024df..34d373822 100644 --- a/src/modules/status-list-credential.js +++ b/src/modules/status-list-credential.js @@ -1,6 +1,6 @@ import StatusList2021Credential from '../status-list-credential/status-list2021-credential'; import { - getNonce, + getDidNonce, getSignatureFromKeyringPair, getStateChange, } from '../utils/misc'; @@ -255,7 +255,7 @@ export default class StatusListCredentialModule { ) { const hexDid = getHexIdentifierFromDID(did); // eslint-disable-next-line no-param-reassign - nonce = await getNonce(hexDid, nonce, didModule); + nonce = await getDidNonce(hexDid, nonce, didModule); const update = { data, diff --git a/src/modules/trust-registry.js b/src/modules/trust-registry.js new file mode 100644 index 000000000..63873f058 --- /dev/null +++ b/src/modules/trust-registry.js @@ -0,0 +1,344 @@ +import StatusList2021Credential from '../status-list-credential/status-list2021-credential'; +import { + getDidNonce, + getSignatureFromKeyringPair, + getStateChange, +} from '../utils/misc'; + +import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; + +/** + * `Trust Registry` module. + */ +export default class TrustRegistryModule { + /** + * Creates a new instance of `StatusListCredentialModule` and sets the api + * @constructor + * @param {object} api - PolkadotJS API Reference + * @param signAndSend + */ + constructor(api, signAndSend) { + this.api = api; + this.module = api.tx.trustRegistry; + this.signAndSend = signAndSend; + } + + /** + * Fetches `StatusList2021Credential` with the supplied identifier. + * @param {*} statusListCredentialId + * @returns {Promise} + */ + async initTrustRegistry(statusListCredentialId) { + let statusListCredential = await this.api.query.trustRegistry.initTrustRegistry( + statusListCredentialId, + ); + + if (statusListCredential.isSome) { + statusListCredential = statusListCredential.unwrap().statusListCredential; + + if (statusListCredential.isStatusList2021Credential) { + return StatusList2021Credential.fromBytes( + statusListCredential.asStatusList2021Credential, + ); + } else { + throw new Error( + "Fetched credential isn't of `StatusList2021Credential` type", + ); + } + } + + return null; + } + + /** + * Create a transaction to create a new status list credential on-chain. + * @param id - is the unique id of the status list credential. The function will check whether `id` is already taken or not. + * @param statusListCredential - the credential to be associated with the given `id` + * @param policy - the credential policy + * @return {Promise} - the extrinsic to sign and send. + */ + buildCreateStatusListCredentialTx(id, statusListCredential, policy) { + const credentialWithPolicy = { + statusListCredential: statusListCredential.toSubstrate(), + policy: policy.toJSON(), + }; + + return this.module.create(id, credentialWithPolicy); + } + + /** + * Create a transaction to update an existing status list credential on-chain. + * @param statusListCredentialUpdate - Update for the status list credential. + * @param didSigs - `DID` signatures over an action with a nonce authorizing this action according to the existing policy. + * @return {Promise} - the extrinsic to sign and send. + */ + buildUpdateStatusListCredentialTx(statusListCredentialUpdate, didSigs) { + return this.module.update(statusListCredentialUpdate, didSigs); + } + + /** + * Create a transaction to remove an existing status list credential from the chain. + * @param statusListCredentialId - is the unique id of the status list credential. The function will check whether `id` is already taken or not. + * @param didSigs - `DID` signatures over an action with a nonce authorizing this action according to the existing policy. + * @return {Promise} - the extrinsic to sign and send. + */ + buildRemoveStatusListCredentialTx(statusListCredentialId, didSigs) { + return this.module.remove(statusListCredentialId, didSigs); + } + + /** + * Create a new status list credential on-chain. + * @param id - is the unique id of the status list credential. The function will check whether `id` is already taken or not. + * @param statusListCredential - The status list credential to be associated with the given `id`. + * @param policy - The credential policy. + * @param waitForFinalization + * @param params + * @return {Promise<*>} - Sent transaction. + */ + createStatusListCredential( + id, + statusListCredential, + policy, + waitForFinalization = true, + params = {}, + ) { + return this.signAndSend( + this.buildCreateStatusListCredentialTx(id, statusListCredential, policy), + waitForFinalization, + params, + ); + } + + /** + * Update a single `StatusListCredential`. Works only with credentials having `OneOf` policy + * @param id - Unique identifier of the status list credential. + * @param statusListCredential - Status list credential. + * @param did - Signer of the transaction payload + * @param keyPair - Signer's keypair + * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. + * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by + * using this + * @param waitForFinalization + * @param params + * @returns {Promise} + */ + async updateStatusListCredentialWithOneOfPolicy( + id, + statusListCredential, + did, + keyPair, + keyId, + { nonce = undefined, didModule = undefined }, + waitForFinalization = true, + params = {}, + ) { + const [payload, sig, sigNonce] = await this.createSignedUpdateStatusListCredential( + id, + statusListCredential, + did, + keyPair, + keyId, + { nonce, didModule }, + ); + return this.updateStatusListCredential( + payload, + [[sig, sigNonce]], + waitForFinalization, + params, + ); + } + + /** + * Remove a single `StatusListCredential`. Works only with credentials having `OneOf` policy + * @param id - Unique identifier of the status list credential. + * @param did - Signer of the transaction payload + * @param keyPair - Signer's keypair + * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. + * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by + * using this + * @param waitForFinalization + * @param params + * @returns {Promise} + */ + async removeStatusListCredentialWithOneOfPolicy( + id, + did, + keyPair, + keyId, + { nonce = undefined, didModule = undefined }, + waitForFinalization = true, + params = {}, + ) { + const [payload, sig, sigNonce] = await this.createSignedRemoveStatusListCredential( + id, + did, + keyPair, + keyId, + { nonce, didModule }, + ); + return this.removeStatusListCredential( + payload, + [[sig, sigNonce]], + waitForFinalization, + params, + ); + } + + /** + * Updates status list credential. + * + * @param updateStatusListCredential + * @param didSigs - Array of pairs with each pair of the form `[DidSig, nonce]` where `nonce` is the nonce used while + * signing the payload + * @param waitForFinalization + * @param params + */ + updateStatusListCredential( + updateStatusListCredential, + didSigs, + waitForFinalization = true, + params = {}, + ) { + return this.signAndSend( + this.buildUpdateStatusListCredentialTx( + updateStatusListCredential, + didSigs, + ), + waitForFinalization, + params, + ); + } + + /** + * Removes status list credential. + * + * @param id - Unique identifier of the status list credential. + * @param didSigs - Array of pairs with each pair of the form `[DidSig, nonce]` where `nonce` is the nonce used while + * signing the payload + * @param waitForFinalization + * @param params + */ + removeStatusListCredential( + id, + didSigs, + waitForFinalization = true, + params = {}, + ) { + return this.signAndSend( + this.buildRemoveStatusListCredentialTx(id, didSigs), + waitForFinalization, + params, + ); + } + + /** + * Creates `DID` signature. + * + * @param createSerializedTx - Function to create a serialized transaction using supplied payload. + * @param data - Payload data. + * @param did - Signer of the transaction payload + * @param keyPair - Signer's keypair + * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. + * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by + * @param params - parameters to be used + */ + async createDidSignature( + createSerializedTx, + data, + did, + keyPair, + keyId, + { nonce = undefined, didModule = undefined }, + ) { + const hexDid = getHexIdentifierFromDID(did); + // eslint-disable-next-line no-param-reassign + nonce = await getDidNonce(hexDid, nonce, didModule); + + const update = { + data, + nonce, + }; + const serializedTx = createSerializedTx.call(this, update); + const signature = getSignatureFromKeyringPair(keyPair, serializedTx); + const didSig = createDidSig(hexDid, keyId, signature); + return [data, didSig, nonce]; + } + + /** + * Creates signed transaction to update status list credential. + * + * @param id - Unique identifier of the status list credential. + * @param statusListCredential - Status list credential. + * @param did - Signer of the transaction payload + * @param keyPair - Signer's keypair + * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. + * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by + * @param params - parameters to be used + */ + async createSignedUpdateStatusListCredential( + id, + statusListCredential, + did, + keyPair, + keyId, + { nonce = undefined, didModule = undefined }, + ) { + return this.createDidSignature( + this.getSerializedUpdateStatusListCredential, + { id, credential: statusListCredential.toSubstrate() }, + did, + keyPair, + keyId, + { nonce, didModule }, + ); + } + + /** + * Creates signed transaction to remove status list credential. + * + * @param id - Unique identifier of the status list credential. + * @param did - Signer of the transaction payload + * @param keyPair - Signer's keypair + * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. + * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by + */ + async createSignedRemoveStatusListCredential( + id, + did, + keyPair, + keyId, + { nonce = undefined, didModule = undefined }, + ) { + return this.createDidSignature( + this.getSerializedRemoveStatusListCredential, + { id }, + did, + keyPair, + keyId, + { nonce, didModule }, + ); + } + + /** + * Serializes a `UpdateStatusListCredential` for signing. + * @param {object} update - `UpdateStatusListCredential` as expected by the Substrate node + * @returns {Array} An array of Uint8 + */ + getSerializedUpdateStatusListCredential(update) { + return getStateChange(this.api, 'UpdateStatusListCredential', update); + } + + /** + * Serializes a `RemoveStatusListCredential` for signing. + * @param {object} removal - `RemoveStatusListCredential` as expected by the Substrate node + * @returns {Array} An array of Uint8 + */ + getSerializedRemoveStatusListCredential(removal) { + return getStateChange(this.api, 'RemoveStatusListCredential', removal); + } +} diff --git a/src/status-list-credential/status-list2021-credential.js b/src/status-list-credential/status-list2021-credential.js index e6e9c5689..880f99054 100644 --- a/src/status-list-credential/status-list2021-credential.js +++ b/src/status-list-credential/status-list2021-credential.js @@ -3,12 +3,12 @@ import { createList, createCredential, StatusList, // eslint-disable-line -} from '@digitalbazaar/vc-status-list'; -import { u8aToHex, u8aToU8a } from '@polkadot/util'; -import { gzip, ungzip } from 'pako'; -import { DockStatusList2021Qualifier } from '../utils/vc/constants'; -import VerifiableCredential from '../verifiable-credential'; -import { ensureStatusListId } from '../utils/type-helpers'; +} from "@digitalbazaar/vc-status-list"; +import { u8aToHex, u8aToU8a } from "@polkadot/util"; +import { gzip, ungzip } from "pako"; +import { DockStatusList2021Qualifier } from "../utils/vc/constants"; +import VerifiableCredential from "../verifiable-credential"; +import { ensureStatusListId } from "../utils/type-helpers"; import { KeyDoc } from "../utils/vc/helpers"; // eslint-disable-line /** @@ -26,15 +26,15 @@ export default class StatusList2021Credential extends VerifiableCredential { let cachedDecodedStatusList; // Caches decoded status list. - Object.defineProperty(this, 'decodedStatusList', { - value: async function decodedStatusList() { + Object.defineProperty(this, "decodedStatusList", { + value: function decodedStatusList() { if ( - encodedStatusList === this.credentialSubject.encodedList - && cachedDecodedStatusList !== void 0 + encodedStatusList === this.credentialSubject.encodedList && + cachedDecodedStatusList !== void 0 ) { return cachedDecodedStatusList; } else { - cachedDecodedStatusList = await decodeList(this.credentialSubject); + cachedDecodedStatusList = decodeList(this.credentialSubject); encodedStatusList = this.credentialSubject.encodedList; return cachedDecodedStatusList; @@ -68,7 +68,7 @@ export default class StatusList2021Credential extends VerifiableCredential { static async create( keyDoc, id, - { statusPurpose = 'revocation', length = 1e4, revokeIndices = [] } = {}, + { statusPurpose = "revocation", length = 1e4, revokeIndices = [] } = {} ) { const statusList = await createList({ length }); this.updateStatusList(statusPurpose, statusList, revokeIndices); @@ -104,7 +104,7 @@ export default class StatusList2021Credential extends VerifiableCredential { this.credentialSubject.statusPurpose, statusList, revokeIndices, - unsuspendIndices, + unsuspendIndices ); this.credentialSubject.encodedList = await statusList.encode(); @@ -149,7 +149,7 @@ export default class StatusList2021Credential extends VerifiableCredential { */ static fromBytes(bytes) { const gzipBufferCred = Buffer.from(u8aToU8a(bytes)); - const stringifiedCred = ungzip(gzipBufferCred, { to: 'string' }); + const stringifiedCred = ungzip(gzipBufferCred, { to: "string" }); const parsedCred = JSON.parse(stringifiedCred); return this.fromJSON(parsedCred); @@ -205,24 +205,24 @@ export default class StatusList2021Credential extends VerifiableCredential { validate() { const { credentialSubject } = this; - if (!credentialSubject) throw new Error('Missing `credentialSubject`'); + if (!credentialSubject) throw new Error("Missing `credentialSubject`"); if (!this.constructor.statusPurposes.has(credentialSubject.statusPurpose)) { throw new Error( `Invalid \`statusPurpose\`, expected one of \`${[ ...this.constructor.statusPurposes, - ].join(', ')}\``, + ].join(", ")}\`` ); } - if (typeof credentialSubject.id !== 'string' || !credentialSubject.id) { - throw new Error('Missing `credentialSubject.id`'); + if (typeof credentialSubject.id !== "string" || !credentialSubject.id) { + throw new Error("Missing `credentialSubject.id`"); } - if (credentialSubject.type !== 'StatusList2021') { + if (credentialSubject.type !== "StatusList2021") { throw new Error( - '`credentialSubject.type` must be set to `StatusList2021`', + "`credentialSubject.type` must be set to `StatusList2021`" ); } if (!credentialSubject.encodedList) { - throw new Error('`credentialSubject.encodedList` must be present'); + throw new Error("`credentialSubject.encodedList` must be present"); } } @@ -243,19 +243,19 @@ export default class StatusList2021Credential extends VerifiableCredential { statusPurpose, statusList, revokeIndices = [], - unsuspendIndices = [], + unsuspendIndices = [] ) { const unsuspendIndiceSet = new Set(unsuspendIndices); - if (statusPurpose !== 'suspension' && unsuspendIndiceSet.size > 0) { + if (statusPurpose !== "suspension" && unsuspendIndiceSet.size > 0) { throw new Error( - `Can't unsuspend indices for credential with \`statusPurpose\` = \`${statusPurpose}\`, it's only possible with \`statusPurpose\` = \`suspension\``, + `Can't unsuspend indices for credential with \`statusPurpose\` = \`${statusPurpose}\`, it's only possible with \`statusPurpose\` = \`suspension\`` ); } for (const idx of revokeIndices) { if (unsuspendIndiceSet.has(idx)) { throw new Error( - `Index \`${idx}\` appears in both revoke and unsuspend sets`, + `Index \`${idx}\` appears in both revoke and unsuspend sets` ); } @@ -270,5 +270,5 @@ export default class StatusList2021Credential extends VerifiableCredential { /** * Allowed status purposes for this credential type. */ -StatusList2021Credential.statusPurposes = new Set(['revocation', 'suspension']); +StatusList2021Credential.statusPurposes = new Set(["revocation", "suspension"]); StatusList2021Credential.qualifier = DockStatusList2021Qualifier; diff --git a/src/utils/codec.js b/src/utils/codec.js index dcc30a038..e5544e287 100644 --- a/src/utils/codec.js +++ b/src/utils/codec.js @@ -1,5 +1,6 @@ -import { u8aToHex } from '@polkadot/util'; -import { decodeAddress, encodeAddress } from '@polkadot/util-crypto'; +import { u8aToHex, isHex } from "@polkadot/util"; +import { decodeAddress, encodeAddress } from "@polkadot/util-crypto"; +import { PublicKeyEd25519, PublicKeySecp256k1, PublicKey } from "../public-keys"; /** * Check if the given input is hexadecimal or not. Optionally checks for the byte size of the hex. Case-insensitive on hex chars @@ -8,7 +9,7 @@ import { decodeAddress, encodeAddress } from '@polkadot/util-crypto'; * @return {Boolean} True if hex (with given size) else false */ export function isHexWithGivenByteSize(value, byteSize = undefined) { - if (typeof value !== 'string') { + if (typeof value !== "string") { return false; } const match = value.match(/^0x([0-9a-f]+$)/i); @@ -16,42 +17,74 @@ export function isHexWithGivenByteSize(value, byteSize = undefined) { if (byteSize !== undefined) { // If `byteSize` is not a positive integer type, then check will fail // 2 hex digits make a byte - return match[1].length === (2 * byteSize); + return match[1].length === 2 * byteSize; } // Don't care about byte size of the match but it must be full byte - return (match[1].length % 2) === 0; + return match[1].length % 2 === 0; } return false; } +class Did { + constructor(rawDid) { + if (!isHex(rawDid)) { + throw new Error( + `Expected a hexadecimal DID, received: \`${rawDid}\`` + ); + } + this.Did = rawDid; + } +} + +class DidMethodKey { + constructor(rawDidMethodKey) { + if (!(rawDidMethodKey instanceof PublicKey)) { + throw new Error( + `Expected an instance of the \`PublicKey\`, received: \`${rawDidMethodKey}\`` + ); + } + this.DidMethodKey = rawDidMethodKey; + } +} + +const SECP_256_K1_PUBLIC_KEY_PREFIX = "zQ3"; +const ED_25519_PUBLIC_KEY_PREFIX = "z6Mk"; + /** * Gets the hexadecimal value of the given string. * @return {string} Returns the hexadecimal representation of the ID. */ -export function getHexIdentifier(id, qualifier, validate, byteSize) { - if (id.startsWith(qualifier)) { - // Fully qualified ID. Remove the qualifier - const ss58Did = id.slice(qualifier.length); - try { - const hex = u8aToHex(decodeAddress(ss58Did)); - // 2 characters for `0x` and 2*byte size of ID - if (hex.length !== (2 + 2 * byteSize)) { - throw new Error('Unexpected byte size'); +export function getHexIdentifier(id, qualifiers, validate, byteSize) { + for (const qualifier of [].concat(qualifiers)) { + if (id.startsWith(qualifier)) { + // Fully qualified ID. Remove the qualifier + const ss58Did = id.slice(qualifier.length); + try { + const hex = u8aToHex(decodeAddress(ss58Did)); + if (ss58Did.startsWith(SECP_256_K1_PUBLIC_KEY_PREFIX)) { + return new DidMethodKey(new PublicKeySecp256k1(hex)); + } else if (ss58Did.startsWith(ED_25519_PUBLIC_KEY_PREFIX)) { + return new DidMethodKey(new PublicKeyEd25519(hex)); + } + // 2 characters for `0x` and 2*byte size of ID + if (hex.length !== 2 + 2 * byteSize) { + throw new Error("Unexpected byte size"); + } + return new Did(hex); + } catch (e) { + throw new Error(`Invalid SS58 ID ${id}. ${e}`); } - return hex; - } catch (e) { - throw new Error(`Invalid SS58 ID ${id}. ${e}`); - } - } else { - try { - // Check if hex and of correct size and return the hex value if successful. - validate(id); - return id; - } catch (e) { - // Cannot parse as hex - throw new Error(`Invalid hexadecimal ID ${id}. ${e}`); } } + + try { + // Check if hex and of correct size and return the hex value if successful. + validate(id); + return id; + } catch (e) { + // Cannot parse as hex + throw new Error(`Invalid hexadecimal ID ${id}. ${e}`); + } } /** @@ -59,16 +92,18 @@ export function getHexIdentifier(id, qualifier, validate, byteSize) { * @param addr - address to convert * @param network - the network to use, allowed values are `main`, `test` and `dev` corresponding to mainnet, testnet and dev node */ -export function asDockAddress(addr, network = 'test') { +export function asDockAddress(addr, network = "test") { switch (network) { - case 'dev': + case "dev": return encodeAddress(addr, 42); - case 'test': + case "test": return encodeAddress(addr, 21); - case 'main': + case "main": return encodeAddress(addr, 22); default: - throw new Error(`Network can be either test or main or dev but was passed as ${network}`); + throw new Error( + `Network can be either test or main or dev but was passed as ${network}` + ); } } @@ -83,7 +118,7 @@ export function normalizeToHex(data) { } else if (isHexWithGivenByteSize(data)) { hex = data; } else { - throw new Error('Require a hex string or a byte array'); + throw new Error("Require a hex string or a byte array"); } return hex; } diff --git a/src/utils/did.js b/src/utils/did.js index 99621f7d5..401f35c05 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -130,3 +130,16 @@ export function createDidSig(did, keyId = 1, sig) { did, keyId, sig: sig.toJSON(), }; } + +/** + * + * @param {string} did - DID as hex + * @param {number} keyId - + * @param {Signature} sig + * @returns {{sig: *, keyId, did}} + */ +export function createDidMethodKeySig(didKey, sig) { + return { + didKey, sig: sig.toJSON(), + }; +} diff --git a/src/utils/misc.js b/src/utils/misc.js index 491565f99..9f312b099 100644 --- a/src/utils/misc.js +++ b/src/utils/misc.js @@ -1,6 +1,7 @@ import elliptic from 'elliptic'; import { blake2AsHex } from '@polkadot/util-crypto'; +import { isHex } from '@polkadot/util'; import { sha256 } from 'js-sha256'; import { PublicKey, PublicKeyEd25519, PublicKeySecp256k1, PublicKeySr25519, // eslint-disable-line @@ -168,12 +169,12 @@ export function bytesToWrappedBytes(bytes) { * using this * @returns {Promise} */ -export async function getNonce(hexDid, nonce = undefined, didModule = undefined) { +export async function getDidNonce(didOrDidMethodKey, nonce = undefined, didModule = undefined) { if (nonce === undefined && didModule === undefined) { throw new Error('Provide either nonce or didModule to fetch nonce but none provided'); } if (nonce === undefined) { - return didModule.getNextNonceForDID(hexDid); + return didModule.getNextNonceForDID(didOrDidMethodKey); } return nonce; } diff --git a/tests/integration/custom-nonce.test.js b/tests/integration/custom-nonce.test.js index e5193e566..8fffb7d81 100644 --- a/tests/integration/custom-nonce.test.js +++ b/tests/integration/custom-nonce.test.js @@ -54,7 +54,7 @@ describe('Custom nonce', () => { }, 10000); test('Add key, controller, service endpoint, blob, BBS+ params and keys and accumulator in a batch', async () => { - const nonce = await dock.didModule.getNonceForDID(getHexIdentifierFromDID(did1)); + const nonce = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did1)); const pair = dock.keyring.addFromUri(seed1); const txs = []; @@ -193,7 +193,7 @@ describe('Custom nonce', () => { await dock.revocation.newRegistry(registryId3, policy, false, false); const pair = dock.keyring.addFromUri(seed1); - let currentNonce = await dock.didModule.getNonceForDID(getHexIdentifierFromDID(did1)); + let currentNonce = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did1)); let txs = []; // Revoke from all 3 registries in the same transaction batch @@ -218,7 +218,7 @@ describe('Custom nonce', () => { } // Remove from all 3 registries in the same transaction batch - currentNonce = await dock.didModule.getNonceForDID(getHexIdentifierFromDID(did1)); + currentNonce = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did1)); txs = []; for (const [regId, nonce] of [[registryId1, currentNonce + 1], [registryId2, currentNonce + 2], [registryId3, currentNonce + 3]]) { const [remove, sig, computedNonce] = await dock.revocation.createSignedRemove(regId, did1, pair, 1, { nonce }); @@ -257,7 +257,7 @@ describe('Custom nonce', () => { const pair = dock.keyring.addFromUri(seed1); - let nonce = await dock.didModule.getNonceForDID(getHexIdentifierFromDID(did1)); + let nonce = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did1)); let txs = []; // Add a key and a service endpoint to each DID @@ -295,9 +295,9 @@ describe('Custom nonce', () => { await expect(dock.did.getServiceEndpoint(did5, spId5)).resolves.toEqual({ type: spType, origins: origins[2] }); // Each DID adds 2 blobs - const nonce3 = await dock.didModule.getNonceForDID(getHexIdentifierFromDID(did3)); - const nonce4 = await dock.didModule.getNonceForDID(getHexIdentifierFromDID(did4)); - const nonce5 = await dock.didModule.getNonceForDID(getHexIdentifierFromDID(did5)); + const nonce3 = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did3)); + const nonce4 = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did4)); + const nonce5 = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did5)); txs = []; const [[blobId1, blobHex1, blob1], [blobId2, blobHex2, blob2], [blobId3, blobHex3, blob3], [blobId4, blobHex4, blob4], [blobId5, blobHex5, blob5], [blobId6, blobHex6, blob6]] = [1, 2, 3, 4, 5, 6].map((_) => { @@ -336,7 +336,7 @@ describe('Custom nonce', () => { } // Remove all DIDs in a batch - nonce = await dock.didModule.getNonceForDID(getHexIdentifierFromDID(did1)); + nonce = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did1)); txs = []; const tx13 = await dock.did.createRemoveTx(did3, did1, pair, 1, nonce + 1); From 9806f6ca844bc46e9c7c0460b19cd19920f7e08d Mon Sep 17 00:00:00 2001 From: olegnn Date: Tue, 12 Dec 2023 14:24:17 +0400 Subject: [PATCH 02/32] Trust Registry and `did:key` --- example/blob.js | 2 +- example/dock-did.js | 8 +- example/revocation.js | 6 +- example/schema.js | 2 +- scripts/hit_1.js | 8 +- scripts/master_voting/vote.js | 6 +- scripts/txn-pricing.js | 66 +- src/dock-api.js | 19 + src/modules/WithParamsAndPublicKeys.js | 65 +- src/modules/accumulator.js | 99 ++- src/modules/bbs-plus.js | 9 +- src/modules/bbs.js | 9 +- src/modules/blob.js | 26 +- src/modules/did/did.js | 669 +++++++++--------- src/modules/did/offchain-did-doc-ref.js | 22 +- src/modules/offchain-signatures.js | 91 ++- src/modules/ps.js | 9 +- src/modules/revocation.js | 26 +- src/modules/schema.js | 2 +- src/modules/status-list-credential.js | 54 +- src/modules/trust-registry.js | 376 ++-------- src/rpc-defs/core-mods-rpc-defs.js | 6 +- .../status-list2021-credential.js | 3 +- src/utils/codec.js | 47 +- src/utils/did.js | 211 +++++- src/utils/misc.js | 68 +- src/utils/revocation/one-of-policy.js | 8 +- src/utils/vc/helpers.js | 2 +- .../integration/anoncreds/accumulator.test.js | 335 +++++++-- tests/integration/anoncreds/demo.test.js | 253 ++++--- .../anoncreds/derived-credentials.test.js | 9 +- tests/integration/anoncreds/issuing.test.js | 6 +- .../prefilled-positive-accumulator.test.js | 12 +- .../anoncreds/presentation.test.js | 7 +- .../integration/anoncreds/r1cs-circom.test.js | 5 +- .../anoncreds/saver-and-bound-check.test.js | 8 +- tests/integration/anoncreds/scheme.test.js | 29 +- tests/integration/anoncreds/utils.js | 4 +- tests/integration/blob.test.js | 24 +- .../integration/credential-revocation.test.js | 12 +- tests/integration/custom-nonce.test.js | 110 +-- tests/integration/did/controllers.test.js | 53 +- tests/integration/did/did-basic.test.js | 27 +- tests/integration/did/keys.test.js | 4 +- tests/integration/did/offchain-did.test.js | 4 +- .../integration/did/service-endpoint.test.js | 6 +- tests/integration/fees.test.js | 26 +- tests/integration/helpers.js | 4 +- ...g-and-presentation-with-2-subjects.test.js | 6 +- tests/integration/issuing.test.js | 8 +- tests/integration/master.test.js | 2 +- tests/integration/presenting.test.js | 10 +- .../private-status-list-credential.test.js | 8 +- tests/integration/resolvers.test.js | 8 +- tests/integration/revocation.test.js | 39 +- tests/integration/schema.test.js | 14 +- .../status-list-credential-module.test.js | 245 ++++--- .../status-list-credential.test.js | 9 +- .../integration/trust-registry-module.test.js | 326 +++++++++ tests/test-constants.js | 6 +- tests/unit/did.test.js | 35 +- tutorials/src/tutorial_blobs_schemas.md | 4 +- tutorials/src/tutorial_did.md | 4 +- tutorials/src/tutorial_revocation.md | 6 +- 64 files changed, 2002 insertions(+), 1585 deletions(-) create mode 100644 tests/integration/trust-registry-module.test.js diff --git a/example/blob.js b/example/blob.js index 5bd1b39fa..e32eb40fa 100644 --- a/example/blob.js +++ b/example/blob.js @@ -20,7 +20,7 @@ async function writeAndReadBlob(dock, blobValue, dockDID, pair) { blob: blobValue, }; - await dock.blob.new(blob, dockDID, pair, 1, { didModule: dock.did }, false); + await dock.blob.new(blob, dockDID, pair, { didModule: dock.did }, false); console.log('Blob written, reading from chain...'); diff --git a/example/dock-did.js b/example/dock-did.js index b2c5c4c8f..46f9acbd9 100644 --- a/example/dock-did.js +++ b/example/dock-did.js @@ -33,7 +33,7 @@ async function removeDID() { // Sign the DID removal with this key pair as this is the current key of the DID const pair = dock.keyring.addFromUri(firstKeySeed, null, 'sr25519'); - return dock.did.remove(dockDID, dockDID, pair, 1, undefined, false); + return dock.did.remove(dockDID, dockDID, pair, undefined, false); } // This function assumes the DID has been written. @@ -50,7 +50,7 @@ async function addServiceEndpoint() { const spId = u8aToHex(encoder.encode(spIdText)); const originsText = ['https://foo.example.com']; const origins = originsText.map((u) => u8aToHex(encoder.encode(u))); - return dock.did.addServiceEndpoint(spId, spType, origins, dockDID, dockDID, pair, 1, undefined, false); + return dock.did.addServiceEndpoint(spId, spType, origins, dockDID, dockDID, pair, undefined, false); } // This function assumes the DID has been written. @@ -62,7 +62,7 @@ async function addController() { const newController = createNewDockDID(); - return dock.did.addControllers([newController], dockDID, dockDID, pair, 1, undefined, false); + return dock.did.addControllers([newController], dockDID, dockDID, pair, undefined, false); } // This function assumes the DID has been written. @@ -81,7 +81,7 @@ async function addKey() { vr.setAuthentication(); const newDidKey = new DidKey(newPk, vr); - return dock.did.addKeys([newDidKey], dockDID, dockDID, pair, 1, undefined, false); + return dock.did.addKeys([newDidKey], dockDID, dockDID, pair, undefined, false); } async function getDIDDoc() { diff --git a/example/revocation.js b/example/revocation.js index 13390d85c..b9e5ab032 100644 --- a/example/revocation.js +++ b/example/revocation.js @@ -40,20 +40,20 @@ async function createRegistry() { async function removeRegistry(pair) { console.log('Removing registry...'); - await dock.revocation.removeRegistryWithOneOfPolicy(registryId, controllerDID, pair, 1, { didModule: dock.did }, false); + await dock.revocation.removeRegistryWithOneOfPolicy(registryId, controllerDID, pair, { didModule: dock.did }, false); console.log('Registry removed. All done.'); } async function unrevoke(pair) { console.log('Trying to undo the revocation (unrevoke) of id:', revokeId); - const extrinsic = await dock.revocation.unrevokeCredentialWithOneOfPolicy(registryId, revokeId, controllerDID, pair, 1, { didModule: dock.did }, false); + const extrinsic = await dock.revocation.unrevokeCredentialWithOneOfPolicy(registryId, revokeId, controllerDID, pair, { didModule: dock.did }, false); await extrinsic; } async function revoke(pair) { console.log('Trying to revoke id:', revokeId); - const extrinsic = await dock.revocation.revokeCredentialWithOneOfPolicy(registryId, revokeId, controllerDID, pair, 1, { didModule: dock.did }, false); + const extrinsic = await dock.revocation.revokeCredentialWithOneOfPolicy(registryId, revokeId, controllerDID, pair, { didModule: dock.did }, false); await extrinsic; } diff --git a/example/schema.js b/example/schema.js index a5e7c0792..96f357f79 100644 --- a/example/schema.js +++ b/example/schema.js @@ -88,7 +88,7 @@ async function main() { console.log('The schema is:', JSON.stringify(schema.toJSON(), null, 2)); console.log('Writing schema to the chain with blob id of', schema.id, '...'); - await schema.writeToChain(dock, dockDID, pair, 1, undefined, false); + await schema.writeToChain(dock, dockDID, pair, undefined, false); console.log(`Schema written, reading from chain (${schema.id})...`); diff --git a/scripts/hit_1.js b/scripts/hit_1.js index 70f57558f..edf3145e6 100644 --- a/scripts/hit_1.js +++ b/scripts/hit_1.js @@ -77,7 +77,7 @@ async function sendAddKeyTxns(count, didPairs) { const newPair = dock.keyring.addFromUri(seed, null, 'sr25519'); const publicKey = getPublicKeyFromKeyringPair(newPair); const didKey = new DidKey(publicKey, new VerificationRelationship()); - const tx = await dock.did.createAddKeysTx([didKey], did, did, currentPair, 1); + const tx = await dock.did.createAddKeysTx([didKey], did, did, currentpair); txs.push(tx); j++; } @@ -105,7 +105,7 @@ async function sendAddControllerTxns(count, didPairs) { while (txs.length < count) { const did = didPairs[j][0]; const currentPair = didPairs[j][1]; - const tx = await dock.did.createAddControllersTx([createNewDockDID()], did, did, currentPair, 1); + const tx = await dock.did.createAddControllersTx([createNewDockDID()], did, did, currentpair); txs.push(tx); j++; } @@ -133,7 +133,7 @@ async function sendRemoveTxns(count, didPairs, waitForFinalization = true) { while (txs.length < count) { const did = didPairs[j][0]; const currentPair = didPairs[j][1]; - const tx = await dock.did.createRemoveTx(did, did, currentPair, 1); + const tx = await dock.did.createRemoveTx(did, did, currentpair); txs.push(tx); j++; } @@ -166,7 +166,7 @@ async function sendBlobTxns(count, didPairs) { id: blobId, blob: randomAsHex(995), }; - const tx = await dock.blob.createNewTx(blob, did, pair, 1, { didModule: dock.did }); + const tx = await dock.blob.createNewTx(blob, did, pair, { didModule: dock.did }); txs.push(tx); blobIds.push(blobId); j++; diff --git a/scripts/master_voting/vote.js b/scripts/master_voting/vote.js index de2954af4..4b2e4afc1 100644 --- a/scripts/master_voting/vote.js +++ b/scripts/master_voting/vote.js @@ -2,7 +2,7 @@ import { u8aToHex } from '@polkadot/util'; import { connect, keypair } from '../helpers'; -import { getHexIdentifierFromDID } from '../../src/utils/did'; +import { typedHexDID } from '../../src/utils/did'; import { getStateChange } from '../../src/utils/misc'; require('dotenv').config(); @@ -45,7 +45,7 @@ async function main() { const round_no = parseIntChecked(process.argv[2]); - const did = getHexIdentifierFromDID(did); + const did = typedHexDID(dock.api, did); const proposal_filename = process.argv[3]; const proposal_unparsed = await fsp.readFile(proposal_filename); @@ -86,7 +86,7 @@ async function main() { console.log(''); const encodedProposal = [...nc.api.createType('Call', proposal).toU8a()]; - const nonce = await nc.didModule.getNextNonceForDID(did); + const nonce = await nc.didModule.getNextNonceForDid(did); const vote = { nonce, proposal: encodedProposal, round_no: actual_round_no }; const encodedStateChange = getStateChange(nc.api, 'MasterVote', vote); diff --git a/scripts/txn-pricing.js b/scripts/txn-pricing.js index 4e746c940..87f8ea3a3 100755 --- a/scripts/txn-pricing.js +++ b/scripts/txn-pricing.js @@ -59,7 +59,7 @@ async function dids() { const [, , dk1] = getDidPair(); await printFeePaid(dock.api, account.address, async () => { console.info('Adding DID key with all verification relationships'); - await dock.did.addKeys([dk1], did, did, pair, 1, undefined, false); + await dock.did.addKeys([dk1], did, did, pair, undefined, false); }); // Add DID key with only 1 verification relationship @@ -67,7 +67,7 @@ async function dids() { dk2.verRels.setAuthentication(); await printFeePaid(dock.api, account.address, async () => { console.info('Adding DID key with only 1 verification relationship'); - await dock.did.addKeys([dk2], did, did, pair, 1, undefined, false); + await dock.did.addKeys([dk2], did, did, pair, undefined, false); }); // Add DID key with only 2 verification relationships @@ -76,7 +76,7 @@ async function dids() { dk3.verRels.setAssertion(); await printFeePaid(dock.api, account.address, async () => { console.info('Adding DID key with only 2 verification relationships'); - await dock.did.addKeys([dk3], did, did, pair, 1, undefined, false); + await dock.did.addKeys([dk3], did, did, pair, undefined, false); }); // Add DID key with 3 verification relationships @@ -86,7 +86,7 @@ async function dids() { dk4.verRels.setCapabilityInvocation(); await printFeePaid(dock.api, account.address, async () => { console.info('Adding DID key with 3 verification relationships'); - await dock.did.addKeys([dk4], did, did, pair, 1, undefined, false); + await dock.did.addKeys([dk4], did, did, pair, undefined, false); }); // Add 2 DID keys with only 1 verification relationship @@ -96,7 +96,7 @@ async function dids() { dk6.verRels.setCapabilityInvocation(); await printFeePaid(dock.api, account.address, async () => { console.info('Adding 2 DID keys with only 1 verification relationship'); - await dock.did.addKeys([dk5, dk6], did, did, pair, 1, undefined, false); + await dock.did.addKeys([dk5, dk6], did, did, pair, undefined, false); }); // Add 3 DID keys with only 1 verification relationship @@ -108,20 +108,20 @@ async function dids() { dk9.verRels.setAssertion(); await printFeePaid(dock.api, account.address, async () => { console.info('Adding 3 DID keys with only 1 verification relationship'); - await dock.did.addKeys([dk7, dk8, dk9], did, did, pair, 1, undefined, false); + await dock.did.addKeys([dk7, dk8, dk9], did, did, pair, undefined, false); }); const newControllers = [createNewDockDID(), createNewDockDID(), createNewDockDID()]; // Add 1 controller await printFeePaid(dock.api, account.address, async () => { console.info('Adding 1 controller'); - await dock.did.addControllers([newControllers[0]], did, did, pair, 1, undefined, false); + await dock.did.addControllers([newControllers[0]], did, did, pair, undefined, false); }); // Add 2 controllers await printFeePaid(dock.api, account.address, async () => { console.info('Adding 2 controllers'); - await dock.did.addControllers([newControllers[1], newControllers[2]], did, did, pair, 1, undefined, false); + await dock.did.addControllers([newControllers[1], newControllers[2]], did, did, pair, undefined, false); }); const spType = new ServiceEndpointType(); @@ -133,13 +133,13 @@ async function dids() { // Add 1 service endpoint with 1 origin await printFeePaid(dock.api, account.address, async () => { console.info('Adding 1 service endpoint with 1 origin'); - await dock.did.addServiceEndpoint(spId1, spType, origins1, did, did, pair, 1, undefined, false); + await dock.did.addServiceEndpoint(spId1, spType, origins1, did, did, pair, undefined, false); }); // Add 1 service endpoint with 2 origins await printFeePaid(dock.api, account.address, async () => { console.info('Adding 1 service endpoint with 2 origins'); - await dock.did.addServiceEndpoint(spId2, spType, origins2, did, did, pair, 1, undefined, false); + await dock.did.addServiceEndpoint(spId2, spType, origins2, did, did, pair, undefined, false); }); // Adding a new DID which doesn't control itself but controlled by one other controller @@ -167,43 +167,43 @@ async function dids() { const [, , dk__] = getDidPair(); await printFeePaid(dock.api, account.address, async () => { console.info('Adding DID key with all verification relationships to a DID that doesnt control itself'); - await dock.did.addKeys([dk__], did1, did, pair, 1, undefined, false); + await dock.did.addKeys([dk__], did1, did, pair, undefined, false); }); // Removing 1 key await printFeePaid(dock.api, account.address, async () => { console.info('Removing 1 key'); - await dock.did.removeKeys([2], did, did, pair, 1, undefined, false); + await dock.did.removeKeys([2], did, did, pair, undefined, false); }); // Removing 2 keys await printFeePaid(dock.api, account.address, async () => { console.info('Removing 2 keys'); - await dock.did.removeKeys([3, 4], did, did, pair, 1, undefined, false); + await dock.did.removeKeys([3, 4], did, did, pair, undefined, false); }); // Removing 1 controller await printFeePaid(dock.api, account.address, async () => { console.info('Removing 1 controller'); - await dock.did.removeControllers([newControllers[0]], did, did, pair, 1, undefined, false); + await dock.did.removeControllers([newControllers[0]], did, did, pair, undefined, false); }); // Removing 2 controllers await printFeePaid(dock.api, account.address, async () => { console.info('Removing 2 controllers'); - await dock.did.removeControllers([newControllers[1], newControllers[2]], did, did, pair, 1, undefined, false); + await dock.did.removeControllers([newControllers[1], newControllers[2]], did, did, pair, undefined, false); }); // Removing 1 service endpoint await printFeePaid(dock.api, account.address, async () => { console.info('Removing service endpoint'); - await dock.did.removeServiceEndpoint(spId1, did, did, pair, 1, undefined, false); + await dock.did.removeServiceEndpoint(spId1, did, did, pair, undefined, false); }); // Remove DID await printFeePaid(dock.api, account.address, async () => { console.info('Removing DID'); - await dock.did.remove(did, did, pair, 1, undefined, false); + await dock.did.remove(did, did, pair, undefined, false); }); } @@ -232,16 +232,16 @@ async function revocation() { revokeIds.add(randomAsHex(32)); } - const [update, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, revokeIds, did, pair, 1, { didModule: dock.did }); - const revTx = dock.revocation.createRevokeTx(update, [[sig, nonce]]); + const [update, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, revokeIds, did, pair, { didModule: dock.did }); + const revTx = dock.revocation.createRevokeTx(update, [[nonce, sig]]); console.info(`Payment info of ${count} revocation is ${(await revTx.paymentInfo(account.address))}`); await printFeePaid(dock.api, account.address, async () => { await dock.signAndSend(revTx, false); }); } - const [update, sig, nonce] = await dock.revocation.createSignedRemove(registryId, did, pair, 1, { didModule: dock.did }); - const revTx = dock.revocation.createRemoveRegistryTx(update, [[sig, nonce]]); + const [update, sig, nonce] = await dock.revocation.createSignedRemove(registryId, did, pair, { didModule: dock.did }); + const revTx = dock.revocation.createRemoveRegistryTx(update, [[nonce, sig]]); console.info(`Payment info of removing registry is ${(await revTx.paymentInfo(account.address))}`); await printFeePaid(dock.api, account.address, async () => { @@ -274,7 +274,7 @@ async function blobs() { }; await printFeePaid(dock.api, account.address, async () => { console.info('Blob write'); - await dock.blob.new(blob, did, pair, 1, { didModule: dock.did }, false); + await dock.blob.new(blob, did, pair, { didModule: dock.did }, false); }); } @@ -295,7 +295,7 @@ async function bbsPlus() { const params = BBSPlusModule.prepareAddParameters(bytes, undefined, label); await printFeePaid(dock.api, account.address, async () => { console.info(`Add BBS+ params with ${attributeCount} attributes`); - await dock.bbsPlusModule.addParams(params, did, pair, 1, { didModule: dock.did }, false); + await dock.bbsPlusModule.addParams(params, did, pair, { didModule: dock.did }, false); }); } @@ -304,19 +304,19 @@ async function bbsPlus() { const pk = BBSPlusModule.prepareAddPublicKey(u8aToHex(kp.publicKey.bytes), undefined, [did, 1]); await printFeePaid(dock.api, account.address, async () => { console.info('Add a BBS+ key'); - await dock.bbsPlusModule.addPublicKey(pk, did, did, pair, 1, { didModule: dock.did }, false); + await dock.bbsPlusModule.addPublicKey(pk, did, did, pair, { didModule: dock.did }, false); }); // Remove public key await printFeePaid(dock.api, account.address, async () => { console.info('Remove BBS+ key'); - await dock.bbsPlusModule.removePublicKey(2, did, did, pair, 1, { didModule: dock.did }, false); + await dock.bbsPlusModule.removePublicKey(2, did, did, pair, { didModule: dock.did }, false); }); // Remove params await printFeePaid(dock.api, account.address, async () => { console.info('Remove BBS+ params'); - await dock.bbsPlusModule.removeParams(1, did, pair, 1, { didModule: dock.did }, false); + await dock.bbsPlusModule.removeParams(1, did, pair, { didModule: dock.did }, false); }); } @@ -334,7 +334,7 @@ async function accumulator() { const params = AccumulatorModule.prepareAddParameters(bytes, undefined, label); await printFeePaid(dock.api, account.address, async () => { console.info('Accumulator params write'); - await dock.accumulatorModule.addParams(params, did, pair, 1, { didModule: dock.did }, false); + await dock.accumulatorModule.addParams(params, did, pair, { didModule: dock.did }, false); }); const kp = Accumulator.generateKeypair(new AccumulatorParams(hexToU8a(params.bytes))); @@ -342,7 +342,7 @@ async function accumulator() { const pk = AccumulatorModule.prepareAddPublicKey(u8aToHex(kp.publicKey.bytes), undefined, [did, 1]); await printFeePaid(dock.api, account.address, async () => { console.info('Accumulator key write'); - await dock.accumulatorModule.addPublicKey(pk, did, pair, 1, { didModule: dock.did }, false); + await dock.accumulatorModule.addPublicKey(pk, did, pair, { didModule: dock.did }, false); }); const accumulatorPos = PositiveAccumulator.initialize(new AccumulatorParams(hexToU8a(params.bytes)), kp.secretKey); @@ -350,14 +350,14 @@ async function accumulator() { const accumulatedPos = u8aToHex(accumulatorPos.accumulated); await printFeePaid(dock.api, account.address, async () => { console.info('Adding a positive accumulator'); - await dock.accumulatorModule.addPositiveAccumulator(accumulatorIdPos, accumulatedPos, [did, 1], did, pair, 1, { didModule: dock.did }, false); + await dock.accumulatorModule.addPositiveAccumulator(accumulatorIdPos, accumulatedPos, [did, 1], did, pair, { didModule: dock.did }, false); }); const accumulatorIdUni = randomAsHex(32); const accumulatedUni = u8aToHex(accumulatorPos.accumulated); await printFeePaid(dock.api, account.address, async () => { console.info('Adding a universal accumulator'); - await dock.accumulatorModule.addUniversalAccumulator(accumulatorIdUni, accumulatedUni, [did, 1], 10000, did, pair, 1, { didModule: dock.did }, false); + await dock.accumulatorModule.addUniversalAccumulator(accumulatorIdUni, accumulatedUni, [did, 1], 10000, did, pair, { didModule: dock.did }, false); }); const start = 10; @@ -372,20 +372,20 @@ async function accumulator() { let witUpd = u8aToHex(WitnessUpdatePublicInfo.new(hexToU8a(accumulated), members, [], kp.secretKey).value); await printFeePaid(dock.api, account.address, async () => { console.info(`Updating a positive accumulator with ${members.length} additions`); - await dock.accumulatorModule.updateAccumulator(accumulatorIdPos, accumulated, { additions: members.map((m) => u8aToHex(m)), witnessUpdateInfo: witUpd }, did, pair, 1, { didModule: dock.did }, false); + await dock.accumulatorModule.updateAccumulator(accumulatorIdPos, accumulated, { additions: members.map((m) => u8aToHex(m)), witnessUpdateInfo: witUpd }, did, pair, { didModule: dock.did }, false); }); witUpd = u8aToHex(WitnessUpdatePublicInfo.new(hexToU8a(accumulated), [], members, kp.secretKey).value); await printFeePaid(dock.api, account.address, async () => { console.info(`Updating a positive accumulator with ${members.length} removals`); - await dock.accumulatorModule.updateAccumulator(accumulatorIdPos, accumulated, { removals: members.map((m) => u8aToHex(m)), witnessUpdateInfo: witUpd }, did, pair, 1, { didModule: dock.did }, false); + await dock.accumulatorModule.updateAccumulator(accumulatorIdPos, accumulated, { removals: members.map((m) => u8aToHex(m)), witnessUpdateInfo: witUpd }, did, pair, { didModule: dock.did }, false); }); } await printFeePaid(dock.api, account.address, async () => { console.info('Removing a positive accumulator'); - await dock.accumulatorModule.removeAccumulator(accumulatorIdPos, did, pair, 1, { didModule: dock.did }, false); + await dock.accumulatorModule.removeAccumulator(accumulatorIdPos, did, pair, { didModule: dock.did }, false); }); } diff --git a/src/dock-api.js b/src/dock-api.js index 8e2291251..e9a1a0bc6 100644 --- a/src/dock-api.js +++ b/src/dock-api.js @@ -22,6 +22,7 @@ import PriceFeedRpcDefs from './rpc-defs/price-feed-rpc-defs'; import CoreModsRpcDefs from './rpc-defs/core-mods-rpc-defs'; import ExtrinsicError from './errors/extrinsic-error'; +import TrustRegistryModule from './modules/trust-registry'; function getExtrinsicError(data, api) { // Loop through each of the parameters @@ -142,6 +143,10 @@ export default class DockAPI { this.api, this.signAndSend.bind(this), ); + this.trustRegistryModule = new TrustRegistryModule( + this.api, + this.signAndSend.bind(this) + ); this.statusListCredentialModule = new StatusListCredentialModule( this.api, this.signAndSend.bind(this), @@ -201,6 +206,7 @@ export default class DockAPI { delete this.migrationModule; delete this.legacyBBSPlus; delete this.statusListCredentialModule; + delete this.trustRegistryModule; } } @@ -369,6 +375,19 @@ export default class DockAPI { return this.statusListCredentialModule; } + /** + * Gets the SDK's TrustRegistryModule module + * @return {TrustRegistryModule} The module to use + */ + get trustRegistry() { + if (!this.trustRegistryModule) { + throw new Error( + 'Unable to get TrustRegistryModule module, SDK is not initialised', + ); + } + return this.trustRegistryModule; + } + /** * Gets the SDK's OffchainSignaturesModule module * @return {OffchainSignaturesModule} The module to use diff --git a/src/modules/WithParamsAndPublicKeys.js b/src/modules/WithParamsAndPublicKeys.js index b2af491b0..12f47158f 100644 --- a/src/modules/WithParamsAndPublicKeys.js +++ b/src/modules/WithParamsAndPublicKeys.js @@ -1,7 +1,7 @@ /* eslint-disable camelcase */ import { u8aToHex } from '@polkadot/util'; -import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; +import { createDidSig, typedHexDID, typedHexDIDFromSubstrate } from '../utils/did'; import { getDidNonce } from '../utils/misc'; /** @@ -9,7 +9,10 @@ import { getDidNonce } from '../utils/misc'; * This logic is common in offchain signatures modules and accumulator */ export default class WithParamsAndPublicKeys { - /// Builds module-specific params from the provided value. + + /** + * Builds module-specific params from the provided value. + */ static buildParams(params) { return params; } @@ -84,7 +87,7 @@ export default class WithParamsAndPublicKeys { throw new Error('Reference should be an array of 2 items'); } try { - parsed[0] = getHexIdentifierFromDID(ref[0]); + parsed[0] = typedHexDID(this.api, ref[0]); } catch (e) { throw new Error( `First item of reference should be a DID but was ${ref[0]}`, @@ -105,7 +108,7 @@ export default class WithParamsAndPublicKeys { * @param params - The BBS+ params to add. * @param signerDid - Signer of the payload * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Reference to the keypair used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -114,17 +117,15 @@ export default class WithParamsAndPublicKeys { async createAddParamsTx( params, signerDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { const offchainParams = this.constructor.buildParams(params); - const hexDid = getHexIdentifierFromDID(signerDid); + const hexDid = typedHexDID(this.api, signerDid); const [addParams, signature] = await this.createSignedAddParams( offchainParams, hexDid, - keyPair, - keyId, + signingKeyRef, { nonce, didModule }, ); return this.module.addParams(addParams, signature); @@ -135,7 +136,7 @@ export default class WithParamsAndPublicKeys { * @param index - Index to uniquely identify BBS+ params * @param signerDid - Signer of the payload * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Reference to the keypair used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -144,16 +145,14 @@ export default class WithParamsAndPublicKeys { async removeParamsTx( index, signerDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const hexDid = getHexIdentifierFromDID(signerDid); + const hexDid = typedHexDID(this.api, signerDid); const [removeParams, signature] = await this.createSignedRemoveParams( index, hexDid, - keyPair, - keyId, + signingKeyRef, { nonce, didModule }, ); return this.module.removeParams(removeParams, signature); @@ -164,7 +163,7 @@ export default class WithParamsAndPublicKeys { * @param param - The signature params to add. * @param signerDid - Signer of the payload * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Reference to the keypair used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -175,13 +174,12 @@ export default class WithParamsAndPublicKeys { async addParams( param, signerDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}, ) { - const tx = await this.createAddParamsTx(param, signerDid, keyPair, keyId, { + const tx = await this.createAddParamsTx(param, signerDid, signingKeyRef, { nonce, didModule, }); @@ -193,7 +191,7 @@ export default class WithParamsAndPublicKeys { * @param index - Index to uniquely identify BBS+ params * @param signerDid - Signer of the blob * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Reference to the keypair used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -204,13 +202,12 @@ export default class WithParamsAndPublicKeys { async removeParams( index, signerDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}, ) { - const tx = await this.removeParamsTx(index, signerDid, keyPair, keyId, { + const tx = await this.removeParamsTx(index, signerDid, signingKeyRef, { nonce, didModule, }); @@ -220,30 +217,28 @@ export default class WithParamsAndPublicKeys { async createSignedAddParams( params, hexDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); const addParams = { params, nonce }; - const signature = this.signAddParams(keyPair, addParams); - const didSig = createDidSig(hexDid, keyId, signature); + const signature = this.signAddParams(signingKeyRef, addParams); + const didSig = createDidSig(hexDid, signingKeyRef, signature); return [addParams, didSig]; } async createSignedRemoveParams( index, hexDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); const removeParams = { paramsRef: [hexDid, index], nonce }; - const signature = this.signRemoveParams(keyPair, removeParams); - const didSig = createDidSig(hexDid, keyId, signature); + const signature = this.signRemoveParams(signingKeyRef, removeParams); + const didSig = createDidSig(hexDid, signingKeyRef, signature); return [removeParams, didSig]; } @@ -258,20 +253,20 @@ export default class WithParamsAndPublicKeys { } async getParams(did, counter) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did); return this.getParamsByHexDid(hexId, counter); } /** * * @param did - * @param keyId + * @param signingKeyRef * @param withParams - If true, return the params referenced by the public key. It will throw an error if paramsRef is null * or params were not found on chain which can happen if they were deleted after this public key was added. * @returns {Promise<{bytes: string}|null>} */ async getPublicKey(did, keyId, withParams = false) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did); return this.getPublicKeyByHexDid(hexId, keyId, withParams); } @@ -342,7 +337,7 @@ export default class WithParamsAndPublicKeys { } if (pk.paramsRef.isSome) { const pr = pk.paramsRef.unwrap(); - pkObj.paramsRef = [u8aToHex(pr[0]), pr[1].toNumber()]; + pkObj.paramsRef = [typedHexDIDFromSubstrate(pr[0]), pr[1].toNumber()]; } else { pkObj.paramsRef = null; } diff --git a/src/modules/accumulator.js b/src/modules/accumulator.js index f6147f804..6e409782c 100644 --- a/src/modules/accumulator.js +++ b/src/modules/accumulator.js @@ -1,10 +1,10 @@ /* eslint-disable camelcase */ import { isHex, u8aToHex } from '@polkadot/util'; -import { getDidNonce, getSignatureFromKeyringPair, getStateChange } from '../utils/misc'; +import { getDidNonce, getStateChange } from '../utils/misc'; import WithParamsAndPublicKeys from './WithParamsAndPublicKeys'; import { getAllExtrinsicsFromBlock } from '../utils/chain-ops'; -import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; +import { createDidSig, typedHexDID, typedHexDIDFromSubstrate } from '../utils/did'; /** Class to manage accumulators on chain */ export default class AccumulatorModule extends WithParamsAndPublicKeys { @@ -17,27 +17,27 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { } static prepareAddPositiveAccumulator(id, accumulated, publicKeyRef) { - const vals = AccumulatorModule.parseRef(publicKeyRef); + const keyRef = AccumulatorModule.parseRef(publicKeyRef); return { id, accumulator: { Positive: { accumulated, - keyRef: vals, + keyRef, }, }, }; } static prepareAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize) { - const vals = AccumulatorModule.parseRef(publicKeyRef); + const keyRef = AccumulatorModule.parseRef(publicKeyRef); return { id, accumulator: { Universal: { common: { accumulated, - keyRef: vals, + keyRef, }, maxSize, }, @@ -77,16 +77,15 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * Create transaction to add accumulator public key * @param publicKey - Accumulator public key * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this * @returns {Promise<*>} */ async createAddPublicKeyTx(publicKey, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = getHexIdentifierFromDID(); - const [addPk, signature] = await this.createSignedAddPublicKey(publicKey, signerDid, signingKeyRef, { nonce, didModule }); + const signerHexDid = typedHexDID(this.api, signerDid); + const [addPk, signature] = await this.createSignedAddPublicKey(publicKey, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addPublicKey(addPk, signature); } @@ -94,15 +93,14 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * Create transaction to remove accumulator public key * @param removeKeyId - Index of the accumulator public key * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this * @returns {Promise<*>} */ async createRemovePublicKeyTx(removeKeyId, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = getHexIdentifierFromDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [remPk, signature] = await this.createSignedRemovePublicKey(removeKeyId, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.removePublicKey(remPk, signature); } @@ -113,15 +111,14 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param accumulated - Current accumulated value. * @param publicKeyRef - Reference to accumulator public key * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this * @returns {Promise<*>} */ async createAddPositiveAccumulatorTx(id, accumulated, publicKeyRef, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = getHexIdentifierFromDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [addAccumulator, signature] = await this.createSignedAddPositiveAccumulator(id, accumulated, publicKeyRef, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addAccumulator(addAccumulator, signature); } @@ -133,15 +130,14 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param publicKeyRef - Reference to accumulator public key * @param maxSize - Maximum size of the accumulator * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this * @returns {Promise<*>} */ async createAddUniversalAccumulatorTx(id, accumulated, publicKeyRef, maxSize, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = getHexIdentifierFromDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [addAccumulator, signature] = await this.createSignedAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addAccumulator(addAccumulator, signature); } @@ -154,8 +150,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param removals * @param witnessUpdateInfo * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -165,7 +160,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { id, newAccumulated, { additions = undefined, removals = undefined, witnessUpdateInfo = undefined }, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const signerHexDid = getHexIdentifierFromDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [update, signature] = await this.createSignedUpdateAccumulator(id, newAccumulated, { additions, removals, witnessUpdateInfo }, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.updateAccumulator(update, signature); @@ -175,15 +170,14 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * Create transaction to remove accumulator * @param id - id to remove * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this * @returns {Promise} */ async removeAccumulatorTx(id, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = getHexIdentifierFromDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [removal, signature] = await this.createSignedRemoveAccumulator(id, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.removeAccumulator(removal, signature); } @@ -192,8 +186,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * Add accumulator public key * @param publicKey - Accumulator public key * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -210,8 +203,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * Remove a public key * @param removeKeyId - Index of the accumulator public key * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -230,8 +222,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param accumulated - Current accumulated value. * @param publicKeyRef - Reference to accumulator public key * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -251,8 +242,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param publicKeyRef - Reference to accumulator public key * @param maxSize - Maximum size of the accumulator * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -273,8 +263,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @param removals * @param witnessUpdateInfo * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -291,11 +280,9 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { /** * Remove the accumulator from chain. This frees up the id for reuse. - * @param id * @param id - id to remove * @param signerDid - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -313,7 +300,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { nonce = await getDidNonce(signerHexDid, nonce, didModule); const addPk = { publicKey, nonce }; const signature = this.signAddPublicKey(signingKeyRef, addPk); - const didSig = createDidSig(signerHexDid, keyId, signature); + const didSig = createDidSig(signerHexDid, signingKeyRef, signature); return [addPk, didSig]; } @@ -322,7 +309,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { nonce = await getDidNonce(signerHexDid, nonce, didModule); const removeKey = { keyRef: [signerHexDid, removeKeyId], nonce }; const signature = this.signRemovePublicKey(signingKeyRef, removeKey); - const didSig = createDidSig(signerHexDid, keyId, signature); + const didSig = createDidSig(signerHexDid, signingKeyRef, signature); return [removeKey, didSig]; } @@ -332,7 +319,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { const accum = AccumulatorModule.prepareAddPositiveAccumulator(id, accumulated, publicKeyRef); const addAccum = { ...accum, nonce }; const signature = this.signAddAccumulator(signingKeyRef, addAccum); - const didSig = createDidSig(signerHexDid, keyId, signature); + const didSig = createDidSig(signerHexDid, signingKeyRef, signature); return [addAccum, didSig]; } @@ -342,7 +329,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { const accum = AccumulatorModule.prepareAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize); const addAccum = { ...accum, nonce }; const signature = this.signAddAccumulator(signingKeyRef, addAccum); - const didSig = createDidSig(signerHexDid, keyId, signature); + const didSig = createDidSig(signerHexDid, signingKeyRef, signature); return [addAccum, didSig]; } @@ -368,7 +355,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { nonce, }; const signature = this.signUpdateAccumulator(signingKeyRef, updateAccum); - const didSig = createDidSig(signerHexDid, keyId, signature); + const didSig = createDidSig(signerHexDid, signingKeyRef, signature); return [updateAccum, didSig]; } @@ -377,7 +364,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { nonce = await getDidNonce(signerHexDid, nonce, didModule); const remAccum = { id, nonce }; const signature = this.signRemoveAccumulator(signingKeyRef, remAccum); - const didSig = createDidSig(signerHexDid, keyId, signature); + const didSig = createDidSig(signerHexDid, signingKeyRef, signature); return [remAccum, didSig]; } @@ -409,9 +396,9 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { accumulatorObj.maxSize = accumInfo.accumulator.asUniversal.maxSize.toNumber(); } accumulatorObj.accumulated = u8aToHex(common.accumulated); - const owner = u8aToHex(common.keyRef[0]); + const owner = common.keyRef[0]; const keyId = common.keyRef[1].toNumber(); - accumulatorObj.keyRef = [owner, keyId]; + accumulatorObj.keyRef = [typedHexDIDFromSubstrate(owner), keyId]; if (withKeyAndParams) { const pk = await this.getPublicKeyByHexDid(owner, keyId, true); @@ -473,7 +460,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<{bytes: string}|null>} */ async getLastParamsWritten(did) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did); const counters = await this.api.query[this.moduleName].accumulatorOwnerCounters(hexId); const counter = counters.paramsCounter.toNumber(); if (counter > 0) { @@ -491,7 +478,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise} */ async getAllParamsByDid(did) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did); const params = []; const counters = await this.api.query[this.moduleName].accumulatorOwnerCounters(hexId); @@ -515,7 +502,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise< object[]>} */ async getAllPublicKeysByDid(did, withParams = false) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did); const pks = []; const counters = await this.api.query[this.moduleName].accumulatorOwnerCounters(hexId); @@ -560,17 +547,17 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { signAddParams(signingKeyRef, params) { const serialized = getStateChange(this.api, 'AddAccumulatorParams', params); - return getSignatureFromKeyringPair(signingKeyRef, serialized); + return signingKeyRef.sign(serialized); } signAddPublicKey(signingKeyRef, pk) { const serialized = getStateChange(this.api, 'AddAccumulatorPublicKey', pk); - return getSignatureFromKeyringPair(signingKeyRef, serialized); + return signingKeyRef.sign(serialized); } signRemoveParams(signingKeyRef, ref) { const serialized = getStateChange(this.api, 'RemoveAccumulatorParams', ref); - return getSignatureFromKeyringPair(signingKeyRef, serialized); + return signingKeyRef.sign(serialized); } signRemovePublicKey(signingKeyRef, ref) { @@ -579,7 +566,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { 'RemoveAccumulatorPublicKey', ref, ); - return getSignatureFromKeyringPair(signingKeyRef, serialized); + return signingKeyRef.sign(serialized); } signAddAccumulator(signingKeyRef, addAccumulator) { @@ -588,16 +575,16 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { 'AddAccumulator', addAccumulator, ); - return getSignatureFromKeyringPair(signingKeyRef, serialized); + return signingKeyRef.sign(serialized); } signUpdateAccumulator(signingKeyRef, update) { const serialized = getStateChange(this.api, 'UpdateAccumulator', update); - return getSignatureFromKeyringPair(signingKeyRef, serialized); + return signingKeyRef.sign(serialized); } signRemoveAccumulator(signingKeyRef, removal) { const serialized = getStateChange(this.api, 'RemoveAccumulator', removal); - return getSignatureFromKeyringPair(signingKeyRef, serialized); + return signingKeyRef.sign(serialized); } } diff --git a/src/modules/bbs-plus.js b/src/modules/bbs-plus.js index 35c13a35d..62fbb9545 100644 --- a/src/modules/bbs-plus.js +++ b/src/modules/bbs-plus.js @@ -6,12 +6,17 @@ import BBSPlusParams from '../offchain-signatures/params/bbs-plus'; /** Class to write `BBS+` parameters and keys on chain */ export default class BBSPlusModule extends OffchainSignaturesModule { - /// Builds `BBS+` params from the provided value. + + /** + * Builds `BBS+` params from the provided value. + */ static buildParams(params) { return new BBSPlusParams(params); } - /// Builds `BBS+` public key from the provided value. + /** + * Builds `BBS+` public key from the provided value. + */ static buildPublicKey(publicKey) { return new BBSPlusPublicKey(publicKey); } diff --git a/src/modules/bbs.js b/src/modules/bbs.js index b90062b5c..0a4a657ca 100644 --- a/src/modules/bbs.js +++ b/src/modules/bbs.js @@ -6,12 +6,17 @@ import BBSParams from '../offchain-signatures/params/bbs'; /** Class to write `BBS` parameters and keys on chain */ export default class BBSModule extends OffchainSignaturesModule { - /// Builds `BBS` params from the provided value. + + /** + * Builds `BBS` params from the provided value. + */ static buildParams(params) { return new BBSParams(params); } - /// Builds `BBS` public key from the provided value. + /** + * Builds `BBS` public key from the provided value. + */ static buildPublicKey(publicKey) { return new BBSPublicKey(publicKey); } diff --git a/src/modules/blob.js b/src/modules/blob.js index cf9e2965d..3d44da243 100644 --- a/src/modules/blob.js +++ b/src/modules/blob.js @@ -1,12 +1,12 @@ import { encodeAddress, randomAsHex } from '@polkadot/util-crypto'; import { - u8aToString, stringToHex, bufferToU8a, u8aToHex, + u8aToString, stringToHex, bufferToU8a, } from '@polkadot/util'; -import { getDidNonce, getSignatureFromKeyringPair, getStateChange } from '../utils/misc'; +import { getDidNonce, getStateChange } from '../utils/misc'; import { isHexWithGivenByteSize, getHexIdentifier } from '../utils/codec'; import NoBlobError from '../utils/errors/no-blob-error'; -import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; +import { typedHexDIDFromSubstrate, createDidSig, typedHexDID } from '../utils/did'; export const DockBlobQualifier = 'blob:dock:'; export const DockBlobIdByteSize = 32; @@ -33,7 +33,10 @@ export function validateBlobIDHexIdentifier(identifier) { * @return {string} Returns the hexadecimal representation of the ID. */ export function getHexIdentifierFromBlobID(id) { - return getHexIdentifier(id, DockBlobQualifier, validateBlobIDHexIdentifier, DockBlobIdByteSize); + const hexId = getHexIdentifier(id, DockBlobQualifier, DockBlobIdByteSize); + validateBlobIDHexIdentifier(hexId); + + return hexId; } /** @@ -74,14 +77,15 @@ class BlobModule { * @param blob * @param signerDid - Signer of the blob * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this * @returns {Promise<*>} */ async createNewTx(blob, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const [addBlob, didSig] = await this.createSignedAddBlob(blob, signerDid, signingKeyRef, { nonce, didModule }); + const signerHexDid = typedHexDID(this.api, signerDid); + const [addBlob, didSig] = await this.createSignedAddBlob(blob, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.new(addBlob, didSig); } @@ -90,7 +94,7 @@ class BlobModule { * @param blob * @param signerDid - Signer of the blob * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -130,7 +134,7 @@ class BlobModule { // no-op, just use default Uint8 array value } - return [u8aToHex(respTuple[0]), value]; + return [typedHexDIDFromSubstrate(respTuple[0]), value]; } throw new Error(`Needed 2 items in response but got${respTuple.length}`); } @@ -140,7 +144,7 @@ class BlobModule { * @param blob * @param hexDid - Signer DID in hex form * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -162,8 +166,8 @@ class BlobModule { nonce, }; const serializedAddBlob = this.getSerializedBlob(addBlob); - const signature = getSignatureFromKeyringPair(keyPair, serializedAddBlob); - const didSig = createDidSig(signerDid, keyId, signature); + const signature = signingKeyRef.sign(serializedAddBlob); + const didSig = createDidSig(signerDid, signingKeyRef, signature); return [addBlob, didSig]; } diff --git a/src/modules/did/did.js b/src/modules/did/did.js index 2268650c6..f9835e4d1 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -1,19 +1,20 @@ -import { encodeAddress } from '@polkadot/util-crypto'; -import { u8aToString, hexToU8a, u8aToHex } from '@polkadot/util'; -import { BTreeSet } from '@polkadot/types'; -import b58 from 'bs58'; +import { encodeAddress } from "@polkadot/util-crypto"; +import { u8aToString, hexToU8a, u8aToHex } from "@polkadot/util"; +import { BTreeSet } from "@polkadot/types"; +import b58 from "bs58"; import { - getHexIdentifierFromDID, + typedHexDID, DockDIDQualifier, NoDIDError, validateDockDIDHexIdentifier, NoOnchainDIDError, NoOffchainDIDError, createDidSig, -} from '../../utils/did'; -import { getSignatureFromKeyringPair, getStateChange } from '../../utils/misc'; + DockDIDMethodKeyQualifier, +} from "../../utils/did"; +import { getStateChange } from "../../utils/misc"; -import OffChainDidDocRef from './offchain-did-doc-ref'; +import OffChainDidDocRef from "./offchain-did-doc-ref"; import { PublicKeyEd25519, PublicKeySecp256k1, @@ -21,11 +22,12 @@ import { PublicKeyX25519, DidKey, VerificationRelationship, -} from '../../public-keys'; -import { ServiceEndpointType } from './service-endpoint'; -import WithParamsAndPublicKeys from '../WithParamsAndPublicKeys'; +} from "../../public-keys"; +import { ServiceEndpointType } from "./service-endpoint"; +import WithParamsAndPublicKeys from "../WithParamsAndPublicKeys"; -export const ATTESTS_IRI = 'https://rdf.dock.io/alpha/2021#attestsDocumentContents'; +export const ATTESTS_IRI = + "https://rdf.dock.io/alpha/2021#attestsDocumentContents"; const valuePropOrIdentity = (val) => val.value || val; @@ -49,7 +51,7 @@ class DIDModule { * @returns {*} */ createNewOffchainTx(did, didDocRef) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did).asDid; return this.module.newOffchain(hexId, didDocRef); } @@ -65,7 +67,7 @@ class DIDModule { return this.signAndSend( this.createNewOffchainTx(did, didDocRef), waitForFinalization, - params, + params ); } @@ -76,7 +78,7 @@ class DIDModule { * @returns {*} */ createSetOffchainDidRefTx(did, didDocRef) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did).asDid; return this.module.setOffchainDidDocRef(hexId, didDocRef); } @@ -92,12 +94,12 @@ class DIDModule { did, didDocRef, waitForFinalization = true, - params = {}, + params = {} ) { return this.signAndSend( this.createSetOffchainDidRefTx(did, didDocRef), waitForFinalization, - params, + params ); } @@ -107,7 +109,7 @@ class DIDModule { * @returns {Promise<*>} */ createRemoveOffchainDidTx(did) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did).asDid; return this.module.removeOffchainDid(hexId); } @@ -122,7 +124,7 @@ class DIDModule { return this.signAndSend( this.createRemoveOffchainDidTx(did), waitForFinalization, - params, + params ); } @@ -137,14 +139,14 @@ class DIDModule { const cnts = new BTreeSet(); if (controllers !== undefined) { controllers.forEach((c) => { - cnts.add(getHexIdentifierFromDID(c)); + cnts.add(typedHexDID(this.api, c)); }); } - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did).asDid; return this.module.newOnchain( hexId, didKeys.map((d) => d.toJSON()), - cnts, + cnts ); } @@ -162,12 +164,12 @@ class DIDModule { didKeys, controllers, waitForFinalization = true, - params = {}, + params = {} ) { return this.signAndSend( this.createNewOnchainTx(did, didKeys, controllers), waitForFinalization, - params, + params ); } @@ -176,8 +178,7 @@ class DIDModule { * @param {DidKey[]} didKeys - Array of `DidKey`s as expected by the Substrate node * @param targetDid - The DID to which keys are being added * @param signerDid - The DID that is adding the keys by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @returns {Promise<*>} @@ -186,19 +187,17 @@ class DIDModule { didKeys, targetDid, signerDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { - const targetHexDid = getHexIdentifierFromDID(targetDid); - const signerHexDid = getHexIdentifierFromDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [addKeys, signature] = await this.createSignedAddKeys( didKeys, targetHexDid, signerHexDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.module.addKeys(addKeys, signature); } @@ -208,8 +207,7 @@ class DIDModule { * @param {DidKey[]} didKeys - Array of `DidKey`s as expected by the Substrate node * @param targetDid - The DID to which keys are being added * @param signerDid - The DID that is adding the keys by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @param waitForFinalization @@ -220,23 +218,21 @@ class DIDModule { didKeys, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {}, + params = {} ) { return this.signAndSend( await this.createAddKeysTx( didKeys, targetDid, signerDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ), waitForFinalization, - params, + params ); } @@ -245,8 +241,7 @@ class DIDModule { * @param controllers - The DIDs that will control the `targetDid` * @param targetDid - The DID to which keys are being added * @param signerDid - The DID that is adding the controllers by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @returns {Promise<*>} @@ -255,19 +250,17 @@ class DIDModule { controllers, targetDid, signerDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { - const targetHexDid = getHexIdentifierFromDID(targetDid); - const signerHexDid = getHexIdentifierFromDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [addControllers, signature] = await this.createSignedAddControllers( controllers, targetHexDid, signerHexDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.module.addControllers(addControllers, signature); } @@ -277,8 +270,7 @@ class DIDModule { * @param controllers - The DIDs that will control the `targetDid` * @param targetDid - The DID to which controllers are being added * @param signerDid - The DID that is adding the controllers by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @param waitForFinalization @@ -289,19 +281,17 @@ class DIDModule { controllers, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {}, + params = {} ) { const tx = await this.createAddControllersTx( controllers, targetDid, signerDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.signAndSend(tx, waitForFinalization, params); } @@ -313,8 +303,7 @@ class DIDModule { * @param {Array} origins - An array of one of URIs encoded as hex. * @param targetDid - The DID to which service endpoint is being added * @param signerDid - The DID that is adding the service endpoint by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @returns {Promise<*>} @@ -325,22 +314,21 @@ class DIDModule { origins, targetDid, signerDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { - const targetHexDid = getHexIdentifierFromDID(targetDid); - const signerHexDid = getHexIdentifierFromDID(signerDid); - const [addServiceEndpoint, signature] = await this.createSignedAddServiceEndpoint( - endpointId, - endpointType, - origins, - targetHexDid, - signerHexDid, - keyPair, - keyId, - nonce, - ); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); + const [addServiceEndpoint, signature] = + await this.createSignedAddServiceEndpoint( + endpointId, + endpointType, + origins, + targetHexDid, + signerHexDid, + signingKeyRef, + nonce + ); return this.module.addServiceEndpoint(addServiceEndpoint, signature); } @@ -351,8 +339,7 @@ class DIDModule { * @param {Array} origins - An array of one of URIs encoded as hex. * @param targetDid - The DID to which service endpoint is being added * @param signerDid - The DID that is adding the service endpoint by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @param waitForFinalization @@ -365,11 +352,10 @@ class DIDModule { origins, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {}, + params = {} ) { const tx = await this.createAddServiceEndpointTx( endpointId, @@ -377,9 +363,8 @@ class DIDModule { origins, targetDid, signerDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.signAndSend(tx, waitForFinalization, params); } @@ -389,8 +374,7 @@ class DIDModule { * @param keyIds - Key indices to remove * @param targetDid - The DID from which keys are being removed * @param signerDid - The DID that is removing the keys by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @returns {Promise<*>} @@ -399,19 +383,17 @@ class DIDModule { keyIds, targetDid, signerDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { - const targetHexDid = getHexIdentifierFromDID(targetDid); - const signerHexDid = getHexIdentifierFromDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [removeKeys, signature] = await this.createSignedRemoveKeys( keyIds, targetHexDid, signerHexDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.module.removeKeys(removeKeys, signature); } @@ -421,8 +403,7 @@ class DIDModule { * @param keyIds - Key indices to remove * @param targetDid - The DID from which keys are being removed * @param signerDid - The DID that is removing the keys by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @param waitForFinalization @@ -433,19 +414,17 @@ class DIDModule { keyIds, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {}, + params = {} ) { const tx = await this.createRemoveKeysTx( keyIds, targetDid, signerDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.signAndSend(tx, waitForFinalization, params); } @@ -455,8 +434,7 @@ class DIDModule { * @param controllers - Controller DIDs to remove. * @param targetDid - The DID from which controllers are being removed * @param signerDid - The DID that is removing the controllers by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @returns {Promise<*>} @@ -465,20 +443,19 @@ class DIDModule { controllers, targetDid, signerDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { - const targetHexDid = getHexIdentifierFromDID(targetDid); - const signerHexDid = getHexIdentifierFromDID(signerDid); - const [removeControllers, signature] = await this.createSignedRemoveControllers( - controllers, - targetHexDid, - signerHexDid, - keyPair, - keyId, - nonce, - ); + const targetHexDid = typedHexDID(this.api, targetDid); + const signerHexDid = typedHexDID(this.api, signerDid); + const [removeControllers, signature] = + await this.createSignedRemoveControllers( + controllers, + targetHexDid, + signerHexDid, + signingKeyRef, + nonce + ); return this.module.removeControllers(removeControllers, signature); } @@ -487,8 +464,7 @@ class DIDModule { * @param controllers - Controller DIDs to remove. * @param targetDid - The DID from which controllers are being removed * @param signerDid - The DID that is removing the controllers by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @param waitForFinalization @@ -499,19 +475,17 @@ class DIDModule { controllers, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {}, + params = {} ) { const tx = await this.removeControllersTx( controllers, targetDid, signerDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.signAndSend(tx, waitForFinalization, params); } @@ -521,8 +495,7 @@ class DIDModule { * @param endpointId - The endpoint to remove * @param targetDid - The DID from which endpoint is being removed * @param signerDid - The DID that is removing the endpoint by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @returns {Promise<*>} @@ -531,20 +504,19 @@ class DIDModule { endpointId, targetDid, signerDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { - const targetHexDid = getHexIdentifierFromDID(targetDid); - const signerHexDid = getHexIdentifierFromDID(signerDid); - const [removeServiceEndpoint, signature] = await this.createSignedRemoveServiceEndpoint( - endpointId, - targetHexDid, - signerHexDid, - keyPair, - keyId, - nonce, - ); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); + const [removeServiceEndpoint, signature] = + await this.createSignedRemoveServiceEndpoint( + endpointId, + targetHexDid, + signerHexDid, + signingKeyRef, + nonce + ); return this.module.removeServiceEndpoint(removeServiceEndpoint, signature); } @@ -553,8 +525,7 @@ class DIDModule { * @param endpointId - The endpoint to remove * @param targetDid - The DID from which endpoint is being removed * @param signerDid - The DID that is removing the endpoint by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @param waitForFinalization @@ -565,19 +536,17 @@ class DIDModule { endpointId, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {}, + params = {} ) { const tx = await this.createRemoveServiceEndpointTx( endpointId, targetDid, signerDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.signAndSend(tx, waitForFinalization, params); } @@ -586,27 +555,19 @@ class DIDModule { * Create a transaction to remove an on-chain DID * @param targetDid - The DID being removed * @param signerDid - The DID that is removing `targetDid` by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @return {Promise} The extrinsic to sign and send. */ - async createRemoveTx( - targetDid, - signerDid, - keyPair, - keyId, - nonce = undefined, - ) { - const hexDid = getHexIdentifierFromDID(targetDid); - const signerHexDid = getHexIdentifierFromDID(signerDid); + async createRemoveTx(targetDid, signerDid, signingKeyRef, nonce = undefined) { + const hexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [didRemoval, signature] = await this.createSignedDidRemoval( hexDid, signerHexDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.module.removeOnchainDid(didRemoval, signature); } @@ -615,8 +576,7 @@ class DIDModule { * Removes an on-chain DID. * @param targetDid - The DID being removed * @param signerDid - The DID that is removing `targetDid` by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's keypair reference * @param nonce - The nonce to be used for sending this transaction. If not provided then an appropriate nonce will be * fetched from chain before creating the transaction * @param waitForFinalization @@ -626,18 +586,16 @@ class DIDModule { async remove( targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {}, + params = {} ) { const tx = await this.createRemoveTx( targetDid, signerDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.signAndSend(tx, waitForFinalization, params); } @@ -647,27 +605,18 @@ class DIDModule { * @param priority * @param iri * @param did - * @param keyPair - * @param keyId + * @param signingKeyRef * @param nonce * @returns {Promise>} */ - async createSetClaimTx( - priority, - iri, - did, - keyPair, - keyId, - nonce = undefined, - ) { - const hexDid = getHexIdentifierFromDID(did); + async createSetClaimTx(priority, iri, did, signingKeyRef, nonce = undefined) { + const hexDid = typedHexDID(this.api, did); const [setAttestation, signature] = await this.createSignedAttestation( priority, iri, hexDid, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.api.tx.attest.setClaim(setAttestation, signature); } @@ -677,8 +626,7 @@ class DIDModule { * @param priority * @param iri * @param did - * @param keyPair - * @param keyId + * @param signingKeyRef * @param nonce * @param waitForFinalization * @param params @@ -687,19 +635,17 @@ class DIDModule { priority, iri, did, - keyPair, - keyId, + signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {}, + params = {} ) { const attestTx = await this.createSetClaimTx( priority, iri, did, - keyPair, - keyId, - nonce, + signingKeyRef, + nonce ); return this.signAndSend(attestTx, waitForFinalization, params); } @@ -713,6 +659,15 @@ class DIDModule { return `${DockDIDQualifier}${did}`; } + /** + * Create the fully qualified DID like "did:dock:..." + * @param {string} didMethodKey - DID + * @return {string} The DID identifier. + */ + getFullyQualifiedDIDMethodKey(didMethodKey) { + return `${DockDIDMethodKeyQualifier}${didMethodKey}`; + } + /** * Fetches the DIDs attestations IRI from the chain * @param {string} hexId - DID in hex format @@ -734,25 +689,31 @@ class DIDModule { */ // eslint-disable-next-line sonarjs/cognitive-complexity async getDocument(did, { getOffchainSigKeys = true } = {}) { - const hexId = getHexIdentifierFromDID(did); - let didDetails = await this.getOnchainDidDetail(hexId); + const typedDid = typedHexDID(this.api, did); + const hexDid = typedDid.asDid; + let didDetails = await this.getOnchainDidDetail(hexDid); didDetails = didDetails.data || didDetails; // Get DIDs attestations - const attests = await this.getAttests(hexId); + const attests = await this.getAttests(typedDid); // If given DID was in hex, encode to SS58 and then construct fully qualified DID else the DID was already fully qualified - const id = (did === hexId) ? this.getFullyQualifiedDID(encodeAddress(hexId)) : did; + const id = + did === hexDid ? this.getFullyQualifiedDID(encodeAddress(hexDid)) : did; // Get controllers const controllers = []; if (didDetails.activeControllers > 0) { - const cnts = await this.api.query.didModule.didControllers.entries(hexId); + const cnts = await this.api.query.didModule.didControllers.entries( + hexDid + ); cnts.forEach(([key, value]) => { if (value.isSome) { const [controlled, controller] = key.toHuman(); - if (controlled !== hexId) { - throw new Error(`Controlled DID ${controlled[0]} was found to be different than queried DID ${hexId}`); + if (controlled !== hexDid) { + throw new Error( + `Controlled DID ${controlled[0]} was found to be different than queried DID ${hexDid}` + ); } controllers.push(controller); } @@ -761,7 +722,9 @@ class DIDModule { // Get service endpoints const serviceEndpoints = []; - const sps = await this.api.query.didModule.didServiceEndpoints.entries(hexId); + const sps = await this.api.query.didModule.didServiceEndpoints.entries( + hexDid + ); sps.forEach(([key, value]) => { if (value.isSome) { const sp = value.unwrap(); @@ -769,8 +732,10 @@ class DIDModule { const [d, spId] = key.args; // eslint-disable-next-line no-underscore-dangle const d_ = u8aToHex(d); - if (d_ !== hexId) { - throw new Error(`DID ${d_} was found to be different than queried DID ${hexId}`); + if (d_ !== hexDid) { + throw new Error( + `DID ${d_} was found to be different than queried DID ${hexDid}` + ); } serviceEndpoints.push([spId, sp]); } @@ -783,7 +748,7 @@ class DIDModule { const capInv = []; const keyAgr = []; if (didDetails.lastKeyId > 0) { - const dks = await this.api.query.didModule.didKeys.entries(hexId); + const dks = await this.api.query.didModule.didKeys.entries(hexDid); dks.forEach(([key, value]) => { if (value.isSome) { const dk = value.unwrap(); @@ -791,24 +756,26 @@ class DIDModule { const [d, i] = key.args; // eslint-disable-next-line no-underscore-dangle const d_ = u8aToHex(d); - if (d_ !== hexId) { - throw new Error(`DID ${d_} was found to be different than queried DID ${hexId}`); + if (d_ !== hexDid) { + throw new Error( + `DID ${d_} was found to be different than queried DID ${hexDid}` + ); } const index = i.toNumber(); const pk = dk.publicKey; let publicKeyRaw; let typ; if (pk.isSr25519) { - typ = 'Sr25519VerificationKey2020'; + typ = "Sr25519VerificationKey2020"; publicKeyRaw = valuePropOrIdentity(pk.asSr25519); } else if (pk.isEd25519) { - typ = 'Ed25519VerificationKey2018'; + typ = "Ed25519VerificationKey2018"; publicKeyRaw = valuePropOrIdentity(pk.asEd25519); } else if (pk.isSecp256k1) { - typ = 'EcdsaSecp256k1VerificationKey2019'; + typ = "EcdsaSecp256k1VerificationKey2019"; publicKeyRaw = valuePropOrIdentity(pk.asSecp256k1); } else if (pk.isX25519) { - typ = 'X25519KeyAgreementKey2019'; + typ = "X25519KeyAgreementKey2019"; publicKeyRaw = valuePropOrIdentity(pk.asX25519); } else { throw new Error(`Cannot parse public key ${pk}`); @@ -849,32 +816,39 @@ class DIDModule { // Query all BBS+ keys in a single RPC call to the node. const queryKeys = []; for (const k of possibleKeyIds) { - queryKeys.push([hexId, k]); + queryKeys.push([hexDid, k]); } if (this.api.query.offchainSignatures != null) { - const resp = await this.api.query.offchainSignatures.publicKeys.multi(queryKeys); + const resp = await this.api.query.offchainSignatures.publicKeys.multi( + queryKeys + ); let currentIter = 0; for (let r of resp) { // The gaps in `keyId` might correspond to removed keys if (r.isSome) { - let rawKey; let - keyType; + let rawKey; + let keyType; r = r.unwrap(); if (r.isBbs) { - keyType = 'Bls12381BBSVerificationKeyDock2023'; + keyType = "Bls12381BBSVerificationKeyDock2023"; rawKey = r.asBbs; } else if (r.isBbsPlus) { - keyType = 'Bls12381G2VerificationKeyDock2022'; + keyType = "Bls12381G2VerificationKeyDock2022"; rawKey = r.asBbsPlus; } else if (r.isPs) { - keyType = 'Bls12381PSVerificationKeyDock2023'; + keyType = "Bls12381PSVerificationKeyDock2023"; rawKey = r.asPs; } // Don't care about signature params for now - const pkObj = WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse(rawKey); - if (pkObj.curveType !== 'Bls12381') { - throw new Error(`Curve type should have been Bls12381 but was ${pkObj.curveType}`); + const pkObj = + WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse( + rawKey + ); + if (pkObj.curveType !== "Bls12381") { + throw new Error( + `Curve type should have been Bls12381 but was ${pkObj.curveType}` + ); } const keyIndex = queryKeys[currentIter][1]; keys.push([keyIndex, keyType, hexToU8a(pkObj.bytes)]); @@ -883,18 +857,25 @@ class DIDModule { currentIter++; } } else { - const resp = await this.api.query.bbsPlus.bbsPlusKeys.multi(queryKeys); + const resp = await this.api.query.bbsPlus.bbsPlusKeys.multi( + queryKeys + ); let currentIter = 0; for (const r of resp) { // The gaps in `keyId` might correspond to removed keys if (r.isSome) { - const keyType = 'Bls12381G2VerificationKeyDock2022'; + const keyType = "Bls12381G2VerificationKeyDock2022"; const rawKey = r.unwrap(); // Don't care about signature params for now - const pkObj = WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse(rawKey); - if (pkObj.curveType !== 'Bls12381') { - throw new Error(`Curve type should have been Bls12381 but was ${pkObj.curveType}`); + const pkObj = + WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse( + rawKey + ); + if (pkObj.curveType !== "Bls12381") { + throw new Error( + `Curve type should have been Bls12381 but was ${pkObj.curveType}` + ); } const keyIndex = queryKeys[currentIter][1]; keys.push([keyIndex, keyType, hexToU8a(pkObj.bytes)]); @@ -925,9 +906,13 @@ class DIDModule { // Construct document const document = { - '@context': ['https://www.w3.org/ns/did/v1'], + "@context": ["https://www.w3.org/ns/did/v1"], id, - controller: [...controllers].map((c) => this.getFullyQualifiedDID(encodeAddress(c))), + controller: [...controllers].map((c) => + c.Did + ? this.getFullyQualifiedDID(encodeAddress(c.Did)) + : this.getFullyQualifiedDIDMethodKey(encodeAddress(c.DidMethodKey)) + ), publicKey: verificationMethod, }; @@ -950,12 +935,12 @@ class DIDModule { const spType = sp.types.toNumber(); if (spType !== 1) { throw new Error( - `Only "LinkedDomains" supported as service endpoint type for now but found ${spType}`, + `Only "LinkedDomains" supported as service endpoint type for now but found ${spType}` ); } return { id: decoder.decode(spId), - type: 'LinkedDomains', + type: "LinkedDomains", serviceEndpoint: sp.origins.map((o) => decoder.decode(o)), }; }); @@ -998,6 +983,18 @@ class DIDModule { }; } + async getDidMethodKeyDetail(did) { + let resp = await this.api.query.didModule.didMethodKeys(did); + if (resp.isNone) { + throw new NoDIDError(`did:key:dock:${did}`); + } + resp = resp.unwrap(); + + return { + nonce: resp.nonce.toNumber(), + }; + } + /** * Gets the DID detail of an on chain DID * @param didIdentifier @@ -1031,21 +1028,27 @@ class DIDModule { /** * Gets the current nonce for the DID. It will throw error if the DID does not exist on * chain or chain returns null response. - * @param {string} didIdentifier - DID identifier as hex. Not accepting full DID intentionally for efficiency as these + * @param {string} did - DID identifier as hex. Not accepting full DID intentionally for efficiency as these * methods are used internally * @return {Promise} */ - async getDidNonceForDID(didIdentifier) { - return (await this.getOnchainDidDetail(didIdentifier)).nonce; + async getNonceForDid(did) { + if (did.isDid) { + return (await this.getOnchainDidDetail(did.asDid)).nonce; + } else if (did.isDidMethodKey) { + return (await this.getDidMethodKeyDetail(did.asDidMethodKey)).nonce; + } else { + throw new Error("Invalid DID provided"); + } } /** * Gets the nonce that should be used for sending the next transaction by this DID. Its 1 more than the current nonce. - * @param didIdentifier + * @param did * @returns {Promise<*>} */ - async getNextNonceForDID(didIdentifier) { - return (await this.getDidNonceForDID(didIdentifier)) + 1; + async getNextNonceForDid(did) { + return (await this.getNonceForDid(did)) + 1; } /** @@ -1055,7 +1058,7 @@ class DIDModule { * @returns {Promise} */ async getDidKey(did, keyIndex) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did).asDid; let resp = await this.api.query.didModule.didKeys(hexId, keyIndex); if (resp.isNone) { throw new Error(`No key for found did ${did} and key index ${keyIndex}`); @@ -1066,19 +1069,27 @@ class DIDModule { let publicKey; if (pk.isSr25519) { - publicKey = new PublicKeySr25519(u8aToHex(valuePropOrIdentity(pk.asSr25519))); + publicKey = new PublicKeySr25519( + u8aToHex(valuePropOrIdentity(pk.asSr25519)) + ); } else if (pk.isEd25519) { - publicKey = new PublicKeyEd25519(u8aToHex(valuePropOrIdentity(pk.asEd25519))); + publicKey = new PublicKeyEd25519( + u8aToHex(valuePropOrIdentity(pk.asEd25519)) + ); } else if (pk.isSecp256k1) { - publicKey = new PublicKeySecp256k1(u8aToHex(valuePropOrIdentity(pk.asSecp256k1))); + publicKey = new PublicKeySecp256k1( + u8aToHex(valuePropOrIdentity(pk.asSecp256k1)) + ); } else if (pk.isX25519) { - publicKey = new PublicKeyX25519(u8aToHex(valuePropOrIdentity(pk.asX25519))); + publicKey = new PublicKeyX25519( + u8aToHex(valuePropOrIdentity(pk.asX25519)) + ); } else { throw new Error(`Cannot parse public key ${pk}`); } return new DidKey( publicKey, - new VerificationRelationship(resp.verRels.toNumber()), + new VerificationRelationship(resp.verRels.toNumber()) ); } @@ -1089,11 +1100,11 @@ class DIDModule { * @returns {Promise} */ async isController(controlled, controller) { - const controlledHexId = getHexIdentifierFromDID(controlled); - const controllerHexId = getHexIdentifierFromDID(controller); + const controlledDid = typedHexDID(this.api, controlled).asDid; + const controllerDid = typedHexDID(this.api, controller); const resp = await this.api.query.didModule.didControllers( - controlledHexId, - controllerHexId, + controlledDid, + controllerDid ); return resp.isSome; } @@ -1105,14 +1116,14 @@ class DIDModule { * @returns {Promise} */ async getServiceEndpoint(did, endpointId) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did).asDid; let resp = await this.api.query.didModule.didServiceEndpoints( hexId, - endpointId, + endpointId ); if (resp.isNone) { throw new Error( - `No service endpoint found for did ${did} and with id ${endpointId}`, + `No service endpoint found for did ${did} and with id ${endpointId}` ); } resp = resp.unwrap(); @@ -1124,22 +1135,21 @@ class DIDModule { async createSignedAddKeys( didKeys, - hexDid, - controllerHexDid, - keyPair, - keyId, - nonce = undefined, + did, + controllerDid, + signingKeyRef, + nonce = undefined ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign - nonce = await this.getNextNonceForDID(controllerHexDid); + nonce = await this.getNextNonceForDid(controllerDid); } const keys = didKeys.map((d) => d.toJSON()); - const addKeys = { did: hexDid, keys, nonce }; + const addKeys = { did, keys, nonce }; const serializedAddKeys = this.getSerializedAddKeys(addKeys); - const signature = getSignatureFromKeyringPair(keyPair, serializedAddKeys); - const didSig = createDidSig(controllerHexDid, keyId, signature); + const signature = signingKeyRef.sign(serializedAddKeys); + const didSig = createDidSig(controllerDid, signingKeyRef, signature); return [addKeys, didSig]; } @@ -1147,26 +1157,23 @@ class DIDModule { controllers, hexDid, controllerHexDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign - nonce = await this.getNextNonceForDID(controllerHexDid); + nonce = await this.getNextNonceForDid(controllerHexDid); } const cnts = new BTreeSet(); controllers.forEach((c) => { - cnts.add(getHexIdentifierFromDID(c)); + cnts.add(typedHexDID(this.api, c)); }); const addControllers = { did: hexDid, controllers: cnts, nonce }; - const serializedAddControllers = this.getSerializedAddControllers(addControllers); - const signature = getSignatureFromKeyringPair( - keyPair, - serializedAddControllers, - ); - const didSig = createDidSig(controllerHexDid, keyId, signature); + const serializedAddControllers = + this.getSerializedAddControllers(addControllers); + const signature = signingKeyRef.sign(serializedAddControllers); + const didSig = createDidSig(controllerHexDid, signingKeyRef, signature); return [addControllers, didSig]; } @@ -1176,13 +1183,12 @@ class DIDModule { origins, hexDid, controllerHexDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign - nonce = await this.getNextNonceForDID(controllerHexDid); + nonce = await this.getNextNonceForDid(controllerHexDid); } const endpoint = { types: endpointType.value, origins }; @@ -1192,12 +1198,10 @@ class DIDModule { endpoint, nonce, }; - const serializedServiceEndpoint = this.getSerializedAddServiceEndpoint(addServiceEndpoint); - const signature = getSignatureFromKeyringPair( - keyPair, - serializedServiceEndpoint, - ); - const didSig = createDidSig(controllerHexDid, keyId, signature); + const serializedServiceEndpoint = + this.getSerializedAddServiceEndpoint(addServiceEndpoint); + const signature = signingKeyRef.sign(serializedServiceEndpoint); + const didSig = createDidSig(controllerHexDid, signingKeyRef, signature); return [addServiceEndpoint, didSig]; } @@ -1205,16 +1209,15 @@ class DIDModule { keyIds, did, controllerDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { - const hexDid = getHexIdentifierFromDID(did); - const controllerHexDid = getHexIdentifierFromDID(controllerDid); + const hexDid = typedHexDID(this.api, did).asDid; + const controllerHexDid = typedHexDID(this.api, controllerDid); if (nonce === undefined) { // eslint-disable-next-line no-param-reassign - nonce = await this.getNextNonceForDID(controllerHexDid); + nonce = await this.getNextNonceForDid(controllerHexDid); } const keys = new BTreeSet(); @@ -1223,11 +1226,8 @@ class DIDModule { }); const removeKeys = { did: hexDid, keys, nonce }; const serializedRemoveKeys = this.getSerializedRemoveKeys(removeKeys); - const signature = getSignatureFromKeyringPair( - keyPair, - serializedRemoveKeys, - ); - const didSig = createDidSig(controllerHexDid, keyId, signature); + const signature = signingKeyRef.sign(serializedRemoveKeys); + const didSig = createDidSig(controllerHexDid, signingKeyRef, signature); return [removeKeys, didSig]; } @@ -1235,30 +1235,27 @@ class DIDModule { controllers, did, controllerDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { - const hexDid = getHexIdentifierFromDID(did); - const controllerHexDid = getHexIdentifierFromDID(controllerDid); + const hexDid = typedHexDID(this.api, did).asDid; + const controllerHexDid = typedHexDID(this.api, controllerDid); if (nonce === undefined) { // eslint-disable-next-line no-param-reassign - nonce = await this.getNextNonceForDID(controllerHexDid); + nonce = await this.getNextNonceForDid(controllerHexDid); } const cnts = new BTreeSet(); controllers.forEach((c) => { - cnts.add(getHexIdentifierFromDID(c)); + cnts.add(typedHexDID(this.api, c)); }); const removeControllers = { did: hexDid, controllers: cnts, nonce }; - const serializedRemoveControllers = this.getSerializedRemoveControllers(removeControllers); - const signature = getSignatureFromKeyringPair( - keyPair, - serializedRemoveControllers, - ); - const didSig = createDidSig(controllerHexDid, keyId, signature); + const serializedRemoveControllers = + this.getSerializedRemoveControllers(removeControllers); + const signature = signingKeyRef.sign(serializedRemoveControllers); + const didSig = createDidSig(controllerHexDid, signingKeyRef, signature); return [removeControllers, didSig]; } @@ -1266,41 +1263,37 @@ class DIDModule { endpointId, hexDid, controllerHexDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign - nonce = await this.getNextNonceForDID(controllerHexDid); + nonce = await this.getNextNonceForDid(controllerHexDid); } const removeServiceEndpoint = { did: hexDid, id: endpointId, nonce }; - const serializedRemoveServiceEndpoint = this.getSerializedRemoveServiceEndpoint(removeServiceEndpoint); - const signature = getSignatureFromKeyringPair( - keyPair, - serializedRemoveServiceEndpoint, - ); - const didSig = createDidSig(controllerHexDid, keyId, signature); + const serializedRemoveServiceEndpoint = + this.getSerializedRemoveServiceEndpoint(removeServiceEndpoint); + const signature = signingKeyRef.sign(serializedRemoveServiceEndpoint); + const didSig = createDidSig(controllerHexDid, signingKeyRef, signature); return [removeServiceEndpoint, didSig]; } async createSignedDidRemoval( - hexDid, - controllerHexDid, - keyPair, - keyId, - nonce = undefined, + did, + controllerDid, + signingKeyRef, + nonce = undefined ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign - nonce = await this.getNextNonceForDID(controllerHexDid); + nonce = await this.getNextNonceForDid(controllerDid); } - const removal = { did: hexDid, nonce }; + const removal = { did, nonce }; const serializedRemoval = this.getSerializedDidRemoval(removal); - const signature = getSignatureFromKeyringPair(keyPair, serializedRemoval); - const didSig = createDidSig(controllerHexDid, keyId, signature); + const signature = signingKeyRef.sign(serializedRemoval); + const didSig = createDidSig(controllerDid, signingKeyRef, signature); return [removal, didSig]; } @@ -1308,13 +1301,12 @@ class DIDModule { priority, iri, hexDid, - keyPair, - keyId, - nonce = undefined, + signingKeyRef, + nonce = undefined ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign - nonce = await this.getNextNonceForDID(hexDid); + nonce = await this.getNextNonceForDid(hexDid); } const setAttestation = { attest: { @@ -1324,11 +1316,8 @@ class DIDModule { nonce, }; const serializedAttestation = this.getSerializedAttestation(setAttestation); - const signature = getSignatureFromKeyringPair( - keyPair, - serializedAttestation, - ); - const didSig = createDidSig(hexDid, keyId, signature); + const signature = signingKeyRef.sign(serializedAttestation); + const didSig = createDidSig(hexDid, signingKeyRef, signature); return [setAttestation, didSig]; } @@ -1338,30 +1327,30 @@ class DIDModule { * @returns {Array} An array of Uint8 */ getSerializedAddKeys(addKeys) { - return getStateChange(this.api, 'AddKeys', addKeys); + return getStateChange(this.api, "AddKeys", addKeys); } getSerializedAddControllers(addControllers) { - return getStateChange(this.api, 'AddControllers', addControllers); + return getStateChange(this.api, "AddControllers", addControllers); } getSerializedAddServiceEndpoint(addServiceEndpoint) { - return getStateChange(this.api, 'AddServiceEndpoint', addServiceEndpoint); + return getStateChange(this.api, "AddServiceEndpoint", addServiceEndpoint); } getSerializedRemoveKeys(removeKeys) { - return getStateChange(this.api, 'RemoveKeys', removeKeys); + return getStateChange(this.api, "RemoveKeys", removeKeys); } getSerializedRemoveControllers(removeControllers) { - return getStateChange(this.api, 'RemoveControllers', removeControllers); + return getStateChange(this.api, "RemoveControllers", removeControllers); } getSerializedRemoveServiceEndpoint(removeServiceEndpoint) { return getStateChange( this.api, - 'RemoveServiceEndpoint', - removeServiceEndpoint, + "RemoveServiceEndpoint", + removeServiceEndpoint ); } @@ -1371,7 +1360,7 @@ class DIDModule { * @returns {Array} An array of Uint8 */ getSerializedDidRemoval(didRemoval) { - return getStateChange(this.api, 'DidRemoval', didRemoval); + return getStateChange(this.api, "DidRemoval", didRemoval); } /** @@ -1380,7 +1369,7 @@ class DIDModule { * @returns {Array} An array of Uint8 */ getSerializedAttestation(setAttestation) { - return getStateChange(this.api, 'SetAttestationClaim', setAttestation); + return getStateChange(this.api, "SetAttestationClaim", setAttestation); } } diff --git a/src/modules/did/offchain-did-doc-ref.js b/src/modules/did/offchain-did-doc-ref.js index 60e4b469e..b100f519e 100644 --- a/src/modules/did/offchain-did-doc-ref.js +++ b/src/modules/did/offchain-did-doc-ref.js @@ -1,4 +1,4 @@ -import { bytesToWrappedBytes } from '../../utils/misc'; +export const FORMATS = new Set(["CID", "URL", "Custom"]); /** * An off-chain DID Doc reference stored on chain. The reference may be @@ -7,21 +7,23 @@ import { bytesToWrappedBytes } from '../../utils/misc'; * - any other format */ export default class OffChainDidDocRef { + constructor(type, bytes) { + if (!FORMATS.has(type)) { + throw new Error(`Unsupported type: ${type}`); + } + + this[type] = bytes; + } + static cid(bytes) { - return { - CID: bytesToWrappedBytes(bytes), - }; + return new this("CID", bytes); } static url(bytes) { - return { - URL: bytesToWrappedBytes(bytes), - }; + return new this("URL", bytes); } static custom(bytes) { - return { - Custom: bytesToWrappedBytes(bytes), - }; + return new this("Custom", bytes); } } diff --git a/src/modules/offchain-signatures.js b/src/modules/offchain-signatures.js index a9bae5214..b895d1cca 100644 --- a/src/modules/offchain-signatures.js +++ b/src/modules/offchain-signatures.js @@ -6,7 +6,7 @@ import { getStateChange, } from '../utils/misc'; import WithParamsAndPublicKeys from './WithParamsAndPublicKeys'; -import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; +import { createDidSig, typedHexDID } from '../utils/did'; const STATE_CHANGES = { AddParams: 'AddOffchainSignatureParams', @@ -38,7 +38,9 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { this.signAndSend = signAndSend; } - /// Builds module-specific public key from the provided value. + /** + * Builds module-specific public key from the provided value. + */ static buildPublicKey(publicKey) { return publicKey; } @@ -49,7 +51,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @returns {Promise<{bytes: string}|null>} */ async getLastParamsWritten(did) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did); const counter = await this.api.query[this.moduleName].paramsCounter(hexId); if (counter > 0) { const resp = await this.queryParamsFromChain(hexId, counter); @@ -66,7 +68,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @returns {Promise} */ async getAllParamsByDid(did) { - const hexId = getHexIdentifierFromDID(did); + const hexId = typedHexDID(this.api, did); const params = []; const counter = await this.api.query[this.moduleName].paramsCounter(hexId); @@ -97,7 +99,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { async queryPublicKeyFromChain(hexDid, keyId) { const key = await this.api.query[this.moduleName][this.methods.PublicKeys]( - hexDid, + hexDid.asDid, keyId, ); @@ -113,7 +115,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @param publicKey - public key to add. * @param targetDid - The DID to which key is being added * @param signerDid - The DID that is adding the key by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair + * @param signingKeyRef - Signer's signingKeyRef * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by @@ -124,19 +126,17 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { publicKey, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { const offchainPublicKey = this.constructor.buildPublicKey(publicKey); - const targetHexDid = getHexIdentifierFromDID(targetDid); - const signerHexDid = getHexIdentifierFromDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [addPk, signature] = await this.createSignedAddPublicKey( offchainPublicKey, targetHexDid, signerHexDid, - keyPair, - keyId, + signingKeyRef, { nonce, didModule }, ); return this.module.addPublicKey(addPk, signature); @@ -147,7 +147,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @param removeKeyId - The key index for key to remove. * @param targetDid - The DID from which key is being removed * @param signerDid - The DID that is removing the key by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair + * @param signingKeyRef - Signer's signingKeyRef * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by @@ -158,18 +158,16 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { removeKeyId, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const targetHexDid = getHexIdentifierFromDID(targetDid); - const signerHexDid = getHexIdentifierFromDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [removePk, signature] = await this.createSignedRemovePublicKey( removeKeyId, targetHexDid, signerHexDid, - keyPair, - keyId, + signingKeyRef, { nonce, didModule }, ); return this.module.removePublicKey(removePk, signature); @@ -180,7 +178,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @param publicKey - public key to add. * @param targetDid - The DID to which key is being added * @param signerDid - The DID that is adding the key by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair + * @param signingKeyRef - Signer's signingKeyRef * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by @@ -193,8 +191,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { publicKey, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}, @@ -203,8 +200,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { publicKey, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, { nonce, didModule }, ); return this.signAndSend(tx, waitForFinalization, params); @@ -215,8 +211,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @param removeKeyId - The key index for key to remove. * @param targetDid - The DID from which key is being removed * @param signerDid - The DID that is removing the key by signing the payload because it controls `targetDid` - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's signing key reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -228,8 +223,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { removeKeyId, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}, @@ -238,8 +232,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { removeKeyId, targetDid, signerDid, - keyPair, - keyId, + signingKeyRef, { nonce, didModule }, ); return this.signAndSend(tx, waitForFinalization, params); @@ -249,15 +242,14 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { publicKey, targetHexDid, signerHexDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(signerHexDid, nonce, didModule); const addPk = { key: publicKey, did: targetHexDid, nonce }; - const signature = this.signAddPublicKey(keyPair, addPk); - const didSig = createDidSig(signerHexDid, keyId, signature); + const signature = this.signAddPublicKey(signingKeyRef, addPk); + const didSig = createDidSig(signerHexDid, signingKeyRef, signature); return [addPk, didSig]; } @@ -265,8 +257,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { removeKeyId, targetHexDid, signerHexDid, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { // eslint-disable-next-line no-param-reassign @@ -276,68 +267,68 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { did: targetHexDid, nonce, }; - const signature = this.signRemovePublicKey(keyPair, removeKey); - const didSig = createDidSig(signerHexDid, keyId, signature); + const signature = this.signRemovePublicKey(signingKeyRef, removeKey); + const didSig = createDidSig(signerHexDid, signingKeyRef, signature); return [removeKey, didSig]; } /** * - * @param keyPair + * @param signingKeyRef * @param params * @returns {Signature} */ - signAddParams(keyPair, params) { + signAddParams(signingKeyRef, params) { const serialized = getStateChange( this.api, this.stateChanges.AddParams, params, ); - return getSignatureFromKeyringPair(keyPair, serialized); + return signingKeyRef.sign(serialized); } /** * - * @param keyPair + * @param signingKeyRef * @param pk * @returns {Signature} */ - signAddPublicKey(keyPair, pk) { + signAddPublicKey(signingKeyRef, pk) { const serialized = getStateChange( this.api, this.stateChanges.AddPublicKey, pk, ); - return getSignatureFromKeyringPair(keyPair, serialized); + return signingKeyRef.sign(serialized); } /** * - * @param keyPair + * @param signingKeyRef * @param ref * @returns {Signature} */ - signRemoveParams(keyPair, ref) { + signRemoveParams(signingKeyRef, ref) { const serialized = getStateChange( this.api, this.stateChanges.RemoveParams, ref, ); - return getSignatureFromKeyringPair(keyPair, serialized); + return signingKeyRef.sign(serialized); } /** * - * @param keyPair + * @param signingKeyRef * @param ref * @returns {Signature} */ - signRemovePublicKey(keyPair, ref) { + signRemovePublicKey(signingKeyRef, ref) { const serialized = getStateChange( this.api, this.stateChanges.RemovePublicKey, ref, ); - return getSignatureFromKeyringPair(keyPair, serialized); + return signingKeyRef.sign(serialized); } } diff --git a/src/modules/ps.js b/src/modules/ps.js index 83a0c06ea..f9da5c3e8 100644 --- a/src/modules/ps.js +++ b/src/modules/ps.js @@ -6,12 +6,17 @@ import PSParams from '../offchain-signatures/params/ps'; /** Class to write `Pointcheval-Sanders` parameters and keys on chain */ export default class PSModule extends OffchainSignaturesModule { - /// Builds `Pointcheval-Sanders` params from the provided value. + + /** + * Builds `Pointcheval-Sanders` params from the provided value. + */ static buildParams(params) { return new PSParams(params); } - /// Builds `Pointcheval-Sanders` public key from the provided value. + /** + * Builds `Pointcheval-Sanders` public key from the provided value. + */ static buildPublicKey(publicKey) { return new PSPublicKey(publicKey); } diff --git a/src/modules/revocation.js b/src/modules/revocation.js index c5d627b7c..ffa4a4438 100644 --- a/src/modules/revocation.js +++ b/src/modules/revocation.js @@ -4,7 +4,7 @@ import { getStateChange, } from '../utils/misc'; -import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; // eslint-disable-line +import { createDidSig, typedHexDID } from '../utils/did'; // eslint-disable-line /** Class to create, update and destroy revocations */ class RevocationModule { @@ -179,7 +179,7 @@ class RevocationModule { * @param registryId - The registry id being updated * @param revId - The revocation id that is being revoked * @param did - * @param keyPair + * @param signingKeyRef * @param keyId * @param nonce * @param didModule @@ -189,7 +189,7 @@ class RevocationModule { */ async revokeCredentialWithOneOfPolicy(registryId, revId, did, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { const [revoke, sig, sigNonce] = await this.createSignedRevoke(registryId, [revId], did, signingKeyRef, { nonce, didModule }); - return this.revoke(revoke, [[sig, sigNonce]], waitForFinalization, params); + return this.revoke(revoke, [[sigNonce, sig]], waitForFinalization, params); } /** @@ -197,7 +197,7 @@ class RevocationModule { * @param registryId * @param revId * @param did - * @param keyPair + * @param signingKeyRef * @param keyId * @param nonce * @param didModule @@ -207,16 +207,16 @@ class RevocationModule { */ async unrevokeCredentialWithOneOfPolicy(registryId, revId, did, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { const [revoke, sig, sigNonce] = await this.createSignedUnRevoke(registryId, [revId], did, signingKeyRef, { nonce, didModule }); - return this.unrevoke(revoke, [[sig, sigNonce]], waitForFinalization, params); + return this.unrevoke(revoke, [[sigNonce, sig]], waitForFinalization, params); } async removeRegistryWithOneOfPolicy(registryId, did, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { const [removal, sig, sigNonce] = await this.createSignedRemove(registryId, did, signingKeyRef, { nonce, didModule }); - return this.removeRegistry(removal, [[sig, sigNonce]], waitForFinalization, params); + return this.removeRegistry(removal, [[sigNonce, sig]], waitForFinalization, params); } async createSignedUpdate(updateFunc, registryId, [...revokeIds], did, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const hexDid = getHexIdentifierFromDID(did); + const hexDid = typedHexDID(this.api, did); // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); @@ -227,9 +227,9 @@ class RevocationModule { }, nonce, }; - const serializedRevoke = updateFunc.bind(this)(update); - const signature = getSignatureFromKeyringPair(keyPair, serializedRevoke); - const didSig = createDidSig(hexDid, keyId, signature); + const serializedRevoke = updateFunc.call(this, update); + const signature = signingKeyRef.sign(serializedRevoke); + const didSig = createDidSig(hexDid, signingKeyRef, signature); return [{ registryId, revokeIds }, didSig, nonce]; } @@ -242,7 +242,7 @@ class RevocationModule { } async createSignedRemove(registryId, did, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const hexDid = getHexIdentifierFromDID(did); + const hexDid = typedHexDID(this.api, did); // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); @@ -251,8 +251,8 @@ class RevocationModule { nonce, }; const serializedRemove = this.getSerializedRemoveRegistry(remove); - const signature = getSignatureFromKeyringPair(keyPair, serializedRemove); - const didSig = createDidSig(hexDid, keyId, signature); + const signature = signingKeyRef.sign(serializedRemove); + const didSig = createDidSig(hexDid, signingKeyRef, signature); return [{ registryId }, didSig, nonce]; } diff --git a/src/modules/schema.js b/src/modules/schema.js index a1fc56cf9..8af7dd8b6 100644 --- a/src/modules/schema.js +++ b/src/modules/schema.js @@ -56,7 +56,7 @@ export default class Schema { */ sign(pair, blobModule) { const serializedBlob = blobModule.getSerializedBlob(this.toBlob()); - this.signature = getSignatureFromKeyringPair(pair, serializedBlob); + this.signature = pair.sign(serializedBlob); return this; } diff --git a/src/modules/status-list-credential.js b/src/modules/status-list-credential.js index 34d373822..07927cc11 100644 --- a/src/modules/status-list-credential.js +++ b/src/modules/status-list-credential.js @@ -5,7 +5,7 @@ import { getStateChange, } from '../utils/misc'; -import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; +import { createDidSig, typedHexDID } from '../utils/did'; /** * Module supporting `StatusList2021Credential` and `RevocationList2020Credential`. @@ -114,8 +114,7 @@ export default class StatusListCredentialModule { * @param id - Unique identifier of the status list credential. * @param statusListCredential - Status list credential. * @param did - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's signing key reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -127,8 +126,7 @@ export default class StatusListCredentialModule { id, statusListCredential, did, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}, @@ -137,13 +135,12 @@ export default class StatusListCredentialModule { id, statusListCredential, did, - keyPair, - keyId, + signingKeyRef, { nonce, didModule }, ); return this.updateStatusListCredential( payload, - [[sig, sigNonce]], + [[sigNonce, sig]], waitForFinalization, params, ); @@ -153,8 +150,7 @@ export default class StatusListCredentialModule { * Remove a single `StatusListCredential`. Works only with credentials having `OneOf` policy * @param id - Unique identifier of the status list credential. * @param did - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's signing key reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -165,8 +161,7 @@ export default class StatusListCredentialModule { async removeStatusListCredentialWithOneOfPolicy( id, did, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}, @@ -174,13 +169,12 @@ export default class StatusListCredentialModule { const [payload, sig, sigNonce] = await this.createSignedRemoveStatusListCredential( id, did, - keyPair, - keyId, + signingKeyRef, { nonce, didModule }, ); return this.removeStatusListCredential( payload, - [[sig, sigNonce]], + [[sigNonce, sig]], waitForFinalization, params, ); @@ -239,8 +233,7 @@ export default class StatusListCredentialModule { * @param createSerializedTx - Function to create a serialized transaction using supplied payload. * @param data - Payload data. * @param did - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's signing key reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * @param params - parameters to be used @@ -249,11 +242,10 @@ export default class StatusListCredentialModule { createSerializedTx, data, did, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const hexDid = getHexIdentifierFromDID(did); + const hexDid = typedHexDID(this.api, did); // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); @@ -262,8 +254,8 @@ export default class StatusListCredentialModule { nonce, }; const serializedTx = createSerializedTx.call(this, update); - const signature = getSignatureFromKeyringPair(keyPair, serializedTx); - const didSig = createDidSig(hexDid, keyId, signature); + const signature = signingKeyRef.sign(serializedTx); + const didSig = createDidSig(hexDid, signingKeyRef, signature); return [data, didSig, nonce]; } @@ -273,8 +265,7 @@ export default class StatusListCredentialModule { * @param id - Unique identifier of the status list credential. * @param statusListCredential - Status list credential. * @param did - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's signing key ref key reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * @param params - parameters to be used @@ -283,16 +274,14 @@ export default class StatusListCredentialModule { id, statusListCredential, did, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { return this.createDidSignature( this.getSerializedUpdateStatusListCredential, { id, credential: statusListCredential.toSubstrate() }, did, - keyPair, - keyId, + signingKeyRef, { nonce, didModule }, ); } @@ -302,24 +291,21 @@ export default class StatusListCredentialModule { * * @param id - Unique identifier of the status list credential. * @param did - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification + * @param signingKeyRef - Signer's signing key reference * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by */ async createSignedRemoveStatusListCredential( id, did, - keyPair, - keyId, + signingKeyRef, { nonce = undefined, didModule = undefined }, ) { return this.createDidSignature( this.getSerializedRemoveStatusListCredential, { id }, did, - keyPair, - keyId, + signingKeyRef, { nonce, didModule }, ); } diff --git a/src/modules/trust-registry.js b/src/modules/trust-registry.js index 63873f058..61216c37f 100644 --- a/src/modules/trust-registry.js +++ b/src/modules/trust-registry.js @@ -1,11 +1,5 @@ -import StatusList2021Credential from '../status-list-credential/status-list2021-credential'; -import { - getDidNonce, - getSignatureFromKeyringPair, - getStateChange, -} from '../utils/misc'; - -import { createDidSig, getHexIdentifierFromDID } from '../utils/did'; +import { typedHexDID } from "../utils/did"; +import { getDidNonce } from '../utils/misc'; /** * `Trust Registry` module. @@ -24,321 +18,107 @@ export default class TrustRegistryModule { } /** - * Fetches `StatusList2021Credential` with the supplied identifier. - * @param {*} statusListCredentialId - * @returns {Promise} - */ - async initTrustRegistry(statusListCredentialId) { - let statusListCredential = await this.api.query.trustRegistry.initTrustRegistry( - statusListCredentialId, - ); - - if (statusListCredential.isSome) { - statusListCredential = statusListCredential.unwrap().statusListCredential; - - if (statusListCredential.isStatusList2021Credential) { - return StatusList2021Credential.fromBytes( - statusListCredential.asStatusList2021Credential, - ); - } else { - throw new Error( - "Fetched credential isn't of `StatusList2021Credential` type", - ); - } - } - - return null; - } - - /** - * Create a transaction to create a new status list credential on-chain. - * @param id - is the unique id of the status list credential. The function will check whether `id` is already taken or not. - * @param statusListCredential - the credential to be associated with the given `id` - * @param policy - the credential policy - * @return {Promise} - the extrinsic to sign and send. - */ - buildCreateStatusListCredentialTx(id, statusListCredential, policy) { - const credentialWithPolicy = { - statusListCredential: statusListCredential.toSubstrate(), - policy: policy.toJSON(), - }; - - return this.module.create(id, credentialWithPolicy); - } - - /** - * Create a transaction to update an existing status list credential on-chain. - * @param statusListCredentialUpdate - Update for the status list credential. - * @param didSigs - `DID` signatures over an action with a nonce authorizing this action according to the existing policy. - * @return {Promise} - the extrinsic to sign and send. - */ - buildUpdateStatusListCredentialTx(statusListCredentialUpdate, didSigs) { - return this.module.update(statusListCredentialUpdate, didSigs); - } - - /** - * Create a transaction to remove an existing status list credential from the chain. - * @param statusListCredentialId - is the unique id of the status list credential. The function will check whether `id` is already taken or not. - * @param didSigs - `DID` signatures over an action with a nonce authorizing this action according to the existing policy. - * @return {Promise} - the extrinsic to sign and send. + * Initializes Trust Registry with the supplied parameters. + * @param {*} convenerDid + * @param {*} registryId + * @param {*} name + * @param {*} signingKeyRef + * @param {*} params + * @param {bool} waitForFinalization + * @param {*} params + * @returns {Promise} */ - buildRemoveStatusListCredentialTx(statusListCredentialId, didSigs) { - return this.module.remove(statusListCredentialId, didSigs); - } - - /** - * Create a new status list credential on-chain. - * @param id - is the unique id of the status list credential. The function will check whether `id` is already taken or not. - * @param statusListCredential - The status list credential to be associated with the given `id`. - * @param policy - The credential policy. - * @param waitForFinalization - * @param params - * @return {Promise<*>} - Sent transaction. - */ - createStatusListCredential( - id, - statusListCredential, - policy, + async init( + convenerDid, + registryId, + name, + signingKeyRef, + { nonce = undefined, didModule = undefined } = {}, waitForFinalization = true, - params = {}, + params = {} ) { + const convenerHexDid = typedHexDID(this.api, convenerDid); + nonce ??= await getDidNonce(convenerHexDid, nonce, didModule); + return this.signAndSend( - this.buildCreateStatusListCredentialTx(id, statusListCredential, policy), + convenerHexDid.changeState( + this.module.initTrustRegistry.bind(this.module), + 'InitTrustRegistry', + { registryId, name, nonce }, + signingKeyRef, + ), waitForFinalization, - params, + params ); } /** - * Update a single `StatusListCredential`. Works only with credentials having `OneOf` policy - * @param id - Unique identifier of the status list credential. - * @param statusListCredential - Status list credential. - * @param did - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification - * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. - * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by - * using this - * @param waitForFinalization - * @param params - * @returns {Promise} + * Appends new schemas to the registry. + * @param {*} convenerDid + * @param {*} registryId + * @param {*} schemas + * @param {*} signingKeyRef + * @param {*} params + * @param {bool} waitForFinalization + * @param {*} params + * @returns {Promise} */ - async updateStatusListCredentialWithOneOfPolicy( - id, - statusListCredential, - did, - keyPair, - keyId, - { nonce = undefined, didModule = undefined }, + async addSchemaMetadata( + convenerDid, + registryId, + schemas, + signingKeyRef, + { nonce = undefined, didModule = undefined } = {}, waitForFinalization = true, - params = {}, + params = {} ) { - const [payload, sig, sigNonce] = await this.createSignedUpdateStatusListCredential( - id, - statusListCredential, - did, - keyPair, - keyId, - { nonce, didModule }, - ); - return this.updateStatusListCredential( - payload, - [[sig, sigNonce]], - waitForFinalization, - params, - ); - } + const convenerHexDid = typedHexDID(this.api, convenerDid); + nonce ??= await getDidNonce(convenerHexDid, nonce, didModule); - /** - * Remove a single `StatusListCredential`. Works only with credentials having `OneOf` policy - * @param id - Unique identifier of the status list credential. - * @param did - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification - * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. - * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by - * using this - * @param waitForFinalization - * @param params - * @returns {Promise} - */ - async removeStatusListCredentialWithOneOfPolicy( - id, - did, - keyPair, - keyId, - { nonce = undefined, didModule = undefined }, - waitForFinalization = true, - params = {}, - ) { - const [payload, sig, sigNonce] = await this.createSignedRemoveStatusListCredential( - id, - did, - keyPair, - keyId, - { nonce, didModule }, - ); - return this.removeStatusListCredential( - payload, - [[sig, sigNonce]], - waitForFinalization, - params, - ); - } - - /** - * Updates status list credential. - * - * @param updateStatusListCredential - * @param didSigs - Array of pairs with each pair of the form `[DidSig, nonce]` where `nonce` is the nonce used while - * signing the payload - * @param waitForFinalization - * @param params - */ - updateStatusListCredential( - updateStatusListCredential, - didSigs, - waitForFinalization = true, - params = {}, - ) { return this.signAndSend( - this.buildUpdateStatusListCredentialTx( - updateStatusListCredential, - didSigs, + convenerHexDid.changeState( + this.module.addSchemaMetadata, + 'AddSchemaMetadata', + { registryId, schemas, nonce }, + signingKeyRef, ), waitForFinalization, - params, + params ); } /** - * Removes status list credential. - * - * @param id - Unique identifier of the status list credential. - * @param didSigs - Array of pairs with each pair of the form `[DidSig, nonce]` where `nonce` is the nonce used while - * signing the payload - * @param waitForFinalization - * @param params + * Updates schemas metadatas in the registry. + * @param {*} convenerDid + * @param {*} registryId + * @param {*} schemas + * @param {*} signingKeyRef + * @param {*} params + * @param {bool} waitForFinalization + * @param {*} params + * @returns {Promise} */ - removeStatusListCredential( - id, - didSigs, + async updateSchemaMetadata( + convenerOrIssuerOrVerifierDid, + registryId, + schemas, + signingKeyRef, + { nonce = undefined, didModule = undefined } = {}, waitForFinalization = true, - params = {}, + params = {} ) { + const convenerOrIssuerOrVerifierHexDid = typedHexDID(this.api, convenerOrIssuerOrVerifierDid); + nonce ??= await getDidNonce(convenerOrIssuerOrVerifierHexDid, nonce, didModule); + return this.signAndSend( - this.buildRemoveStatusListCredentialTx(id, didSigs), + convenerOrIssuerOrVerifierHexDid.changeState( + this.module.updateSchemaMetadata, + 'UpdateSchemaMetadata', + { registryId, schemas, nonce }, + signingKeyRef, + ), waitForFinalization, - params, - ); - } - - /** - * Creates `DID` signature. - * - * @param createSerializedTx - Function to create a serialized transaction using supplied payload. - * @param data - Payload data. - * @param did - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification - * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. - * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by - * @param params - parameters to be used - */ - async createDidSignature( - createSerializedTx, - data, - did, - keyPair, - keyId, - { nonce = undefined, didModule = undefined }, - ) { - const hexDid = getHexIdentifierFromDID(did); - // eslint-disable-next-line no-param-reassign - nonce = await getDidNonce(hexDid, nonce, didModule); - - const update = { - data, - nonce, - }; - const serializedTx = createSerializedTx.call(this, update); - const signature = getSignatureFromKeyringPair(keyPair, serializedTx); - const didSig = createDidSig(hexDid, keyId, signature); - return [data, didSig, nonce]; - } - - /** - * Creates signed transaction to update status list credential. - * - * @param id - Unique identifier of the status list credential. - * @param statusListCredential - Status list credential. - * @param did - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification - * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. - * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by - * @param params - parameters to be used - */ - async createSignedUpdateStatusListCredential( - id, - statusListCredential, - did, - keyPair, - keyId, - { nonce = undefined, didModule = undefined }, - ) { - return this.createDidSignature( - this.getSerializedUpdateStatusListCredential, - { id, credential: statusListCredential.toSubstrate() }, - did, - keyPair, - keyId, - { nonce, didModule }, - ); - } - - /** - * Creates signed transaction to remove status list credential. - * - * @param id - Unique identifier of the status list credential. - * @param did - Signer of the transaction payload - * @param keyPair - Signer's keypair - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification - * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. - * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by - */ - async createSignedRemoveStatusListCredential( - id, - did, - keyPair, - keyId, - { nonce = undefined, didModule = undefined }, - ) { - return this.createDidSignature( - this.getSerializedRemoveStatusListCredential, - { id }, - did, - keyPair, - keyId, - { nonce, didModule }, + params ); } - - /** - * Serializes a `UpdateStatusListCredential` for signing. - * @param {object} update - `UpdateStatusListCredential` as expected by the Substrate node - * @returns {Array} An array of Uint8 - */ - getSerializedUpdateStatusListCredential(update) { - return getStateChange(this.api, 'UpdateStatusListCredential', update); - } - - /** - * Serializes a `RemoveStatusListCredential` for signing. - * @param {object} removal - `RemoveStatusListCredential` as expected by the Substrate node - * @returns {Array} An array of Uint8 - */ - getSerializedRemoveStatusListCredential(removal) { - return getStateChange(this.api, 'RemoveStatusListCredential', removal); - } } diff --git a/src/rpc-defs/core-mods-rpc-defs.js b/src/rpc-defs/core-mods-rpc-defs.js index 91c3188f1..4a7a052da 100644 --- a/src/rpc-defs/core-mods-rpc-defs.js +++ b/src/rpc-defs/core-mods-rpc-defs.js @@ -17,7 +17,7 @@ export default { params: [ { name: 'did', - type: 'Did', + type: 'DidOrDidMethodKey', }, ], type: 'BTreeMap', @@ -47,7 +47,7 @@ export default { params: [ { name: 'did', - type: 'Did', + type: 'DidOrDidMethodKey', }, ], type: 'BTreeMap', @@ -77,7 +77,7 @@ export default { params: [ { name: 'did', - type: 'Did', + type: 'DidOrDidMethodKey', }, ], type: 'BTreeMap', diff --git a/src/status-list-credential/status-list2021-credential.js b/src/status-list-credential/status-list2021-credential.js index 880f99054..e19b2f653 100644 --- a/src/status-list-credential/status-list2021-credential.js +++ b/src/status-list-credential/status-list2021-credential.js @@ -64,6 +64,7 @@ export default class StatusList2021Credential extends VerifiableCredential { * Can be either `revocation` or `suspension`. * @param {number} [params.length=1e4] - length of the underlying `StatusList`. * @param {Iterable} [params.revokeIndices=[]] - iterable producing indices to be revoked or suspended initially + * @returns {Promise} */ static async create( keyDoc, @@ -94,7 +95,7 @@ export default class StatusList2021Credential extends VerifiableCredential { * @param {object} [update={}] * @param {Iterable} update.revokeIndices - indices to be revoked or suspended * @param {Iterable} update.unsuspendIndices - indices to be unsuspended - * @returns {this} + * @returns {Promise} */ async update(keyDoc, { revokeIndices = [], unsuspendIndices = [] }) { const statusList = new StatusList({ diff --git a/src/utils/codec.js b/src/utils/codec.js index e5544e287..6cffa323f 100644 --- a/src/utils/codec.js +++ b/src/utils/codec.js @@ -1,6 +1,6 @@ -import { u8aToHex, isHex } from "@polkadot/util"; +import { u8aToHex } from "@polkadot/util"; import { decodeAddress, encodeAddress } from "@polkadot/util-crypto"; -import { PublicKeyEd25519, PublicKeySecp256k1, PublicKey } from "../public-keys"; +import { DockDIDQualifier } from "../../dist/utils/did.cjs"; /** * Check if the given input is hexadecimal or not. Optionally checks for the byte size of the hex. Case-insensitive on hex chars @@ -25,52 +25,22 @@ export function isHexWithGivenByteSize(value, byteSize = undefined) { return false; } -class Did { - constructor(rawDid) { - if (!isHex(rawDid)) { - throw new Error( - `Expected a hexadecimal DID, received: \`${rawDid}\`` - ); - } - this.Did = rawDid; - } -} - -class DidMethodKey { - constructor(rawDidMethodKey) { - if (!(rawDidMethodKey instanceof PublicKey)) { - throw new Error( - `Expected an instance of the \`PublicKey\`, received: \`${rawDidMethodKey}\`` - ); - } - this.DidMethodKey = rawDidMethodKey; - } -} - -const SECP_256_K1_PUBLIC_KEY_PREFIX = "zQ3"; -const ED_25519_PUBLIC_KEY_PREFIX = "z6Mk"; - /** * Gets the hexadecimal value of the given string. * @return {string} Returns the hexadecimal representation of the ID. */ -export function getHexIdentifier(id, qualifiers, validate, byteSize) { +export function getHexIdentifier(id, qualifiers, byteSize) { for (const qualifier of [].concat(qualifiers)) { if (id.startsWith(qualifier)) { // Fully qualified ID. Remove the qualifier const ss58Did = id.slice(qualifier.length); try { const hex = u8aToHex(decodeAddress(ss58Did)); - if (ss58Did.startsWith(SECP_256_K1_PUBLIC_KEY_PREFIX)) { - return new DidMethodKey(new PublicKeySecp256k1(hex)); - } else if (ss58Did.startsWith(ED_25519_PUBLIC_KEY_PREFIX)) { - return new DidMethodKey(new PublicKeyEd25519(hex)); - } // 2 characters for `0x` and 2*byte size of ID if (hex.length !== 2 + 2 * byteSize) { throw new Error("Unexpected byte size"); } - return new Did(hex); + return hex; } catch (e) { throw new Error(`Invalid SS58 ID ${id}. ${e}`); } @@ -79,11 +49,14 @@ export function getHexIdentifier(id, qualifiers, validate, byteSize) { try { // Check if hex and of correct size and return the hex value if successful. - validate(id); + if (!isHexWithGivenByteSize(id, byteSize)) { + throw new Error(`Expected ${byteSize}-byte sequence`) + }; + return id; - } catch (e) { + } catch (error) { // Cannot parse as hex - throw new Error(`Invalid hexadecimal ID ${id}. ${e}`); + throw new Error(`Invalid hex Did \`${id}\`: ${error}`); } } diff --git a/src/utils/did.js b/src/utils/did.js index 401f35c05..b3899a94a 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -2,16 +2,130 @@ // Import some utils from Polkadot JS // eslint-disable-next-line max-classes-per-file -import { randomAsHex, encodeAddress } from '@polkadot/util-crypto'; -import { isHexWithGivenByteSize, getHexIdentifier } from './codec'; +import { randomAsHex, encodeAddress } from "@polkadot/util-crypto"; +import { isHexWithGivenByteSize, getHexIdentifier } from "./codec"; +import { PublicKeyEd25519, PublicKeySecp256k1 } from "../public-keys"; +import { u8aToHex } from "@polkadot/util"; -import { Signature } from '../signatures'; // eslint-disable-line -import { PublicKey, VerificationRelationship } from '../public-keys'; // eslint-disable-line +import { Signature } from "../signatures"; // eslint-disable-line +import { PublicKey, VerificationRelationship } from "../public-keys"; // eslint-disable-line +import { + getPublicKeyFromKeyringPair, + getSignatureFromKeyringPair, + getStateChange, +} from "../utils/misc"; -export const DockDIDMethod = 'dock'; +export const DockDIDMethod = "dock"; export const DockDIDQualifier = `did:${DockDIDMethod}:`; +export const DockDIDMethodKeyQualifier = `did:key:${DockDIDMethod}:`; export const DockDIDByteSize = 32; +export class DidKeypair { + constructor(keyPair, keyId) { + this.keyPair = keyPair; + this.keyId = keyId; + } + + publicKey() { + return getPublicKeyFromKeyringPair(this.keyPair); + } + + sign(message) { + return getSignatureFromKeyringPair(this.keyPair, message); + } +} + +const SECP256K1_PUBLIC_KEY_PREFIX = "zQ3"; +const ED_25519_PUBLIC_KEY_PREFIX = "z6Mk"; + +const DockDidMethodKeySecp256k1Prefix = `${DockDIDQualifier}${SECP256K1_PUBLIC_KEY_PREFIX}`; +const DockDidMethodKeyEd25519Prefix = `${DockDIDMethodKeyQualifier}${ED_25519_PUBLIC_KEY_PREFIX}`; + +export class DockDidOrDidMethodKey { + constructor(api) { + Object.defineProperty(this, 'api', { value: api }); + } + + get asDid() { + throw new Error("Not a `Did`"); + } + + get asDidMethodKey() { + throw new Error("Not a `DidMethodKey`"); + } + + get isDid() { + return false; + } + + get isDidMethodKey() { + return false; + } + + signStateChange(name, payload, keyRef) { + const stateChange = getStateChange(this.api, name, payload); + const keySignature = keyRef.sign(stateChange); + + return createDidSig(this, keyRef, keySignature); + } + + changeState(method, name, payload, keyRef) { + const signature = this.signStateChange( + name, + payload, + keyRef + ); + + return method(payload, signature); + } +} + +export class DockDid extends DockDidOrDidMethodKey { + constructor(did, api) { + super(api); + this.did = did; + } + + get isDid() { + return true; + } + + get asDid() { + return this.did; + } + + toJSON() { + return { Did: this.did }; + } + + toString() { + return `${DockDIDQualifier}${this.asDid}`; + } +} + +export class DockDidMethodKey extends DockDidOrDidMethodKey { + constructor(didMethodKey, api) { + super(api); + this.didMethodKey = didMethodKey; + } + + get isDidMethodKey() { + return true; + } + + get asDidMethodKey() { + return this.didMethodKey; + } + + toJSON() { + return { DidMethodKey: this.didMethodKey }; + } + + toString() { + return `${DockDIDMethodKeyQualifier}${this.asDidMethodKey}`; + } +} + /** * Error thrown when a DID document lookup was successful, but the DID in question does not exist. * This is different from a network error. @@ -19,9 +133,10 @@ export const DockDIDByteSize = 32; export class NoDIDError extends Error { constructor(did) { super(`DID (${did}) does not exist`); - this.name = 'NoDIDError'; + this.name = "NoDIDError"; this.did = did; - this.message = 'A DID document lookup was successful, but the DID in question does not exist. This is different from a network error.'; + this.message = + "A DID document lookup was successful, but the DID in question does not exist. This is different from a network error."; } } @@ -31,9 +146,10 @@ export class NoDIDError extends Error { export class NoOnchainDIDError extends Error { constructor(did) { super(`DID (${did}) is an off-chain DID`); - this.name = 'NoOnchainDIDError'; + this.name = "NoOnchainDIDError"; this.did = did; - this.message = 'The DID exists on chain but is an off-chain DID, meaning the DID document exists off-chain.'; + this.message = + "The DID exists on chain but is an off-chain DID, meaning the DID document exists off-chain."; } } @@ -43,9 +159,10 @@ export class NoOnchainDIDError extends Error { export class NoOffchainDIDError extends Error { constructor(did) { super(`DID (${did}) is an on-chain DID`); - this.name = 'NoOffchainDIDError'; + this.name = "NoOffchainDIDError"; this.did = did; - this.message = 'The DID exists on chain and is an on-chain DID but the lookup was performed for an off-chain DID.'; + this.message = + "The DID exists on chain and is an on-chain DID but the lookup was performed for an off-chain DID."; } } @@ -71,7 +188,7 @@ export function validateDockDIDSS58Identifier(identifier) { const regex = new RegExp(/^[5KL][1-9A-HJ-NP-Za-km-z]{47}$/); const matches = regex.exec(identifier); if (!matches) { - throw new Error('The identifier must be 32 bytes and valid SS58 string'); + throw new Error("The identifier must be 32 bytes and valid SS58 string"); } } @@ -81,8 +198,36 @@ export function validateDockDIDSS58Identifier(identifier) { * a 32 byte hex string * @return {string} Returns the hexadecimal representation of the DID. */ -export function getHexIdentifierFromDID(did) { - return getHexIdentifier(did, DockDIDQualifier, validateDockDIDHexIdentifier, DockDIDByteSize); +export function typedHexDID(api, did) { + const hex = getHexIdentifier( + did, + [DockDIDQualifier, DockDIDMethodKeyQualifier], + DockDIDByteSize + ); + + if (did.startsWith(DockDidMethodKeySecp256k1Prefix)) { + return new DockDidMethodKey(new PublicKeySecp256k1(hex), api); + } else if (did.startsWith(DockDidMethodKeyEd25519Prefix)) { + return new DockDidMethodKey(new PublicKeyEd25519(hex), api); + } else { + validateDockDIDHexIdentifier(hex, 32); + return new DockDid(hex, api); + } +} + +export function typedHexDIDFromSubstrate(did) { + const hex = getHexIdentifier( + u8aToHex(did.isDid ? did.asDid : did.asDidMethodKey), + [], + DockDIDByteSize + ); + throw JSON.stringify({ did }); + + if (did.isDid) { + return new DockDid(hex); + } else { + return new DockDidMethodKey(hex); + } } /** @@ -125,21 +270,27 @@ export function createDidKey(publicKey, verRel) { * @param {Signature} sig * @returns {{sig: *, keyId, did}} */ -export function createDidSig(did, keyId = 1, sig) { - return { - did, keyId, sig: sig.toJSON(), - }; -} +export function createDidSig(did, { keyId }, rawSig) { + const sig = rawSig.toJSON(); -/** - * - * @param {string} did - DID as hex - * @param {number} keyId - - * @param {Signature} sig - * @returns {{sig: *, keyId, did}} - */ -export function createDidMethodKeySig(didKey, sig) { - return { - didKey, sig: sig.toJSON(), - }; + if (did instanceof DockDid) { + return { + DidSignature: { + did: did.asDid, + keyId, + sig, + }, + }; + } else if (did instanceof DockDidMethodKey) { + return { + DidMethodKeySignature: { + didKey: did.asDidMethodKey, + sig, + }, + }; + } else { + throw new Error( + `Incorrect DID passed: \`${did}\`, expected instance of either \`DockDid\` or \`DockDidMethodKey\`` + ); + } } diff --git a/src/utils/misc.js b/src/utils/misc.js index 9f312b099..5f7372686 100644 --- a/src/utils/misc.js +++ b/src/utils/misc.js @@ -1,17 +1,22 @@ -import elliptic from 'elliptic'; -import { blake2AsHex } from '@polkadot/util-crypto'; +import elliptic from "elliptic"; +import { blake2AsHex } from "@polkadot/util-crypto"; -import { isHex } from '@polkadot/util'; -import { sha256 } from 'js-sha256'; +import { sha256 } from "js-sha256"; import { - PublicKey, PublicKeyEd25519, PublicKeySecp256k1, PublicKeySr25519, // eslint-disable-line -} from '../public-keys'; + PublicKey, + PublicKeyEd25519, + PublicKeySecp256k1, + PublicKeySr25519, // eslint-disable-line +} from "../public-keys"; import { - Signature, SignatureEd25519, SignatureSecp256k1, SignatureSr25519, // eslint-disable-line -} from '../signatures'; + Signature, + SignatureEd25519, + SignatureSecp256k1, + SignatureSr25519, // eslint-disable-line +} from "../signatures"; const EC = elliptic.ec; -const secp256k1Curve = new EC('secp256k1'); +const secp256k1Curve = new EC("secp256k1"); /** // TODO: Error handling when `stateChange` is not registered * Helper function to return bytes of a `StateChange` enum. Updates like key change, DID removal, revocation, etc @@ -21,7 +26,7 @@ const secp256k1Curve = new EC('secp256k1'); * @return {array} An array of Uint8 */ export function getBytesForStateChange(api, stateChange) { - return api.createType('StateChange', stateChange).toU8a(); + return api.createType("StateChange", stateChange).toU8a(); } export function getStateChange(api, name, value) { @@ -61,7 +66,11 @@ export function verifyEcdsaSecp256k1Sig(message, signature, publicKey) { * @param {PublicKeySecp256k1} publicKey - Secp256k1 public key for verification * @returns {boolean} True when signature is valid, false otherwise */ -export function verifyEcdsaSecp256k1SigPrehashed(messageHash, signature, publicKey) { +export function verifyEcdsaSecp256k1SigPrehashed( + messageHash, + signature, + publicKey +) { // Remove the leading `0x` const sigHex = signature.value.slice(2); // Break it in 2 chunks of 32 bytes each @@ -70,7 +79,7 @@ export function verifyEcdsaSecp256k1SigPrehashed(messageHash, signature, publicK const pkHex = publicKey.value.slice(2); // Generate public key object. Not extracting the public key for signature as the verifier // should always know what public key is being used. - const pk = secp256k1Curve.keyFromPublic(pkHex, 'hex'); + const pk = secp256k1Curve.keyFromPublic(pkHex, "hex"); return secp256k1Curve.verify(messageHash, sig, pk); } @@ -86,9 +95,9 @@ export function getKeyPairType(pair) { if (pair.ec && pair.priv) { // elliptic library's pair has `ec`, `priv` and `pub`. There is not a cleaner way to detect that - return 'secp256k1'; + return "secp256k1"; } - throw new Error('Cannot detect key pair type'); + throw new Error("Cannot detect key pair type"); } /** @@ -99,9 +108,9 @@ export function getKeyPairType(pair) { export function getPublicKeyFromKeyringPair(pair) { const type = getKeyPairType(pair); let Cls; - if (type === 'ed25519') { + if (type === "ed25519") { Cls = PublicKeyEd25519; - } else if (type === 'sr25519') { + } else if (type === "sr25519") { Cls = PublicKeySr25519; } else { Cls = PublicKeySecp256k1; @@ -118,9 +127,9 @@ export function getPublicKeyFromKeyringPair(pair) { export function getSignatureFromKeyringPair(pair, message) { const type = getKeyPairType(pair); let Cls; - if (type === 'ed25519') { + if (type === "ed25519") { Cls = SignatureEd25519; - } else if (type === 'sr25519') { + } else if (type === "sr25519") { Cls = SignatureSr25519; } else { Cls = SignatureSecp256k1; @@ -149,16 +158,7 @@ export function getUniqueElementsFromArray(a, filterCallback) { * @returns {string} */ export function encodeExtrinsicAsHash(api, tx) { - return blake2AsHex(api.createType('Call', tx).toU8a()); -} - -/** - * Convert bytes to struct `WrappedBytes` expected by chain - * @param bytes - * @returns {{'0'}} - */ -export function bytesToWrappedBytes(bytes) { - return bytes; + return blake2AsHex(api.createType("Call", tx).toU8a()); } /** @@ -169,12 +169,18 @@ export function bytesToWrappedBytes(bytes) { * using this * @returns {Promise} */ -export async function getDidNonce(didOrDidMethodKey, nonce = undefined, didModule = undefined) { +export async function getDidNonce( + didOrDidMethodKey, + nonce = undefined, + didModule = undefined +) { if (nonce === undefined && didModule === undefined) { - throw new Error('Provide either nonce or didModule to fetch nonce but none provided'); + throw new Error( + "Provide either nonce or didModule to fetch nonce but none provided" + ); } if (nonce === undefined) { - return didModule.getNextNonceForDID(didOrDidMethodKey); + return didModule.getNextNonceForDid(didOrDidMethodKey); } return nonce; } diff --git a/src/utils/revocation/one-of-policy.js b/src/utils/revocation/one-of-policy.js index 285d8cc86..ed1dfe689 100644 --- a/src/utils/revocation/one-of-policy.js +++ b/src/utils/revocation/one-of-policy.js @@ -1,4 +1,4 @@ -import { getHexIdentifierFromDID } from '../did'; +import { typedHexDID } from '../did'; import Policy from './policy'; // Revocation policy that allows one of the pre-decided controllers to update the registry. @@ -10,7 +10,7 @@ export default class OneOfPolicy extends Policy { */ constructor(controllers = []) { super(); - this.controllers = new Set([...controllers].map((did) => getHexIdentifierFromDID(did))); + this.controllers = new Set(controllers); } /** @@ -18,7 +18,7 @@ export default class OneOfPolicy extends Policy { * @param {string} ownerDID - Owner's DID */ addOwner(ownerDID) { - this.controllers.add(getHexIdentifierFromDID(ownerDID)); + this.controllers.add(ownerDID); } /** @@ -26,7 +26,7 @@ export default class OneOfPolicy extends Policy { * @param {string} ownerDID - Owner's DID */ controllerIds() { - const controllerIds = [...this.controllers]; + const controllerIds = [...this.controllers].map(controller => typedHexDID(null, controller)); // Sort the controller ids as the node is expecting sorted ids and keeping ids unsorted is giving a signature // verification error. This is a workaround and is needed for now. It maybe fixed later controllerIds.sort(); diff --git a/src/utils/vc/helpers.js b/src/utils/vc/helpers.js index dd6ab9a04..e444d95f2 100644 --- a/src/utils/vc/helpers.js +++ b/src/utils/vc/helpers.js @@ -41,7 +41,7 @@ export function getKeyDoc(did, keypair, type, id) { id: id || `${did}#keys-1`, controller: did, type, - keypair, + keypair: keypair.keyPair || keypair, }; } diff --git a/tests/integration/anoncreds/accumulator.test.js b/tests/integration/anoncreds/accumulator.test.js index 7c83fa10b..0a90a290f 100644 --- a/tests/integration/anoncreds/accumulator.test.js +++ b/tests/integration/anoncreds/accumulator.test.js @@ -1,18 +1,30 @@ -import { randomAsHex } from '@polkadot/util-crypto'; +import { randomAsHex } from "@polkadot/util-crypto"; import { - initializeWasm, Accumulator, PositiveAccumulator, WitnessUpdatePublicInfo, AccumulatorParams, -} from '@docknetwork/crypto-wasm-ts'; -import { InMemoryState } from '@docknetwork/crypto-wasm-ts/lib/accumulator/in-memory-persistence'; -import { hexToU8a, stringToHex, u8aToHex } from '@polkadot/util'; -import { DockAPI } from '../../../src'; -import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../../test-constants'; -import { createNewDockDID, getHexIdentifierFromDID } from '../../../src/utils/did'; - -import AccumulatorModule from '../../../src/modules/accumulator'; -import { getAllEventsFromBlock } from '../../../src/utils/chain-ops'; -import { registerNewDIDUsingPair } from '../helpers'; - -describe('Accumulator Module', () => { + initializeWasm, + Accumulator, + PositiveAccumulator, + WitnessUpdatePublicInfo, + AccumulatorParams, +} from "@docknetwork/crypto-wasm-ts"; +import { InMemoryState } from "@docknetwork/crypto-wasm-ts/lib/accumulator/in-memory-persistence"; +import { hexToU8a, stringToHex, u8aToHex } from "@polkadot/util"; +import { DockAPI } from "../../../src"; +import { + FullNodeEndpoint, + TestAccountURI, + TestKeyringOpts, +} from "../../test-constants"; +import { + DidKeypair, + createNewDockDID, + typedHexDID, +} from "../../../src/utils/did"; + +import AccumulatorModule from "../../../src/modules/accumulator"; +import { getAllEventsFromBlock } from "../../../src/utils/chain-ops"; +import { registerNewDIDUsingPair } from "../helpers"; + +describe("Accumulator Module", () => { const dock = new DockAPI(); let account; let did1; @@ -35,8 +47,8 @@ describe('Accumulator Module', () => { chainModule = dock.accumulatorModule; account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); - pair1 = dock.keyring.addFromUri(seed1); - pair2 = dock.keyring.addFromUri(seed2); + pair1 = new DidKeypair(dock.keyring.addFromUri(seed1), 1); + pair2 = new DidKeypair(dock.keyring.addFromUri(seed2), 1); did1 = createNewDockDID(); did2 = createNewDockDID(); await registerNewDIDUsingPair(dock, did1, pair1); @@ -44,12 +56,22 @@ describe('Accumulator Module', () => { await initializeWasm(); }, 20000); - test('Can create new params', async () => { - let label = stringToHex('accumulator-params-label'); + test("Can create new params", async () => { + let label = stringToHex("accumulator-params-label"); let params = Accumulator.generateParams(hexToU8a(label)); const bytes1 = u8aToHex(params.bytes); - const params1 = chainModuleClass.prepareAddParameters(bytes1, undefined, label); - await chainModule.addParams(params1, did1, pair1, 1, { didModule: dock.did }, false); + const params1 = chainModuleClass.prepareAddParameters( + bytes1, + undefined, + label + ); + await chainModule.addParams( + params1, + did1, + pair1, + { didModule: dock.did }, + false + ); const paramsWritten1 = await chainModule.getLastParamsWritten(did1); expect(paramsWritten1.bytes).toEqual(params1.bytes); expect(paramsWritten1.label).toEqual(params1.label); @@ -57,11 +79,17 @@ describe('Accumulator Module', () => { const queriedParams1 = await chainModule.getParams(did1, 1); expect(paramsWritten1).toEqual(queriedParams1); - label = stringToHex('some label'); + label = stringToHex("some label"); params = Accumulator.generateParams(hexToU8a(label)); const bytes2 = u8aToHex(params.bytes); const params2 = chainModuleClass.prepareAddParameters(bytes2); - await chainModule.addParams(params2, did2, pair2, 1, { didModule: dock.did }, false); + await chainModule.addParams( + params2, + did2, + pair2, + { didModule: dock.did }, + false + ); const paramsWritten2 = await chainModule.getLastParamsWritten(did2); expect(paramsWritten2.bytes).toEqual(params2.bytes); expect(paramsWritten2.label).toBe(null); @@ -69,11 +97,17 @@ describe('Accumulator Module', () => { const queriedParams2 = await chainModule.getParams(did2, 1); expect(paramsWritten2).toEqual(queriedParams2); - label = stringToHex('some label'); + label = stringToHex("some label"); params = Accumulator.generateParams(hexToU8a(label)); const bytes3 = u8aToHex(params.bytes); const params3 = chainModuleClass.prepareAddParameters(bytes3); - await chainModule.addParams(params3, did1, pair1, 1, { didModule: dock.did }, false); + await chainModule.addParams( + params3, + did1, + pair1, + { didModule: dock.did }, + false + ); const paramsWritten3 = await chainModule.getLastParamsWritten(did1); expect(paramsWritten3.bytes).toEqual(params3.bytes); expect(paramsWritten3.label).toBe(null); @@ -89,12 +123,18 @@ describe('Accumulator Module', () => { expect(paramsByDid2[0]).toEqual(paramsWritten2); }, 30000); - test('Can create public keys', async () => { + test("Can create public keys", async () => { const params = Accumulator.generateParams(); let keypair = Accumulator.generateKeypair(params); const bytes1 = u8aToHex(keypair.publicKey.bytes); const pk1 = chainModuleClass.prepareAddPublicKey(bytes1); - await chainModule.addPublicKey(pk1, did1, pair1, 1, { didModule: dock.did }, false); + await chainModule.addPublicKey( + pk1, + did1, + pair1, + { didModule: dock.did }, + false + ); const queriedPk1 = await chainModule.getPublicKey(did1, 1); expect(queriedPk1.bytes).toEqual(pk1.bytes); @@ -104,12 +144,21 @@ describe('Accumulator Module', () => { const aparams1 = new AccumulatorParams(hexToU8a(params1.bytes)); keypair = Accumulator.generateKeypair(aparams1, hexToU8a(seedAccum)); const bytes2 = u8aToHex(keypair.publicKey.bytes); - const pk2 = chainModuleClass.prepareAddPublicKey(bytes2, undefined, [did1, 1]); - await chainModule.addPublicKey(pk2, did2, pair2, 1, { didModule: dock.did }, false); + const pk2 = chainModuleClass.prepareAddPublicKey(bytes2, undefined, [ + did1, + 1, + ]); + await chainModule.addPublicKey( + pk2, + did2, + pair2, + { didModule: dock.did }, + false + ); const queriedPk2 = await chainModule.getPublicKey(did2, 1); expect(queriedPk2.bytes).toEqual(pk2.bytes); - expect(queriedPk2.paramsRef).toEqual([getHexIdentifierFromDID(did1), 1]); + expect(queriedPk2.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); const queriedPk2WithParams = await chainModule.getPublicKey(did2, 1, true); expect(queriedPk2WithParams.params).toEqual(params1); @@ -118,12 +167,21 @@ describe('Accumulator Module', () => { const aparams2 = new AccumulatorParams(hexToU8a(params2.bytes)); keypair = Accumulator.generateKeypair(aparams2); const bytes3 = u8aToHex(keypair.publicKey.bytes); - const pk3 = chainModuleClass.prepareAddPublicKey(bytes3, undefined, [did1, 2]); - await chainModule.addPublicKey(pk3, did2, pair2, 1, { didModule: dock.did }, false); + const pk3 = chainModuleClass.prepareAddPublicKey(bytes3, undefined, [ + did1, + 2, + ]); + await chainModule.addPublicKey( + pk3, + did2, + pair2, + { didModule: dock.did }, + false + ); const queriedPk3 = await chainModule.getPublicKey(did2, 2); expect(queriedPk3.bytes).toEqual(pk3.bytes); - expect(queriedPk3.paramsRef).toEqual([getHexIdentifierFromDID(did1), 2]); + expect(queriedPk3.paramsRef).toEqual([typedHexDID(dock.api, did1), 2]); const queriedPk3WithParams = await chainModule.getPublicKey(did2, 2, true); expect(queriedPk3WithParams.params).toEqual(params2); @@ -137,38 +195,55 @@ describe('Accumulator Module', () => { const pksWithParamsByDid2 = await chainModule.getAllPublicKeysByDid( did2, - true, + true ); expect(pksWithParamsByDid2[0]).toEqual(queriedPk2WithParams); expect(pksWithParamsByDid2[1]).toEqual(queriedPk3WithParams); }, 30000); - test('Can add and remove accumulator', async () => { + test("Can add and remove accumulator", async () => { const id1 = randomAsHex(32); const accumulated1 = randomAsHex(100); - await chainModule.addPositiveAccumulator(id1, accumulated1, [did1, 1], did1, pair1, 1, { didModule: dock.did }, false); + await chainModule.addPositiveAccumulator( + id1, + accumulated1, + [did1, 1], + did1, + pair1, + { didModule: dock.did }, + false + ); const id2 = randomAsHex(32); const accumulated2 = randomAsHex(100); const maxSize = 100000; - await chainModule.addUniversalAccumulator(id2, accumulated2, [did2, 1], maxSize, did2, pair2, 1, { didModule: dock.did }, false); + await chainModule.addUniversalAccumulator( + id2, + accumulated2, + [did2, 1], + maxSize, + did2, + pair2, + { didModule: dock.did }, + false + ); const accum1 = await chainModule.getAccumulator(id1, false); expect(accum1.created > 0).toBe(true); expect(accum1.lastModified > 0).toBe(true); expect(accum1.created).toEqual(accum1.lastModified); - expect(accum1.type).toEqual('positive'); + expect(accum1.type).toEqual("positive"); expect(accum1.accumulated).toEqual(accumulated1); - expect(accum1.keyRef).toEqual([getHexIdentifierFromDID(did1), 1]); + expect(accum1.keyRef).toEqual([typedHexDID(dock.api, did1), 1]); expect(accum1.publicKey).toBeUndefined(); const accum2 = await chainModule.getAccumulator(id2, false); expect(accum2.created > 0).toBe(true); expect(accum2.lastModified > 0).toBe(true); expect(accum2.created).toEqual(accum2.lastModified); - expect(accum2.type).toEqual('universal'); + expect(accum2.type).toEqual("universal"); expect(accum2.accumulated).toEqual(accumulated2); - expect(accum2.keyRef).toEqual([getHexIdentifierFromDID(did2), 1]); + expect(accum2.keyRef).toEqual([typedHexDID(dock.api, did2), 1]); expect(accum2.publicKey).toBeUndefined(); const keyWithParams = await chainModule.getPublicKey(did2, 1, true); @@ -176,37 +251,70 @@ describe('Accumulator Module', () => { expect(accum2WithKeyAndParams.created > 0).toBe(true); expect(accum2WithKeyAndParams.lastModified > 0).toBe(true); expect(accum2WithKeyAndParams.created).toEqual( - accum2WithKeyAndParams.lastModified, + accum2WithKeyAndParams.lastModified ); - expect(accum2WithKeyAndParams.type).toEqual('universal'); + expect(accum2WithKeyAndParams.type).toEqual("universal"); expect(accum2WithKeyAndParams.accumulated).toEqual(accumulated2); - expect(accum2WithKeyAndParams.keyRef).toEqual([getHexIdentifierFromDID(did2), 1]); + expect(accum2WithKeyAndParams.keyRef).toEqual([typedHexDID(dock.api, did2), 1]); expect(accum2WithKeyAndParams.publicKey).toEqual(keyWithParams); - await chainModule.removeAccumulator(id1, did1, pair1, 1, { didModule: dock.did }, false); + await chainModule.removeAccumulator( + id1, + did1, + pair1, + { didModule: dock.did }, + false + ); expect(await chainModule.getAccumulator(id1, false)).toEqual(null); - await chainModule.removeAccumulator(id2, did2, pair2, 1, { didModule: dock.did }, false); + await chainModule.removeAccumulator( + id2, + did2, + pair2, + { didModule: dock.did }, + false + ); expect(await chainModule.getAccumulator(id2, false)).toEqual(null); }, 50000); - test('Update accumulator', async () => { + test("Update accumulator", async () => { const queriedPkWithParams = await chainModule.getPublicKey(did2, 1, true); - const aparams = new AccumulatorParams(hexToU8a(queriedPkWithParams.params.bytes)); + const aparams = new AccumulatorParams( + hexToU8a(queriedPkWithParams.params.bytes) + ); const keypair = Accumulator.generateKeypair(aparams, hexToU8a(seedAccum)); - const accumulator = PositiveAccumulator.initialize(aparams, keypair.secretKey); + const accumulator = PositiveAccumulator.initialize( + aparams, + keypair.secretKey + ); const member1 = Accumulator.encodePositiveNumberAsAccumulatorMember(25); await accumulator.add(member1, keypair.secretKey, accumState); const accumulated1 = u8aToHex(accumulator.accumulated); const id = randomAsHex(32); - await chainModule.addPositiveAccumulator(id, accumulated1, [did2, 1], did2, pair2, 1, { didModule: dock.did }, false); + await chainModule.addPositiveAccumulator( + id, + accumulated1, + [did2, 1], + did2, + pair2, + { didModule: dock.did }, + false + ); const accum1 = await chainModule.getAccumulator(id, false); expect(accum1.accumulated).toEqual(accumulated1); const accumulated2 = u8aToHex(accumulator.accumulated); - await chainModule.updateAccumulator(id, accumulated2, {}, did2, pair2, 1, { didModule: dock.did }, false); + await chainModule.updateAccumulator( + id, + accumulated2, + {}, + did2, + pair2, + { didModule: dock.did }, + false + ); const accum2 = await chainModule.getAccumulator(id, false); expect(accum2.accumulated).toEqual(accumulated2); @@ -221,8 +329,27 @@ describe('Accumulator Module', () => { const accumulated3 = u8aToHex(accumulator.accumulated); const additions1 = [u8aToHex(member2), u8aToHex(member3)]; const removals1 = [u8aToHex(member1)]; - const witUpd1 = u8aToHex(WitnessUpdatePublicInfo.new(hexToU8a(accumulated2), [member2, member3], [member1], keypair.secretKey).value); - await chainModule.updateAccumulator(id, accumulated3, { additions: additions1, removals: removals1, witnessUpdateInfo: witUpd1 }, did2, pair2, 1, { didModule: dock.did }, false); + const witUpd1 = u8aToHex( + WitnessUpdatePublicInfo.new( + hexToU8a(accumulated2), + [member2, member3], + [member1], + keypair.secretKey + ).value + ); + await chainModule.updateAccumulator( + id, + accumulated3, + { + additions: additions1, + removals: removals1, + witnessUpdateInfo: witUpd1, + }, + did2, + pair2, + { didModule: dock.did }, + false + ); const accum3 = await chainModule.getAccumulator(id, false); expect(accum3.accumulated).toEqual(accumulated3); @@ -234,8 +361,23 @@ describe('Accumulator Module', () => { const accumulated4 = u8aToHex(accumulator.accumulated); const additions2 = [u8aToHex(member4), u8aToHex(member5)]; - const witUpd2 = u8aToHex(WitnessUpdatePublicInfo.new(hexToU8a(accumulated3), [member4, member5], [], keypair.secretKey).value); - await chainModule.updateAccumulator(id, accumulated4, { additions: additions2, witnessUpdateInfo: witUpd2 }, did2, pair2, 1, { didModule: dock.did }, false); + const witUpd2 = u8aToHex( + WitnessUpdatePublicInfo.new( + hexToU8a(accumulated3), + [member4, member5], + [], + keypair.secretKey + ).value + ); + await chainModule.updateAccumulator( + id, + accumulated4, + { additions: additions2, witnessUpdateInfo: witUpd2 }, + did2, + pair2, + { didModule: dock.did }, + false + ); const accum4 = await chainModule.getAccumulator(id, false); expect(accum4.accumulated).toEqual(accumulated4); @@ -244,14 +386,29 @@ describe('Accumulator Module', () => { const accumulated5 = u8aToHex(accumulator.accumulated); const removals3 = [u8aToHex(member2), u8aToHex(member4)]; - const witUpd3 = u8aToHex(WitnessUpdatePublicInfo.new(hexToU8a(accumulated4), [], [member2, member4], keypair.secretKey).value); - await chainModule.updateAccumulator(id, accumulated5, { removals: removals3, witnessUpdateInfo: witUpd3 }, did2, pair2, 1, { didModule: dock.did }, false); + const witUpd3 = u8aToHex( + WitnessUpdatePublicInfo.new( + hexToU8a(accumulated4), + [], + [member2, member4], + keypair.secretKey + ).value + ); + await chainModule.updateAccumulator( + id, + accumulated5, + { removals: removals3, witnessUpdateInfo: witUpd3 }, + did2, + pair2, + { didModule: dock.did }, + false + ); const accum5 = await chainModule.getAccumulator(id, false); expect(accum5.accumulated).toEqual(accumulated5); const updates1 = await chainModule.getUpdatesFromBlock( id, - accum2.lastModified, + accum2.lastModified ); expect(updates1[0].newAccumulated).toEqual(accumulated2); expect(updates1[0].additions).toEqual(null); @@ -260,15 +417,15 @@ describe('Accumulator Module', () => { const events1 = ( await getAllEventsFromBlock(chainModule.api, accum2.lastModified, false) - ).filter(({ event }) => event.section === 'accumulator'); + ).filter(({ event }) => event.section === "accumulator"); expect( - chainModuleClass.parseEventAsAccumulatorUpdate(events1[0].event), + chainModuleClass.parseEventAsAccumulatorUpdate(events1[0].event) ).toEqual([id, accumulated2]); const updates2 = await chainModule.getUpdatesFromBlock( id, - accum3.lastModified, + accum3.lastModified ); expect(updates2[0].newAccumulated).toEqual(accumulated3); expect(updates2[0].additions).toEqual(additions1); @@ -277,14 +434,14 @@ describe('Accumulator Module', () => { const events2 = ( await getAllEventsFromBlock(chainModule.api, accum3.lastModified, false) - ).filter(({ event }) => event.section === 'accumulator'); + ).filter(({ event }) => event.section === "accumulator"); expect( - chainModuleClass.parseEventAsAccumulatorUpdate(events2[0].event), + chainModuleClass.parseEventAsAccumulatorUpdate(events2[0].event) ).toEqual([id, accumulated3]); const updates3 = await chainModule.getUpdatesFromBlock( id, - accum4.lastModified, + accum4.lastModified ); expect(updates3[0].newAccumulated).toEqual(accumulated4); expect(updates3[0].additions).toEqual(additions2); @@ -293,7 +450,7 @@ describe('Accumulator Module', () => { const updates4 = await chainModule.getUpdatesFromBlock( id, - accum5.lastModified, + accum5.lastModified ); expect(updates4[0].newAccumulated).toEqual(accumulated5); expect(updates4[0].additions).toEqual(null); @@ -301,21 +458,39 @@ describe('Accumulator Module', () => { expect(updates4[0].witnessUpdateInfo).toEqual(witUpd3); }, 50000); - test('Can remove public keys and params', async () => { - await chainModule.removePublicKey(1, did1, pair1, 1, { didModule: dock.did }, false); + test("Can remove public keys and params", async () => { + await chainModule.removePublicKey( + 1, + did1, + pair1, + { didModule: dock.did }, + false + ); const pk1 = await chainModule.getPublicKey(did1, 1); expect(pk1).toEqual(null); const pksByDid1 = await chainModule.getAllPublicKeysByDid(did1); expect(pksByDid1.length).toEqual(0); - await chainModule.removeParams(1, did1, pair1, 1, { didModule: dock.did }, false); + await chainModule.removeParams( + 1, + did1, + pair1, + { didModule: dock.did }, + false + ); const params1 = await chainModule.getParams(did1, 1); expect(params1).toEqual(null); await expect(chainModule.getPublicKey(did2, 1, true)).rejects.toThrow(); - await chainModule.removePublicKey(1, did2, pair2, 1, { didModule: dock.did }, false); + await chainModule.removePublicKey( + 1, + did2, + pair2, + { didModule: dock.did }, + false + ); const pk2 = await chainModule.getPublicKey(did2, 1); expect(pk2).toEqual(null); @@ -325,15 +500,33 @@ describe('Accumulator Module', () => { const queriedPk2 = await chainModule.getPublicKey(did2, 2); expect(pksByDid2[0]).toEqual(queriedPk2); - await chainModule.removePublicKey(2, did2, pair2, 1, { didModule: dock.did }, false); + await chainModule.removePublicKey( + 2, + did2, + pair2, + { didModule: dock.did }, + false + ); const pk3 = await chainModule.getPublicKey(did2, 2); expect(pk3).toEqual(null); - await chainModule.removeParams(2, did1, pair1, 1, { didModule: dock.did }, false); + await chainModule.removeParams( + 2, + did1, + pair1, + { didModule: dock.did }, + false + ); const params2 = await chainModule.getParams(did1, 2); expect(params2).toEqual(null); - await chainModule.removeParams(1, did2, pair2, 1, { didModule: dock.did }, false); + await chainModule.removeParams( + 1, + did2, + pair2, + { didModule: dock.did }, + false + ); const params3 = await chainModule.getParams(did2, 1); expect(params3).toEqual(null); }, 50000); diff --git a/tests/integration/anoncreds/demo.test.js b/tests/integration/anoncreds/demo.test.js index 811c0120a..3ab9e94be 100644 --- a/tests/integration/anoncreds/demo.test.js +++ b/tests/integration/anoncreds/demo.test.js @@ -1,7 +1,5 @@ -import { randomAsHex } from '@polkadot/util-crypto'; -import { - hexToU8a, stringToHex, stringToU8a, u8aToHex, -} from '@polkadot/util'; +import { randomAsHex } from "@polkadot/util-crypto"; +import { hexToU8a, stringToHex, stringToU8a, u8aToHex } from "@polkadot/util"; import { Accumulator, PositiveAccumulator, @@ -18,20 +16,20 @@ import { AccumulatorParams, AccumulatorPublicKey, initializeWasm, -} from '@docknetwork/crypto-wasm-ts'; -import { InMemoryState } from '@docknetwork/crypto-wasm-ts/lib/accumulator/in-memory-persistence'; -import { DockAPI } from '../../../src'; +} from "@docknetwork/crypto-wasm-ts"; +import { InMemoryState } from "@docknetwork/crypto-wasm-ts/lib/accumulator/in-memory-persistence"; +import { DockAPI } from "../../../src"; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts, Schemes, -} from '../../test-constants'; -import { createNewDockDID } from '../../../src/utils/did'; -import AccumulatorModule from '../../../src/modules/accumulator'; -import { getAllEventsFromBlock } from '../../../src/utils/chain-ops'; -import { getRevealedUnrevealed } from './utils'; -import { registerNewDIDUsingPair } from '../helpers'; +} from "../../test-constants"; +import { createNewDockDID, DidKeypair } from "../../../src/utils/did"; +import AccumulatorModule from "../../../src/modules/accumulator"; +import { getAllEventsFromBlock } from "../../../src/utils/chain-ops"; +import { getRevealedUnrevealed } from "./utils"; +import { registerNewDIDUsingPair } from "../helpers"; for (const { Name, @@ -65,12 +63,12 @@ for (const { // User's attributes which will be signed by the issuer of the credential const attributes = [ - stringToU8a('John'), // First name - stringToU8a('Smith'), // Last name - stringToU8a('M'), // Gender - stringToU8a('New York'), // City - stringToU8a('129086521911'), // SSN - stringToU8a('userid-xyz'), // user/credential id, this is put in the accumulator and used for revocation + stringToU8a("John"), // First name + stringToU8a("Smith"), // Last name + stringToU8a("M"), // Gender + stringToU8a("New York"), // City + stringToU8a("129086521911"), // SSN + stringToU8a("userid-xyz"), // user/credential id, this is put in the accumulator and used for revocation ]; const attributeCount = attributes.length; @@ -96,21 +94,21 @@ for (const { revealedAttrIndices.add(1); const [revealedAttrs, unrevealedAttrs] = getRevealedUnrevealed( encodedAttrs, - revealedAttrIndices, + revealedAttrIndices ); const queriedPk = await getModule(dock).getPublicKey(issuerDid, 2, true); const sigParams = new SignatureParams( - SignatureParams.valueFromBytes(hexToU8a(queriedPk.params.bytes)), + SignatureParams.valueFromBytes(hexToU8a(queriedPk.params.bytes)) ); const sigPk = new PublicKey(hexToU8a(queriedPk.bytes)); const accum = await dock.accumulatorModule.getAccumulator( accumulatorId, - true, + true ); const accumParams = new AccumulatorParams( - hexToU8a(accum.publicKey.params.bytes), + hexToU8a(accum.publicKey.params.bytes) ); const accumPk = new AccumulatorPublicKey(hexToU8a(accum.publicKey.bytes)); const accumulated = hexToU8a(accum.accumulated); @@ -121,7 +119,7 @@ for (const { accumParams, accumPk, provingKey, - accumulated, + accumulated ); const statements = new Statements(); statements.add(statement1); @@ -135,19 +133,19 @@ for (const { const metaStatements = new MetaStatements(); metaStatements.add(ms); - const context = stringToU8a('some context'); + const context = stringToU8a("some context"); const proofSpec = new ProofSpecG1( statements, metaStatements, [], - context, + context ); const witness1 = buildWitness(signature, unrevealedAttrs, false); const witness2 = Witness.accumulatorMembership( encodedAttrs[attributeCount - 1], - membershipWitness, + membershipWitness ); const witnesses = new Witnesses(); witnesses.add(witness1); @@ -165,123 +163,125 @@ for (const { }); account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); - issuerKeypair = dock.keyring.addFromUri(randomAsHex(32)); + issuerKeypair = new DidKeypair( + dock.keyring.addFromUri(randomAsHex(32)), + 1 + ); issuerDid = createNewDockDID(); await registerNewDIDUsingPair(dock, issuerDid, issuerKeypair); - accumulatorManagerKeypair = dock.keyring.addFromUri(randomAsHex(32)); + accumulatorManagerKeypair = new DidKeypair( + dock.keyring.addFromUri(randomAsHex(32)), + 1 + ); accumulatorManagerDid = createNewDockDID(); await registerNewDIDUsingPair( dock, accumulatorManagerDid, - accumulatorManagerKeypair, + accumulatorManagerKeypair ); await initializeWasm(); }, 20000); - test('Create params', async () => { - const label = stringToHex('My params'); + test("Create params", async () => { + const label = stringToHex("My params"); const bytes = u8aToHex( - SignatureParams.generate(attributeCount, hexToU8a(label)).toBytes(), + SignatureParams.generate(attributeCount, hexToU8a(label)).toBytes() ); const params = Module.prepareAddParameters(bytes, undefined, label); await getModule(dock).addParams( params, issuerDid, issuerKeypair, - 1, { didModule: dock.did }, - false, + false ); const paramsWritten = await getModule(dock).getLastParamsWritten( - issuerDid, + issuerDid ); expect(paramsWritten.bytes).toEqual(params.bytes); expect(paramsWritten.label).toEqual(params.label); }, 10000); - test('Create keypair', async () => { + test("Create keypair", async () => { const queriedParams = await getModule(dock).getParams(issuerDid, 1); const paramsVal = SignatureParams.valueFromBytes( - hexToU8a(queriedParams.bytes), + hexToU8a(queriedParams.bytes) ); const params = new SignatureParams( paramsVal, - hexToU8a(queriedParams.label), + hexToU8a(queriedParams.label) ); issuerBbsPlusKeypair = KeyPair.generate(params); const pk = Module.prepareAddPublicKey( u8aToHex(issuerBbsPlusKeypair.publicKey.bytes), undefined, - [issuerDid, 1], + [issuerDid, 1] ); await getModule(dock).addPublicKey( pk, issuerDid, issuerDid, issuerKeypair, - 1, { didModule: dock.did }, - false, + false ); }, 10000); - test('Create Accumulator params', async () => { - const label = stringToHex('My Accumulator params'); + test("Create Accumulator params", async () => { + const label = stringToHex("My Accumulator params"); const bytes = u8aToHex(Accumulator.generateParams(hexToU8a(label)).bytes); const params = AccumulatorModule.prepareAddParameters( bytes, undefined, - label, + label ); await dock.accumulatorModule.addParams( params, accumulatorManagerDid, accumulatorManagerKeypair, - 1, { didModule: dock.did }, - false, + false ); const paramsWritten = await dock.accumulatorModule.getLastParamsWritten( - accumulatorManagerDid, + accumulatorManagerDid ); expect(paramsWritten.bytes).toEqual(params.bytes); expect(paramsWritten.label).toEqual(params.label); }, 10000); - test('Create Accumulator keypair', async () => { + test("Create Accumulator keypair", async () => { const queriedParams = await dock.accumulatorModule.getParams( accumulatorManagerDid, - 1, + 1 ); accumulatorKeypair = Accumulator.generateKeypair( new AccumulatorParams(hexToU8a(queriedParams.bytes)), - hexToU8a(seedAccum), + hexToU8a(seedAccum) ); const pk = AccumulatorModule.prepareAddPublicKey( u8aToHex(accumulatorKeypair.publicKey.bytes), undefined, - [accumulatorManagerDid, 1], + [accumulatorManagerDid, 1] ); await dock.accumulatorModule.addPublicKey( pk, accumulatorManagerDid, accumulatorManagerKeypair, - 1, { didModule: dock.did }, - false, + false ); }, 10000); - test('Create Accumulator', async () => { + test("Create Accumulator", async () => { const queriedParams = await dock.accumulatorModule.getParams( accumulatorManagerDid, - 1, + 1 ); accumulator = PositiveAccumulator.initialize( new AccumulatorParams(hexToU8a(queriedParams.bytes)), - accumulatorKeypair.secretKey, + accumulatorKeypair.secretKey ); accumulatorId = randomAsHex(32); @@ -292,27 +292,26 @@ for (const { [accumulatorManagerDid, 1], accumulatorManagerDid, accumulatorManagerKeypair, - 1, { didModule: dock.did }, - false, + false ); }, 10000); - test('Sign attributes, i.e. issue credential', async () => { + test("Sign attributes, i.e. issue credential", async () => { const encodedAttrs = encodedAttributes(attributes); const queriedPk = await getModule(dock).getPublicKey(issuerDid, 2, true); const paramsVal = SignatureParams.valueFromBytes( - hexToU8a(queriedPk.params.bytes), + hexToU8a(queriedPk.params.bytes) ); const params = new SignatureParams( paramsVal, - hexToU8a(queriedPk.params.label), + hexToU8a(queriedPk.params.label) ); signature = Signature.generate( encodedAttrs, issuerBbsPlusKeypair.secretKey, params, - false, + false ); // User verifies the credential (signature) @@ -320,26 +319,26 @@ for (const { encodedAttrs, new PublicKey(hexToU8a(queriedPk.bytes)), params, - false, + false ); expect(result.verified).toEqual(true); }); - test('Add attribute to accumulator for checking revocation later', async () => { + test("Add attribute to accumulator for checking revocation later", async () => { const encodedAttrs = encodedAttributes(attributes); await accumulator.add( encodedAttrs[attributeCount - 1], accumulatorKeypair.secretKey, - accumulatorState, + accumulatorState ); await expect( - accumulatorState.has(encodedAttrs[attributeCount - 1]), + accumulatorState.has(encodedAttrs[attributeCount - 1]) ).resolves.toEqual(true); membershipWitness = await accumulator.membershipWitness( encodedAttrs[attributeCount - 1], accumulatorKeypair.secretKey, - accumulatorState, + accumulatorState ); const accumulated = u8aToHex(accumulator.accumulated); @@ -349,53 +348,52 @@ for (const { { additions: [u8aToHex(encodedAttrs[attributeCount - 1])] }, accumulatorManagerDid, accumulatorManagerKeypair, - 1, { didModule: dock.did }, - false, + false ); const queriedAccum = await dock.accumulatorModule.getAccumulator( accumulatorId, - true, + true ); expect(queriedAccum.accumulated).toEqual(accumulated); const tempAccumulator = PositiveAccumulator.fromAccumulated( - hexToU8a(queriedAccum.accumulated), + hexToU8a(queriedAccum.accumulated) ); expect( tempAccumulator.verifyMembershipWitness( encodedAttrs[attributeCount - 1], membershipWitness, new AccumulatorPublicKey(hexToU8a(queriedAccum.publicKey.bytes)), - new AccumulatorParams(hexToU8a(queriedAccum.publicKey.params.bytes)), - ), + new AccumulatorParams(hexToU8a(queriedAccum.publicKey.params.bytes)) + ) ).toEqual(true); }, 20000); - test('Prove knowledge of signature, i.e. possession of credential and accumulator membership', async () => { + test("Prove knowledge of signature, i.e. possession of credential and accumulator membership", async () => { await proveAndVerify(); }); - test('Add new members to the accumulator and update witness', async () => { + test("Add new members to the accumulator and update witness", async () => { const encodedAttrs = encodedAttributes(attributes); const member1 = Accumulator.encodePositiveNumberAsAccumulatorMember(100); const member2 = Accumulator.encodePositiveNumberAsAccumulatorMember(105); await accumulator.addBatch( [member1, member2], accumulatorKeypair.secretKey, - accumulatorState, + accumulatorState ); let accum = await dock.accumulatorModule.getAccumulator( accumulatorId, - false, + false ); const witnessUpdInfo = WitnessUpdatePublicInfo.new( hexToU8a(accum.accumulated), [member1, member2], [], - accumulatorKeypair.secretKey, + accumulatorKeypair.secretKey ); await dock.accumulatorModule.updateAccumulator( accumulatorId, @@ -406,19 +404,18 @@ for (const { }, accumulatorManagerDid, accumulatorManagerKeypair, - 1, { didModule: dock.did }, - false, + false ); accum = await dock.accumulatorModule.getAccumulator(accumulatorId, false); const updates = await dock.accumulatorModule.getUpdatesFromBlock( accumulatorId, - accum.lastModified, + accum.lastModified ); expect(updates.length).toEqual(1); const queriedWitnessInfo = new WitnessUpdatePublicInfo( - hexToU8a(updates[0].witnessUpdateInfo), + hexToU8a(updates[0].witnessUpdateInfo) ); const additions = []; const removals = []; @@ -436,31 +433,31 @@ for (const { encodedAttrs[attributeCount - 1], additions, removals, - queriedWitnessInfo, + queriedWitnessInfo ); const queriedAccum = await dock.accumulatorModule.getAccumulator( accumulatorId, - true, + true ); const tempAccumulator = PositiveAccumulator.fromAccumulated( - hexToU8a(queriedAccum.accumulated), + hexToU8a(queriedAccum.accumulated) ); expect( tempAccumulator.verifyMembershipWitness( encodedAttrs[attributeCount - 1], membershipWitness, new AccumulatorPublicKey(hexToU8a(queriedAccum.publicKey.bytes)), - new AccumulatorParams(hexToU8a(queriedAccum.publicKey.params.bytes)), - ), + new AccumulatorParams(hexToU8a(queriedAccum.publicKey.params.bytes)) + ) ).toEqual(true); }); - test('After witness update, prove knowledge of signature, i.e. possession of credential and accumulator membership', async () => { + test("After witness update, prove knowledge of signature, i.e. possession of credential and accumulator membership", async () => { await proveAndVerify(); }); - test('Do several updates to the accumulator and update witness', async () => { + test("Do several updates to the accumulator and update witness", async () => { const encodedAttrs = encodedAttributes(attributes); const member1 = Accumulator.encodePositiveNumberAsAccumulatorMember(100); @@ -475,18 +472,18 @@ for (const { [member3, member4], [member1, member2], accumulatorKeypair.secret_key, - accumulatorState, + accumulatorState ); let accum = await dock.accumulatorModule.getAccumulator( accumulatorId, - false, + false ); let witnessUpdInfo = WitnessUpdatePublicInfo.new( hexToU8a(accum.accumulated), [member3, member4], [member1, member2], - accumulatorKeypair.secretKey, + accumulatorKeypair.secretKey ); await dock.accumulatorModule.updateAccumulator( accumulatorId, @@ -498,9 +495,8 @@ for (const { }, accumulatorManagerDid, accumulatorManagerKeypair, - 1, { didModule: dock.did }, - false, + false ); const member5 = Accumulator.encodePositiveNumberAsAccumulatorMember(200); @@ -510,7 +506,7 @@ for (const { [member5, member6], [member4], accumulatorKeypair.secret_key, - accumulatorState, + accumulatorState ); accum = await dock.accumulatorModule.getAccumulator(accumulatorId, false); @@ -519,7 +515,7 @@ for (const { hexToU8a(accum.accumulated), [member5, member6], [member4], - accumulatorKeypair.secretKey, + accumulatorKeypair.secretKey ); await dock.accumulatorModule.updateAccumulator( accumulatorId, @@ -531,9 +527,8 @@ for (const { }, accumulatorManagerDid, accumulatorManagerKeypair, - 1, { didModule: dock.did }, - false, + false ); const member7 = Accumulator.encodePositiveNumberAsAccumulatorMember(201); @@ -543,7 +538,7 @@ for (const { await accumulator.addBatch( [member7, member8, member9], accumulatorKeypair.secret_key, - accumulatorState, + accumulatorState ); accum = await dock.accumulatorModule.getAccumulator(accumulatorId, false); @@ -551,7 +546,7 @@ for (const { hexToU8a(accum.accumulated), [member7, member8, member9], [], - accumulatorKeypair.secretKey, + accumulatorKeypair.secretKey ); await dock.accumulatorModule.updateAccumulator( accumulatorId, @@ -563,9 +558,8 @@ for (const { }, accumulatorManagerDid, accumulatorManagerKeypair, - 1, { didModule: dock.did }, - false, + false ); accum = await dock.accumulatorModule.getAccumulator(accumulatorId, true); @@ -578,11 +572,11 @@ for (const { const evs = await getAllEventsFromBlock( dock.api, currentBlockNo, - false, + false ); for (const event of evs) { const ret = AccumulatorModule.parseEventAsAccumulatorUpdate( - event.event, + event.event ); if (ret !== null && ret[0] === accumulatorId) { blockNosWithUpdates.push(currentBlockNo); @@ -596,10 +590,10 @@ for (const { // eslint-disable-next-line no-await-in-loop const updates = await dock.accumulatorModule.getUpdatesFromBlock( accumulatorId, - blockNo, + blockNo ); const wi = new WitnessUpdatePublicInfo( - hexToU8a(updates[0].witnessUpdateInfo), + hexToU8a(updates[0].witnessUpdateInfo) ); updateInfo.push(wi); } @@ -612,41 +606,41 @@ for (const { [member7, member8, member9], ], [[member1, member2], [member4], []], - [updateInfo[0], updateInfo[1], updateInfo[2]], + [updateInfo[0], updateInfo[1], updateInfo[2]] ); const tempAccumulator = PositiveAccumulator.fromAccumulated( - hexToU8a(accum.accumulated), + hexToU8a(accum.accumulated) ); expect( tempAccumulator.verifyMembershipWitness( encodedAttrs[attributeCount - 1], membershipWitness, new AccumulatorPublicKey(hexToU8a(accum.publicKey.bytes)), - new AccumulatorParams(hexToU8a(accum.publicKey.params.bytes)), - ), + new AccumulatorParams(hexToU8a(accum.publicKey.params.bytes)) + ) ).toEqual(true); }, 30000); - test('After another witness update, prove knowledge of signature, i.e. possession of credential and accumulator membership', async () => { + test("After another witness update, prove knowledge of signature, i.e. possession of credential and accumulator membership", async () => { await proveAndVerify(); }); - test('Revoke by removing from the accumulator', async () => { + test("Revoke by removing from the accumulator", async () => { const encodedAttrs = encodedAttributes(attributes); await accumulator.remove( encodedAttrs[attributeCount - 1], - accumulatorKeypair.secretKey, + accumulatorKeypair.secretKey ); const accum = await dock.accumulatorModule.getAccumulator( accumulatorId, - false, + false ); const witnessUpdInfo = WitnessUpdatePublicInfo.new( hexToU8a(accum.accumulated), [], [encodedAttrs[attributeCount - 1]], - accumulatorKeypair.secretKey, + accumulatorKeypair.secretKey ); await dock.accumulatorModule.updateAccumulator( accumulatorId, @@ -658,35 +652,36 @@ for (const { }, accumulatorManagerDid, accumulatorManagerKeypair, - 1, { didModule: dock.did }, - false, + false ); }); - test('Witness update should not be possible after removal from accumulator', async () => { + test("Witness update should not be possible after removal from accumulator", async () => { const encodedAttrs = encodedAttributes(attributes); const accum = await dock.accumulatorModule.getAccumulator( accumulatorId, - false, + false ); const updates = await dock.accumulatorModule.getUpdatesFromBlock( accumulatorId, - accum.lastModified, + accum.lastModified ); expect(updates.length).toEqual(1); const queriedWitnessInfo = new WitnessUpdatePublicInfo( - hexToU8a(updates[0].witnessUpdateInfo), + hexToU8a(updates[0].witnessUpdateInfo) ); - expect(() => membershipWitness.updateUsingPublicInfoPostBatchUpdate( - encodedAttrs[attributeCount - 1], - [], - [hexToU8a(updates[0].removals[0])], - queriedWitnessInfo, - )).toThrow(); + expect(() => + membershipWitness.updateUsingPublicInfoPostBatchUpdate( + encodedAttrs[attributeCount - 1], + [], + [hexToU8a(updates[0].removals[0])], + queriedWitnessInfo + ) + ).toThrow(); }); - test('After revocation, i.e. removing from accumulator, prove verification should fail', async () => { + test("After revocation, i.e. removing from accumulator, prove verification should fail", async () => { let failed = false; try { await proveAndVerify(); diff --git a/tests/integration/anoncreds/derived-credentials.test.js b/tests/integration/anoncreds/derived-credentials.test.js index 99a7a1467..55b56a33b 100644 --- a/tests/integration/anoncreds/derived-credentials.test.js +++ b/tests/integration/anoncreds/derived-credentials.test.js @@ -8,7 +8,7 @@ import { TestKeyringOpts, Schemes, } from '../../test-constants'; -import { createNewDockDID } from '../../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../../src/utils/did'; import { registerNewDIDUsingPair } from '../helpers'; import { getKeyDoc } from '../../../src/utils/vc/helpers'; import { @@ -122,7 +122,7 @@ describe.each(Schemes)('Derived Credentials', ({ account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); - pair1 = dock.keyring.addFromUri(randomAsHex(32)); + pair1 = new DidKeypair(dock.keyring.addFromUri(randomAsHex(32)), 1); did1 = createNewDockDID(); await registerNewDIDUsingPair(dock, did1, pair1); @@ -136,7 +136,6 @@ describe.each(Schemes)('Derived Credentials', ({ did1, did1, pair1, - 1, { didModule: dock.did }, false, ); @@ -151,14 +150,14 @@ describe.each(Schemes)('Derived Credentials', ({ await registerNewDIDUsingPair( dock, holder3DID, - dock.keyring.addFromUri(holder3KeySeed, null, 'sr25519'), + new DidKeypair(dock.keyring.addFromUri(holder3KeySeed, null, 'sr25519'), 1), ); }, 30000); async function createAndVerifyPresentation(credentials, verifyOptions = {}) { const holderKey = getKeyDoc( holder3DID, - dock.keyring.addFromUri(holder3KeySeed, null, 'sr25519'), + new DidKeypair(dock.keyring.addFromUri(holder3KeySeed, null, 'sr25519'), 1), 'Sr25519VerificationKey2020', ); diff --git a/tests/integration/anoncreds/issuing.test.js b/tests/integration/anoncreds/issuing.test.js index 5650a7d40..57a74ba9d 100644 --- a/tests/integration/anoncreds/issuing.test.js +++ b/tests/integration/anoncreds/issuing.test.js @@ -2,7 +2,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { u8aToHex } from '@polkadot/util'; import { CredentialBuilder, CredentialSchema, initializeWasm } from '@docknetwork/crypto-wasm-ts'; import { DockAPI } from '../../../src'; -import { createNewDockDID } from '../../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../../src/utils/did'; import { DockResolver } from '../../../src/resolver'; import { registerNewDIDUsingPair, @@ -47,9 +47,9 @@ describe.each(Schemes)('Issuance', ({ address: FullNodeEndpoint, }); chainModule = getModule(dock); - account = dock.keyring.addFromUri(TestAccountURI); + account = new DidKeypair(dock.keyring.addFromUri(TestAccountURI), 1); dock.setAccount(account); - pair1 = dock.keyring.addFromUri(randomAsHex(32)); + pair1 = new DidKeypair(dock.keyring.addFromUri(randomAsHex(32)), 1); did1 = createNewDockDID(); await registerNewDIDUsingPair(dock, did1, pair1); }, 20000); diff --git a/tests/integration/anoncreds/prefilled-positive-accumulator.test.js b/tests/integration/anoncreds/prefilled-positive-accumulator.test.js index 99d2c4b27..db2145a64 100644 --- a/tests/integration/anoncreds/prefilled-positive-accumulator.test.js +++ b/tests/integration/anoncreds/prefilled-positive-accumulator.test.js @@ -11,7 +11,7 @@ import { InMemoryState } from '@docknetwork/crypto-wasm-ts/lib/accumulator/in-me import { DockAPI } from '../../../src'; import AccumulatorModule from '../../../src/modules/accumulator'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../../test-constants'; -import { createNewDockDID } from '../../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../../src/utils/did'; import { registerNewDIDUsingPair } from '../helpers'; describe('Prefilled positive accumulator', () => { @@ -53,7 +53,7 @@ describe('Prefilled positive accumulator', () => { chainModule = dock.accumulatorModule; account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); - pair = dock.keyring.addFromUri(seed1); + pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); did = createNewDockDID(); await registerNewDIDUsingPair(dock, did, pair); await initializeWasm(); @@ -64,12 +64,12 @@ describe('Prefilled positive accumulator', () => { const params = Accumulator.generateParams(hexToU8a(label)); const bytes1 = u8aToHex(params.bytes); const params1 = chainModuleClass.prepareAddParameters(bytes1, undefined, label); - await chainModule.addParams(params1, did, pair, 1, { didModule: dock.didModule }, false); + await chainModule.addParams(params1, did, pair, { didModule: dock.didModule }, false); keypair = Accumulator.generateKeypair(params, seedAccum); const bytes2 = u8aToHex(keypair.publicKey.bytes); const pk1 = chainModuleClass.prepareAddPublicKey(bytes2, undefined, [did, 1]); - await chainModule.addPublicKey(pk1, did, pair, 1, { didModule: dock.didModule }, false); + await chainModule.addPublicKey(pk1, did, pair, { didModule: dock.didModule }, false); accumulator = PositiveAccumulator.initialize(params, keypair.secretKey); @@ -81,7 +81,7 @@ describe('Prefilled positive accumulator', () => { accumulatorId = randomAsHex(32); const accumulated = u8aToHex(accumulator.accumulated); - await dock.accumulatorModule.addPositiveAccumulator(accumulatorId, accumulated, [did, 1], did, pair, 1, { didModule: dock.didModule }, false); + await dock.accumulatorModule.addPositiveAccumulator(accumulatorId, accumulated, [did, 1], did, pair, { didModule: dock.didModule }, false); const queriedAccum = await dock.accumulatorModule.getAccumulator(accumulatorId, true); expect(queriedAccum.accumulated).toEqual(u8aToHex(accumulator.accumulated)); }); @@ -118,7 +118,7 @@ describe('Prefilled positive accumulator', () => { let accum = await dock.accumulatorModule.getAccumulator(accumulatorId, false); const accumulated = u8aToHex(accumulator.accumulated); const witUpdBytes = u8aToHex(witnessUpdInfo.value); - await dock.accumulatorModule.updateAccumulator(accumulatorId, accumulated, { removals: [u8aToHex(member2)], witnessUpdateInfo: witUpdBytes }, did, pair, 1, { didModule: dock.didModule }, false); + await dock.accumulatorModule.updateAccumulator(accumulatorId, accumulated, { removals: [u8aToHex(member2)], witnessUpdateInfo: witUpdBytes }, did, pair, { didModule: dock.didModule }, false); queriedAccum = await dock.accumulatorModule.getAccumulator(accumulatorId, true); expect(queriedAccum.accumulated).toEqual(accumulated); diff --git a/tests/integration/anoncreds/presentation.test.js b/tests/integration/anoncreds/presentation.test.js index 4c2c98e94..90a9976b1 100644 --- a/tests/integration/anoncreds/presentation.test.js +++ b/tests/integration/anoncreds/presentation.test.js @@ -11,7 +11,7 @@ import { TestKeyringOpts, Schemes, } from '../../test-constants'; -import { createNewDockDID } from '../../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../../src/utils/did'; import { registerNewDIDUsingPair } from '../helpers'; import { getKeyDoc } from '../../../src/utils/vc/helpers'; import { issueCredential, verifyPresentation } from '../../../src/utils/vc'; @@ -49,7 +49,7 @@ describe.each(Schemes)('Presentation', ({ account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); - pair1 = dock.keyring.addFromUri(randomAsHex(32)); + pair1 = new DidKeypair(dock.keyring.addFromUri(randomAsHex(32)), 1); did1 = createNewDockDID(); await registerNewDIDUsingPair(dock, did1, pair1); @@ -66,7 +66,6 @@ describe.each(Schemes)('Presentation', ({ did1, did1, pair1, - 1, { didModule: dock.did }, false, ); @@ -103,7 +102,7 @@ describe.each(Schemes)('Presentation', ({ } test(`from ${Name} credentials with external schema reference and embedded schema`, async () => { - const [externalSchemaEncoded, schemaId] = await setupExternalSchema(residentCardSchema, 'Resident Card Example', did1, pair1, 1, dock); + const [externalSchemaEncoded, schemaId] = await setupExternalSchema(residentCardSchema, 'Resident Card Example', did1, pair1, dock); const issuerKey = getKeyDoc(did1, keypair, keypair.type, keypair.id); // This credential has external schema diff --git a/tests/integration/anoncreds/r1cs-circom.test.js b/tests/integration/anoncreds/r1cs-circom.test.js index 41b9de14d..7a54152cf 100644 --- a/tests/integration/anoncreds/r1cs-circom.test.js +++ b/tests/integration/anoncreds/r1cs-circom.test.js @@ -27,7 +27,7 @@ import { TestKeyringOpts, Schemes, } from '../../test-constants'; -import { createNewDockDID } from '../../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../../src/utils/did'; import { getWasmBytes, parseR1CSFile } from './utils'; import { checkMapsEqual, registerNewDIDUsingPair } from '../helpers'; @@ -119,7 +119,7 @@ for (const { account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); - issuerKeypair = dock.keyring.addFromUri(randomAsHex(32)); + issuerKeypair = new DidKeypair(dock.keyring.addFromUri(randomAsHex(32)), 1); issuerDid = createNewDockDID(); await registerNewDIDUsingPair(dock, issuerDid, issuerKeypair); @@ -152,7 +152,6 @@ for (const { issuerDid, issuerDid, issuerKeypair, - 1, { didModule: dock.didModule }, false, ); diff --git a/tests/integration/anoncreds/saver-and-bound-check.test.js b/tests/integration/anoncreds/saver-and-bound-check.test.js index 9ff37d7d5..0a6e42611 100644 --- a/tests/integration/anoncreds/saver-and-bound-check.test.js +++ b/tests/integration/anoncreds/saver-and-bound-check.test.js @@ -27,7 +27,7 @@ import { TestKeyringOpts, Schemes, } from '../../test-constants'; -import { createNewDockDID } from '../../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../../src/utils/did'; import { getRevealedUnrevealed } from './utils'; import { registerNewDIDUsingPair } from '../helpers'; @@ -93,11 +93,11 @@ for (const { account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); - issuerKeypair = dock.keyring.addFromUri(randomAsHex(32)); + issuerKeypair = new DidKeypair(dock.keyring.addFromUri(randomAsHex(32)), 1); issuerDid = createNewDockDID(); await registerNewDIDUsingPair(dock, issuerDid, issuerKeypair); - decryptorKeypair = dock.keyring.addFromUri(randomAsHex(32)); + decryptorKeypair = new DidKeypair(dock.keyring.addFromUri(randomAsHex(32)), 1); decryptorDid = createNewDockDID(); await registerNewDIDUsingPair(dock, decryptorDid, decryptorKeypair); @@ -116,7 +116,6 @@ for (const { params, issuerDid, issuerKeypair, - 1, { didModule: dock.didModule }, false, ); @@ -137,7 +136,6 @@ for (const { issuerDid, issuerDid, issuerKeypair, - 1, { didModule: dock.didModule }, false, ); diff --git a/tests/integration/anoncreds/scheme.test.js b/tests/integration/anoncreds/scheme.test.js index 3e5c4dd32..abc0152a3 100644 --- a/tests/integration/anoncreds/scheme.test.js +++ b/tests/integration/anoncreds/scheme.test.js @@ -10,7 +10,8 @@ import { } from '../../test-constants'; import { createNewDockDID, - getHexIdentifierFromDID, + typedHexDID, + DidKeypair, } from '../../../src/utils/did'; import { registerNewDIDUsingPair } from '../helpers'; @@ -54,8 +55,8 @@ for (const { chainModule = getModule(dock); account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); - pair1 = dock.keyring.addFromUri(seed1); - pair2 = dock.keyring.addFromUri(seed2); + pair1 = new DidKeypair(dock.keyring.addFromUri(seed1), 1); + pair2 = new DidKeypair(dock.keyring.addFromUri(seed2), 1); did1 = createNewDockDID(); did2 = createNewDockDID(); await registerNewDIDUsingPair(dock, did1, pair1); @@ -76,7 +77,6 @@ for (const { params1, did1, pair1, - 1, { didModule: dock.did }, false, ); @@ -86,7 +86,7 @@ for (const { expect(paramsWritten1.label).toEqual(params1.label); const allParams = await getParamsByDid( dock.api, - getHexIdentifierFromDID(did1), + typedHexDID(dock.api, did1), ); expect(Object.values(allParams.toJSON())).toEqual([params1]); @@ -100,7 +100,6 @@ for (const { params2, did2, pair2, - 1, { didModule: dock.did }, false, ); @@ -123,7 +122,6 @@ for (const { params3, did1, pair1, - 1, { didModule: dock.did }, false, ); @@ -152,7 +150,6 @@ for (const { did1, did1, pair1, - 1, { didModule: dock.did }, false, ); @@ -179,15 +176,14 @@ for (const { did2, did2, pair2, - 1, { didModule: dock.did }, false, ); const queriedPk2 = await chainModule.getPublicKey(did2, 2); expect(queriedPk2.bytes).toEqual(pk2.bytes); - expect(queriedPk2.paramsRef).toEqual([getHexIdentifierFromDID(did1), 1]); + expect(queriedPk2.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); const keyWithParams = await getPublicKeyWithParamsByStorageKey(dock.api, [ - getHexIdentifierFromDID(did2), + typedHexDID(dock.api, did2).asDid, 2, ]); const jsonKeyWithParams = keyWithParams.toJSON(); @@ -220,14 +216,13 @@ for (const { did2, did2, pair2, - 1, { didModule: dock.did }, false, ); const queriedPk3 = await chainModule.getPublicKey(did2, 3); expect(queriedPk3.bytes).toEqual(pk3.bytes); - expect(queriedPk3.paramsRef).toEqual([getHexIdentifierFromDID(did1), 2]); + expect(queriedPk3.paramsRef).toEqual([typedHexDID(dock.api, did1), 2]); const queriedPk3WithParams = await chainModule.getPublicKey( did2, @@ -237,7 +232,7 @@ for (const { expect(queriedPk3WithParams.params).toEqual(queriedParams2); const allPks = await getPublicKeysByDid( dock.api, - getHexIdentifierFromDID(did2), + typedHexDID(dock.api, did2), ); expect( Object.values(allPks.toJSON()).map((keyWithParams) => { @@ -279,7 +274,6 @@ for (const { did1, did1, pair1, - 1, { didModule: dock.did }, false, ); @@ -299,7 +293,6 @@ for (const { 1, did1, pair1, - 1, { didModule: dock.did }, false, ); @@ -313,7 +306,6 @@ for (const { did2, did2, pair2, - 1, { didModule: dock.did }, false, ); @@ -337,7 +329,6 @@ for (const { did2, did2, pair2, - 1, { didModule: dock.did }, false, ); @@ -357,7 +348,6 @@ for (const { 2, did1, pair1, - 1, { didModule: dock.did }, false, ); @@ -368,7 +358,6 @@ for (const { 1, did2, pair2, - 1, { didModule: dock.did }, false, ); diff --git a/tests/integration/anoncreds/utils.js b/tests/integration/anoncreds/utils.js index 35e11d367..48a4500ac 100644 --- a/tests/integration/anoncreds/utils.js +++ b/tests/integration/anoncreds/utils.js @@ -50,7 +50,7 @@ export async function parseR1CSFile(r1csName) { * @param dock * @returns {Promise<[{id: string, type: string},{$schema: string, title, type: string, $id: string},string]>} */ -export async function setupExternalSchema(fullSchema, title, did, pair, keyId, dock) { +export async function setupExternalSchema(fullSchema, title, did, pair, dock) { const blobId = randomAsHex(DockBlobIdByteSize); const schemaExternal = { $schema: 'http://json-schema.org/draft-07/schema#', @@ -64,7 +64,7 @@ export async function setupExternalSchema(fullSchema, title, did, pair, keyId, d id: blobId, blob: stringToHex(blobStr), }; - await dock.blob.new(blob, did, pair, keyId, { didModule: dock.didModule }, false); + await dock.blob.new(blob, did, pair, { didModule: dock.didModule }, false); return [{ id: `data:application/json;charset=utf-8,${encodeURIComponent( diff --git a/tests/integration/blob.test.js b/tests/integration/blob.test.js index 4e96e8374..8545bbed8 100644 --- a/tests/integration/blob.test.js +++ b/tests/integration/blob.test.js @@ -3,7 +3,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockAPI } from '../../src/index'; -import { createNewDockDID, getHexIdentifierFromDID } from '../../src/utils/did'; +import { createNewDockDID, typedHexDID } from '../../src/utils/did'; import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI } from '../test-constants'; import { DockBlobIdByteSize, BLOB_MAX_BYTE_SIZE } from '../../src/modules/blob'; import { registerNewDIDUsingPair } from './helpers'; @@ -55,13 +55,13 @@ describe('Blob Module', () => { id: blobId, blob: blobJSON, }; - const result = await dock.blob.new(blob, dockDID, pair, 1, { didModule: dock.didModule }, false); + const result = await dock.blob.new(blob, dockDID, pair, { didModule: dock.didModule }, false); expect(!!result).toBe(true); const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(getHexIdentifierFromDID(dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); expect(chainBlob[1]).toEqual(blobJSON); }, 30000); @@ -71,13 +71,13 @@ describe('Blob Module', () => { id: blobId, blob: blobHex, }; - const result = await dock.blob.new(blob, dockDID, pair, 1, { didModule: dock.didModule }, false); + const result = await dock.blob.new(blob, dockDID, pair, { didModule: dock.didModule }, false); expect(!!result).toBe(true); const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(getHexIdentifierFromDID(dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); expect(u8aToString(chainBlob[1])).toEqual(blobHex); }, 30000); @@ -88,13 +88,13 @@ describe('Blob Module', () => { blob: blobHex, }; - const result = await dock.blob.new(blob, dockDID, pair, 1, { didModule: dock.didModule }, false); + const result = await dock.blob.new(blob, dockDID, pair, { didModule: dock.didModule }, false); expect(!!result).toBe(true); const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(getHexIdentifierFromDID(dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); expect(u8aToHex(chainBlob[1])).toEqual(blobHex); }, 30000); @@ -105,13 +105,13 @@ describe('Blob Module', () => { blob: blobVect, }; - const result = await dock.blob.new(blob, dockDID, pair, 1, { didModule: dock.didModule }, false); + const result = await dock.blob.new(blob, dockDID, pair, { didModule: dock.didModule }, false); expect(!!result).toBe(true); const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(getHexIdentifierFromDID(dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); expect(chainBlob[1]).toEqual(blobVect); }, 30000); @@ -121,7 +121,7 @@ describe('Blob Module', () => { id: blobId, blob: blobHex, }; - await expect(dock.blob.new(blob, dockDID, pair, 1, { didModule: dock.didModule }, false)).rejects.toThrow(); + await expect(dock.blob.new(blob, dockDID, pair, { didModule: dock.didModule }, false)).rejects.toThrow(); await expect( dock.blob.get(blobId), @@ -134,7 +134,7 @@ describe('Blob Module', () => { id: blobId, blob: blobHexFirst, }; - const resultFirst = await dock.blob.new(blob, dockDID, pair, 1, { didModule: dock.didModule }, false); + const resultFirst = await dock.blob.new(blob, dockDID, pair, { didModule: dock.didModule }, false); expect(!!resultFirst).toBe(true); expect(errorInResult(resultFirst)).toBe(false); @@ -144,7 +144,7 @@ describe('Blob Module', () => { blob: randomAsHex(123), }; - await expect(dock.blob.new(blob, dockDID, pair, 1, { didModule: dock.didModule }, false)).rejects.toThrow(); + await expect(dock.blob.new(blob, dockDID, pair, { didModule: dock.didModule }, false)).rejects.toThrow(); }, 60000); test('Should throw error when cannot read blob with given id from chain.', async () => { diff --git a/tests/integration/credential-revocation.test.js b/tests/integration/credential-revocation.test.js index b784fafb9..a219a2ceb 100644 --- a/tests/integration/credential-revocation.test.js +++ b/tests/integration/credential-revocation.test.js @@ -21,7 +21,7 @@ import { registerNewDIDUsingPair, } from './helpers'; import { getKeyDoc } from '../../src/utils/vc/helpers'; -import { createNewDockDID } from '../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../src/utils/did'; import { addRevRegIdToCredential, getPrivateStatus } from '../../src/utils/vc/credentials'; import { getPrivateStatuses } from '../../src/utils/vc/presentations'; @@ -59,11 +59,11 @@ describe('Credential revocation with issuer as the revocation authority', () => dockAPI.setAccount(account); // Register issuer DID - issuerKeyPair = dockAPI.keyring.addFromUri(issuerSeed, null, 'ed25519'); + issuerKeyPair = new DidKeypair(dockAPI.keyring.addFromUri(issuerSeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dockAPI, issuerDID, issuerKeyPair); // Register holder DID - const pair1 = dockAPI.keyring.addFromUri(holderSeed, null, 'ed25519'); + const pair1 = new DidKeypair(dockAPI.keyring.addFromUri(holderSeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dockAPI, holderDID, pair1); // Create a new policy @@ -99,7 +99,7 @@ describe('Credential revocation with issuer as the revocation authority', () => expect(getPrivateStatus(credential)).not.toBeDefined(); // Revoke the credential - await dockAPI.revocation.revokeCredentialWithOneOfPolicy(registryId, revId, issuerDID, issuerKeyPair, 1, { didModule: dockAPI.did }, false); + await dockAPI.revocation.revokeCredentialWithOneOfPolicy(registryId, revId, issuerDID, issuerKeyPair, { didModule: dockAPI.did }, false); // The credential verification should fail as the credential has been revoked. const result1 = await verifyCredential(credential, { @@ -114,7 +114,7 @@ describe('Credential revocation with issuer as the revocation authority', () => test('Holder can create a presentation and verifier can verify it successfully when it is not revoked else the verification fails', async () => { // The previous test revokes credential so unrevoke it. Its fine if the previous test is not run as unrevoking does not // throw error if the credential is not revoked. - await dockAPI.revocation.unrevokeCredentialWithOneOfPolicy(registryId, revId, issuerDID, issuerKeyPair, 1, { didModule: dockAPI.did }, false); + await dockAPI.revocation.unrevokeCredentialWithOneOfPolicy(registryId, revId, issuerDID, issuerKeyPair, { didModule: dockAPI.did }, false); const holderKey = getKeyDoc(holderDID, dockAPI.keyring.addFromUri(holderSeed, null, 'ed25519'), 'Ed25519VerificationKey2018'); @@ -145,7 +145,7 @@ describe('Credential revocation with issuer as the revocation authority', () => expect(getPrivateStatuses(signedPres)[0]).not.toBeDefined(); // Revoke credential - await dockAPI.revocation.revokeCredentialWithOneOfPolicy(registryId, revId, issuerDID, issuerKeyPair, 1, { didModule: dockAPI.did }, false); + await dockAPI.revocation.revokeCredentialWithOneOfPolicy(registryId, revId, issuerDID, issuerKeyPair, { didModule: dockAPI.did }, false); // As the credential is revoked, the presentation should verify successfully. const result1 = await verifyPresentation(signedPres, { diff --git a/tests/integration/custom-nonce.test.js b/tests/integration/custom-nonce.test.js index 8fffb7d81..ae8958733 100644 --- a/tests/integration/custom-nonce.test.js +++ b/tests/integration/custom-nonce.test.js @@ -1,15 +1,15 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { - hexToU8a, stringToHex, u8aToHex, u8aToString, + hexToU8a, stringToHex, u8aToHex, } from '@polkadot/util'; import { Accumulator, initializeWasm, BBSPlusKeypairG2, BBSPlusSignatureParamsG1, } from '@docknetwork/crypto-wasm-ts'; import { DockAPI, PublicKeySecp256k1 } from '../../src'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../test-constants'; -import { createNewDockDID, getHexIdentifierFromDID, NoDIDError } from '../../src/utils/did'; +import { createNewDockDID, typedHexDID, NoDIDError, DidKeypair } from '../../src/utils/did'; import { registerNewDIDUsingPair } from './helpers'; -import { generateEcdsaSecp256k1Keypair, getPublicKeyFromKeyringPair } from '../../src/utils/misc'; +import { generateEcdsaSecp256k1Keypair } from '../../src/utils/misc'; import { DidKey, VerificationRelationship } from '../../src/public-keys'; import { ServiceEndpointType } from '../../src/modules/did/service-endpoint'; import { DockBlobIdByteSize } from '../../src/modules/blob'; @@ -44,7 +44,7 @@ describe('Custom nonce', () => { }); const account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); - const pair = dock.keyring.addFromUri(seed1); + const pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); await registerNewDIDUsingPair(dock, did1, pair); await initializeWasm(); }); @@ -54,9 +54,9 @@ describe('Custom nonce', () => { }, 10000); test('Add key, controller, service endpoint, blob, BBS+ params and keys and accumulator in a batch', async () => { - const nonce = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did1)); + const nonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); - const pair = dock.keyring.addFromUri(seed1); + const pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); const txs = []; // Add key @@ -65,11 +65,11 @@ describe('Custom nonce', () => { const verRels = new VerificationRelationship(); verRels.setAssertion(); const didKey = new DidKey(publicKey, verRels); - const tx1 = await dock.did.createAddKeysTx([didKey], did1, did1, pair, 1, nonce + 1); + const tx1 = await dock.did.createAddKeysTx([didKey], did1, did1, pair, nonce + 1); txs.push(tx1); // Add controller - const tx2 = await dock.did.createAddControllersTx([did2], did1, did1, pair, 1, nonce + 2); + const tx2 = await dock.did.createAddControllersTx([did2], did1, did1, pair, nonce + 2); txs.push(tx2); // Add service endpoint @@ -77,7 +77,7 @@ describe('Custom nonce', () => { spType.setLinkedDomains(); const spId = randomAsHex(10); const origins = [randomAsHex(50), randomAsHex(70)]; - const tx3 = await dock.did.createAddServiceEndpointTx(spId, spType, origins, did1, did1, pair, 1, nonce + 3); + const tx3 = await dock.did.createAddServiceEndpointTx(spId, spType, origins, did1, did1, pair, nonce + 3); txs.push(tx3); // Add a blob @@ -87,42 +87,42 @@ describe('Custom nonce', () => { id: blobId, blob: blobHex, }; - const tx4 = await dock.blob.createNewTx(blob, did1, pair, 1, { nonce: nonce + 4 }); + const tx4 = await dock.blob.createNewTx(blob, did1, pair, { nonce: nonce + 4 }); txs.push(tx4); // Add BBS+ params and keys const label = stringToHex('test-label'); const params = BBSPlusSignatureParamsG1.generate(10, hexToU8a(label)); const addParams = BBSPlusModule.prepareAddParameters(u8aToHex(params.toBytes()), undefined, label); - const tx5 = await dock.bbsPlusModule.createAddParamsTx(addParams, did1, pair, 1, { nonce: nonce + 5 }); + const tx5 = await dock.bbsPlusModule.createAddParamsTx(addParams, did1, pair, { nonce: nonce + 5 }); txs.push(tx5); const keypair = BBSPlusKeypairG2.generate(params); const pk = BBSPlusModule.prepareAddPublicKey(u8aToHex(keypair.publicKey.bytes), undefined, [did1, 1]); - const tx6 = await dock.bbsPlusModule.createAddPublicKeyTx(pk, did1, did1, pair, 1, { nonce: nonce + 6 }); + const tx6 = await dock.bbsPlusModule.createAddPublicKeyTx(pk, did1, did1, pair, { nonce: nonce + 6 }); txs.push(tx6); // Add accumulator params and keys const params1 = Accumulator.generateParams(hexToU8a(label)); const addParams1 = AccumulatorModule.prepareAddParameters(u8aToHex(params1.bytes), undefined, label); - const tx7 = await dock.accumulatorModule.createAddParamsTx(addParams1, did1, pair, 1, { nonce: nonce + 7 }); + const tx7 = await dock.accumulatorModule.createAddParamsTx(addParams1, did1, pair, { nonce: nonce + 7 }); txs.push(tx7); const keypair1 = Accumulator.generateKeypair(params1); const pk1 = AccumulatorModule.prepareAddPublicKey(u8aToHex(keypair1.publicKey.bytes), undefined, [did1, 1]); - const tx8 = await dock.accumulatorModule.createAddPublicKeyTx(pk1, did1, pair, 1, { nonce: nonce + 8 }); + const tx8 = await dock.accumulatorModule.createAddPublicKeyTx(pk1, did1, pair, { nonce: nonce + 8 }); txs.push(tx8); // Add accumulators const id1 = randomAsHex(32); const accumulated1 = randomAsHex(100); - const tx9 = await dock.accumulatorModule.createAddPositiveAccumulatorTx(id1, accumulated1, [did1, 1], did1, pair, 1, { nonce: nonce + 9 }); + const tx9 = await dock.accumulatorModule.createAddPositiveAccumulatorTx(id1, accumulated1, [did1, 1], did1, pair, { nonce: nonce + 9 }); txs.push(tx9); const id2 = randomAsHex(32); const accumulated2 = randomAsHex(100); const maxSize = 100000; - const tx10 = await dock.accumulatorModule.createAddUniversalAccumulatorTx(id2, accumulated2, [did1, 1], maxSize, did1, pair, 1, { nonce: nonce + 10 }); + const tx10 = await dock.accumulatorModule.createAddUniversalAccumulatorTx(id2, accumulated2, [did1, 1], maxSize, did1, pair, { nonce: nonce + 10 }); txs.push(tx10); // Send batch of transactions @@ -148,7 +148,7 @@ describe('Custom nonce', () => { const queriedPk = await dock.bbsPlusModule.getPublicKey(did1, 3); expect(queriedPk.bytes).toEqual(pk.bytes); - expect(queriedPk.paramsRef).toEqual([getHexIdentifierFromDID(did1), 1]); + expect(queriedPk.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); const queriedParams1 = await dock.accumulatorModule.getParams(did1, 1); expect(queriedParams1.bytes).toEqual(addParams1.bytes); @@ -156,17 +156,17 @@ describe('Custom nonce', () => { const queriedPk1 = await dock.accumulatorModule.getPublicKey(did1, 1); expect(queriedPk1.bytes).toEqual(pk1.bytes); - expect(queriedPk1.paramsRef).toEqual([getHexIdentifierFromDID(did1), 1]); + expect(queriedPk1.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); const accum1 = await dock.accumulatorModule.getAccumulator(id1, true); expect(accum1.type).toEqual('positive'); expect(accum1.accumulated).toEqual(accumulated1); - expect(accum1.keyRef).toEqual([getHexIdentifierFromDID(did1), 1]); + expect(accum1.keyRef).toEqual([typedHexDID(dock.api, did1), 1]); const accum2 = await dock.accumulatorModule.getAccumulator(id2, true); expect(accum2.type).toEqual('universal'); expect(accum2.accumulated).toEqual(accumulated2); - expect(accum2.keyRef).toEqual([getHexIdentifierFromDID(did1), 1]); + expect(accum2.keyRef).toEqual([typedHexDID(dock.api, did1), 1]); expect(accum1.created).toEqual(accum2.created); expect(accum1.lastModified).toEqual(accum2.lastModified); }, 20000); @@ -192,15 +192,15 @@ describe('Custom nonce', () => { await dock.revocation.newRegistry(registryId2, policy, false, false); await dock.revocation.newRegistry(registryId3, policy, false, false); - const pair = dock.keyring.addFromUri(seed1); - let currentNonce = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did1)); + const pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); + let currentNonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); let txs = []; // Revoke from all 3 registries in the same transaction batch for (const [regId, revs, nonce] of [[registryId1, revokeIds1, currentNonce + 1], [registryId2, revokeIds2, currentNonce + 2], [registryId3, revokeIds3, currentNonce + 3]]) { - const [revoke, sig, computedNonce] = await dock.revocation.createSignedRevoke(regId, revs, did1, pair, 1, { nonce }); + const [revoke, sig, computedNonce] = await dock.revocation.createSignedRevoke(regId, revs, did1, pair, { nonce }); expect(computedNonce).toEqual(nonce); - const tx = await dock.revocation.createRevokeTx(revoke, [{ sig, nonce }]); + const tx = await dock.revocation.createRevokeTx(revoke, [{ nonce, data: sig }]); txs.push(tx); } @@ -218,12 +218,12 @@ describe('Custom nonce', () => { } // Remove from all 3 registries in the same transaction batch - currentNonce = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did1)); + currentNonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); txs = []; for (const [regId, nonce] of [[registryId1, currentNonce + 1], [registryId2, currentNonce + 2], [registryId3, currentNonce + 3]]) { - const [remove, sig, computedNonce] = await dock.revocation.createSignedRemove(regId, did1, pair, 1, { nonce }); + const [remove, sig, computedNonce] = await dock.revocation.createSignedRemove(regId, did1, pair, { nonce }); expect(computedNonce).toEqual(nonce); - const tx = await dock.revocation.createRemoveRegistryTx(remove, [[sig, nonce]]); + const tx = await dock.revocation.createRemoveRegistryTx(remove, [{ nonce, data: sig }]); txs.push(tx); } @@ -248,26 +248,26 @@ describe('Custom nonce', () => { let vr = new VerificationRelationship(); vr.setAuthentication(); - const pair3 = dock.keyring.addFromUri(seed3); - const pair4 = dock.keyring.addFromUri(seed4); - const pair5 = dock.keyring.addFromUri(seed5); + const pair3 = new DidKeypair(dock.keyring.addFromUri(seed3), 1); + const pair4 = new DidKeypair(dock.keyring.addFromUri(seed4), 1); + const pair5 = new DidKeypair(dock.keyring.addFromUri(seed5), 1); await registerNewDIDUsingPair(dock, did3, pair3, vr, [did1]); await registerNewDIDUsingPair(dock, did4, pair4, vr, [did1]); await registerNewDIDUsingPair(dock, did5, pair5, vr, [did1]); - const pair = dock.keyring.addFromUri(seed1); + const pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); - let nonce = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did1)); + let nonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); let txs = []; // Add a key and a service endpoint to each DID vr = new VerificationRelationship(); vr.setAssertion(); - const tx1 = await dock.did.createAddKeysTx([new DidKey(getPublicKeyFromKeyringPair(pair3), vr)], did3, did1, pair, 1, nonce + 1); + const tx1 = await dock.did.createAddKeysTx([new DidKey(pair3.publicKey(), vr)], did3, did1, pair, nonce + 1); txs.push(tx1); - const tx2 = await dock.did.createAddKeysTx([new DidKey(getPublicKeyFromKeyringPair(pair4), vr)], did4, did1, pair, 1, nonce + 2); + const tx2 = await dock.did.createAddKeysTx([new DidKey(pair4.publicKey(), vr)], did4, did1, pair, nonce + 2); txs.push(tx2); - const tx3 = await dock.did.createAddKeysTx([new DidKey(getPublicKeyFromKeyringPair(pair5), vr)], did5, did1, pair, 1, nonce + 3); + const tx3 = await dock.did.createAddKeysTx([new DidKey(pair5.publicKey(), vr)], did5, did1, pair, nonce + 3); txs.push(tx3); const spType = new ServiceEndpointType(); @@ -276,28 +276,28 @@ describe('Custom nonce', () => { const spId3 = randomAsHex(10); const spId4 = randomAsHex(10); const spId5 = randomAsHex(10); - const tx4 = await dock.did.createAddServiceEndpointTx(spId3, spType, origins[0], did3, did1, pair, 1, nonce + 4); + const tx4 = await dock.did.createAddServiceEndpointTx(spId3, spType, origins[0], did3, did1, pair, nonce + 4); txs.push(tx4); - const tx5 = await dock.did.createAddServiceEndpointTx(spId4, spType, origins[1], did4, did1, pair, 1, nonce + 5); + const tx5 = await dock.did.createAddServiceEndpointTx(spId4, spType, origins[1], did4, did1, pair, nonce + 5); txs.push(tx5); - const tx6 = await dock.did.createAddServiceEndpointTx(spId5, spType, origins[2], did5, did1, pair, 1, nonce + 6); + const tx6 = await dock.did.createAddServiceEndpointTx(spId5, spType, origins[2], did5, did1, pair, nonce + 6); txs.push(tx6); // Send batch of transactions await sendBatch(txs); // Check results of all transactions - await expect(dock.did.getDidKey(did3, 2)).resolves.toEqual(new DidKey(getPublicKeyFromKeyringPair(pair3), vr)); - await expect(dock.did.getDidKey(did4, 2)).resolves.toEqual(new DidKey(getPublicKeyFromKeyringPair(pair4), vr)); - await expect(dock.did.getDidKey(did5, 2)).resolves.toEqual(new DidKey(getPublicKeyFromKeyringPair(pair5), vr)); + await expect(dock.did.getDidKey(did3, 2)).resolves.toEqual(new DidKey(pair3.publicKey(), vr)); + await expect(dock.did.getDidKey(did4, 2)).resolves.toEqual(new DidKey(pair4.publicKey(), vr)); + await expect(dock.did.getDidKey(did5, 2)).resolves.toEqual(new DidKey(pair5.publicKey(), vr)); await expect(dock.did.getServiceEndpoint(did3, spId3)).resolves.toEqual({ type: spType, origins: origins[0] }); await expect(dock.did.getServiceEndpoint(did4, spId4)).resolves.toEqual({ type: spType, origins: origins[1] }); await expect(dock.did.getServiceEndpoint(did5, spId5)).resolves.toEqual({ type: spType, origins: origins[2] }); // Each DID adds 2 blobs - const nonce3 = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did3)); - const nonce4 = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did4)); - const nonce5 = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did5)); + const nonce3 = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did3)); + const nonce4 = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did4)); + const nonce5 = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did5)); txs = []; const [[blobId1, blobHex1, blob1], [blobId2, blobHex2, blob2], [blobId3, blobHex3, blob3], [blobId4, blobHex4, blob4], [blobId5, blobHex5, blob5], [blobId6, blobHex6, blob6]] = [1, 2, 3, 4, 5, 6].map((_) => { @@ -309,18 +309,18 @@ describe('Custom nonce', () => { }; return [bi, bh, b]; }); - const tx7 = await dock.blob.createNewTx(blob1, did3, pair3, 1, { nonce: nonce3 + 1 }); - const tx8 = await dock.blob.createNewTx(blob2, did3, pair3, 1, { nonce: nonce3 + 2 }); + const tx7 = await dock.blob.createNewTx(blob1, did3, pair3, { nonce: nonce3 + 1 }); + const tx8 = await dock.blob.createNewTx(blob2, did3, pair3, { nonce: nonce3 + 2 }); txs.push(tx7); txs.push(tx8); - const tx9 = await dock.blob.createNewTx(blob3, did4, pair4, 1, { nonce: nonce4 + 1 }); - const tx10 = await dock.blob.createNewTx(blob4, did4, pair4, 1, { nonce: nonce4 + 2 }); + const tx9 = await dock.blob.createNewTx(blob3, did4, pair4, { nonce: nonce4 + 1 }); + const tx10 = await dock.blob.createNewTx(blob4, did4, pair4, { nonce: nonce4 + 2 }); txs.push(tx9); txs.push(tx10); - const tx11 = await dock.blob.createNewTx(blob5, did5, pair5, 1, { nonce: nonce5 + 1 }); - const tx12 = await dock.blob.createNewTx(blob6, did5, pair5, 1, { nonce: nonce5 + 2 }); + const tx11 = await dock.blob.createNewTx(blob5, did5, pair5, { nonce: nonce5 + 1 }); + const tx12 = await dock.blob.createNewTx(blob6, did5, pair5, { nonce: nonce5 + 2 }); txs.push(tx11); txs.push(tx12); @@ -332,18 +332,18 @@ describe('Custom nonce', () => { const chainBlob = await dock.blob.get(bi); expect(!!chainBlob).toBe(true); expect(u8aToHex(chainBlob[1])).toEqual(bh); - expect(chainBlob[0]).toEqual(getHexIdentifierFromDID(d)); + expect(chainBlob[0]).toEqual(typedHexDID(dock.api, d)); } // Remove all DIDs in a batch - nonce = await dock.didModule.getDidNonceForDID(getHexIdentifierFromDID(did1)); + nonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); txs = []; - const tx13 = await dock.did.createRemoveTx(did3, did1, pair, 1, nonce + 1); + const tx13 = await dock.did.createRemoveTx(did3, did1, pair, nonce + 1); txs.push(tx13); - const tx14 = await dock.did.createRemoveTx(did4, did1, pair, 1, nonce + 2); + const tx14 = await dock.did.createRemoveTx(did4, did1, pair, nonce + 2); txs.push(tx14); - const tx15 = await dock.did.createRemoveTx(did5, did1, pair, 1, nonce + 3); + const tx15 = await dock.did.createRemoveTx(did5, did1, pair, nonce + 3); txs.push(tx15); // Send batch of transactions diff --git a/tests/integration/did/controllers.test.js b/tests/integration/did/controllers.test.js index b20ed26e0..1451d3342 100644 --- a/tests/integration/did/controllers.test.js +++ b/tests/integration/did/controllers.test.js @@ -1,6 +1,6 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockAPI } from '../../../src'; -import { createNewDockDID, getHexIdentifierFromDID, NoDIDError } from '../../../src/utils/did'; +import { createNewDockDID, typedHexDID, NoDIDError, DidKeypair } from '../../../src/utils/did'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../../test-constants'; import { getPublicKeyFromKeyringPair } from '../../../src/utils/misc'; import { DidKey, VerificationRelationship } from '../../../src/public-keys'; @@ -10,15 +10,15 @@ describe('DID controllers', () => { const dock = new DockAPI(); const dockDid1 = createNewDockDID(); - const hexDid1 = getHexIdentifierFromDID(dockDid1); + const hexDid1 = typedHexDID(dock.api, dockDid1); // This DID will be controlled by itself and dockDid1 const dockDid2 = createNewDockDID(); - const hexDid2 = getHexIdentifierFromDID(dockDid2); + const hexDid2 = typedHexDID(dock.api, dockDid2); // This DID will not control itself but will be controlled by dockDid1 and dockDid2 const dockDid3 = createNewDockDID(); - const hexDid3 = getHexIdentifierFromDID(dockDid3); + const hexDid3 = typedHexDID(dock.api, dockDid3); const seed1 = randomAsHex(32); const seed2 = randomAsHex(32); @@ -51,13 +51,13 @@ describe('DID controllers', () => { const didKey2 = new DidKey(publicKey2, verRels2); await dock.did.new(dockDid2, [didKey2], [dockDid1], false); - const didDetail1 = await dock.did.getOnchainDidDetail(hexDid1); + const didDetail1 = await dock.did.getOnchainDidDetail(hexDid1.asDid); expect(didDetail1.lastKeyId).toBe(1); expect(didDetail1.activeControllerKeys).toBe(1); expect(didDetail1.activeControllers).toBe(1); await expect(dock.did.isController(dockDid1, dockDid1)).resolves.toEqual(true); - const didDetail2 = await dock.did.getOnchainDidDetail(hexDid2); + const didDetail2 = await dock.did.getOnchainDidDetail(hexDid2.asDid); expect(didDetail2.lastKeyId).toBe(1); expect(didDetail2.activeControllerKeys).toBe(1); expect(didDetail2.activeControllers).toBe(2); @@ -71,9 +71,8 @@ describe('DID controllers', () => { verRels.setAssertion(); const didKey = new DidKey(publicKey, verRels); - await dock.did.addKeys([didKey], dockDid2, signer, pair, 1); - - const didDetail = await dock.did.getOnchainDidDetail(hexDid2); + await dock.did.addKeys([didKey], dockDid2, signer, new DidKeypair(pair)); + const didDetail = await dock.did.getOnchainDidDetail(hexDid2.asDid); expect(didDetail.lastKeyId).toBe(keyCount); expect(didDetail.activeControllerKeys).toBe(1); expect(didDetail.activeControllers).toBe(2); @@ -113,7 +112,7 @@ describe('DID controllers', () => { test('Create DID controlled by other', async () => { await dock.did.new(dockDid3, [], [dockDid1], false); - const didDetail1 = await dock.did.getOnchainDidDetail(hexDid3); + const didDetail1 = await dock.did.getOnchainDidDetail(hexDid3.asDid); expect(didDetail1.lastKeyId).toBe(0); expect(didDetail1.activeControllerKeys).toBe(0); expect(didDetail1.activeControllers).toBe(1); @@ -131,7 +130,7 @@ describe('DID controllers', () => { }, 10000); test('Add keys and more controllers to a DID by its other controller', async () => { - const pair1 = dock.keyring.addFromUri(seed1); + const pair1 = new DidKeypair(dock.keyring.addFromUri(seed1), 1); // Add key to the DID using its controller const pair3 = dock.keyring.addFromUri(seed3); @@ -140,9 +139,9 @@ describe('DID controllers', () => { verRels1.setAuthentication(); const didKey3 = new DidKey(publicKey1, verRels1); - await dock.did.addKeys([didKey3], dockDid3, dockDid1, pair1, 1); + await dock.did.addKeys([didKey3], dockDid3, dockDid1, pair1); - let didDetail = await dock.did.getOnchainDidDetail(hexDid3); + let didDetail = await dock.did.getOnchainDidDetail(hexDid3.asDid); expect(didDetail.lastKeyId).toBe(1); expect(didDetail.activeControllerKeys).toBe(0); expect(didDetail.activeControllers).toBe(1); @@ -157,9 +156,9 @@ describe('DID controllers', () => { expect(dk1.verRels.isKeyAgreement()).toEqual(false); // Add another controller to the DID using its existing controller - await dock.did.addControllers([dockDid2], dockDid3, dockDid1, pair1, 1); + await dock.did.addControllers([dockDid2], dockDid3, dockDid1, pair1); - didDetail = await dock.did.getOnchainDidDetail(hexDid3); + didDetail = await dock.did.getOnchainDidDetail(hexDid3.asDid); expect(didDetail.lastKeyId).toBe(1); expect(didDetail.activeControllerKeys).toBe(0); expect(didDetail.activeControllers).toBe(2); @@ -180,10 +179,10 @@ describe('DID controllers', () => { }, 10000); test('Remove existing controllers from a DID by its controller', async () => { - const pair2 = dock.keyring.addFromUri(seed2); - await dock.did.removeControllers([dockDid1], dockDid3, dockDid2, pair2, 1); + const pair2 = new DidKeypair(dock.keyring.addFromUri(seed2), 1); + await dock.did.removeControllers([dockDid1], dockDid3, dockDid2, pair2); - const didDetail = await dock.did.getOnchainDidDetail(hexDid3); + const didDetail = await dock.did.getOnchainDidDetail(hexDid3.asDid); expect(didDetail.lastKeyId).toBe(1); expect(didDetail.activeControllerKeys).toBe(0); expect(didDetail.activeControllers).toBe(1); @@ -193,31 +192,31 @@ describe('DID controllers', () => { }); test('Remove DID using its controller', async () => { - const pair2 = dock.keyring.addFromUri(seed2); - await dock.did.remove(dockDid3, dockDid2, pair2, 1); + const pair2 = new DidKeypair(dock.keyring.addFromUri(seed2), 1); + await dock.did.remove(dockDid3, dockDid2, pair2); await expect(dock.did.getDocument(dockDid3)).rejects.toThrow(NoDIDError); - await expect(dock.did.getOnchainDidDetail(hexDid3)).rejects.toThrow(NoDIDError); + await expect(dock.did.getOnchainDidDetail(hexDid3.asDid)).rejects.toThrow(NoDIDError); await expect(dock.did.getDidKey(dockDid3, 1)).rejects.toThrow(); await expect(dock.did.isController(dockDid3, dockDid2)).resolves.toEqual(false); }); test('Add and remove multiple controllers', async () => { - const pair1 = dock.keyring.addFromUri(seed1); - const pair2 = dock.keyring.addFromUri(seed2); + const pair1 = new DidKeypair(dock.keyring.addFromUri(seed1), 1); + const pair2 = new DidKeypair(dock.keyring.addFromUri(seed2), 1); const dockDid4 = createNewDockDID(); - await dock.did.addControllers([dockDid3, dockDid4], dockDid2, dockDid1, pair1, 1); + await dock.did.addControllers([dockDid3, dockDid4], dockDid2, dockDid1, pair1); - let didDetail = await dock.did.getOnchainDidDetail(hexDid2); + let didDetail = await dock.did.getOnchainDidDetail(hexDid2.asDid); expect(didDetail.activeControllers).toBe(4); await expect(dock.did.isController(dockDid2, dockDid1)).resolves.toEqual(true); await expect(dock.did.isController(dockDid2, dockDid2)).resolves.toEqual(true); await expect(dock.did.isController(dockDid2, dockDid3)).resolves.toEqual(true); await expect(dock.did.isController(dockDid2, dockDid4)).resolves.toEqual(true); - await dock.did.removeControllers([dockDid1, dockDid3, dockDid4], dockDid2, dockDid2, pair2, 1); - didDetail = await dock.did.getOnchainDidDetail(hexDid2); + await dock.did.removeControllers([dockDid1, dockDid3, dockDid4], dockDid2, dockDid2, pair2); + didDetail = await dock.did.getOnchainDidDetail(hexDid2.asDid); expect(didDetail.activeControllers).toBe(1); await expect(dock.did.isController(dockDid2, dockDid1)).resolves.toEqual(false); await expect(dock.did.isController(dockDid2, dockDid2)).resolves.toEqual(true); diff --git a/tests/integration/did/did-basic.test.js b/tests/integration/did/did-basic.test.js index 927d13048..6bdf209af 100644 --- a/tests/integration/did/did-basic.test.js +++ b/tests/integration/did/did-basic.test.js @@ -5,12 +5,12 @@ import { ATTESTS_IRI } from '../../../src/modules/did'; import { createNewDockDID, - getHexIdentifierFromDID, + typedHexDID, NoDIDError, NoOffchainDIDError, + DidKeypair, } from '../../../src/utils/did'; import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI } from '../../test-constants'; -import { getPublicKeyFromKeyringPair } from '../../../src/utils/misc'; import { VerificationRelationship, DidKey, } from '../../../src/public-keys'; @@ -21,7 +21,8 @@ describe('Basic DID tests', () => { // Generate a random DID const dockDid = createNewDockDID(); - const hexDid = getHexIdentifierFromDID(dockDid); + const typedDid = typedHexDID(dock.api, dockDid); + const hexDid = typedDid.asDid; // Generate first key with this seed. The key type is Sr25519 const seed = randomAsHex(32); @@ -48,8 +49,8 @@ describe('Basic DID tests', () => { // DID does not exist already await expect(dock.did.getOnchainDidDetail(hexDid)).rejects.toThrow(NoDIDError); - const pair = dock.keyring.addFromUri(seed); - const publicKey = getPublicKeyFromKeyringPair(pair); + const pair = new DidKeypair(dock.keyring.addFromUri(seed)); + const publicKey = pair.publicKey(); const verRels = new VerificationRelationship(); const didKey = new DidKey(publicKey, verRels); @@ -67,8 +68,8 @@ describe('Basic DID tests', () => { test('Get key for DID', async () => { const dk = await dock.did.getDidKey(dockDid, 1); - const pair = dock.keyring.addFromUri(seed); - expect(dk.publicKey).toEqual(getPublicKeyFromKeyringPair(pair)); + const pair = new DidKeypair(dock.keyring.addFromUri(seed)); + expect(dk.publicKey).toEqual(pair.publicKey()); expect(dk.verRels.isAuthentication()).toEqual(true); expect(dk.verRels.isAssertion()).toEqual(true); expect(dk.verRels.isCapabilityInvocation()).toEqual(true); @@ -102,11 +103,11 @@ describe('Basic DID tests', () => { test('Can attest with a DID', async () => { const priority = 1; const iri = 'my iri'; - const pair = dock.keyring.addFromUri(seed); + const pair = new DidKeypair(dock.keyring.addFromUri(seed), 1); - await dock.did.setClaim(priority, iri, dockDid, pair, 1, undefined, false); + await dock.did.setClaim(priority, iri, dockDid, pair, undefined, false); - const att = await dock.did.getAttests(hexDid); + const att = await dock.did.getAttests(typedDid); expect(att).toEqual(iri); // Get document to verify the claim is there @@ -117,12 +118,12 @@ describe('Basic DID tests', () => { }, 30000); test('Can remove DID', async () => { - const pair = dock.keyring.addFromUri(seed); - await dock.did.remove(dockDid, dockDid, pair, 1, undefined, false); + const pair = new DidKeypair(dock.keyring.addFromUri(seed), 1); + await dock.did.remove(dockDid, dockDid, pair, undefined, false); // DID removed await expect(dock.did.getDocument(dockDid)).rejects.toThrow(NoDIDError); await expect(dock.did.getOnchainDidDetail(hexDid)).rejects.toThrow(NoDIDError); await expect(dock.did.getDidKey(dockDid, 1)).rejects.toThrow(); - await expect(dock.did.isController(hexDid, hexDid)).resolves.toEqual(false); + await expect(dock.did.isController(dockDid, dockDid)).resolves.toEqual(false); }); }); diff --git a/tests/integration/did/keys.test.js b/tests/integration/did/keys.test.js index 8d8ff2777..7882d706d 100644 --- a/tests/integration/did/keys.test.js +++ b/tests/integration/did/keys.test.js @@ -1,6 +1,6 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockAPI, PublicKeySecp256k1 } from '../../../src'; -import { createNewDockDID, getHexIdentifierFromDID } from '../../../src/utils/did'; +import { createNewDockDID, typedHexDID } from '../../../src/utils/did'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../../test-constants'; import { generateEcdsaSecp256k1Keypair, getPublicKeyFromKeyringPair } from '../../../src/utils/misc'; import { DidKey, VerificationRelationship } from '../../../src/public-keys'; @@ -12,7 +12,7 @@ describe('Key support for DIDs', () => { // Generate a random DID const dockDid = createNewDockDID(); - const hexDid = getHexIdentifierFromDID(dockDid); + const hexDid = typedHexDID(dock.api, dockDid); const seed1 = randomAsHex(32); const seed2 = randomAsHex(32); diff --git a/tests/integration/did/offchain-did.test.js b/tests/integration/did/offchain-did.test.js index c5bcd7f17..0b0d60ae5 100644 --- a/tests/integration/did/offchain-did.test.js +++ b/tests/integration/did/offchain-did.test.js @@ -3,7 +3,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { u8aToHex } from '@polkadot/util'; import { DockAPI } from '../../../src'; import { - createNewDockDID, getHexIdentifierFromDID, NoDIDError, NoOnchainDIDError, + createNewDockDID, typedHexDID, NoDIDError, NoOnchainDIDError, } from '../../../src/utils/did'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../../test-constants'; import { OffChainDidDocRef } from '../../../src/modules/did'; @@ -13,7 +13,7 @@ describe('Off-chain DIDs', () => { // Generate a random DID const dockDID = createNewDockDID(); - const hexDID = getHexIdentifierFromDID(dockDID); + const hexDID = typedHexDID(dock.api, dockDID); const firstDocRef = randomAsHex(100); const secondDocRef = randomAsHex(110); diff --git a/tests/integration/did/service-endpoint.test.js b/tests/integration/did/service-endpoint.test.js index 31ce0415e..9fd8cc085 100644 --- a/tests/integration/did/service-endpoint.test.js +++ b/tests/integration/did/service-endpoint.test.js @@ -1,7 +1,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { u8aToHex } from '@polkadot/util'; import { DockAPI } from '../../../src'; -import { createNewDockDID, getHexIdentifierFromDID, NoDIDError } from '../../../src/utils/did'; +import { createNewDockDID, typedHexDID, NoDIDError } from '../../../src/utils/did'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../../test-constants'; import { getPublicKeyFromKeyringPair } from '../../../src/utils/misc'; import { DidKey, VerificationRelationship } from '../../../src/public-keys'; @@ -13,11 +13,11 @@ describe('DID service endpoints', () => { const dock = new DockAPI(); const dockDid1 = createNewDockDID(); - const hexDid1 = getHexIdentifierFromDID(dockDid1); + const hexDid1 = typedHexDID(dock.api, dockDid1); // This DID will not be controlled by itself const dockDid2 = createNewDockDID(); - const hexDid2 = getHexIdentifierFromDID(dockDid2); + const hexDid2 = typedHexDID(dock.api, dockDid2); const seed1 = randomAsHex(32); const seed2 = randomAsHex(32); diff --git a/tests/integration/fees.test.js b/tests/integration/fees.test.js index 030a85045..c236ac161 100644 --- a/tests/integration/fees.test.js +++ b/tests/integration/fees.test.js @@ -114,32 +114,32 @@ describe.skip('Fees', () => { // Add DID key with all verification relationships const [, , dk1] = createDidPair(dock); - await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk1], did, did, pair, 1, undefined, false)); + await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk1], did, did, pair, undefined, false)); // Add DID key with only 1 verification relationship const [, , dk2] = createDidPair(dock); dk2.verRels.setAuthentication(); - await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk2], did, did, pair, 1, undefined, false)); + await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk2], did, did, pair, undefined, false)); // Add DID key with only 2 verification relationships const [, , dk3] = createDidPair(dock); dk3.verRels.setAuthentication(); dk3.verRels.setAssertion(); - await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk3], did, did, pair, 1, undefined, false)); + await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk3], did, did, pair, undefined, false)); // Add DID key with 3 verification relationships const [, , dk4] = createDidPair(dock); dk4.verRels.setAuthentication(); dk4.verRels.setAssertion(); dk4.verRels.setCapabilityInvocation(); - await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk4], did, did, pair, 1, undefined, false)); + await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk4], did, did, pair, undefined, false)); // Add 2 DID keys with only 1 verification relationship const [, , dk5] = createDidPair(dock); const [, , dk6] = createDidPair(dock); dk5.verRels.setAuthentication(); dk6.verRels.setCapabilityInvocation(); - await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk5, dk6], did, did, pair, 1, undefined, false)); + await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk5, dk6], did, did, pair, undefined, false)); // Add 3 DID keys with only 1 verification relationship const [, , dk7] = createDidPair(dock); @@ -231,13 +231,13 @@ describe.skip('Fees', () => { // Add DID key with all verification relationships to a DID that doesn't control itself const [, , dk__] = createDidPair(dock); - await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk__], did1, did, pair, 1, undefined, false)); + await withPaidFeeMatchingSnapshot(() => dock.did.addKeys([dk__], did1, did, pair, undefined, false)); // Removing 1 key - await withPaidFeeMatchingSnapshot(() => dock.did.removeKeys([2], did, did, pair, 1, undefined, false)); + await withPaidFeeMatchingSnapshot(() => dock.did.removeKeys([2], did, did, pair, undefined, false)); // Removing 2 keys - await withPaidFeeMatchingSnapshot(() => dock.did.removeKeys([3, 4], did, did, pair, 1, undefined, false)); + await withPaidFeeMatchingSnapshot(() => dock.did.removeKeys([3, 4], did, did, pair, undefined, false)); // Removing 1 controller await withPaidFeeMatchingSnapshot(() => dock.did.removeControllers( @@ -273,7 +273,7 @@ describe.skip('Fees', () => { )); // Remove DID - await withPaidFeeMatchingSnapshot(() => dock.did.remove(did, did, pair, 1, undefined, false)); + await withPaidFeeMatchingSnapshot(() => dock.did.remove(did, did, pair, undefined, false)); }, 40000); test('revocation', async () => { @@ -303,7 +303,7 @@ describe.skip('Fees', () => { 1, { didModule: dock.did }, ); - const revTx = dock.revocation.createRevokeTx(update, [[sig, nonce]]); + const revTx = dock.revocation.createRevokeTx(update, [[nonce, sig]]); await withPaidFeeMatchingSnapshot(async () => { await dock.signAndSend(revTx, false); @@ -318,11 +318,11 @@ describe.skip('Fees', () => { { didModule: dock.did }, ); const revTx = dock.revocation.createRemoveRegistryTx(update, [ - [sig, nonce], + [nonce, sig], ]); await withPaidFeeMatchingSnapshot(() => dock.signAndSend(revTx, false)); - }, 40000); + }, 40000);- test('anchors', async () => { const anc = randomAsHex(32); @@ -338,7 +338,7 @@ describe.skip('Fees', () => { id: blobId, blob: randomAsHex(BLOB_MAX_BYTE_SIZE), }; - await withPaidFeeMatchingSnapshot(() => dock.blob.new(blob, did, pair, 1, { didModule: dock.did }, false)); + await withPaidFeeMatchingSnapshot(() => dock.blob.new(blob, did, pair, { didModule: dock.did }, false)); }, 30000); test('bbsPlus', async () => { diff --git a/tests/integration/helpers.js b/tests/integration/helpers.js index 7bed24ec1..4b1e09ad5 100644 --- a/tests/integration/helpers.js +++ b/tests/integration/helpers.js @@ -15,13 +15,11 @@ import { createNewDockDID } from '../../src/utils/did'; * @returns {Promise} */ export async function registerNewDIDUsingPair(dockAPI, did, pair, verRels = undefined, controllers = []) { - const publicKey = getPublicKeyFromKeyringPair(pair); - if (verRels === undefined) { verRels = new VerificationRelationship(); } // No additional controller - const didKey = new DidKey(publicKey, verRels); + const didKey = new DidKey(pair.publicKey(), verRels); return dockAPI.did.new(did, [didKey], controllers, false); } diff --git a/tests/integration/issuing-and-presentation-with-2-subjects.test.js b/tests/integration/issuing-and-presentation-with-2-subjects.test.js index 4149b365f..91c126239 100644 --- a/tests/integration/issuing-and-presentation-with-2-subjects.test.js +++ b/tests/integration/issuing-and-presentation-with-2-subjects.test.js @@ -4,7 +4,7 @@ import jsonld from 'jsonld'; import mockAxios from '../mocks/axios'; import { - createNewDockDID, + createNewDockDID, DidKeypair, } from '../../src/utils/did'; import { DockAPI } from '../../src/index'; @@ -77,11 +77,11 @@ describe('Verifiable Credential issuance and presentation where the credential h // The DIDs should be written before any test begins // issuer DID - const pair1 = dock.keyring.addFromUri(issuerKeySeed, null, 'ed25519'); + const pair1 = new DidKeypair(dock.keyring.addFromUri(issuerKeySeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dock, issuerDID, pair1); // 1st subject's DID - const pair2 = dock.keyring.addFromUri(subject1Seed, null, 'ed25519'); + const pair2 = new DidKeypair(dock.keyring.addFromUri(subject1Seed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dock, subject1DID, pair2); // 2nd subject's DID, has no key but is controlled by subject1DID diff --git a/tests/integration/issuing.test.js b/tests/integration/issuing.test.js index ca696eb3f..74b17d196 100644 --- a/tests/integration/issuing.test.js +++ b/tests/integration/issuing.test.js @@ -2,7 +2,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import mockAxios from '../mocks/axios'; -import { createNewDockDID } from '../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../src/utils/did'; import { DockAPI } from '../../src/index'; import { DockResolver } from '../../src/resolver'; @@ -54,15 +54,15 @@ describe('Verifiable Credential issuance where issuer has a Dock DID', () => { // The DIDs should be written before any test begins // DID with ed25519 key - const pair1 = dock.keyring.addFromUri(issuer1KeySeed, null, 'ed25519'); + const pair1 = new DidKeypair(dock.keyring.addFromUri(issuer1KeySeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dock, issuer1DID, pair1); // DID with secp key - const pair2 = generateEcdsaSecp256k1Keypair(issuer2KeyEntropy); + const pair2 = new DidKeypair(generateEcdsaSecp256k1Keypair(issuer2KeyEntropy), 1); await registerNewDIDUsingPair(dock, issuer2DID, pair2); // DID with sr25519 key - const pair3 = dock.keyring.addFromUri(issuer3KeySeed, null, 'sr25519'); + const pair3 = new DidKeypair(dock.keyring.addFromUri(issuer3KeySeed, null, 'sr25519'), 1); await registerNewDIDUsingPair(dock, issuer3DID, pair3); }, 60000); diff --git a/tests/integration/master.test.js b/tests/integration/master.test.js index d375c17de..310140dc8 100644 --- a/tests/integration/master.test.js +++ b/tests/integration/master.test.js @@ -244,7 +244,7 @@ async function allVote( const votes = []; for (const [did, key] of did_to_key) { - const nonce = await nc.didModule.getNextNonceForDID(did); + const nonce = await nc.didModule.getNextNonceForDid(did); const vote = { nonce, data: { proposal: encodedProposal, roundNo } }; const encodedStateChange = getStateChange(nc.api, 'MasterVote', vote); const signature = getSignatureFromKeyringPair(key, encodedStateChange); diff --git a/tests/integration/presenting.test.js b/tests/integration/presenting.test.js index 1ec1c0594..d9f51d64e 100644 --- a/tests/integration/presenting.test.js +++ b/tests/integration/presenting.test.js @@ -1,7 +1,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { - createNewDockDID, + createNewDockDID, DidKeypair, } from '../../src/utils/did'; import { DockAPI } from '../../src/index'; @@ -63,19 +63,19 @@ describe('Verifiable Presentation where both issuer and holder have a Dock DID', // The DIDs should be written before any test begins // Register issuer DID with ed25519 key - const pair1 = dock.keyring.addFromUri(issuerKeySeed, null, 'ed25519'); + const pair1 = new DidKeypair(dock.keyring.addFromUri(issuerKeySeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dock, issuerDID, pair1); // Register holder DID with ed25519 key - const pair2 = dock.keyring.addFromUri(holder1KeySeed, null, 'ed25519'); + const pair2 = new DidKeypair(dock.keyring.addFromUri(holder1KeySeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dock, holder1DID, pair2); // Register holder DID with secp key - const pair3 = generateEcdsaSecp256k1Keypair(holder2KeyEntropy); + const pair3 = new DidKeypair(generateEcdsaSecp256k1Keypair(holder2KeyEntropy), 1); await registerNewDIDUsingPair(dock, holder2DID, pair3); // Register holder DID with sr25519 key - const pair4 = dock.keyring.addFromUri(holder3KeySeed, null, 'sr25519'); + const pair4 = new DidKeypair(dock.keyring.addFromUri(holder3KeySeed, null, 'sr25519'), 1); await registerNewDIDUsingPair(dock, holder3DID, pair4); const issuerKeyDoc = getKeyDoc(issuerDID, dock.keyring.addFromUri(issuerKeySeed, null, 'ed25519'), 'Ed25519VerificationKey2018'); diff --git a/tests/integration/private-status-list-credential.test.js b/tests/integration/private-status-list-credential.test.js index 13a9449ae..793a40dc2 100644 --- a/tests/integration/private-status-list-credential.test.js +++ b/tests/integration/private-status-list-credential.test.js @@ -1,7 +1,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockAPI } from '../../src'; import { DockResolver } from '../../src/resolver'; -import { createNewDockDID } from '../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../src/utils/did'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../test-constants'; import { getUnsignedCred, registerNewDIDUsingPair } from './helpers'; import { @@ -65,11 +65,11 @@ describe('PrivateStatusList2021Credential', () => { dockAPI.setAccount(account); // Register issuer DID - issuerKeyPair = dockAPI.keyring.addFromUri(issuerSeed, null, 'ed25519'); + issuerKeyPair = new DidKeypair(dockAPI.keyring.addFromUri(issuerSeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dockAPI, issuerDID, issuerKeyPair); // Register holder DID - const pair1 = dockAPI.keyring.addFromUri(holderSeed, null, 'ed25519'); + const pair1 = new DidKeypair(dockAPI.keyring.addFromUri(holderSeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dockAPI, holderDID, pair1); issuerKey = getKeyDoc( @@ -159,7 +159,7 @@ describe('PrivateStatusList2021Credential', () => { const holderKey = getKeyDoc( holderDID, - dockAPI.keyring.addFromUri(holderSeed, null, 'ed25519'), + new DidKeypair(dockAPI.keyring.addFromUri(holderSeed, null, 'ed25519'), 1), 'Ed25519VerificationKey2018', ); diff --git a/tests/integration/resolvers.test.js b/tests/integration/resolvers.test.js index 750bddf69..8d3689eb8 100644 --- a/tests/integration/resolvers.test.js +++ b/tests/integration/resolvers.test.js @@ -1,6 +1,6 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockResolver, DockStatusList2021Resolver } from '../../src/resolver'; -import { getHexIdentifierFromDID, createNewDockDID } from '../../src/utils/did'; +import { typedHexDID, createNewDockDID } from '../../src/utils/did'; import { DockAPI } from '../../src/index'; @@ -54,7 +54,7 @@ describe('Resolvers', () => { dock.setAccount(account); // Thees DIDs should be written before any test begins - pair = dock.keyring.addFromUri(ownerSeed, null, 'sr25519'); + pair = new DidKeypair(dock.keyring.addFromUri(ownerSeed, null, 'sr25519'), 1); // The controller is same as the DID await registerNewDIDUsingPair(dock, ownerDID, pair); @@ -88,7 +88,7 @@ describe('Resolvers', () => { expect(resolver.supports('status-list2021:*:')).toBe(false); expect(resolver.supports('status-list2020:doc:')).toBe(false); expect(await resolver.resolve(ownerDID)).toEqual( - await dock.did.getDocument(getHexIdentifierFromDID(ownerDID)), + await dock.did.getDocument(typedHexDID(dock.api, ownerDID)), ); if (!DisableStatusListTests) { expect(await resolver.resolve(statusListCred.id)).toEqual( @@ -124,7 +124,7 @@ describe('Resolvers', () => { expect(resolver.supports('status-list2021:*:')).toBe(false); expect(resolver.supports('status-list2020:doc:')).toBe(false); expect(await resolver.resolve(ownerDID)).toEqual( - await dock.did.getDocument(getHexIdentifierFromDID(ownerDID)), + await dock.did.getDocument(typedHexDID(dock.api, ownerDID)), ); if (!DisableStatusListTests) { expect(resolver.resolve(statusListCred.id)).rejects.toThrowError( diff --git a/tests/integration/revocation.test.js b/tests/integration/revocation.test.js index 22750d4d5..549bb4206 100644 --- a/tests/integration/revocation.test.js +++ b/tests/integration/revocation.test.js @@ -7,6 +7,7 @@ import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI } from '../test-const import { OneOfPolicy, } from '../../src/utils/revocation'; +import { DidKeypair } from '../../src/utils/did' import { registerNewDIDUsingPair } from './helpers'; describe('Revocation Module', () => { @@ -49,8 +50,8 @@ describe('Revocation Module', () => { dock.setAccount(account); // Thees DIDs should be written before any test begins - pair = dock.keyring.addFromUri(ownerSeed, null, 'sr25519'); - pair2 = dock.keyring.addFromUri(ownerSeed2, null, 'sr25519'); + pair = new DidKeypair(dock.keyring.addFromUri(ownerSeed, null, 'sr25519'), 1); + pair2 = new DidKeypair(dock.keyring.addFromUri(ownerSeed2, null, 'sr25519'), 1); // The controller is same as the DID await registerNewDIDUsingPair(dock, ownerDID, pair); @@ -69,15 +70,15 @@ describe('Revocation Module', () => { }, 40000); test('Can revoke single from a registry', async () => { - const [revoke, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, revokeIds, ownerDID, pair, 1, { didModule: dock.did }); - await dock.revocation.revoke(revoke, [[sig, nonce]], false); + const [revoke, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, revokeIds, ownerDID, pair, { didModule: dock.did }); + await dock.revocation.revoke(revoke, [[nonce, sig]], false); const revocationStatus = await dock.revocation.getIsRevoked(registryId, revokeId); expect(revocationStatus).toBe(true); }, 40000); test('Can unrevoke single from a registry', async () => { - const [unrevoke, sig, nonce] = await dock.revocation.createSignedUnRevoke(registryId, revokeIds, ownerDID, pair, 1, { didModule: dock.did }); - await dock.revocation.unrevoke(unrevoke, [[sig, nonce]], false); + const [unrevoke, sig, nonce] = await dock.revocation.createSignedUnRevoke(registryId, revokeIds, ownerDID, pair, { didModule: dock.did }); + await dock.revocation.unrevoke(unrevoke, [[nonce, sig]], false); const revocationStatus = await dock.revocation.getIsRevoked(registryId, revokeId); expect(revocationStatus).toBe(false); @@ -93,8 +94,8 @@ describe('Revocation Module', () => { const rIdsArr = Array.from(rIds); - const [revoke, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, rIds, ownerDID, pair, 1, { didModule: dock.did }); - await dock.revocation.revoke(revoke, [[sig, nonce]], false); + const [revoke, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, rIds, ownerDID, pair, { didModule: dock.did }); + await dock.revocation.revoke(revoke, [[nonce, sig]], false); console.time(`Check ${count} revocation status one by one`); for (let i = 0; i < rIdsArr.length; i++) { @@ -110,7 +111,7 @@ describe('Revocation Module', () => { revocationStatuses.forEach((s) => expect(s).toBe(true)); console.timeEnd(`Check ${count} revocation status in a batch`); - const [unrevoke, sig1, nonce1] = await dock.revocation.createSignedUnRevoke(registryId, rIds, ownerDID, pair, 1, { didModule: dock.did }); + const [unrevoke, sig1, nonce1] = await dock.revocation.createSignedUnRevoke(registryId, rIds, ownerDID, pair, { didModule: dock.did }); // Note: Intentionally passing true and waiting for finalization as not doing that makes the multi-query check fail. // This seems like a bug since the single query check done in next loop work. Even the upgrade to @polkadot/api version 9.14 didn't fix @@ -128,8 +129,8 @@ describe('Revocation Module', () => { }, 40000); test('Can remove a registry', async () => { - const [remove, sig, nonce] = await dock.revocation.createSignedRemove(registryId, ownerDID, pair, 1, { didModule: dock.did }); - await dock.revocation.removeRegistry(remove, [[sig, nonce]], false); + const [remove, sig, nonce] = await dock.revocation.createSignedRemove(registryId, ownerDID, pair, { didModule: dock.did }); + await dock.revocation.removeRegistry(remove, [[nonce, sig]], false); await expect(dock.revocation.getRevocationRegistry(registryId)).rejects.toThrow(/Could not find revocation registry/); }, 40000); @@ -143,8 +144,8 @@ describe('Revocation Module', () => { const reg = await dock.revocation.getRevocationRegistry(registryId); expect(!!reg).toBe(true); - const [revoke, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, revokeIds, ownerDID, pair, 1, { didModule: dock.did }); - await dock.revocation.revoke(revoke, [[sig, nonce]], false); + const [revoke, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, revokeIds, ownerDID, pair, { didModule: dock.did }); + await dock.revocation.revoke(revoke, [[nonce, sig]], false); const revocationStatus = await dock.revocation.getIsRevoked(registryId, revokeId); expect(revocationStatus).toBe(true); @@ -154,9 +155,9 @@ describe('Revocation Module', () => { const reg = await dock.revocation.getRevocationRegistry(registryId); expect(!!reg).toBe(true); - const [unrevoke, sig, nonce] = await dock.revocation.createSignedUnRevoke(registryId, revokeIds, ownerDID, pair, 1, { didModule: dock.did }); + const [unrevoke, sig, nonce] = await dock.revocation.createSignedUnRevoke(registryId, revokeIds, ownerDID, pair, { didModule: dock.did }); await expect( - dock.revocation.unrevoke(unrevoke, [[sig, nonce]], false), + dock.revocation.unrevoke(unrevoke, [[nonce, sig]], false), ).rejects.toThrow(); const revocationStatus = await dock.revocation.getIsRevoked(registryId, revokeId); @@ -167,9 +168,9 @@ describe('Revocation Module', () => { const reg = await dock.revocation.getRevocationRegistry(registryId); expect(!!reg).toBe(true); - const [remove, sig, nonce] = await dock.revocation.createSignedRemove(registryId, ownerDID, pair, 1, { didModule: dock.did }); + const [remove, sig, nonce] = await dock.revocation.createSignedRemove(registryId, ownerDID, pair, { didModule: dock.did }); await expect( - dock.revocation.removeRegistry(remove, [[sig, nonce]], false), + dock.revocation.removeRegistry(remove, [[nonce, sig]], false), ).rejects.toThrow(); await expect(dock.revocation.getRevocationRegistry(registryId)).resolves.toBeDefined(); @@ -205,7 +206,7 @@ describe('Revocation Module', () => { const revId = randomAsHex(32); // Revoke - await dock.revocation.revokeCredentialWithOneOfPolicy(multipleControllerRegistryID, revId, ownerDID, pair, 1, { didModule: dock.did }, false); + await dock.revocation.revokeCredentialWithOneOfPolicy(multipleControllerRegistryID, revId, ownerDID, pair, { didModule: dock.did }, false); const revocationStatus = await dock.revocation.getIsRevoked(multipleControllerRegistryID, revId); expect(revocationStatus).toBe(true); @@ -215,7 +216,7 @@ describe('Revocation Module', () => { expect(revocationStatus1).toBe(false); // Remove - await dock.revocation.removeRegistryWithOneOfPolicy(multipleControllerRegistryID, ownerDID, pair, 1, { didModule: dock.did }, false); + await dock.revocation.removeRegistryWithOneOfPolicy(multipleControllerRegistryID, ownerDID, pair, { didModule: dock.did }, false); await expect(dock.revocation.getRevocationRegistry(multipleControllerRegistryID)).rejects.toThrow(/Could not find revocation registry/); }, 30000); }); diff --git a/tests/integration/schema.test.js b/tests/integration/schema.test.js index 7f657b1dc..11a92821c 100644 --- a/tests/integration/schema.test.js +++ b/tests/integration/schema.test.js @@ -4,7 +4,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockAPI } from '../../src/index'; import { - createNewDockDID, getHexIdentifierFromDID, hexDIDToQualified, + createNewDockDID, typedHexDID, hexDIDToQualified, DidKeypair } from '../../src/utils/did'; import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI } from '../test-constants'; import { verifyCredential, verifyPresentation } from '../../src/utils/vc/index'; @@ -56,9 +56,9 @@ describe('Schema Blob Module Integration', () => { }); account = dockApi.keyring.addFromUri(TestAccountURI); dockApi.setAccount(account); - pair = dockApi.keyring.addFromUri(firstKeySeed); + pair = new DidKeypair(dockApi.keyring.addFromUri(firstKeySeed), 1); dockDID = createNewDockDID(); - hexDid = getHexIdentifierFromDID(dockDID); + hexDid = typedHexDID(dock.api, dockDID); await registerNewDIDUsingPair(dockApi, dockDID, pair); blobId = randomAsHex(DockBlobIdByteSize); @@ -68,7 +68,7 @@ describe('Schema Blob Module Integration', () => { id: invalidFormatBlobId, blob: stringToHex('hello world'), }; - await dockApi.blob.new(blob, dockDID, pair, 1, { didModule: dockApi.didModule }, false); + await dockApi.blob.new(blob, dockDID, pair, { didModule: dockApi.didModule }, false); // Write schema blob const blobStr = JSON.stringify(exampleSchema); @@ -76,7 +76,7 @@ describe('Schema Blob Module Integration', () => { id: blobId, blob: stringToHex(blobStr), }; - await dockApi.blob.new(blob, dockDID, pair, 1, { didModule: dockApi.didModule }, false); + await dockApi.blob.new(blob, dockDID, pair, { didModule: dockApi.didModule }, false); // Properly format a keyDoc to use for signing keyDoc = getKeyDoc( @@ -122,11 +122,11 @@ describe('Schema Blob Module Integration', () => { test('Set and get schema', async () => { const schema = new Schema(); await schema.setJSONSchema(exampleSchema); - await dockApi.blob.new(schema.toBlob(), hexDid, pair, 1, { didModule: dockApi.didModule }, false); + await dockApi.blob.new(schema.toBlob(), hexDid, pair, { didModule: dockApi.didModule }, false); await expect(Schema.get(blobId, dockApi)).resolves.toMatchObject({ ...exampleSchema, id: blobId, - author: hexDIDToQualified(getHexIdentifierFromDID(dockDID)), + author: hexDIDToQualified(typedHexDID(dock.api, dockDID)), }); }, 20000); diff --git a/tests/integration/status-list-credential-module.test.js b/tests/integration/status-list-credential-module.test.js index d93411509..6a0ecce42 100644 --- a/tests/integration/status-list-credential-module.test.js +++ b/tests/integration/status-list-credential-module.test.js @@ -1,30 +1,35 @@ -import { randomAsHex } from '@polkadot/util-crypto'; +import { randomAsHex } from "@polkadot/util-crypto"; -import { DockAPI } from '../../src/index'; +import { DockAPI } from "../../src/index"; import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI, DisableStatusListTests, -} from '../test-constants'; +} from "../test-constants"; -import { getHexIdentifierFromDID, createNewDockDID } from '../../src/utils/did'; -import { OneOfPolicy } from '../../src/utils/revocation'; -import { registerNewDIDUsingPair } from './helpers'; -import { getKeyDoc } from '../../src/utils/vc/helpers'; -import StatusList2021Credential from '../../src/status-list-credential/status-list2021-credential'; +import { + typedHexDID, + createNewDockDID, + DidKeypair, + typedHexDIDFromSubstrate, +} from "../../src/utils/did"; +import { OneOfPolicy } from "../../src/utils/revocation"; +import { registerNewDIDUsingPair } from "./helpers"; +import { getKeyDoc } from "../../src/utils/vc/helpers"; +import StatusList2021Credential from "../../src/status-list-credential/status-list2021-credential"; const expectEqualCreds = (cred1, cred2) => { expect(cred1).toEqual(cred2); expect(cred1.toJSON()).toEqual(cred2.toJSON()); expect(StatusList2021Credential.fromJSON(cred1.toJSON())).toEqual( - StatusList2021Credential.fromJSON(cred2.toJSON()), + StatusList2021Credential.fromJSON(cred2.toJSON()) ); }; const buildTest = DisableStatusListTests ? describe.skip : describe; -buildTest('StatusListCredential Module', () => { +buildTest("StatusListCredential Module", () => { const dock = new DockAPI(); let pair; let pair2; @@ -63,14 +68,14 @@ buildTest('StatusListCredential Module', () => { ownerKey = getKeyDoc( ownerDID, - dock.keyring.addFromUri(ownerSeed, null, 'ed25519'), - 'Ed25519VerificationKey2018', + dock.keyring.addFromUri(ownerSeed, null, "ed25519"), + "Ed25519VerificationKey2018" ); ownerKey2 = getKeyDoc( ownerDID2, - dock.keyring.addFromUri(ownerSeed2, null, 'ed25519'), - 'Ed25519VerificationKey2018', + dock.keyring.addFromUri(ownerSeed2, null, "ed25519"), + "Ed25519VerificationKey2018" ); // The keyring should be initialized before any test begins as this suite is testing statusListCredentialModule @@ -78,8 +83,14 @@ buildTest('StatusListCredential Module', () => { dock.setAccount(account); // Thees DIDs should be written before any test begins - pair = dock.keyring.addFromUri(ownerSeed, null, 'sr25519'); - pair2 = dock.keyring.addFromUri(ownerSeed2, null, 'sr25519'); + pair = new DidKeypair( + dock.keyring.addFromUri(ownerSeed, null, "sr25519"), + 1 + ); + pair2 = new DidKeypair( + dock.keyring.addFromUri(ownerSeed2, null, "sr25519"), + 1 + ); // The controller is same as the DID await registerNewDIDUsingPair(dock, ownerDID, pair); @@ -91,141 +102,144 @@ buildTest('StatusListCredential Module', () => { await dock.disconnect(); }, 10000); - test('Can create a status list with a OneOf policy', async () => { + test("Can create a status list with a OneOf policy", async () => { const cred = await StatusList2021Credential.create( ownerKey, - statusListCredId, + statusListCredId ); await expect( dock.statusListCredential.createStatusListCredential( statusListCredId, cred, policy, - false, - ), + false + ) ).resolves.toBeDefined(); - const fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId, - ); + const fetchedCred = + await dock.statusListCredential.fetchStatusList2021Credential( + statusListCredId + ); expectEqualCreds(cred, fetchedCred); }, 40000); - test('Can revoke index from a status list credential', async () => { + test("Can revoke index from a status list credential", async () => { const cred = await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId, + statusListCredId ); await cred.update(ownerKey, { revokeIndices: revokeIds }); - const [revoke, sig, nonce] = await dock.statusListCredential.createSignedUpdateStatusListCredential( - statusListCredId, - cred, - ownerDID, - pair, - 1, - { didModule: dock.did }, - ); + const [revoke, sig, nonce] = + await dock.statusListCredential.createSignedUpdateStatusListCredential( + statusListCredId, + cred, + ownerDID, + pair, + { didModule: dock.did } + ); await dock.statusListCredential.updateStatusListCredential( revoke, - [[sig, nonce]], - false, - ); - const fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId, + [[nonce, sig]], + false ); + const fetchedCred = + await dock.statusListCredential.fetchStatusList2021Credential( + statusListCredId + ); expectEqualCreds(cred, fetchedCred); expect(await fetchedCred.revoked(revokeId)).toBe(true); }, 40000); - test('Cant unsuspend from a status list credential with `statusPurpose` = `revocation`', async () => { + test("Cant unsuspend from a status list credential with `statusPurpose` = `revocation`", async () => { const cred = await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId, + statusListCredId ); expect( - cred.update(ownerKey, { unsuspendIndices: revokeIds }), + cred.update(ownerKey, { unsuspendIndices: revokeIds }) ).rejects.toEqual( new Error( - "Can't unsuspend indices for credential with `statusPurpose` = `revocation`, it's only possible with `statusPurpose` = `suspension`", - ), + "Can't unsuspend indices for credential with `statusPurpose` = `revocation`, it's only possible with `statusPurpose` = `suspension`" + ) ); expect( - cred.update(ownerKey, { unsuspendIndices: revokeIds }), + cred.update(ownerKey, { unsuspendIndices: revokeIds }) ).rejects.toEqual( new Error( - "Can't unsuspend indices for credential with `statusPurpose` = `revocation`, it's only possible with `statusPurpose` = `suspension`", - ), + "Can't unsuspend indices for credential with `statusPurpose` = `revocation`, it's only possible with `statusPurpose` = `suspension`" + ) ); expect(await cred.revokedBatch(revokeIds)).toEqual( - Array.from(revokeIds, () => true), + Array.from(revokeIds, () => true) ); }, 40000); - test('Can unsuspend from a status list credential', async () => { + test("Can unsuspend from a status list credential", async () => { const credential = await StatusList2021Credential.create( ownerKey, statusListCredId, - { statusPurpose: 'suspension', revokeIndices: revokeIds }, - ); - let [update, sig, nonce] = await dock.statusListCredential.createSignedUpdateStatusListCredential( - statusListCredId, - credential, - ownerDID, - pair, - 1, - { didModule: dock.did }, + { statusPurpose: "suspension", revokeIndices: revokeIds } ); + let [update, sig, nonce] = + await dock.statusListCredential.createSignedUpdateStatusListCredential( + statusListCredId, + credential, + ownerDID, + pair, + { didModule: dock.did } + ); await dock.statusListCredential.updateStatusListCredential( update, - [[sig, nonce]], - false, - ); - let fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId, + [[nonce, sig]], + false ); + let fetchedCred = + await dock.statusListCredential.fetchStatusList2021Credential( + statusListCredId + ); expectEqualCreds(credential, fetchedCred); await fetchedCred.update(ownerKey, { unsuspendIndices: revokeIds }); expect(await fetchedCred.revokedBatch(revokeIds)).toEqual( - Array.from(revokeIds, () => false), - ); - [update, sig, nonce] = await dock.statusListCredential.createSignedUpdateStatusListCredential( - statusListCredId, - fetchedCred, - ownerDID, - pair, - 1, - { didModule: dock.did }, + Array.from(revokeIds, () => false) ); + [update, sig, nonce] = + await dock.statusListCredential.createSignedUpdateStatusListCredential( + statusListCredId, + fetchedCred, + ownerDID, + pair, + { didModule: dock.did } + ); await dock.statusListCredential.updateStatusListCredential( update, - [[sig, nonce]], - false, + [[nonce, sig]], + false ); fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId, + statusListCredId ); expect(await fetchedCred.revoked(revokeId)).toBe(false); }, 40000); - test('Can remove a status list', async () => { - const [remove, sig, nonce] = await dock.statusListCredential.createSignedRemoveStatusListCredential( - statusListCredId, - ownerDID, - pair, - 1, - { didModule: dock.did }, - ); + test("Can remove a status list", async () => { + const [remove, sig, nonce] = + await dock.statusListCredential.createSignedRemoveStatusListCredential( + statusListCredId, + ownerDID, + pair, + { didModule: dock.did } + ); await dock.statusListCredential.removeStatusListCredential( remove, - [[sig, nonce]], - false, + [[nonce, sig]], + false ); expect( await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId, - ), + statusListCredId + ) ).toBe(null); }, 40000); - test('Can create a status list with multiple owners', async () => { + test("Can create a status list with multiple owners", async () => { const controllersNew = new Set(); controllersNew.add(ownerDID); controllersNew.add(ownerDID2); @@ -233,7 +247,7 @@ buildTest('StatusListCredential Module', () => { const cred = await StatusList2021Credential.create( ownerKey, multipleControllerstatusListCredID, - { statusPurpose: 'suspension' }, + { statusPurpose: "suspension" } ); // Create policy and status list with multiple owners @@ -244,37 +258,45 @@ buildTest('StatusListCredential Module', () => { cred, policyNew, false, - false, - ), + false + ) ).resolves.toBeDefined(); const fetchedCred = ( await dock.api.query.statusListCredential.statusListCredentials( - multipleControllerstatusListCredID, + multipleControllerstatusListCredID ) ).unwrap(); expect(fetchedCred.policy.isOneOf).toBe(true); - const controllerSet = fetchedCred.policy.toJSON().oneOf; - expect(controllerSet.length).toBe(2); + const controllerSet = fetchedCred.policy.asOneOf; + expect(controllerSet.toJSON().length).toBe(2); let hasFirstDID = false; let hasSecondDID = false; - controllerSet.forEach((controller) => { - if (controller === getHexIdentifierFromDID(ownerDID)) { - hasFirstDID = true; - } else if (controller === getHexIdentifierFromDID(ownerDID2)) { - hasSecondDID = true; - } - }); + [...controllerSet.entries()] + .flatMap((v) => v) + .map(typedHexDIDFromSubstrate) + .forEach((controller) => { + if ( + controller.toString() === typedHexDID(dock.api, ownerDID).toString() + ) { + hasFirstDID = true; + } else if ( + controller.toString() === typedHexDID(dock.api, ownerDID2).toString() + ) { + hasSecondDID = true; + } + }); expect(hasFirstDID && hasSecondDID).toBe(true); }, 40000); - test('Can revoke, unsuspend and remove status list with multiple owners', async () => { + test("Can revoke, unsuspend and remove status list with multiple owners", async () => { const revId = (Math.random() * 10e3) | 0; - let fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( - multipleControllerstatusListCredID, - ); + let fetchedCred = + await dock.statusListCredential.fetchStatusList2021Credential( + multipleControllerstatusListCredID + ); await fetchedCred.update(ownerKey, { revokeIndices: [revId] }); // Revoke await dock.statusListCredential.updateStatusListCredentialWithOneOfPolicy( @@ -282,13 +304,12 @@ buildTest('StatusListCredential Module', () => { fetchedCred, ownerDID, pair, - 1, { didModule: dock.did }, - false, + false ); fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( multipleControllerstatusListCredID, - revId, + revId ); expect(await fetchedCred.revoked(revId)).toBe(true); @@ -300,12 +321,11 @@ buildTest('StatusListCredential Module', () => { fetchedCred, ownerDID2, pair2, - 1, { didModule: dock.did }, - false, + false ); fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( - multipleControllerstatusListCredID, + multipleControllerstatusListCredID ); expect(await fetchedCred.revoked(revId)).toBe(false); @@ -314,12 +334,11 @@ buildTest('StatusListCredential Module', () => { multipleControllerstatusListCredID, ownerDID, pair, - 1, { didModule: dock.did }, - false, + false ); fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( - multipleControllerstatusListCredID, + multipleControllerstatusListCredID ); expect(fetchedCred).toBe(null); }, 30000); diff --git a/tests/integration/status-list-credential.test.js b/tests/integration/status-list-credential.test.js index e89b594a7..f1ad7f68f 100644 --- a/tests/integration/status-list-credential.test.js +++ b/tests/integration/status-list-credential.test.js @@ -21,7 +21,7 @@ import { createPresentation } from '../create-presentation'; import { OneOfPolicy } from '../../src/utils/revocation'; import { getUnsignedCred, registerNewDIDUsingPair } from './helpers'; import { getKeyDoc } from '../../src/utils/vc/helpers'; -import { createNewDockDID } from '../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../src/utils/did'; import StatusList2021Credential from '../../src/status-list-credential/status-list2021-credential'; import { addStatusList21EntryToCredential } from '../../src/utils/vc/credentials'; @@ -62,11 +62,11 @@ buildTest('StatusList2021Credential', () => { dockAPI.setAccount(account); // Register issuer DID - issuerKeyPair = dockAPI.keyring.addFromUri(issuerSeed, null, 'ed25519'); + issuerKeyPair = new DidKeypair(dockAPI.keyring.addFromUri(issuerSeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dockAPI, issuerDID, issuerKeyPair); // Register holder DID - const pair1 = dockAPI.keyring.addFromUri(holderSeed, null, 'ed25519'); + const pair1 = new DidKeypair(dockAPI.keyring.addFromUri(holderSeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dockAPI, holderDID, pair1); // Create a new policy @@ -144,7 +144,6 @@ buildTest('StatusList2021Credential', () => { fetchedCred, issuerDID, issuerKeyPair, - 1, dockAPI, ); @@ -175,7 +174,6 @@ buildTest('StatusList2021Credential', () => { fetchedCred, issuerDID, issuerKeyPair, - 1, dockAPI, ); const holderKey = getKeyDoc( @@ -219,7 +217,6 @@ buildTest('StatusList2021Credential', () => { fetchedCred, issuerDID, issuerKeyPair, - 1, dockAPI, ); diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js new file mode 100644 index 000000000..81e52de0f --- /dev/null +++ b/tests/integration/trust-registry-module.test.js @@ -0,0 +1,326 @@ +import { randomAsHex } from "@polkadot/util-crypto"; +import { BTreeSet, BTreeMap } from "@polkadot/types"; + +import { DockAPI } from "../../src/index"; + +import { + FullNodeEndpoint, + TestKeyringOpts, + TestAccountURI, + DisableTrustRegistryTests, +} from "../test-constants"; + +import { createNewDockDID, DidKeypair, typedHexDID } from "../../src/utils/did"; +import { registerNewDIDUsingPair } from "./helpers"; + +const buildTest = DisableTrustRegistryTests ? describe.skip : describe; + +buildTest("Trust Registry", () => { + const dock = new DockAPI(); + + // Create a random status list id + const trustRegistryId = randomAsHex(32); + + // Create a new owner DID, the DID will be registered on the network and own the status list + const convenerDID = createNewDockDID(); + const ownerSeed = randomAsHex(32); + let convenerPair; + + const issuerDID = createNewDockDID(); + const issuerSeed = randomAsHex(32); + let issuerPair; + + const issuerDID2 = createNewDockDID(); + const issuerSeed2 = randomAsHex(32); + let issuerPair2; + + const verifierDID = createNewDockDID(); + const verifierSeed = randomAsHex(32); + let verifierPair; + + const verifierDID2 = createNewDockDID(); + const verifierSeed2 = randomAsHex(32); + let verifierPair2; + + // Create revoke IDs + const revokeId = (Math.random() * 10e3) | 0; + const revokeIds = new Set(); + revokeIds.add(revokeId); + + beforeAll(async () => { + await dock.init({ + keyring: TestKeyringOpts, + address: FullNodeEndpoint, + }); + + convenerPair = new DidKeypair( + dock.keyring.addFromUri(ownerSeed, null, "ed25519"), + 1 + ); + + issuerPair = new DidKeypair( + dock.keyring.addFromUri(issuerSeed, null, "ed25519"), + 1 + ); + + issuerPair2 = new DidKeypair( + dock.keyring.addFromUri(issuerSeed2, null, "ed25519"), + 1 + ); + + verifierPair = new DidKeypair( + dock.keyring.addFromUri(verifierSeed, null, "ed25519"), + 1 + ); + + verifierPair2 = new DidKeypair( + dock.keyring.addFromUri(verifierSeed2, null, "ed25519"), + 1 + ); + + // The keyring should be initialized before any test begins as this suite is testing statusListCredentialModule + const account = dock.keyring.addFromUri(TestAccountURI); + dock.setAccount(account); + + // Register convener + await registerNewDIDUsingPair(dock, convenerDID, convenerPair); + // Register issuer DID + await registerNewDIDUsingPair(dock, issuerDID, issuerPair); + await registerNewDIDUsingPair(dock, issuerDID2, issuerPair2); + await registerNewDIDUsingPair(dock, verifierDID, verifierPair); + await registerNewDIDUsingPair(dock, verifierDID2, verifierPair2); + }, 40000); + + it("Initializes Trust Registry", async () => { + expect( + (await dock.api.query.trustRegistry.trustRegistriesInfo(trustRegistryId)) + .isNone + ).toEqual(true); + + await dock.trustRegistry.init( + convenerDID, + trustRegistryId, + "Test Registry", + convenerPair, + dock + ); + + const registryInfo = ( + await dock.api.query.trustRegistry.trustRegistriesInfo(trustRegistryId) + ).toJSON(); + expect(registryInfo).toEqual({ + convener: typedHexDID(dock.api, convenerDID), + name: "Test Registry", + }); + }); + + it("Adds schemas to the existing Trust Registry", async () => { + // Create a random status list id + const schemaId = randomAsHex(32); + + await dock.trustRegistry.init( + convenerDID, + trustRegistryId, + "Test Registry", + convenerPair, + dock + ); + + const verifiers = new BTreeSet(); + verifiers.add(typedHexDID(dock.api, issuerDID)); + verifiers.add(typedHexDID(dock.api, issuerDID2)); + + const issuers = new BTreeMap(); + const issuerPrices = new BTreeMap(); + issuerPrices.set("A", 20); + const issuer2Prices = new BTreeMap(); + issuer2Prices.set("A", 20); + + issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); + issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); + + const schemas = new BTreeMap(); + schemas.set(schemaId, { + issuers, + verifiers, + }); + + await dock.trustRegistry.addSchemaMetadata( + convenerDID, + trustRegistryId, + schemas, + convenerPair, + dock + ); + + expect( + ( + await dock.api.query.trustRegistry.trustRegistrySchemasMetadata( + schemaId, + trustRegistryId + ) + ).toJSON() + ).toEqual({ + issuers: Object.fromEntries( + [...issuers.entries()].map(([issuer, prices]) => [ + JSON.stringify({ did: issuer.asDid }), + Object.fromEntries([...prices.entries()]), + ]) + ), + verifiers: [...verifiers.values()] + .map((verifier) => ({ did: verifier.asDid })) + .sort((a, b) => a.did.localeCompare(b.did)), + }); + }); + + it("Updates schemas to the existing Trust Registry", async () => { + // Create a random status list id + const schemaId = randomAsHex(32); + + await dock.trustRegistry.init( + convenerDID, + trustRegistryId, + "Test Registry", + convenerPair, + dock + ); + + let verifiers = new BTreeSet(); + verifiers.add(typedHexDID(dock.api, issuerDID)); + verifiers.add(typedHexDID(dock.api, issuerDID2)); + + let issuers = new BTreeMap(); + let issuerPrices = new BTreeMap(); + issuerPrices.set("A", 20); + let issuer2Prices = new BTreeMap(); + issuer2Prices.set("A", 20); + + issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); + issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); + + let schemas = new BTreeMap(); + schemas.set(schemaId, { + issuers, + verifiers, + }); + + await dock.trustRegistry.addSchemaMetadata( + convenerDID, + trustRegistryId, + schemas, + convenerPair, + dock + ); + + expect( + ( + await dock.api.query.trustRegistry.trustRegistrySchemasMetadata( + schemaId, + trustRegistryId + ) + ).toJSON() + ).toEqual({ + issuers: Object.fromEntries( + [...issuers.entries()].map(([issuer, prices]) => [ + JSON.stringify({ did: issuer.asDid }), + Object.fromEntries([...prices.entries()]), + ]) + ), + verifiers: [...verifiers.values()] + .map((verifier) => ({ did: verifier.asDid })) + .sort((a, b) => a.did.localeCompare(b.did)), + }); + + schemas = new BTreeMap(); + + verifiers = new BTreeSet(); + verifiers.add(typedHexDID(dock.api, issuerDID)); + verifiers.add(typedHexDID(dock.api, issuerDID2)); + + issuers = new BTreeMap(); + issuerPrices = new BTreeMap(); + issuerPrices.set("A", 65); + issuer2Prices = new BTreeMap(); + issuer2Prices.set("A", 75); + + issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); + issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); + + schemas.set(schemaId, { + Set: { + issuers, + verifiers + }, + }); + + await dock.trustRegistry.updateSchemaMetadata( + convenerDID, + trustRegistryId, + schemas, + convenerPair, + dock + ); + + expect( + ( + await dock.api.query.trustRegistry.trustRegistrySchemasMetadata( + schemaId, + trustRegistryId + ) + ).toJSON() + ).toEqual({ + issuers: Object.fromEntries( + [...issuers.entries()].map(([issuer, prices]) => [ + JSON.stringify({ did: issuer.asDid }), + Object.fromEntries([...prices.entries()]), + ]) + ), + verifiers: [...verifiers.values()] + .map((verifier) => ({ did: verifier.asDid })) + .sort((a, b) => a.did.localeCompare(b.did)), + }); + + schemas = new BTreeMap(); + issuer2Prices = new BTreeMap(); + issuer2Prices.set("A", 60); + + let issuersUpdate = new BTreeMap(); + issuer2Prices.set("A", 75); + issuer2Prices.set("B", 60); + issuersUpdate.set(issuerDID2, issuer2Prices); + schemas.set(schemaId, { + Modify: { + issuers: { + Set: issuersUpdate, + }, + }, + }); + + await dock.trustRegistry.updateSchemaMetadata( + issuerDID2, + trustRegistryId, + schemas, + issuerPair2, + dock + ); + + expect( + ( + await dock.api.query.trustRegistry.trustRegistrySchemasMetadata( + schemaId, + trustRegistryId + ) + ).toJSON() + ).toEqual({ + issuers: Object.fromEntries( + [...issuers.entries()].map(([issuer, prices]) => [ + JSON.stringify({ did: issuer.asDid }), + Object.fromEntries([...prices.entries()]), + ]) + ), + verifiers: [...verifiers.values()] + .map((verifier) => ({ did: verifier.asDid })) + .sort((a, b) => a.did.localeCompare(b.did)), + }); + }); +}); diff --git a/tests/test-constants.js b/tests/test-constants.js index 04b5e6036..dcd6045f4 100644 --- a/tests/test-constants.js +++ b/tests/test-constants.js @@ -100,7 +100,7 @@ export const BBS = { VerKey: 'Bls12381BBSVerificationKeyDock2023', getParamsByDid: (api, did) => api.rpc.core_mods.bbsParamsByDid(did), getPublicKeyWithParamsByStorageKey: (api, storageKey) => api.rpc.core_mods.bbsPublicKeyWithParams(storageKey), - getPublicKeysByDid: (api, did) => api.rpc.core_mods.bbsPublicKeysByDid(did), + getPublicKeysByDid: (api, did) => api.rpc.core_mods.bbsPublicKeysByDid(did.asDid), }; export const BBSPlus = { Name: 'BBS+', @@ -123,7 +123,7 @@ export const BBSPlus = { SigType: 'Bls12381BBS+SignatureDock2022', getParamsByDid: (api, did) => api.rpc.core_mods.bbsPlusParamsByDid(did), getPublicKeyWithParamsByStorageKey: (api, storageKey) => api.rpc.core_mods.bbsPlusPublicKeyWithParams(storageKey), - getPublicKeysByDid: (api, did) => api.rpc.core_mods.bbsPlusPublicKeysByDid(did), + getPublicKeysByDid: (api, did) => api.rpc.core_mods.bbsPlusPublicKeysByDid(did.asDid), }; export const PS = { Name: 'PS', @@ -146,7 +146,7 @@ export const PS = { VerKey: 'Bls12381PSVerificationKeyDock2023', getParamsByDid: (api, did) => api.rpc.core_mods.psParamsByDid(did), getPublicKeyWithParamsByStorageKey: (api, storageKey) => api.rpc.core_mods.psPublicKeyWithParams(storageKey), - getPublicKeysByDid: (api, did) => api.rpc.core_mods.psPublicKeysByDid(did), + getPublicKeysByDid: (api, did) => api.rpc.core_mods.psPublicKeysByDid(did.asDid), }; export const AllSchemes = Object.setPrototypeOf({ BBS, BBSPlus, PS }, null); diff --git a/tests/unit/did.test.js b/tests/unit/did.test.js index 9494ce28b..bffae078b 100644 --- a/tests/unit/did.test.js +++ b/tests/unit/did.test.js @@ -3,10 +3,15 @@ import { randomAsHex, encodeAddress } from '@polkadot/util-crypto'; import { validateDockDIDHexIdentifier, validateDockDIDSS58Identifier, - getHexIdentifierFromDID, DockDIDQualifier, } from '../../src/utils/did'; +const hexDid = did => getHexIdentifier( + did, + [DockDIDQualifier, DockDIDMethodKeyQualifier], + DockDIDByteSize +); + describe('DID utilities', () => { test('On input as 40 byte hex, validateDockDIDIdentifier throws error', () => { expect(() => validateDockDIDHexIdentifier(randomAsHex(40))).toThrow(/DID identifier must be 32 bytes/); @@ -20,48 +25,48 @@ describe('DID utilities', () => { expect(() => validateDockDIDHexIdentifier(randomAsHex(32))).not.toThrow(); }); - test('On input as 33 byte hex, getHexIdentifierFromDID throws error', () => { + test('On input as 33 byte hex, hexDid throws error', () => { const hex = randomAsHex(33); - expect(() => getHexIdentifierFromDID(hex)).toThrow(/Invalid hex/); + expect(() => hexDid(hex)).toThrow(/Invalid hex/); }); - test('On input as 32 byte hex, getHexIdentifierFromDID returns the input', () => { + test('On input as 32 byte hex, hexDid returns the input', () => { const hex = randomAsHex(32); - expect(getHexIdentifierFromDID(hex)).toBe(hex); + expect(hexDid(hex)).toBe(hex); }); - test('On input valid SS58 but without qualifier, getHexIdentifierFromDID throws error', () => { + test('On input valid SS58 but without qualifier, hexDid throws error', () => { const hex = randomAsHex(32); const id = encodeAddress(hex); // Without the qualifier, the function tries to parse as hex - expect(() => getHexIdentifierFromDID(id)).toThrow(/Invalid hex/); + expect(() => hexDid(id)).toThrow(/Invalid hex/); }); - test('On input invalid SS58 but with qualifier, getHexIdentifierFromDID throws error', () => { + test('On input invalid SS58 but with qualifier, hexDid throws error', () => { const did = `${DockDIDQualifier}oO12`; // Without the qualifier, the function tries to parse as hex - expect(() => getHexIdentifierFromDID(did)).toThrow(/Invalid SS58/); + expect(() => hexDid(did)).toThrow(/Invalid SS58/); }); - test('On input fully qualified Dock DID, getHexIdentifierFromDID returns valid hex representation', () => { + test('On input fully qualified Dock DID, hexDid returns valid hex representation', () => { // create a valid DID const hex = randomAsHex(32); const did = `${DockDIDQualifier}${encodeAddress(hex)}`; - expect(getHexIdentifierFromDID(did)).toBe(hex); + expect(hexDid(did)).toBe(hex); }); - test('On input valid SS58 and with qualifier but smaller than 32 bytes, getHexIdentifierFromDID throws error', () => { + test('On input valid SS58 and with qualifier but smaller than 32 bytes, hexDid throws error', () => { const hex = randomAsHex(8); const did = `${DockDIDQualifier}${encodeAddress(hex)}`; // Without the qualifier, the function tries to parse as hex - expect(() => getHexIdentifierFromDID(did)).toThrow(/Invalid SS58/); + expect(() => hexDid(did)).toThrow(/Invalid SS58/); }); - test('On input valid SS58 and with qualifier but larger than 32 bytes, getHexIdentifierFromDID throws error', () => { + test('On input valid SS58 and with qualifier but larger than 32 bytes, hexDid throws error', () => { const ss58 = encodeAddress(randomAsHex(32)); const did = `${DockDIDQualifier}${ss58}${ss58}`; // Without the qualifier, the function tries to parse as hex - expect(() => getHexIdentifierFromDID(did)).toThrow(/Invalid SS58/); + expect(() => hexDid(did)).toThrow(/Invalid SS58/); }); test('On input valid SS58 identifier but smaller than 32 bytes, validateDockDIDSS58Identifier throws error', () => { diff --git a/tutorials/src/tutorial_blobs_schemas.md b/tutorials/src/tutorial_blobs_schemas.md index 04617391c..3dbc89fc6 100644 --- a/tutorials/src/tutorial_blobs_schemas.md +++ b/tutorials/src/tutorial_blobs_schemas.md @@ -31,7 +31,7 @@ const blobStruct = { id: blobId, blob: blobHexOrArray, // Contents of your blob as a hex string or byte array } -const result = await dock.blob.new(blobStruct, signerDid, keyPair, 1, { didModule: dock.didModule }); +const result = await dock.blob.new(blobStruct, signerDid, keypair, { didModule: dock.didModule }); ``` If everything worked properly `result` will indicate a successful transaction. We'll see how to retrieve the blob next. @@ -117,7 +117,7 @@ to be able to use it. That's where the `toBlob` method comes in handy: Writing a Schema to the Dock chain is similar to writing any other Blob. `1` is the key id for the on-chain public key corresponding to `keyPair` ```javascript > const formattedBlob = myNewSchema.toBlob(dockDID); -> await myNewSchema.writeToChain(dock, dockDID, keyPair, 1); +> await myNewSchema.writeToChain(dock, dockDID, keypair); ``` ### Reading a Schema from the Dock chain diff --git a/tutorials/src/tutorial_did.md b/tutorials/src/tutorial_did.md index 1c63411d9..2d07c3c2a 100644 --- a/tutorials/src/tutorial_did.md +++ b/tutorials/src/tutorial_did.md @@ -127,7 +127,7 @@ which 1 is greater than the last used index. Key indices start from 1. In the arguments, the first `did` specifies that a key must be added to DID `did` and the second `did` specifies that DID `did` is signing the payload The `1` below is for the key index. ```js - dock.did.addKeys([newDidKey], did, did, currentPair, 1, undefined, false); + dock.did.addKeys([newDidKey], did, did, currentpair, undefined, false); ``` ## Removing an existing DID from chain @@ -139,7 +139,7 @@ A DID can be removed from the chain by sending the corresponding message signed ``` 1. Now send the message with the signature to the chain in a transaction ```js - dock.did.remove(did, did, pair, 1) + dock.did.remove(did, did, pair) ``` For more details see example in `examples/dock-did.js` or the integration tests. diff --git a/tutorials/src/tutorial_revocation.md b/tutorials/src/tutorial_revocation.md index 1bb116401..c76ed4cb6 100644 --- a/tutorials/src/tutorial_revocation.md +++ b/tutorials/src/tutorial_revocation.md @@ -43,7 +43,7 @@ Now get the registry id, `registryId` and the revocation id (the hash of credent Revoking an already revoked credential has no effect. ```js -await dock.revocation.revokeCredentialWithOneOfPolicy(registryId, revokeId, ownerDID, ownerKeypair, 1, {didModule: dock.did}); +await dock.revocation.revokeCredentialWithOneOfPolicy(registryId, revokeId, ownerDID, ownerKeypair, {didModule: dock.did}); ``` Revoking multiple ids in a single transaction is possible but with a lower level method `dock.revocation.revoke`. See tests for its usage @@ -54,7 +54,7 @@ Get the registry id, `registryId` and the revocation id to undo, `revokeId` and Unrevoking an unrevoked credential has no effect. ```js -await dock.revocation.unrevokeCredentialWithOneOfPolicy(registryId, revokeId, ownerDID, ownerKeypair, 1, {didModule: dock.did}); +await dock.revocation.unrevokeCredentialWithOneOfPolicy(registryId, revokeId, ownerDID, ownerKeypair, {didModule: dock.did}); ``` Undoing revocation for multiple ids in a single transaction is possible but with a lower level method `dock.revocation.unrevoke`. See tests for its usage @@ -72,5 +72,5 @@ To get the details of the registry like policy, add-only status and block number A registry can be deleted leading to all the corresponding revocation ids being deleted as well. This requires the signature from owner like other updates. Use the `dock.revocation.removeRegistry` method to remove a registry. ```js -await dock.revocation.removeRegistryWithOneOfPolicy(registryId, ownerDID, ownerKeypair, 1, {didModule: dock.did}, false); +await dock.revocation.removeRegistryWithOneOfPolicy(registryId, ownerDID, ownerKeypair, {didModule: dock.did}, false); ``` From 92706463fe5f0e882510047daad3b17578441669 Mon Sep 17 00:00:00 2001 From: olegnn Date: Tue, 12 Dec 2023 14:31:02 +0400 Subject: [PATCH 03/32] fmt and tweaks --- src/dock-api.js | 4 +- src/modules/WithParamsAndPublicKeys.js | 1 - src/modules/bbs-plus.js | 1 - src/modules/bbs.js | 1 - src/modules/did/did.js | 275 +++++++++--------- src/modules/did/offchain-did-doc-ref.js | 8 +- src/modules/offchain-signatures.js | 1 - src/modules/ps.js | 1 - src/modules/revocation.js | 1 - src/modules/schema.js | 1 - src/modules/status-list-credential.js | 1 - src/modules/trust-registry.js | 26 +- .../status-list2021-credential.js | 48 +-- src/utils/codec.js | 25 +- src/utils/did.js | 53 ++-- src/utils/misc.js | 36 +-- src/utils/revocation/one-of-policy.js | 2 +- 17 files changed, 233 insertions(+), 252 deletions(-) diff --git a/src/dock-api.js b/src/dock-api.js index e9a1a0bc6..7dc9956dc 100644 --- a/src/dock-api.js +++ b/src/dock-api.js @@ -145,7 +145,7 @@ export default class DockAPI { ); this.trustRegistryModule = new TrustRegistryModule( this.api, - this.signAndSend.bind(this) + this.signAndSend.bind(this), ); this.statusListCredentialModule = new StatusListCredentialModule( this.api, @@ -375,7 +375,7 @@ export default class DockAPI { return this.statusListCredentialModule; } - /** + /** * Gets the SDK's TrustRegistryModule module * @return {TrustRegistryModule} The module to use */ diff --git a/src/modules/WithParamsAndPublicKeys.js b/src/modules/WithParamsAndPublicKeys.js index 12f47158f..37eba5c05 100644 --- a/src/modules/WithParamsAndPublicKeys.js +++ b/src/modules/WithParamsAndPublicKeys.js @@ -9,7 +9,6 @@ import { getDidNonce } from '../utils/misc'; * This logic is common in offchain signatures modules and accumulator */ export default class WithParamsAndPublicKeys { - /** * Builds module-specific params from the provided value. */ diff --git a/src/modules/bbs-plus.js b/src/modules/bbs-plus.js index 62fbb9545..e4435af7e 100644 --- a/src/modules/bbs-plus.js +++ b/src/modules/bbs-plus.js @@ -6,7 +6,6 @@ import BBSPlusParams from '../offchain-signatures/params/bbs-plus'; /** Class to write `BBS+` parameters and keys on chain */ export default class BBSPlusModule extends OffchainSignaturesModule { - /** * Builds `BBS+` params from the provided value. */ diff --git a/src/modules/bbs.js b/src/modules/bbs.js index 0a4a657ca..f823486a7 100644 --- a/src/modules/bbs.js +++ b/src/modules/bbs.js @@ -6,7 +6,6 @@ import BBSParams from '../offchain-signatures/params/bbs'; /** Class to write `BBS` parameters and keys on chain */ export default class BBSModule extends OffchainSignaturesModule { - /** * Builds `BBS` params from the provided value. */ diff --git a/src/modules/did/did.js b/src/modules/did/did.js index f9835e4d1..1f726c28f 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -1,7 +1,7 @@ -import { encodeAddress } from "@polkadot/util-crypto"; -import { u8aToString, hexToU8a, u8aToHex } from "@polkadot/util"; -import { BTreeSet } from "@polkadot/types"; -import b58 from "bs58"; +import { encodeAddress } from '@polkadot/util-crypto'; +import { u8aToString, hexToU8a, u8aToHex } from '@polkadot/util'; +import { BTreeSet } from '@polkadot/types'; +import b58 from 'bs58'; import { typedHexDID, DockDIDQualifier, @@ -11,10 +11,10 @@ import { NoOffchainDIDError, createDidSig, DockDIDMethodKeyQualifier, -} from "../../utils/did"; -import { getStateChange } from "../../utils/misc"; +} from '../../utils/did'; +import { getStateChange } from '../../utils/misc'; -import OffChainDidDocRef from "./offchain-did-doc-ref"; +import OffChainDidDocRef from './offchain-did-doc-ref'; import { PublicKeyEd25519, PublicKeySecp256k1, @@ -22,12 +22,11 @@ import { PublicKeyX25519, DidKey, VerificationRelationship, -} from "../../public-keys"; -import { ServiceEndpointType } from "./service-endpoint"; -import WithParamsAndPublicKeys from "../WithParamsAndPublicKeys"; +} from '../../public-keys'; +import { ServiceEndpointType } from './service-endpoint'; +import WithParamsAndPublicKeys from '../WithParamsAndPublicKeys'; -export const ATTESTS_IRI = - "https://rdf.dock.io/alpha/2021#attestsDocumentContents"; +export const ATTESTS_IRI = 'https://rdf.dock.io/alpha/2021#attestsDocumentContents'; const valuePropOrIdentity = (val) => val.value || val; @@ -67,7 +66,7 @@ class DIDModule { return this.signAndSend( this.createNewOffchainTx(did, didDocRef), waitForFinalization, - params + params, ); } @@ -94,12 +93,12 @@ class DIDModule { did, didDocRef, waitForFinalization = true, - params = {} + params = {}, ) { return this.signAndSend( this.createSetOffchainDidRefTx(did, didDocRef), waitForFinalization, - params + params, ); } @@ -124,7 +123,7 @@ class DIDModule { return this.signAndSend( this.createRemoveOffchainDidTx(did), waitForFinalization, - params + params, ); } @@ -146,7 +145,7 @@ class DIDModule { return this.module.newOnchain( hexId, didKeys.map((d) => d.toJSON()), - cnts + cnts, ); } @@ -164,12 +163,12 @@ class DIDModule { didKeys, controllers, waitForFinalization = true, - params = {} + params = {}, ) { return this.signAndSend( this.createNewOnchainTx(did, didKeys, controllers), waitForFinalization, - params + params, ); } @@ -188,7 +187,7 @@ class DIDModule { targetDid, signerDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { const targetHexDid = typedHexDID(this.api, targetDid).asDid; const signerHexDid = typedHexDID(this.api, signerDid); @@ -197,7 +196,7 @@ class DIDModule { targetHexDid, signerHexDid, signingKeyRef, - nonce + nonce, ); return this.module.addKeys(addKeys, signature); } @@ -221,7 +220,7 @@ class DIDModule { signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {} + params = {}, ) { return this.signAndSend( await this.createAddKeysTx( @@ -229,10 +228,10 @@ class DIDModule { targetDid, signerDid, signingKeyRef, - nonce + nonce, ), waitForFinalization, - params + params, ); } @@ -251,7 +250,7 @@ class DIDModule { targetDid, signerDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { const targetHexDid = typedHexDID(this.api, targetDid).asDid; const signerHexDid = typedHexDID(this.api, signerDid); @@ -260,7 +259,7 @@ class DIDModule { targetHexDid, signerHexDid, signingKeyRef, - nonce + nonce, ); return this.module.addControllers(addControllers, signature); } @@ -284,14 +283,14 @@ class DIDModule { signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {} + params = {}, ) { const tx = await this.createAddControllersTx( controllers, targetDid, signerDid, signingKeyRef, - nonce + nonce, ); return this.signAndSend(tx, waitForFinalization, params); } @@ -315,20 +314,19 @@ class DIDModule { targetDid, signerDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { const targetHexDid = typedHexDID(this.api, targetDid).asDid; const signerHexDid = typedHexDID(this.api, signerDid); - const [addServiceEndpoint, signature] = - await this.createSignedAddServiceEndpoint( - endpointId, - endpointType, - origins, - targetHexDid, - signerHexDid, - signingKeyRef, - nonce - ); + const [addServiceEndpoint, signature] = await this.createSignedAddServiceEndpoint( + endpointId, + endpointType, + origins, + targetHexDid, + signerHexDid, + signingKeyRef, + nonce, + ); return this.module.addServiceEndpoint(addServiceEndpoint, signature); } @@ -355,7 +353,7 @@ class DIDModule { signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {} + params = {}, ) { const tx = await this.createAddServiceEndpointTx( endpointId, @@ -364,7 +362,7 @@ class DIDModule { targetDid, signerDid, signingKeyRef, - nonce + nonce, ); return this.signAndSend(tx, waitForFinalization, params); } @@ -384,7 +382,7 @@ class DIDModule { targetDid, signerDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { const targetHexDid = typedHexDID(this.api, targetDid).asDid; const signerHexDid = typedHexDID(this.api, signerDid); @@ -393,7 +391,7 @@ class DIDModule { targetHexDid, signerHexDid, signingKeyRef, - nonce + nonce, ); return this.module.removeKeys(removeKeys, signature); } @@ -417,14 +415,14 @@ class DIDModule { signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {} + params = {}, ) { const tx = await this.createRemoveKeysTx( keyIds, targetDid, signerDid, signingKeyRef, - nonce + nonce, ); return this.signAndSend(tx, waitForFinalization, params); } @@ -444,18 +442,17 @@ class DIDModule { targetDid, signerDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { const targetHexDid = typedHexDID(this.api, targetDid); const signerHexDid = typedHexDID(this.api, signerDid); - const [removeControllers, signature] = - await this.createSignedRemoveControllers( - controllers, - targetHexDid, - signerHexDid, - signingKeyRef, - nonce - ); + const [removeControllers, signature] = await this.createSignedRemoveControllers( + controllers, + targetHexDid, + signerHexDid, + signingKeyRef, + nonce, + ); return this.module.removeControllers(removeControllers, signature); } @@ -478,14 +475,14 @@ class DIDModule { signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {} + params = {}, ) { const tx = await this.removeControllersTx( controllers, targetDid, signerDid, signingKeyRef, - nonce + nonce, ); return this.signAndSend(tx, waitForFinalization, params); } @@ -505,18 +502,17 @@ class DIDModule { targetDid, signerDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { const targetHexDid = typedHexDID(this.api, targetDid).asDid; const signerHexDid = typedHexDID(this.api, signerDid); - const [removeServiceEndpoint, signature] = - await this.createSignedRemoveServiceEndpoint( - endpointId, - targetHexDid, - signerHexDid, - signingKeyRef, - nonce - ); + const [removeServiceEndpoint, signature] = await this.createSignedRemoveServiceEndpoint( + endpointId, + targetHexDid, + signerHexDid, + signingKeyRef, + nonce, + ); return this.module.removeServiceEndpoint(removeServiceEndpoint, signature); } @@ -539,14 +535,14 @@ class DIDModule { signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {} + params = {}, ) { const tx = await this.createRemoveServiceEndpointTx( endpointId, targetDid, signerDid, signingKeyRef, - nonce + nonce, ); return this.signAndSend(tx, waitForFinalization, params); } @@ -567,7 +563,7 @@ class DIDModule { hexDid, signerHexDid, signingKeyRef, - nonce + nonce, ); return this.module.removeOnchainDid(didRemoval, signature); } @@ -589,13 +585,13 @@ class DIDModule { signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {} + params = {}, ) { const tx = await this.createRemoveTx( targetDid, signerDid, signingKeyRef, - nonce + nonce, ); return this.signAndSend(tx, waitForFinalization, params); } @@ -616,7 +612,7 @@ class DIDModule { iri, hexDid, signingKeyRef, - nonce + nonce, ); return this.api.tx.attest.setClaim(setAttestation, signature); } @@ -638,14 +634,14 @@ class DIDModule { signingKeyRef, nonce = undefined, waitForFinalization = true, - params = {} + params = {}, ) { const attestTx = await this.createSetClaimTx( priority, iri, did, signingKeyRef, - nonce + nonce, ); return this.signAndSend(attestTx, waitForFinalization, params); } @@ -698,21 +694,20 @@ class DIDModule { const attests = await this.getAttests(typedDid); // If given DID was in hex, encode to SS58 and then construct fully qualified DID else the DID was already fully qualified - const id = - did === hexDid ? this.getFullyQualifiedDID(encodeAddress(hexDid)) : did; + const id = did === hexDid ? this.getFullyQualifiedDID(encodeAddress(hexDid)) : did; // Get controllers const controllers = []; if (didDetails.activeControllers > 0) { const cnts = await this.api.query.didModule.didControllers.entries( - hexDid + hexDid, ); cnts.forEach(([key, value]) => { if (value.isSome) { const [controlled, controller] = key.toHuman(); if (controlled !== hexDid) { throw new Error( - `Controlled DID ${controlled[0]} was found to be different than queried DID ${hexDid}` + `Controlled DID ${controlled[0]} was found to be different than queried DID ${hexDid}`, ); } controllers.push(controller); @@ -723,7 +718,7 @@ class DIDModule { // Get service endpoints const serviceEndpoints = []; const sps = await this.api.query.didModule.didServiceEndpoints.entries( - hexDid + hexDid, ); sps.forEach(([key, value]) => { if (value.isSome) { @@ -734,7 +729,7 @@ class DIDModule { const d_ = u8aToHex(d); if (d_ !== hexDid) { throw new Error( - `DID ${d_} was found to be different than queried DID ${hexDid}` + `DID ${d_} was found to be different than queried DID ${hexDid}`, ); } serviceEndpoints.push([spId, sp]); @@ -758,7 +753,7 @@ class DIDModule { const d_ = u8aToHex(d); if (d_ !== hexDid) { throw new Error( - `DID ${d_} was found to be different than queried DID ${hexDid}` + `DID ${d_} was found to be different than queried DID ${hexDid}`, ); } const index = i.toNumber(); @@ -766,16 +761,16 @@ class DIDModule { let publicKeyRaw; let typ; if (pk.isSr25519) { - typ = "Sr25519VerificationKey2020"; + typ = 'Sr25519VerificationKey2020'; publicKeyRaw = valuePropOrIdentity(pk.asSr25519); } else if (pk.isEd25519) { - typ = "Ed25519VerificationKey2018"; + typ = 'Ed25519VerificationKey2018'; publicKeyRaw = valuePropOrIdentity(pk.asEd25519); } else if (pk.isSecp256k1) { - typ = "EcdsaSecp256k1VerificationKey2019"; + typ = 'EcdsaSecp256k1VerificationKey2019'; publicKeyRaw = valuePropOrIdentity(pk.asSecp256k1); } else if (pk.isX25519) { - typ = "X25519KeyAgreementKey2019"; + typ = 'X25519KeyAgreementKey2019'; publicKeyRaw = valuePropOrIdentity(pk.asX25519); } else { throw new Error(`Cannot parse public key ${pk}`); @@ -820,7 +815,7 @@ class DIDModule { } if (this.api.query.offchainSignatures != null) { const resp = await this.api.query.offchainSignatures.publicKeys.multi( - queryKeys + queryKeys, ); let currentIter = 0; for (let r of resp) { @@ -831,23 +826,22 @@ class DIDModule { r = r.unwrap(); if (r.isBbs) { - keyType = "Bls12381BBSVerificationKeyDock2023"; + keyType = 'Bls12381BBSVerificationKeyDock2023'; rawKey = r.asBbs; } else if (r.isBbsPlus) { - keyType = "Bls12381G2VerificationKeyDock2022"; + keyType = 'Bls12381G2VerificationKeyDock2022'; rawKey = r.asBbsPlus; } else if (r.isPs) { - keyType = "Bls12381PSVerificationKeyDock2023"; + keyType = 'Bls12381PSVerificationKeyDock2023'; rawKey = r.asPs; } // Don't care about signature params for now - const pkObj = - WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse( - rawKey - ); - if (pkObj.curveType !== "Bls12381") { + const pkObj = WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse( + rawKey, + ); + if (pkObj.curveType !== 'Bls12381') { throw new Error( - `Curve type should have been Bls12381 but was ${pkObj.curveType}` + `Curve type should have been Bls12381 but was ${pkObj.curveType}`, ); } const keyIndex = queryKeys[currentIter][1]; @@ -858,23 +852,22 @@ class DIDModule { } } else { const resp = await this.api.query.bbsPlus.bbsPlusKeys.multi( - queryKeys + queryKeys, ); let currentIter = 0; for (const r of resp) { // The gaps in `keyId` might correspond to removed keys if (r.isSome) { - const keyType = "Bls12381G2VerificationKeyDock2022"; + const keyType = 'Bls12381G2VerificationKeyDock2022'; const rawKey = r.unwrap(); // Don't care about signature params for now - const pkObj = - WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse( - rawKey - ); - if (pkObj.curveType !== "Bls12381") { + const pkObj = WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse( + rawKey, + ); + if (pkObj.curveType !== 'Bls12381') { throw new Error( - `Curve type should have been Bls12381 but was ${pkObj.curveType}` + `Curve type should have been Bls12381 but was ${pkObj.curveType}`, ); } const keyIndex = queryKeys[currentIter][1]; @@ -906,13 +899,11 @@ class DIDModule { // Construct document const document = { - "@context": ["https://www.w3.org/ns/did/v1"], + '@context': ['https://www.w3.org/ns/did/v1'], id, - controller: [...controllers].map((c) => - c.Did - ? this.getFullyQualifiedDID(encodeAddress(c.Did)) - : this.getFullyQualifiedDIDMethodKey(encodeAddress(c.DidMethodKey)) - ), + controller: [...controllers].map((c) => (c.Did + ? this.getFullyQualifiedDID(encodeAddress(c.Did)) + : this.getFullyQualifiedDIDMethodKey(encodeAddress(c.DidMethodKey)))), publicKey: verificationMethod, }; @@ -935,12 +926,12 @@ class DIDModule { const spType = sp.types.toNumber(); if (spType !== 1) { throw new Error( - `Only "LinkedDomains" supported as service endpoint type for now but found ${spType}` + `Only "LinkedDomains" supported as service endpoint type for now but found ${spType}`, ); } return { id: decoder.decode(spId), - type: "LinkedDomains", + type: 'LinkedDomains', serviceEndpoint: sp.origins.map((o) => decoder.decode(o)), }; }); @@ -1038,7 +1029,7 @@ class DIDModule { } else if (did.isDidMethodKey) { return (await this.getDidMethodKeyDetail(did.asDidMethodKey)).nonce; } else { - throw new Error("Invalid DID provided"); + throw new Error('Invalid DID provided'); } } @@ -1070,26 +1061,26 @@ class DIDModule { let publicKey; if (pk.isSr25519) { publicKey = new PublicKeySr25519( - u8aToHex(valuePropOrIdentity(pk.asSr25519)) + u8aToHex(valuePropOrIdentity(pk.asSr25519)), ); } else if (pk.isEd25519) { publicKey = new PublicKeyEd25519( - u8aToHex(valuePropOrIdentity(pk.asEd25519)) + u8aToHex(valuePropOrIdentity(pk.asEd25519)), ); } else if (pk.isSecp256k1) { publicKey = new PublicKeySecp256k1( - u8aToHex(valuePropOrIdentity(pk.asSecp256k1)) + u8aToHex(valuePropOrIdentity(pk.asSecp256k1)), ); } else if (pk.isX25519) { publicKey = new PublicKeyX25519( - u8aToHex(valuePropOrIdentity(pk.asX25519)) + u8aToHex(valuePropOrIdentity(pk.asX25519)), ); } else { throw new Error(`Cannot parse public key ${pk}`); } return new DidKey( publicKey, - new VerificationRelationship(resp.verRels.toNumber()) + new VerificationRelationship(resp.verRels.toNumber()), ); } @@ -1104,7 +1095,7 @@ class DIDModule { const controllerDid = typedHexDID(this.api, controller); const resp = await this.api.query.didModule.didControllers( controlledDid, - controllerDid + controllerDid, ); return resp.isSome; } @@ -1119,11 +1110,11 @@ class DIDModule { const hexId = typedHexDID(this.api, did).asDid; let resp = await this.api.query.didModule.didServiceEndpoints( hexId, - endpointId + endpointId, ); if (resp.isNone) { throw new Error( - `No service endpoint found for did ${did} and with id ${endpointId}` + `No service endpoint found for did ${did} and with id ${endpointId}`, ); } resp = resp.unwrap(); @@ -1138,7 +1129,7 @@ class DIDModule { did, controllerDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign @@ -1158,7 +1149,7 @@ class DIDModule { hexDid, controllerHexDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign @@ -1170,8 +1161,7 @@ class DIDModule { cnts.add(typedHexDID(this.api, c)); }); const addControllers = { did: hexDid, controllers: cnts, nonce }; - const serializedAddControllers = - this.getSerializedAddControllers(addControllers); + const serializedAddControllers = this.getSerializedAddControllers(addControllers); const signature = signingKeyRef.sign(serializedAddControllers); const didSig = createDidSig(controllerHexDid, signingKeyRef, signature); return [addControllers, didSig]; @@ -1184,7 +1174,7 @@ class DIDModule { hexDid, controllerHexDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign @@ -1198,8 +1188,7 @@ class DIDModule { endpoint, nonce, }; - const serializedServiceEndpoint = - this.getSerializedAddServiceEndpoint(addServiceEndpoint); + const serializedServiceEndpoint = this.getSerializedAddServiceEndpoint(addServiceEndpoint); const signature = signingKeyRef.sign(serializedServiceEndpoint); const didSig = createDidSig(controllerHexDid, signingKeyRef, signature); return [addServiceEndpoint, didSig]; @@ -1210,7 +1199,7 @@ class DIDModule { did, controllerDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { const hexDid = typedHexDID(this.api, did).asDid; const controllerHexDid = typedHexDID(this.api, controllerDid); @@ -1236,7 +1225,7 @@ class DIDModule { did, controllerDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { const hexDid = typedHexDID(this.api, did).asDid; const controllerHexDid = typedHexDID(this.api, controllerDid); @@ -1252,8 +1241,7 @@ class DIDModule { }); const removeControllers = { did: hexDid, controllers: cnts, nonce }; - const serializedRemoveControllers = - this.getSerializedRemoveControllers(removeControllers); + const serializedRemoveControllers = this.getSerializedRemoveControllers(removeControllers); const signature = signingKeyRef.sign(serializedRemoveControllers); const didSig = createDidSig(controllerHexDid, signingKeyRef, signature); return [removeControllers, didSig]; @@ -1264,7 +1252,7 @@ class DIDModule { hexDid, controllerHexDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign @@ -1272,8 +1260,7 @@ class DIDModule { } const removeServiceEndpoint = { did: hexDid, id: endpointId, nonce }; - const serializedRemoveServiceEndpoint = - this.getSerializedRemoveServiceEndpoint(removeServiceEndpoint); + const serializedRemoveServiceEndpoint = this.getSerializedRemoveServiceEndpoint(removeServiceEndpoint); const signature = signingKeyRef.sign(serializedRemoveServiceEndpoint); const didSig = createDidSig(controllerHexDid, signingKeyRef, signature); return [removeServiceEndpoint, didSig]; @@ -1283,7 +1270,7 @@ class DIDModule { did, controllerDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign @@ -1302,7 +1289,7 @@ class DIDModule { iri, hexDid, signingKeyRef, - nonce = undefined + nonce = undefined, ) { if (nonce === undefined) { // eslint-disable-next-line no-param-reassign @@ -1327,30 +1314,30 @@ class DIDModule { * @returns {Array} An array of Uint8 */ getSerializedAddKeys(addKeys) { - return getStateChange(this.api, "AddKeys", addKeys); + return getStateChange(this.api, 'AddKeys', addKeys); } getSerializedAddControllers(addControllers) { - return getStateChange(this.api, "AddControllers", addControllers); + return getStateChange(this.api, 'AddControllers', addControllers); } getSerializedAddServiceEndpoint(addServiceEndpoint) { - return getStateChange(this.api, "AddServiceEndpoint", addServiceEndpoint); + return getStateChange(this.api, 'AddServiceEndpoint', addServiceEndpoint); } getSerializedRemoveKeys(removeKeys) { - return getStateChange(this.api, "RemoveKeys", removeKeys); + return getStateChange(this.api, 'RemoveKeys', removeKeys); } getSerializedRemoveControllers(removeControllers) { - return getStateChange(this.api, "RemoveControllers", removeControllers); + return getStateChange(this.api, 'RemoveControllers', removeControllers); } getSerializedRemoveServiceEndpoint(removeServiceEndpoint) { return getStateChange( this.api, - "RemoveServiceEndpoint", - removeServiceEndpoint + 'RemoveServiceEndpoint', + removeServiceEndpoint, ); } @@ -1360,7 +1347,7 @@ class DIDModule { * @returns {Array} An array of Uint8 */ getSerializedDidRemoval(didRemoval) { - return getStateChange(this.api, "DidRemoval", didRemoval); + return getStateChange(this.api, 'DidRemoval', didRemoval); } /** @@ -1369,7 +1356,7 @@ class DIDModule { * @returns {Array} An array of Uint8 */ getSerializedAttestation(setAttestation) { - return getStateChange(this.api, "SetAttestationClaim", setAttestation); + return getStateChange(this.api, 'SetAttestationClaim', setAttestation); } } diff --git a/src/modules/did/offchain-did-doc-ref.js b/src/modules/did/offchain-did-doc-ref.js index b100f519e..0b42fad47 100644 --- a/src/modules/did/offchain-did-doc-ref.js +++ b/src/modules/did/offchain-did-doc-ref.js @@ -1,4 +1,4 @@ -export const FORMATS = new Set(["CID", "URL", "Custom"]); +export const FORMATS = new Set(['CID', 'URL', 'Custom']); /** * An off-chain DID Doc reference stored on chain. The reference may be @@ -16,14 +16,14 @@ export default class OffChainDidDocRef { } static cid(bytes) { - return new this("CID", bytes); + return new this('CID', bytes); } static url(bytes) { - return new this("URL", bytes); + return new this('URL', bytes); } static custom(bytes) { - return new this("Custom", bytes); + return new this('Custom', bytes); } } diff --git a/src/modules/offchain-signatures.js b/src/modules/offchain-signatures.js index b895d1cca..9001d1f58 100644 --- a/src/modules/offchain-signatures.js +++ b/src/modules/offchain-signatures.js @@ -2,7 +2,6 @@ import { getDidNonce, - getSignatureFromKeyringPair, getStateChange, } from '../utils/misc'; import WithParamsAndPublicKeys from './WithParamsAndPublicKeys'; diff --git a/src/modules/ps.js b/src/modules/ps.js index f9da5c3e8..7ec4da97f 100644 --- a/src/modules/ps.js +++ b/src/modules/ps.js @@ -6,7 +6,6 @@ import PSParams from '../offchain-signatures/params/ps'; /** Class to write `Pointcheval-Sanders` parameters and keys on chain */ export default class PSModule extends OffchainSignaturesModule { - /** * Builds `Pointcheval-Sanders` params from the provided value. */ diff --git a/src/modules/revocation.js b/src/modules/revocation.js index ffa4a4438..932569517 100644 --- a/src/modules/revocation.js +++ b/src/modules/revocation.js @@ -1,6 +1,5 @@ import { getDidNonce, - getSignatureFromKeyringPair, getStateChange, } from '../utils/misc'; diff --git a/src/modules/schema.js b/src/modules/schema.js index 8af7dd8b6..0c4827838 100644 --- a/src/modules/schema.js +++ b/src/modules/schema.js @@ -3,7 +3,6 @@ import { validate } from 'jsonschema'; import axios from 'axios'; import { hexDIDToQualified } from '../utils/did'; -import { getSignatureFromKeyringPair } from '../utils/misc'; import { createNewDockBlobId, diff --git a/src/modules/status-list-credential.js b/src/modules/status-list-credential.js index 07927cc11..2240b9dd9 100644 --- a/src/modules/status-list-credential.js +++ b/src/modules/status-list-credential.js @@ -1,7 +1,6 @@ import StatusList2021Credential from '../status-list-credential/status-list2021-credential'; import { getDidNonce, - getSignatureFromKeyringPair, getStateChange, } from '../utils/misc'; diff --git a/src/modules/trust-registry.js b/src/modules/trust-registry.js index 61216c37f..5f4407b12 100644 --- a/src/modules/trust-registry.js +++ b/src/modules/trust-registry.js @@ -1,4 +1,4 @@ -import { typedHexDID } from "../utils/did"; +import { typedHexDID } from '../utils/did'; import { getDidNonce } from '../utils/misc'; /** @@ -35,20 +35,20 @@ export default class TrustRegistryModule { signingKeyRef, { nonce = undefined, didModule = undefined } = {}, waitForFinalization = true, - params = {} + params = {}, ) { const convenerHexDid = typedHexDID(this.api, convenerDid); - nonce ??= await getDidNonce(convenerHexDid, nonce, didModule); + const lastNonce = nonce ?? await getDidNonce(convenerHexDid, nonce, didModule); return this.signAndSend( convenerHexDid.changeState( this.module.initTrustRegistry.bind(this.module), 'InitTrustRegistry', - { registryId, name, nonce }, + { registryId, name, nonce: lastNonce }, signingKeyRef, ), waitForFinalization, - params + params, ); } @@ -70,20 +70,20 @@ export default class TrustRegistryModule { signingKeyRef, { nonce = undefined, didModule = undefined } = {}, waitForFinalization = true, - params = {} + params = {}, ) { const convenerHexDid = typedHexDID(this.api, convenerDid); - nonce ??= await getDidNonce(convenerHexDid, nonce, didModule); + const lastNonce = nonce ?? await getDidNonce(convenerHexDid, nonce, didModule); return this.signAndSend( convenerHexDid.changeState( this.module.addSchemaMetadata, 'AddSchemaMetadata', - { registryId, schemas, nonce }, + { registryId, schemas, nonce: lastNonce }, signingKeyRef, ), waitForFinalization, - params + params, ); } @@ -105,20 +105,20 @@ export default class TrustRegistryModule { signingKeyRef, { nonce = undefined, didModule = undefined } = {}, waitForFinalization = true, - params = {} + params = {}, ) { const convenerOrIssuerOrVerifierHexDid = typedHexDID(this.api, convenerOrIssuerOrVerifierDid); - nonce ??= await getDidNonce(convenerOrIssuerOrVerifierHexDid, nonce, didModule); + const lastNonce = nonce ?? await getDidNonce(convenerOrIssuerOrVerifierHexDid, nonce, didModule); return this.signAndSend( convenerOrIssuerOrVerifierHexDid.changeState( this.module.updateSchemaMetadata, 'UpdateSchemaMetadata', - { registryId, schemas, nonce }, + { registryId, schemas, nonce: lastNonce }, signingKeyRef, ), waitForFinalization, - params + params, ); } } diff --git a/src/status-list-credential/status-list2021-credential.js b/src/status-list-credential/status-list2021-credential.js index e19b2f653..0f31dd1ca 100644 --- a/src/status-list-credential/status-list2021-credential.js +++ b/src/status-list-credential/status-list2021-credential.js @@ -3,12 +3,12 @@ import { createList, createCredential, StatusList, // eslint-disable-line -} from "@digitalbazaar/vc-status-list"; -import { u8aToHex, u8aToU8a } from "@polkadot/util"; -import { gzip, ungzip } from "pako"; -import { DockStatusList2021Qualifier } from "../utils/vc/constants"; -import VerifiableCredential from "../verifiable-credential"; -import { ensureStatusListId } from "../utils/type-helpers"; +} from '@digitalbazaar/vc-status-list'; +import { u8aToHex, u8aToU8a } from '@polkadot/util'; +import { gzip, ungzip } from 'pako'; +import { DockStatusList2021Qualifier } from '../utils/vc/constants'; +import VerifiableCredential from '../verifiable-credential'; +import { ensureStatusListId } from '../utils/type-helpers'; import { KeyDoc } from "../utils/vc/helpers"; // eslint-disable-line /** @@ -26,11 +26,11 @@ export default class StatusList2021Credential extends VerifiableCredential { let cachedDecodedStatusList; // Caches decoded status list. - Object.defineProperty(this, "decodedStatusList", { + Object.defineProperty(this, 'decodedStatusList', { value: function decodedStatusList() { if ( - encodedStatusList === this.credentialSubject.encodedList && - cachedDecodedStatusList !== void 0 + encodedStatusList === this.credentialSubject.encodedList + && cachedDecodedStatusList !== void 0 ) { return cachedDecodedStatusList; } else { @@ -69,7 +69,7 @@ export default class StatusList2021Credential extends VerifiableCredential { static async create( keyDoc, id, - { statusPurpose = "revocation", length = 1e4, revokeIndices = [] } = {} + { statusPurpose = 'revocation', length = 1e4, revokeIndices = [] } = {}, ) { const statusList = await createList({ length }); this.updateStatusList(statusPurpose, statusList, revokeIndices); @@ -105,7 +105,7 @@ export default class StatusList2021Credential extends VerifiableCredential { this.credentialSubject.statusPurpose, statusList, revokeIndices, - unsuspendIndices + unsuspendIndices, ); this.credentialSubject.encodedList = await statusList.encode(); @@ -150,7 +150,7 @@ export default class StatusList2021Credential extends VerifiableCredential { */ static fromBytes(bytes) { const gzipBufferCred = Buffer.from(u8aToU8a(bytes)); - const stringifiedCred = ungzip(gzipBufferCred, { to: "string" }); + const stringifiedCred = ungzip(gzipBufferCred, { to: 'string' }); const parsedCred = JSON.parse(stringifiedCred); return this.fromJSON(parsedCred); @@ -206,24 +206,24 @@ export default class StatusList2021Credential extends VerifiableCredential { validate() { const { credentialSubject } = this; - if (!credentialSubject) throw new Error("Missing `credentialSubject`"); + if (!credentialSubject) throw new Error('Missing `credentialSubject`'); if (!this.constructor.statusPurposes.has(credentialSubject.statusPurpose)) { throw new Error( `Invalid \`statusPurpose\`, expected one of \`${[ ...this.constructor.statusPurposes, - ].join(", ")}\`` + ].join(', ')}\``, ); } - if (typeof credentialSubject.id !== "string" || !credentialSubject.id) { - throw new Error("Missing `credentialSubject.id`"); + if (typeof credentialSubject.id !== 'string' || !credentialSubject.id) { + throw new Error('Missing `credentialSubject.id`'); } - if (credentialSubject.type !== "StatusList2021") { + if (credentialSubject.type !== 'StatusList2021') { throw new Error( - "`credentialSubject.type` must be set to `StatusList2021`" + '`credentialSubject.type` must be set to `StatusList2021`', ); } if (!credentialSubject.encodedList) { - throw new Error("`credentialSubject.encodedList` must be present"); + throw new Error('`credentialSubject.encodedList` must be present'); } } @@ -244,19 +244,19 @@ export default class StatusList2021Credential extends VerifiableCredential { statusPurpose, statusList, revokeIndices = [], - unsuspendIndices = [] + unsuspendIndices = [], ) { const unsuspendIndiceSet = new Set(unsuspendIndices); - if (statusPurpose !== "suspension" && unsuspendIndiceSet.size > 0) { + if (statusPurpose !== 'suspension' && unsuspendIndiceSet.size > 0) { throw new Error( - `Can't unsuspend indices for credential with \`statusPurpose\` = \`${statusPurpose}\`, it's only possible with \`statusPurpose\` = \`suspension\`` + `Can't unsuspend indices for credential with \`statusPurpose\` = \`${statusPurpose}\`, it's only possible with \`statusPurpose\` = \`suspension\``, ); } for (const idx of revokeIndices) { if (unsuspendIndiceSet.has(idx)) { throw new Error( - `Index \`${idx}\` appears in both revoke and unsuspend sets` + `Index \`${idx}\` appears in both revoke and unsuspend sets`, ); } @@ -271,5 +271,5 @@ export default class StatusList2021Credential extends VerifiableCredential { /** * Allowed status purposes for this credential type. */ -StatusList2021Credential.statusPurposes = new Set(["revocation", "suspension"]); +StatusList2021Credential.statusPurposes = new Set(['revocation', 'suspension']); StatusList2021Credential.qualifier = DockStatusList2021Qualifier; diff --git a/src/utils/codec.js b/src/utils/codec.js index 6cffa323f..8cbd293ad 100644 --- a/src/utils/codec.js +++ b/src/utils/codec.js @@ -1,6 +1,5 @@ -import { u8aToHex } from "@polkadot/util"; -import { decodeAddress, encodeAddress } from "@polkadot/util-crypto"; -import { DockDIDQualifier } from "../../dist/utils/did.cjs"; +import { u8aToHex } from '@polkadot/util'; +import { decodeAddress, encodeAddress } from '@polkadot/util-crypto'; /** * Check if the given input is hexadecimal or not. Optionally checks for the byte size of the hex. Case-insensitive on hex chars @@ -9,7 +8,7 @@ import { DockDIDQualifier } from "../../dist/utils/did.cjs"; * @return {Boolean} True if hex (with given size) else false */ export function isHexWithGivenByteSize(value, byteSize = undefined) { - if (typeof value !== "string") { + if (typeof value !== 'string') { return false; } const match = value.match(/^0x([0-9a-f]+$)/i); @@ -38,7 +37,7 @@ export function getHexIdentifier(id, qualifiers, byteSize) { const hex = u8aToHex(decodeAddress(ss58Did)); // 2 characters for `0x` and 2*byte size of ID if (hex.length !== 2 + 2 * byteSize) { - throw new Error("Unexpected byte size"); + throw new Error('Unexpected byte size'); } return hex; } catch (e) { @@ -50,8 +49,8 @@ export function getHexIdentifier(id, qualifiers, byteSize) { try { // Check if hex and of correct size and return the hex value if successful. if (!isHexWithGivenByteSize(id, byteSize)) { - throw new Error(`Expected ${byteSize}-byte sequence`) - }; + throw new Error(`Expected ${byteSize}-byte sequence`); + } return id; } catch (error) { @@ -65,17 +64,17 @@ export function getHexIdentifier(id, qualifiers, byteSize) { * @param addr - address to convert * @param network - the network to use, allowed values are `main`, `test` and `dev` corresponding to mainnet, testnet and dev node */ -export function asDockAddress(addr, network = "test") { +export function asDockAddress(addr, network = 'test') { switch (network) { - case "dev": + case 'dev': return encodeAddress(addr, 42); - case "test": + case 'test': return encodeAddress(addr, 21); - case "main": + case 'main': return encodeAddress(addr, 22); default: throw new Error( - `Network can be either test or main or dev but was passed as ${network}` + `Network can be either test or main or dev but was passed as ${network}`, ); } } @@ -91,7 +90,7 @@ export function normalizeToHex(data) { } else if (isHexWithGivenByteSize(data)) { hex = data; } else { - throw new Error("Require a hex string or a byte array"); + throw new Error('Require a hex string or a byte array'); } return hex; } diff --git a/src/utils/did.js b/src/utils/did.js index b3899a94a..c34d246fc 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -2,10 +2,10 @@ // Import some utils from Polkadot JS // eslint-disable-next-line max-classes-per-file -import { randomAsHex, encodeAddress } from "@polkadot/util-crypto"; -import { isHexWithGivenByteSize, getHexIdentifier } from "./codec"; -import { PublicKeyEd25519, PublicKeySecp256k1 } from "../public-keys"; -import { u8aToHex } from "@polkadot/util"; +import { randomAsHex, encodeAddress } from '@polkadot/util-crypto'; +import { u8aToHex } from '@polkadot/util'; +import { isHexWithGivenByteSize, getHexIdentifier } from './codec'; +import { PublicKeyEd25519, PublicKeySecp256k1 } from '../public-keys'; import { Signature } from "../signatures"; // eslint-disable-line import { PublicKey, VerificationRelationship } from "../public-keys"; // eslint-disable-line @@ -13,9 +13,9 @@ import { getPublicKeyFromKeyringPair, getSignatureFromKeyringPair, getStateChange, -} from "../utils/misc"; +} from './misc'; -export const DockDIDMethod = "dock"; +export const DockDIDMethod = 'dock'; export const DockDIDQualifier = `did:${DockDIDMethod}:`; export const DockDIDMethodKeyQualifier = `did:key:${DockDIDMethod}:`; export const DockDIDByteSize = 32; @@ -35,8 +35,8 @@ export class DidKeypair { } } -const SECP256K1_PUBLIC_KEY_PREFIX = "zQ3"; -const ED_25519_PUBLIC_KEY_PREFIX = "z6Mk"; +const SECP256K1_PUBLIC_KEY_PREFIX = 'zQ3'; +const ED_25519_PUBLIC_KEY_PREFIX = 'z6Mk'; const DockDidMethodKeySecp256k1Prefix = `${DockDIDQualifier}${SECP256K1_PUBLIC_KEY_PREFIX}`; const DockDidMethodKeyEd25519Prefix = `${DockDIDMethodKeyQualifier}${ED_25519_PUBLIC_KEY_PREFIX}`; @@ -47,11 +47,11 @@ export class DockDidOrDidMethodKey { } get asDid() { - throw new Error("Not a `Did`"); + throw new Error('Not a `Did`'); } get asDidMethodKey() { - throw new Error("Not a `DidMethodKey`"); + throw new Error('Not a `DidMethodKey`'); } get isDid() { @@ -73,7 +73,7 @@ export class DockDidOrDidMethodKey { const signature = this.signStateChange( name, payload, - keyRef + keyRef, ); return method(payload, signature); @@ -133,10 +133,9 @@ export class DockDidMethodKey extends DockDidOrDidMethodKey { export class NoDIDError extends Error { constructor(did) { super(`DID (${did}) does not exist`); - this.name = "NoDIDError"; + this.name = 'NoDIDError'; this.did = did; - this.message = - "A DID document lookup was successful, but the DID in question does not exist. This is different from a network error."; + this.message = 'A DID document lookup was successful, but the DID in question does not exist. This is different from a network error.'; } } @@ -146,10 +145,9 @@ export class NoDIDError extends Error { export class NoOnchainDIDError extends Error { constructor(did) { super(`DID (${did}) is an off-chain DID`); - this.name = "NoOnchainDIDError"; + this.name = 'NoOnchainDIDError'; this.did = did; - this.message = - "The DID exists on chain but is an off-chain DID, meaning the DID document exists off-chain."; + this.message = 'The DID exists on chain but is an off-chain DID, meaning the DID document exists off-chain.'; } } @@ -159,10 +157,9 @@ export class NoOnchainDIDError extends Error { export class NoOffchainDIDError extends Error { constructor(did) { super(`DID (${did}) is an on-chain DID`); - this.name = "NoOffchainDIDError"; + this.name = 'NoOffchainDIDError'; this.did = did; - this.message = - "The DID exists on chain and is an on-chain DID but the lookup was performed for an off-chain DID."; + this.message = 'The DID exists on chain and is an on-chain DID but the lookup was performed for an off-chain DID.'; } } @@ -188,12 +185,13 @@ export function validateDockDIDSS58Identifier(identifier) { const regex = new RegExp(/^[5KL][1-9A-HJ-NP-Za-km-z]{47}$/); const matches = regex.exec(identifier); if (!matches) { - throw new Error("The identifier must be 32 bytes and valid SS58 string"); + throw new Error('The identifier must be 32 bytes and valid SS58 string'); } } /** * Gets the hexadecimal value of the given DID. + * @param {*} api * @param {string} did - The DID can be passed as fully qualified DID like `did:dock:` or * a 32 byte hex string * @return {string} Returns the hexadecimal representation of the DID. @@ -202,7 +200,7 @@ export function typedHexDID(api, did) { const hex = getHexIdentifier( did, [DockDIDQualifier, DockDIDMethodKeyQualifier], - DockDIDByteSize + DockDIDByteSize, ); if (did.startsWith(DockDidMethodKeySecp256k1Prefix)) { @@ -215,13 +213,18 @@ export function typedHexDID(api, did) { } } +/** + * Gets the hexadecimal value of the given DID received from the substrate side. + * @param {string} did - The DID can be passed as fully qualified DID like `did:dock:` or + * a 32 byte hex string + * @return {string} Returns the hexadecimal representation of the DID. + */ export function typedHexDIDFromSubstrate(did) { const hex = getHexIdentifier( u8aToHex(did.isDid ? did.asDid : did.asDidMethodKey), [], - DockDIDByteSize + DockDIDByteSize, ); - throw JSON.stringify({ did }); if (did.isDid) { return new DockDid(hex); @@ -290,7 +293,7 @@ export function createDidSig(did, { keyId }, rawSig) { }; } else { throw new Error( - `Incorrect DID passed: \`${did}\`, expected instance of either \`DockDid\` or \`DockDidMethodKey\`` + `Incorrect DID passed: \`${did}\`, expected instance of either \`DockDid\` or \`DockDidMethodKey\``, ); } } diff --git a/src/utils/misc.js b/src/utils/misc.js index 5f7372686..db5c19c9b 100644 --- a/src/utils/misc.js +++ b/src/utils/misc.js @@ -1,22 +1,22 @@ -import elliptic from "elliptic"; -import { blake2AsHex } from "@polkadot/util-crypto"; +import elliptic from 'elliptic'; +import { blake2AsHex } from '@polkadot/util-crypto'; -import { sha256 } from "js-sha256"; +import { sha256 } from 'js-sha256'; import { PublicKey, PublicKeyEd25519, PublicKeySecp256k1, PublicKeySr25519, // eslint-disable-line -} from "../public-keys"; +} from '../public-keys'; import { Signature, SignatureEd25519, SignatureSecp256k1, SignatureSr25519, // eslint-disable-line -} from "../signatures"; +} from '../signatures'; const EC = elliptic.ec; -const secp256k1Curve = new EC("secp256k1"); +const secp256k1Curve = new EC('secp256k1'); /** // TODO: Error handling when `stateChange` is not registered * Helper function to return bytes of a `StateChange` enum. Updates like key change, DID removal, revocation, etc @@ -26,7 +26,7 @@ const secp256k1Curve = new EC("secp256k1"); * @return {array} An array of Uint8 */ export function getBytesForStateChange(api, stateChange) { - return api.createType("StateChange", stateChange).toU8a(); + return api.createType('StateChange', stateChange).toU8a(); } export function getStateChange(api, name, value) { @@ -69,7 +69,7 @@ export function verifyEcdsaSecp256k1Sig(message, signature, publicKey) { export function verifyEcdsaSecp256k1SigPrehashed( messageHash, signature, - publicKey + publicKey, ) { // Remove the leading `0x` const sigHex = signature.value.slice(2); @@ -79,7 +79,7 @@ export function verifyEcdsaSecp256k1SigPrehashed( const pkHex = publicKey.value.slice(2); // Generate public key object. Not extracting the public key for signature as the verifier // should always know what public key is being used. - const pk = secp256k1Curve.keyFromPublic(pkHex, "hex"); + const pk = secp256k1Curve.keyFromPublic(pkHex, 'hex'); return secp256k1Curve.verify(messageHash, sig, pk); } @@ -95,9 +95,9 @@ export function getKeyPairType(pair) { if (pair.ec && pair.priv) { // elliptic library's pair has `ec`, `priv` and `pub`. There is not a cleaner way to detect that - return "secp256k1"; + return 'secp256k1'; } - throw new Error("Cannot detect key pair type"); + throw new Error('Cannot detect key pair type'); } /** @@ -108,9 +108,9 @@ export function getKeyPairType(pair) { export function getPublicKeyFromKeyringPair(pair) { const type = getKeyPairType(pair); let Cls; - if (type === "ed25519") { + if (type === 'ed25519') { Cls = PublicKeyEd25519; - } else if (type === "sr25519") { + } else if (type === 'sr25519') { Cls = PublicKeySr25519; } else { Cls = PublicKeySecp256k1; @@ -127,9 +127,9 @@ export function getPublicKeyFromKeyringPair(pair) { export function getSignatureFromKeyringPair(pair, message) { const type = getKeyPairType(pair); let Cls; - if (type === "ed25519") { + if (type === 'ed25519') { Cls = SignatureEd25519; - } else if (type === "sr25519") { + } else if (type === 'sr25519') { Cls = SignatureSr25519; } else { Cls = SignatureSecp256k1; @@ -158,7 +158,7 @@ export function getUniqueElementsFromArray(a, filterCallback) { * @returns {string} */ export function encodeExtrinsicAsHash(api, tx) { - return blake2AsHex(api.createType("Call", tx).toU8a()); + return blake2AsHex(api.createType('Call', tx).toU8a()); } /** @@ -172,11 +172,11 @@ export function encodeExtrinsicAsHash(api, tx) { export async function getDidNonce( didOrDidMethodKey, nonce = undefined, - didModule = undefined + didModule = undefined, ) { if (nonce === undefined && didModule === undefined) { throw new Error( - "Provide either nonce or didModule to fetch nonce but none provided" + 'Provide either nonce or didModule to fetch nonce but none provided', ); } if (nonce === undefined) { diff --git a/src/utils/revocation/one-of-policy.js b/src/utils/revocation/one-of-policy.js index ed1dfe689..16ed2b47a 100644 --- a/src/utils/revocation/one-of-policy.js +++ b/src/utils/revocation/one-of-policy.js @@ -26,7 +26,7 @@ export default class OneOfPolicy extends Policy { * @param {string} ownerDID - Owner's DID */ controllerIds() { - const controllerIds = [...this.controllers].map(controller => typedHexDID(null, controller)); + const controllerIds = [...this.controllers].map((controller) => typedHexDID(null, controller)); // Sort the controller ids as the node is expecting sorted ids and keeping ids unsorted is giving a signature // verification error. This is a workaround and is needed for now. It maybe fixed later controllerIds.sort(); From e478e60aabf8ebc456d1aa376f09ba1139f351eb Mon Sep 17 00:00:00 2001 From: olegnn Date: Tue, 12 Dec 2023 22:30:10 +0400 Subject: [PATCH 04/32] Fix `Trust Registry` tests --- .../integration/trust-registry-module.test.js | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js index 81e52de0f..8a68a9a97 100644 --- a/tests/integration/trust-registry-module.test.js +++ b/tests/integration/trust-registry-module.test.js @@ -231,7 +231,7 @@ buildTest("Trust Registry", () => { .sort((a, b) => a.did.localeCompare(b.did)), }); - schemas = new BTreeMap(); + let schemasUpdate = new BTreeMap(); verifiers = new BTreeSet(); verifiers.add(typedHexDID(dock.api, issuerDID)); @@ -246,17 +246,16 @@ buildTest("Trust Registry", () => { issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); - schemas.set(schemaId, { - Set: { - issuers, - verifiers + schemasUpdate.set(schemaId, { + issuers: { + Set: issuers, }, }); await dock.trustRegistry.updateSchemaMetadata( convenerDID, trustRegistryId, - schemas, + schemasUpdate, convenerPair, dock ); @@ -280,26 +279,27 @@ buildTest("Trust Registry", () => { .sort((a, b) => a.did.localeCompare(b.did)), }); - schemas = new BTreeMap(); + schemasUpdate = new BTreeMap(); issuer2Prices = new BTreeMap(); - issuer2Prices.set("A", 60); + issuer2Prices.set("A", 25); + issuer2Prices.set("B", 36); let issuersUpdate = new BTreeMap(); - issuer2Prices.set("A", 75); - issuer2Prices.set("B", 60); - issuersUpdate.set(issuerDID2, issuer2Prices); - schemas.set(schemaId, { - Modify: { - issuers: { - Set: issuersUpdate, - }, + issuersUpdate.set(typedHexDID(dock.api, issuerDID2), { Set: issuer2Prices }); + schemasUpdate.set(schemaId, { + issuers: { + Modify: issuersUpdate, }, }); + issuers = new BTreeMap(); + issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); + issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); + schemas.set(schemaId, { issuers, verifiers: schemas.get(schemaId).verifiers }); await dock.trustRegistry.updateSchemaMetadata( issuerDID2, trustRegistryId, - schemas, + schemasUpdate, issuerPair2, dock ); From ed64db5901da7f8408b37557c722659013fb6a9d Mon Sep 17 00:00:00 2001 From: olegnn Date: Tue, 12 Dec 2023 22:46:40 +0400 Subject: [PATCH 05/32] Tweaks --- src/utils/did.js | 3 +-- src/utils/misc.js | 2 -- tests/integration/did/keys.test.js | 14 +++++++------- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/utils/did.js b/src/utils/did.js index c34d246fc..56c9bcfb7 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -5,10 +5,9 @@ import { randomAsHex, encodeAddress } from '@polkadot/util-crypto'; import { u8aToHex } from '@polkadot/util'; import { isHexWithGivenByteSize, getHexIdentifier } from './codec'; -import { PublicKeyEd25519, PublicKeySecp256k1 } from '../public-keys'; +import { PublicKeyEd25519, PublicKeySecp256k1, PublicKey, VerificationRelationship } from '../public-keys'; import { Signature } from "../signatures"; // eslint-disable-line -import { PublicKey, VerificationRelationship } from "../public-keys"; // eslint-disable-line import { getPublicKeyFromKeyringPair, getSignatureFromKeyringPair, diff --git a/src/utils/misc.js b/src/utils/misc.js index db5c19c9b..6cc5b26a1 100644 --- a/src/utils/misc.js +++ b/src/utils/misc.js @@ -3,13 +3,11 @@ import { blake2AsHex } from '@polkadot/util-crypto'; import { sha256 } from 'js-sha256'; import { - PublicKey, PublicKeyEd25519, PublicKeySecp256k1, PublicKeySr25519, // eslint-disable-line } from '../public-keys'; import { - Signature, SignatureEd25519, SignatureSecp256k1, SignatureSr25519, // eslint-disable-line diff --git a/tests/integration/did/keys.test.js b/tests/integration/did/keys.test.js index 7882d706d..eee6b76dc 100644 --- a/tests/integration/did/keys.test.js +++ b/tests/integration/did/keys.test.js @@ -51,7 +51,7 @@ describe('Key support for DIDs', () => { await dock.did.new(dockDid, [didKey1, didKey2, didKey3], [], false); - const didDetail = await dock.did.getOnchainDidDetail(hexDid); + const didDetail = await dock.did.getOnchainDidDetail(hexDid.asDid); expect(didDetail.lastKeyId).toBe(3); expect(didDetail.activeControllerKeys).toBe(2); expect(didDetail.activeControllers).toBe(1); @@ -113,9 +113,9 @@ describe('Key support for DIDs', () => { const didKey1 = new DidKey(publicKey1, verRels1); const pair = dock.keyring.addFromUri(seed2, null, 'ed25519'); - await dock.did.addKeys([didKey1], dockDid, dockDid, pair, 2); + await dock.did.addKeys([didKey1], dockDid, dockDid, pair); - const didDetail = await dock.did.getOnchainDidDetail(hexDid); + const didDetail = await dock.did.getOnchainDidDetail(hexDid.asDid); expect(didDetail.lastKeyId).toBe(4); expect(didDetail.activeControllerKeys).toBe(3); expect(didDetail.activeControllers).toBe(1); @@ -166,9 +166,9 @@ describe('Key support for DIDs', () => { test('Remove keys from DID', async () => { const pair = generateEcdsaSecp256k1Keypair(seed4); - await dock.did.removeKeys([1, 3], dockDid, dockDid, pair, 4); + await dock.did.removeKeys([1, 3], dockDid, dockDid, pair); - const didDetail = await dock.did.getOnchainDidDetail(hexDid); + const didDetail = await dock.did.getOnchainDidDetail(hexDid.asDid); expect(didDetail.lastKeyId).toBe(4); expect(didDetail.activeControllerKeys).toBe(2); expect(didDetail.activeControllers).toBe(1); @@ -221,8 +221,8 @@ describe('Key support for DIDs', () => { const didKey = new DidKey(publicKey, verRels); const pair = dock.keyring.addFromUri(seed2, null, 'ed25519'); - await dock.did.addKeys([didKey], dockDid, dockDid, pair, 2); - const didDetail = await dock.did.getOnchainDidDetail(hexDid); + await dock.did.addKeys([didKey], dockDid, dockDid, pair); + const didDetail = await dock.did.getOnchainDidDetail(hexDid.asDid); expect(didDetail.lastKeyId).toBe(5); const dk = await dock.did.getDidKey(dockDid, 5); expect(dk.publicKey).toEqual(publicKey); From f14501dd6082a45a9956b2d6773df7637ad2fd11 Mon Sep 17 00:00:00 2001 From: lovesh Date: Wed, 13 Dec 2023 20:03:58 +0530 Subject: [PATCH 06/32] Fix import in test and remove extra argument from helper Signed-off-by: lovesh --- src/utils/did.js | 6 ++++-- tests/unit/did.test.js | 7 ++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/utils/did.js b/src/utils/did.js index 56c9bcfb7..7c3ed69ce 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -5,7 +5,9 @@ import { randomAsHex, encodeAddress } from '@polkadot/util-crypto'; import { u8aToHex } from '@polkadot/util'; import { isHexWithGivenByteSize, getHexIdentifier } from './codec'; -import { PublicKeyEd25519, PublicKeySecp256k1, PublicKey, VerificationRelationship } from '../public-keys'; +import { + PublicKeyEd25519, PublicKeySecp256k1, PublicKey, VerificationRelationship, +} from '../public-keys'; import { Signature } from "../signatures"; // eslint-disable-line import { @@ -207,7 +209,7 @@ export function typedHexDID(api, did) { } else if (did.startsWith(DockDidMethodKeyEd25519Prefix)) { return new DockDidMethodKey(new PublicKeyEd25519(hex), api); } else { - validateDockDIDHexIdentifier(hex, 32); + validateDockDIDHexIdentifier(hex); return new DockDid(hex, api); } } diff --git a/tests/unit/did.test.js b/tests/unit/did.test.js index bffae078b..f89a0886e 100644 --- a/tests/unit/did.test.js +++ b/tests/unit/did.test.js @@ -3,13 +3,14 @@ import { randomAsHex, encodeAddress } from '@polkadot/util-crypto'; import { validateDockDIDHexIdentifier, validateDockDIDSS58Identifier, - DockDIDQualifier, + DockDIDQualifier, DockDIDByteSize, DockDIDMethodKeyQualifier, } from '../../src/utils/did'; +import { getHexIdentifier } from '../../src/utils/codec'; -const hexDid = did => getHexIdentifier( +const hexDid = (did) => getHexIdentifier( did, [DockDIDQualifier, DockDIDMethodKeyQualifier], - DockDIDByteSize + DockDIDByteSize, ); describe('DID utilities', () => { From 159fc121a1b2d2fa9051860be25c4b9588830ae5 Mon Sep 17 00:00:00 2001 From: lovesh Date: Wed, 13 Dec 2023 20:07:16 +0530 Subject: [PATCH 07/32] Add flag to run trust registry tests Signed-off-by: lovesh --- tests/test-constants.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test-constants.js b/tests/test-constants.js index dcd6045f4..b340d3814 100644 --- a/tests/test-constants.js +++ b/tests/test-constants.js @@ -78,6 +78,9 @@ export const TestSchemes = fromEnv('TestSchemes', DefaultTestSchemes); export const DisableStatusListTests = boolEnv( fromEnv('DisableStatusListTests', 'false'), ); +export const DisableTrustRegistryTests = boolEnv( + fromEnv('DisableTrustRegistryTests', 'false'), +); export const BBS = { Name: 'BBS', From 1ff74ad07f73436c028ea7e70e5127b74380aa3d Mon Sep 17 00:00:00 2001 From: lovesh Date: Wed, 13 Dec 2023 20:59:02 +0530 Subject: [PATCH 08/32] Fix some tests Signed-off-by: lovesh --- src/utils/did.js | 8 ++++---- tests/integration/helpers.js | 1 + tests/integration/revocation.test.js | 8 ++++---- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/utils/did.js b/src/utils/did.js index 7c3ed69ce..f1ba7b57d 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -165,7 +165,7 @@ export class NoOffchainDIDError extends Error { } /** - * Check if the given identifier is 32 byte hex + * Check if the given identifier is the hex representation of a Dock DID. * @param {string} identifier - The identifier to check. * @return {void} Throws exception if invalid identifier */ @@ -191,11 +191,11 @@ export function validateDockDIDSS58Identifier(identifier) { } /** - * Gets the hexadecimal value of the given DID. + * Takes a DID string, gets the hexadecimal value of that and returns a `DockDidMethodKey` or `DockDid` object. * @param {*} api * @param {string} did - The DID can be passed as fully qualified DID like `did:dock:` or - * a 32 byte hex string - * @return {string} Returns the hexadecimal representation of the DID. + * `did:key:` or a 32 byte hex string + * @return {DockDidOrDidMethodKey} Returns a `DockDidMethodKey` or `DockDid` object. */ export function typedHexDID(api, did) { const hex = getHexIdentifier( diff --git a/tests/integration/helpers.js b/tests/integration/helpers.js index 4b1e09ad5..db7f3a189 100644 --- a/tests/integration/helpers.js +++ b/tests/integration/helpers.js @@ -16,6 +16,7 @@ import { createNewDockDID } from '../../src/utils/did'; */ export async function registerNewDIDUsingPair(dockAPI, did, pair, verRels = undefined, controllers = []) { if (verRels === undefined) { + // eslint-disable-next-line no-param-reassign verRels = new VerificationRelationship(); } // No additional controller diff --git a/tests/integration/revocation.test.js b/tests/integration/revocation.test.js index 549bb4206..7dceff087 100644 --- a/tests/integration/revocation.test.js +++ b/tests/integration/revocation.test.js @@ -7,7 +7,7 @@ import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI } from '../test-const import { OneOfPolicy, } from '../../src/utils/revocation'; -import { DidKeypair } from '../../src/utils/did' +import { DidKeypair } from '../../src/utils/did'; import { registerNewDIDUsingPair } from './helpers'; describe('Revocation Module', () => { @@ -115,7 +115,7 @@ describe('Revocation Module', () => { // Note: Intentionally passing true and waiting for finalization as not doing that makes the multi-query check fail. // This seems like a bug since the single query check done in next loop work. Even the upgrade to @polkadot/api version 9.14 didn't fix - await dock.revocation.unrevoke(unrevoke, [[sig1, nonce1]], true); + await dock.revocation.unrevoke(unrevoke, [[nonce1, sig1]], true); for (let i = 0; i < rIdsArr.length; i++) { // eslint-disable-next-line no-await-in-loop @@ -170,7 +170,7 @@ describe('Revocation Module', () => { const [remove, sig, nonce] = await dock.revocation.createSignedRemove(registryId, ownerDID, pair, { didModule: dock.did }); await expect( - dock.revocation.removeRegistry(remove, [[nonce, sig]], false), + dock.revocation.removeRegistry(remove, [[sig, nonce]], false), ).rejects.toThrow(); await expect(dock.revocation.getRevocationRegistry(registryId)).resolves.toBeDefined(); @@ -211,7 +211,7 @@ describe('Revocation Module', () => { expect(revocationStatus).toBe(true); // Unrevoke from another DID - await dock.revocation.unrevokeCredentialWithOneOfPolicy(multipleControllerRegistryID, revId, ownerDID2, pair2, 1, { didModule: dock.did }, false); + await dock.revocation.unrevokeCredentialWithOneOfPolicy(multipleControllerRegistryID, revId, ownerDID2, pair2, { didModule: dock.did }, false); const revocationStatus1 = await dock.revocation.getIsRevoked(multipleControllerRegistryID, revId); expect(revocationStatus1).toBe(false); From a54f12c702f1d93a31fe7f0d074856ed5e752c46 Mon Sep 17 00:00:00 2001 From: lovesh Date: Wed, 13 Dec 2023 21:01:29 +0530 Subject: [PATCH 09/32] Fix test Signed-off-by: lovesh --- tests/integration/revocation.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/integration/revocation.test.js b/tests/integration/revocation.test.js index 7dceff087..8a2239e08 100644 --- a/tests/integration/revocation.test.js +++ b/tests/integration/revocation.test.js @@ -193,9 +193,9 @@ describe('Revocation Module', () => { let hasFirstDID = false; let hasSecondDID = false; controllerSet.forEach((controller) => { - if (controller === ownerDID) { + if (controller.did === ownerDID) { hasFirstDID = true; - } else if (controller === ownerDID2) { + } else if (controller.did === ownerDID2) { hasSecondDID = true; } }); From dd8fc95e0ba6d5210665d955636325257ddbbf72 Mon Sep 17 00:00:00 2001 From: lovesh Date: Wed, 13 Dec 2023 23:05:43 +0530 Subject: [PATCH 10/32] Fix some schema tests and function types Signed-off-by: lovesh --- src/modules/blob.js | 5 +---- src/modules/did/did.js | 5 +++-- src/modules/offchain-signatures.js | 3 --- src/modules/revocation.js | 2 -- src/modules/schema.js | 7 +++---- src/utils/did.js | 2 +- src/utils/misc.js | 2 +- tests/integration/anoncreds/utils.js | 1 - tests/integration/schema.test.js | 8 ++++---- 9 files changed, 13 insertions(+), 22 deletions(-) diff --git a/src/modules/blob.js b/src/modules/blob.js index 3d44da243..e121a15c8 100644 --- a/src/modules/blob.js +++ b/src/modules/blob.js @@ -76,7 +76,6 @@ class BlobModule { * Create a signed transaction for adding a new blob * @param blob * @param signerDid - Signer of the blob - * @param keyPair - Signer's keypair * @param signingKeyRef - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by @@ -93,7 +92,6 @@ class BlobModule { * Write a new blob on chain. * @param blob * @param signerDid - Signer of the blob - * @param keyPair - Signer's keypair * @param signingKeyRef - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by @@ -142,8 +140,7 @@ class BlobModule { /** * Create an `AddBlob` struct as expected by node and return along with signature. * @param blob - * @param hexDid - Signer DID in hex form - * @param keyPair - Signer's keypair + * @param {DockDidOrDidMethodKey} signerDid - Signer DID * @param signingKeyRef - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by diff --git a/src/modules/did/did.js b/src/modules/did/did.js index 1f726c28f..fefb37988 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -36,6 +36,7 @@ class DIDModule { * Creates a new instance of DIDModule and sets the api * @constructor * @param {object} api - PolkadotJS API Reference + * @param signAndSend - Function to sign and send transaction */ constructor(api, signAndSend) { this.api = api; @@ -1019,7 +1020,7 @@ class DIDModule { /** * Gets the current nonce for the DID. It will throw error if the DID does not exist on * chain or chain returns null response. - * @param {string} did - DID identifier as hex. Not accepting full DID intentionally for efficiency as these + * @param {DockDidOrDidMethodKey} did - DID identifier as hex. Not accepting full DID intentionally for efficiency as these * methods are used internally * @return {Promise} */ @@ -1035,7 +1036,7 @@ class DIDModule { /** * Gets the nonce that should be used for sending the next transaction by this DID. Its 1 more than the current nonce. - * @param did + * @param {DockDidOrDidMethodKey} did * @returns {Promise<*>} */ async getNextNonceForDid(did) { diff --git a/src/modules/offchain-signatures.js b/src/modules/offchain-signatures.js index 9001d1f58..d0739f551 100644 --- a/src/modules/offchain-signatures.js +++ b/src/modules/offchain-signatures.js @@ -115,7 +115,6 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @param targetDid - The DID to which key is being added * @param signerDid - The DID that is adding the key by signing the payload because it controls `targetDid` * @param signingKeyRef - Signer's signingKeyRef - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -147,7 +146,6 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @param targetDid - The DID from which key is being removed * @param signerDid - The DID that is removing the key by signing the payload because it controls `targetDid` * @param signingKeyRef - Signer's signingKeyRef - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this @@ -178,7 +176,6 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @param targetDid - The DID to which key is being added * @param signerDid - The DID that is adding the key by signing the payload because it controls `targetDid` * @param signingKeyRef - Signer's signingKeyRef - * @param keyId - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification * @param nonce - The nonce to be used for sending this transaction. If not provided then `didModule` must be provided. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this diff --git a/src/modules/revocation.js b/src/modules/revocation.js index 932569517..f610cc2ea 100644 --- a/src/modules/revocation.js +++ b/src/modules/revocation.js @@ -179,7 +179,6 @@ class RevocationModule { * @param revId - The revocation id that is being revoked * @param did * @param signingKeyRef - * @param keyId * @param nonce * @param didModule * @param waitForFinalization @@ -197,7 +196,6 @@ class RevocationModule { * @param revId * @param did * @param signingKeyRef - * @param keyId * @param nonce * @param didModule * @param waitForFinalization diff --git a/src/modules/schema.js b/src/modules/schema.js index 0c4827838..096e5c7f5 100644 --- a/src/modules/schema.js +++ b/src/modules/schema.js @@ -94,20 +94,19 @@ export default class Schema { * @param {object} dock - The dock API * @param signerDid * @param keyPair - * @param keyId * @param nonce * @param waitForFinalization * @param params * @return {Promise} The extrinsic to sign and send. */ - async writeToChain(dock, signerDid, keyPair, keyId, nonce = undefined, waitForFinalization, params = {}) { + async writeToChain(dock, signerDid, keyPair, nonce = undefined, waitForFinalization, params = {}) { let arg; if (nonce === undefined) { arg = { didModule: dock.did }; } else { arg = { nonce }; } - return dock.blob.new(this.toBlob(), signerDid, keyPair, keyId, arg, waitForFinalization, params); + return dock.blob.new(this.toBlob(), signerDid, keyPair, arg, waitForFinalization, params); } /** @@ -141,7 +140,7 @@ export default class Schema { return { ...chainValue, id, - author: hexDIDToQualified(chainBlob[0]), + author: hexDIDToQualified(chainBlob[0].did), }; } throw new Error('Incorrect schema format'); diff --git a/src/utils/did.js b/src/utils/did.js index f1ba7b57d..5b41d92e7 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -269,7 +269,7 @@ export function createDidKey(publicKey, verRel) { /** * - * @param {string} did - DID as hex + * @param {DockDidOrDidMethodKey} did - DID as hex * @param {number} keyId - * @param {Signature} sig * @returns {{sig: *, keyId, did}} diff --git a/src/utils/misc.js b/src/utils/misc.js index 6cc5b26a1..2be84e5ad 100644 --- a/src/utils/misc.js +++ b/src/utils/misc.js @@ -161,7 +161,7 @@ export function encodeExtrinsicAsHash(api, tx) { /** * Get the nonce to be used for sending the next transaction if not provided already. - * @param hexDid - DID whose nonce is needed + * @param {DockDidOrDidMethodKey} didOrDidMethodKey - DID whose nonce is needed * @param nonce - If provided, returned as it is. * @param didModule - Reference to the DID module. If nonce is not provided then the next nonce for the DID is fetched by * using this diff --git a/tests/integration/anoncreds/utils.js b/tests/integration/anoncreds/utils.js index 48a4500ac..11fc893d5 100644 --- a/tests/integration/anoncreds/utils.js +++ b/tests/integration/anoncreds/utils.js @@ -46,7 +46,6 @@ export async function parseR1CSFile(r1csName) { * @param title * @param did * @param pair - * @param keyId * @param dock * @returns {Promise<[{id: string, type: string},{$schema: string, title, type: string, $id: string},string]>} */ diff --git a/tests/integration/schema.test.js b/tests/integration/schema.test.js index 11a92821c..02f2669e9 100644 --- a/tests/integration/schema.test.js +++ b/tests/integration/schema.test.js @@ -4,7 +4,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockAPI } from '../../src/index'; import { - createNewDockDID, typedHexDID, hexDIDToQualified, DidKeypair + createNewDockDID, typedHexDID, hexDIDToQualified, DidKeypair, } from '../../src/utils/did'; import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI } from '../test-constants'; import { verifyCredential, verifyPresentation } from '../../src/utils/vc/index'; @@ -58,7 +58,7 @@ describe('Schema Blob Module Integration', () => { dockApi.setAccount(account); pair = new DidKeypair(dockApi.keyring.addFromUri(firstKeySeed), 1); dockDID = createNewDockDID(); - hexDid = typedHexDID(dock.api, dockDID); + hexDid = typedHexDID(dockApi.api, dockDID); await registerNewDIDUsingPair(dockApi, dockDID, pair); blobId = randomAsHex(DockBlobIdByteSize); @@ -122,11 +122,11 @@ describe('Schema Blob Module Integration', () => { test('Set and get schema', async () => { const schema = new Schema(); await schema.setJSONSchema(exampleSchema); - await dockApi.blob.new(schema.toBlob(), hexDid, pair, { didModule: dockApi.didModule }, false); + await dockApi.blob.new(schema.toBlob(), hexDid.did, pair, { didModule: dockApi.didModule }, false); await expect(Schema.get(blobId, dockApi)).resolves.toMatchObject({ ...exampleSchema, id: blobId, - author: hexDIDToQualified(typedHexDID(dock.api, dockDID)), + author: dockDID, }); }, 20000); From eee7cff2a09af178f834dd7276260b2305bd8d4c Mon Sep 17 00:00:00 2001 From: lovesh Date: Thu, 14 Dec 2023 02:06:28 +0530 Subject: [PATCH 11/32] Fix more schema tests Signed-off-by: lovesh --- src/utils/vc/schema.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/vc/schema.js b/src/utils/vc/schema.js index 128a764fe..7327ebb46 100644 --- a/src/utils/vc/schema.js +++ b/src/utils/vc/schema.js @@ -88,7 +88,7 @@ export async function getAndValidateSchemaIfPresent( schemaObj = { ...data, id: schemaUri, - author: hexDIDToQualified(author), + author: hexDIDToQualified(author.did), }; } else { schemaObj = document; From e96424b57d93cb0fbf9025e4ed29e5163406f82c Mon Sep 17 00:00:00 2001 From: lovesh Date: Thu, 14 Dec 2023 02:31:00 +0530 Subject: [PATCH 12/32] Fix imports Signed-off-by: lovesh --- src/presentation.js | 4 +--- src/utils/vc/credentials.js | 3 +-- src/utils/vc/crypto/Bls12381BBSKeyPairDock2023.js | 3 +-- src/utils/vc/crypto/Bls12381BBSSignatureDock2022.js | 2 +- src/utils/vc/crypto/Bls12381BBSSignatureDock2023.js | 2 +- src/utils/vc/crypto/Bls12381G2KeyPairDock2022.js | 5 +---- src/utils/vc/crypto/Bls12381PSKeyPairDock2023.js | 3 +-- src/utils/vc/crypto/Bls12381PSSignatureDock2023.js | 2 +- src/utils/vc/crypto/common/DockCryptoSignature.js | 4 +--- src/utils/vc/crypto/common/DockCryptoSignatureProof.js | 2 +- src/utils/vc/presentations.js | 4 ++-- src/utils/vc/schema.js | 1 + 12 files changed, 13 insertions(+), 22 deletions(-) diff --git a/src/presentation.js b/src/presentation.js index 6859c5438..4a0a5c211 100644 --- a/src/presentation.js +++ b/src/presentation.js @@ -4,12 +4,10 @@ import { isWasmInitialized, BBSPublicKey, PSPublicKey, + PresentationBuilder, } from '@docknetwork/crypto-wasm-ts'; import b58 from 'bs58'; import { stringToU8a } from '@polkadot/util'; -import { - PresentationBuilder, -} from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials'; import { ensureArray } from './utils/type-helpers'; import Bls12381BBSSignatureDock2022 from './utils/vc/crypto/Bls12381BBSSignatureDock2022'; diff --git a/src/utils/vc/credentials.js b/src/utils/vc/credentials.js index fec200277..027bb96b1 100644 --- a/src/utils/vc/credentials.js +++ b/src/utils/vc/credentials.js @@ -3,8 +3,7 @@ import jsigs from 'jsonld-signatures'; import { statusTypeMatches, checkStatus } from '@digitalbazaar/vc-status-list'; import base64url from 'base64url'; -import { CredentialBuilder } from '@docknetwork/crypto-wasm-ts'; -import { CredentialSchema } from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials'; +import { CredentialBuilder, CredentialSchema } from '@docknetwork/crypto-wasm-ts'; import CredentialIssuancePurpose from './CredentialIssuancePurpose'; import defaultDocumentLoader from './document-loader'; import { getAndValidateSchemaIfPresent } from './schema'; diff --git a/src/utils/vc/crypto/Bls12381BBSKeyPairDock2023.js b/src/utils/vc/crypto/Bls12381BBSKeyPairDock2023.js index 99c56decb..7e4884fc6 100644 --- a/src/utils/vc/crypto/Bls12381BBSKeyPairDock2023.js +++ b/src/utils/vc/crypto/Bls12381BBSKeyPairDock2023.js @@ -4,10 +4,9 @@ import { BBSPublicKey, BBSSecretKey, BBSSignatureParams, + BBS_SIGNATURE_PARAMS_LABEL_BYTES, } from '@docknetwork/crypto-wasm-ts'; -import { BBS_SIGNATURE_PARAMS_LABEL_BYTES } from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials'; - import { Bls12381BBS23DockVerKeyName } from './constants'; import DockCryptoKeyPair from './common/DockCryptoKeyPair'; diff --git a/src/utils/vc/crypto/Bls12381BBSSignatureDock2022.js b/src/utils/vc/crypto/Bls12381BBSSignatureDock2022.js index 4f5358d86..d5896eac3 100644 --- a/src/utils/vc/crypto/Bls12381BBSSignatureDock2022.js +++ b/src/utils/vc/crypto/Bls12381BBSSignatureDock2022.js @@ -1,7 +1,7 @@ import { BBSPlusCredential, BBSPlusCredentialBuilder, -} from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials'; +} from '@docknetwork/crypto-wasm-ts'; import { Bls12381BBSSigDockSigName } from './constants'; diff --git a/src/utils/vc/crypto/Bls12381BBSSignatureDock2023.js b/src/utils/vc/crypto/Bls12381BBSSignatureDock2023.js index 6726e116d..2bee076fa 100644 --- a/src/utils/vc/crypto/Bls12381BBSSignatureDock2023.js +++ b/src/utils/vc/crypto/Bls12381BBSSignatureDock2023.js @@ -1,7 +1,7 @@ import { BBSCredential, BBSCredentialBuilder, -} from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials'; +} from '@docknetwork/crypto-wasm-ts'; import { Bls12381BBS23SigDockSigName } from './constants'; diff --git a/src/utils/vc/crypto/Bls12381G2KeyPairDock2022.js b/src/utils/vc/crypto/Bls12381G2KeyPairDock2022.js index a7ea90caa..65f50dd75 100644 --- a/src/utils/vc/crypto/Bls12381G2KeyPairDock2022.js +++ b/src/utils/vc/crypto/Bls12381G2KeyPairDock2022.js @@ -4,11 +4,8 @@ import { BBSPlusSecretKey, BBSPlusSignatureParamsG1, BBSPlusPublicKeyG2, -} from '@docknetwork/crypto-wasm-ts'; - -import { BBS_PLUS_SIGNATURE_PARAMS_LABEL_BYTES, -} from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials'; +} from '@docknetwork/crypto-wasm-ts'; import { Bls12381BBSDockVerKeyName } from './constants'; import DockCryptoKeyPair from './common/DockCryptoKeyPair'; diff --git a/src/utils/vc/crypto/Bls12381PSKeyPairDock2023.js b/src/utils/vc/crypto/Bls12381PSKeyPairDock2023.js index fe8948dd0..16636527f 100644 --- a/src/utils/vc/crypto/Bls12381PSKeyPairDock2023.js +++ b/src/utils/vc/crypto/Bls12381PSKeyPairDock2023.js @@ -4,10 +4,9 @@ import { PSPublicKey, PSSecretKey, PSSignatureParams, + PS_SIGNATURE_PARAMS_LABEL_BYTES, } from '@docknetwork/crypto-wasm-ts'; -import { PS_SIGNATURE_PARAMS_LABEL_BYTES } from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials'; - import { Bls12381PSDockVerKeyName } from './constants'; import DockCryptoKeyPair from './common/DockCryptoKeyPair'; diff --git a/src/utils/vc/crypto/Bls12381PSSignatureDock2023.js b/src/utils/vc/crypto/Bls12381PSSignatureDock2023.js index 863163a06..d587d6920 100644 --- a/src/utils/vc/crypto/Bls12381PSSignatureDock2023.js +++ b/src/utils/vc/crypto/Bls12381PSSignatureDock2023.js @@ -1,7 +1,7 @@ import { PSCredential, PSCredentialBuilder, -} from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials'; +} from '@docknetwork/crypto-wasm-ts'; import { Bls12381PSSigDockSigName } from './constants'; diff --git a/src/utils/vc/crypto/common/DockCryptoSignature.js b/src/utils/vc/crypto/common/DockCryptoSignature.js index c63f855e7..00e3fc158 100644 --- a/src/utils/vc/crypto/common/DockCryptoSignature.js +++ b/src/utils/vc/crypto/common/DockCryptoSignature.js @@ -1,6 +1,4 @@ -import { CredentialSchema, DefaultSchemaParsingOpts } from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials'; -import * as _ from 'underscore'; -import { initializeWasm } from '@docknetwork/crypto-wasm-ts'; +import { initializeWasm, CredentialSchema, DefaultSchemaParsingOpts } from '@docknetwork/crypto-wasm-ts'; import jsonld from 'jsonld'; import { SECURITY_CONTEXT_URL } from 'jsonld-signatures'; diff --git a/src/utils/vc/crypto/common/DockCryptoSignatureProof.js b/src/utils/vc/crypto/common/DockCryptoSignatureProof.js index 577aa56f6..b33fe116d 100644 --- a/src/utils/vc/crypto/common/DockCryptoSignatureProof.js +++ b/src/utils/vc/crypto/common/DockCryptoSignatureProof.js @@ -1,4 +1,4 @@ -import { Presentation } from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials/presentation'; +import { Presentation } from '@docknetwork/crypto-wasm-ts'; import b58 from 'bs58'; import { withExtendedStaticProperties } from '../../../inheritance'; diff --git a/src/utils/vc/presentations.js b/src/utils/vc/presentations.js index 2b56abaf4..146a0e97d 100644 --- a/src/utils/vc/presentations.js +++ b/src/utils/vc/presentations.js @@ -4,10 +4,10 @@ import { BBSPlusPublicKeyG2, BBSPublicKey, PSPublicKey, + Presentation, + CredentialSchema, } from '@docknetwork/crypto-wasm-ts'; -import { Presentation } from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials/presentation'; import b58 from 'bs58'; -import { CredentialSchema } from '@docknetwork/crypto-wasm-ts/lib/anonymous-credentials'; import { getPrivateStatus, verifyCredential } from './credentials'; import DIDResolver from "../../resolver/did/did-resolver"; // eslint-disable-line diff --git a/src/utils/vc/schema.js b/src/utils/vc/schema.js index 7327ebb46..1533e2f3f 100644 --- a/src/utils/vc/schema.js +++ b/src/utils/vc/schema.js @@ -16,6 +16,7 @@ import { * @param {object} credential - The credential to use, must be expanded JSON-LD * @param {object} schema - The schema to use * @param context + * @param documentLoader * @returns {Promise} - Returns promise to a boolean or throws error */ export async function validateCredentialSchema( From 219b9412d9a3e1bfff12c008a8da886b82794e05 Mon Sep 17 00:00:00 2001 From: lovesh Date: Thu, 14 Dec 2023 03:05:51 +0530 Subject: [PATCH 13/32] Fix more tests Signed-off-by: lovesh --- src/modules/did/did.js | 1 + tests/integration/anoncreds/demo.test.js | 236 ++++++++++---------- tests/integration/anoncreds/issuing.test.js | 3 +- tests/integration/resolvers.test.js | 6 +- 4 files changed, 123 insertions(+), 123 deletions(-) diff --git a/src/modules/did/did.js b/src/modules/did/did.js index fefb37988..82aa92c0e 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -682,6 +682,7 @@ class DIDModule { * Throws NoDID if the DID does not exist on chain. * @param {string} did - The DID can be passed as fully qualified DID like `did:dock:` or * a 32 byte hex string + * @param getOffchainSigKeys * @return {Promise} The DID document. */ // eslint-disable-next-line sonarjs/cognitive-complexity diff --git a/tests/integration/anoncreds/demo.test.js b/tests/integration/anoncreds/demo.test.js index 3ab9e94be..eb906612d 100644 --- a/tests/integration/anoncreds/demo.test.js +++ b/tests/integration/anoncreds/demo.test.js @@ -1,5 +1,7 @@ -import { randomAsHex } from "@polkadot/util-crypto"; -import { hexToU8a, stringToHex, stringToU8a, u8aToHex } from "@polkadot/util"; +import { randomAsHex } from '@polkadot/util-crypto'; +import { + hexToU8a, stringToHex, stringToU8a, u8aToHex, +} from '@polkadot/util'; import { Accumulator, PositiveAccumulator, @@ -16,20 +18,20 @@ import { AccumulatorParams, AccumulatorPublicKey, initializeWasm, -} from "@docknetwork/crypto-wasm-ts"; -import { InMemoryState } from "@docknetwork/crypto-wasm-ts/lib/accumulator/in-memory-persistence"; -import { DockAPI } from "../../../src"; +} from '@docknetwork/crypto-wasm-ts'; +import { InMemoryState } from '@docknetwork/crypto-wasm-ts/lib/accumulator/in-memory-persistence'; +import { DockAPI } from '../../../src'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts, Schemes, -} from "../../test-constants"; -import { createNewDockDID, DidKeypair } from "../../../src/utils/did"; -import AccumulatorModule from "../../../src/modules/accumulator"; -import { getAllEventsFromBlock } from "../../../src/utils/chain-ops"; -import { getRevealedUnrevealed } from "./utils"; -import { registerNewDIDUsingPair } from "../helpers"; +} from '../../test-constants'; +import { createNewDockDID, DidKeypair } from '../../../src/utils/did'; +import AccumulatorModule from '../../../src/modules/accumulator'; +import { getAllEventsFromBlock } from '../../../src/utils/chain-ops'; +import { getRevealedUnrevealed } from './utils'; +import { registerNewDIDUsingPair } from '../helpers'; for (const { Name, @@ -63,12 +65,12 @@ for (const { // User's attributes which will be signed by the issuer of the credential const attributes = [ - stringToU8a("John"), // First name - stringToU8a("Smith"), // Last name - stringToU8a("M"), // Gender - stringToU8a("New York"), // City - stringToU8a("129086521911"), // SSN - stringToU8a("userid-xyz"), // user/credential id, this is put in the accumulator and used for revocation + stringToU8a('John'), // First name + stringToU8a('Smith'), // Last name + stringToU8a('M'), // Gender + stringToU8a('New York'), // City + stringToU8a('129086521911'), // SSN + stringToU8a('userid-xyz'), // user/credential id, this is put in the accumulator and used for revocation ]; const attributeCount = attributes.length; @@ -94,21 +96,21 @@ for (const { revealedAttrIndices.add(1); const [revealedAttrs, unrevealedAttrs] = getRevealedUnrevealed( encodedAttrs, - revealedAttrIndices + revealedAttrIndices, ); const queriedPk = await getModule(dock).getPublicKey(issuerDid, 2, true); const sigParams = new SignatureParams( - SignatureParams.valueFromBytes(hexToU8a(queriedPk.params.bytes)) + SignatureParams.valueFromBytes(hexToU8a(queriedPk.params.bytes)), ); const sigPk = new PublicKey(hexToU8a(queriedPk.bytes)); const accum = await dock.accumulatorModule.getAccumulator( accumulatorId, - true + true, ); const accumParams = new AccumulatorParams( - hexToU8a(accum.publicKey.params.bytes) + hexToU8a(accum.publicKey.params.bytes), ); const accumPk = new AccumulatorPublicKey(hexToU8a(accum.publicKey.bytes)); const accumulated = hexToU8a(accum.accumulated); @@ -119,7 +121,7 @@ for (const { accumParams, accumPk, provingKey, - accumulated + accumulated, ); const statements = new Statements(); statements.add(statement1); @@ -133,19 +135,19 @@ for (const { const metaStatements = new MetaStatements(); metaStatements.add(ms); - const context = stringToU8a("some context"); + const context = stringToU8a('some context'); const proofSpec = new ProofSpecG1( statements, metaStatements, [], - context + context, ); const witness1 = buildWitness(signature, unrevealedAttrs, false); const witness2 = Witness.accumulatorMembership( encodedAttrs[attributeCount - 1], - membershipWitness + membershipWitness, ); const witnesses = new Witnesses(); witnesses.add(witness1); @@ -165,27 +167,27 @@ for (const { dock.setAccount(account); issuerKeypair = new DidKeypair( dock.keyring.addFromUri(randomAsHex(32)), - 1 + 1, ); issuerDid = createNewDockDID(); await registerNewDIDUsingPair(dock, issuerDid, issuerKeypair); accumulatorManagerKeypair = new DidKeypair( dock.keyring.addFromUri(randomAsHex(32)), - 1 + 1, ); accumulatorManagerDid = createNewDockDID(); await registerNewDIDUsingPair( dock, accumulatorManagerDid, - accumulatorManagerKeypair + accumulatorManagerKeypair, ); await initializeWasm(); }, 20000); - test("Create params", async () => { - const label = stringToHex("My params"); + test('Create params', async () => { + const label = stringToHex('My params'); const bytes = u8aToHex( - SignatureParams.generate(attributeCount, hexToU8a(label)).toBytes() + SignatureParams.generate(attributeCount, hexToU8a(label)).toBytes(), ); const params = Module.prepareAddParameters(bytes, undefined, label); await getModule(dock).addParams( @@ -193,30 +195,30 @@ for (const { issuerDid, issuerKeypair, { didModule: dock.did }, - false + false, ); const paramsWritten = await getModule(dock).getLastParamsWritten( - issuerDid + issuerDid, ); expect(paramsWritten.bytes).toEqual(params.bytes); expect(paramsWritten.label).toEqual(params.label); }, 10000); - test("Create keypair", async () => { + test('Create keypair', async () => { const queriedParams = await getModule(dock).getParams(issuerDid, 1); const paramsVal = SignatureParams.valueFromBytes( - hexToU8a(queriedParams.bytes) + hexToU8a(queriedParams.bytes), ); const params = new SignatureParams( paramsVal, - hexToU8a(queriedParams.label) + hexToU8a(queriedParams.label), ); issuerBbsPlusKeypair = KeyPair.generate(params); const pk = Module.prepareAddPublicKey( u8aToHex(issuerBbsPlusKeypair.publicKey.bytes), undefined, - [issuerDid, 1] + [issuerDid, 1], ); await getModule(dock).addPublicKey( pk, @@ -224,64 +226,64 @@ for (const { issuerDid, issuerKeypair, { didModule: dock.did }, - false + false, ); }, 10000); - test("Create Accumulator params", async () => { - const label = stringToHex("My Accumulator params"); + test('Create Accumulator params', async () => { + const label = stringToHex('My Accumulator params'); const bytes = u8aToHex(Accumulator.generateParams(hexToU8a(label)).bytes); const params = AccumulatorModule.prepareAddParameters( bytes, undefined, - label + label, ); await dock.accumulatorModule.addParams( params, accumulatorManagerDid, accumulatorManagerKeypair, { didModule: dock.did }, - false + false, ); const paramsWritten = await dock.accumulatorModule.getLastParamsWritten( - accumulatorManagerDid + accumulatorManagerDid, ); expect(paramsWritten.bytes).toEqual(params.bytes); expect(paramsWritten.label).toEqual(params.label); }, 10000); - test("Create Accumulator keypair", async () => { + test('Create Accumulator keypair', async () => { const queriedParams = await dock.accumulatorModule.getParams( accumulatorManagerDid, - 1 + 1, ); accumulatorKeypair = Accumulator.generateKeypair( new AccumulatorParams(hexToU8a(queriedParams.bytes)), - hexToU8a(seedAccum) + hexToU8a(seedAccum), ); const pk = AccumulatorModule.prepareAddPublicKey( u8aToHex(accumulatorKeypair.publicKey.bytes), undefined, - [accumulatorManagerDid, 1] + [accumulatorManagerDid, 1], ); await dock.accumulatorModule.addPublicKey( pk, accumulatorManagerDid, accumulatorManagerKeypair, { didModule: dock.did }, - false + false, ); }, 10000); - test("Create Accumulator", async () => { + test('Create Accumulator', async () => { const queriedParams = await dock.accumulatorModule.getParams( accumulatorManagerDid, - 1 + 1, ); accumulator = PositiveAccumulator.initialize( new AccumulatorParams(hexToU8a(queriedParams.bytes)), - accumulatorKeypair.secretKey + accumulatorKeypair.secretKey, ); accumulatorId = randomAsHex(32); @@ -293,25 +295,25 @@ for (const { accumulatorManagerDid, accumulatorManagerKeypair, { didModule: dock.did }, - false + false, ); }, 10000); - test("Sign attributes, i.e. issue credential", async () => { + test('Sign attributes, i.e. issue credential', async () => { const encodedAttrs = encodedAttributes(attributes); const queriedPk = await getModule(dock).getPublicKey(issuerDid, 2, true); const paramsVal = SignatureParams.valueFromBytes( - hexToU8a(queriedPk.params.bytes) + hexToU8a(queriedPk.params.bytes), ); const params = new SignatureParams( paramsVal, - hexToU8a(queriedPk.params.label) + hexToU8a(queriedPk.params.label), ); signature = Signature.generate( encodedAttrs, issuerBbsPlusKeypair.secretKey, params, - false + false, ); // User verifies the credential (signature) @@ -319,26 +321,26 @@ for (const { encodedAttrs, new PublicKey(hexToU8a(queriedPk.bytes)), params, - false + false, ); expect(result.verified).toEqual(true); }); - test("Add attribute to accumulator for checking revocation later", async () => { + test('Add attribute to accumulator for checking revocation later', async () => { const encodedAttrs = encodedAttributes(attributes); await accumulator.add( encodedAttrs[attributeCount - 1], accumulatorKeypair.secretKey, - accumulatorState + accumulatorState, ); await expect( - accumulatorState.has(encodedAttrs[attributeCount - 1]) + accumulatorState.has(encodedAttrs[attributeCount - 1]), ).resolves.toEqual(true); membershipWitness = await accumulator.membershipWitness( encodedAttrs[attributeCount - 1], accumulatorKeypair.secretKey, - accumulatorState + accumulatorState, ); const accumulated = u8aToHex(accumulator.accumulated); @@ -349,51 +351,51 @@ for (const { accumulatorManagerDid, accumulatorManagerKeypair, { didModule: dock.did }, - false + false, ); const queriedAccum = await dock.accumulatorModule.getAccumulator( accumulatorId, - true + true, ); expect(queriedAccum.accumulated).toEqual(accumulated); const tempAccumulator = PositiveAccumulator.fromAccumulated( - hexToU8a(queriedAccum.accumulated) + hexToU8a(queriedAccum.accumulated), ); expect( tempAccumulator.verifyMembershipWitness( encodedAttrs[attributeCount - 1], membershipWitness, new AccumulatorPublicKey(hexToU8a(queriedAccum.publicKey.bytes)), - new AccumulatorParams(hexToU8a(queriedAccum.publicKey.params.bytes)) - ) + new AccumulatorParams(hexToU8a(queriedAccum.publicKey.params.bytes)), + ), ).toEqual(true); }, 20000); - test("Prove knowledge of signature, i.e. possession of credential and accumulator membership", async () => { + test('Prove knowledge of signature, i.e. possession of credential and accumulator membership', async () => { await proveAndVerify(); }); - test("Add new members to the accumulator and update witness", async () => { + test('Add new members to the accumulator and update witness', async () => { const encodedAttrs = encodedAttributes(attributes); const member1 = Accumulator.encodePositiveNumberAsAccumulatorMember(100); const member2 = Accumulator.encodePositiveNumberAsAccumulatorMember(105); await accumulator.addBatch( [member1, member2], accumulatorKeypair.secretKey, - accumulatorState + accumulatorState, ); let accum = await dock.accumulatorModule.getAccumulator( accumulatorId, - false + false, ); const witnessUpdInfo = WitnessUpdatePublicInfo.new( hexToU8a(accum.accumulated), [member1, member2], [], - accumulatorKeypair.secretKey + accumulatorKeypair.secretKey, ); await dock.accumulatorModule.updateAccumulator( accumulatorId, @@ -405,17 +407,17 @@ for (const { accumulatorManagerDid, accumulatorManagerKeypair, { didModule: dock.did }, - false + false, ); accum = await dock.accumulatorModule.getAccumulator(accumulatorId, false); const updates = await dock.accumulatorModule.getUpdatesFromBlock( accumulatorId, - accum.lastModified + accum.lastModified, ); expect(updates.length).toEqual(1); const queriedWitnessInfo = new WitnessUpdatePublicInfo( - hexToU8a(updates[0].witnessUpdateInfo) + hexToU8a(updates[0].witnessUpdateInfo), ); const additions = []; const removals = []; @@ -433,31 +435,31 @@ for (const { encodedAttrs[attributeCount - 1], additions, removals, - queriedWitnessInfo + queriedWitnessInfo, ); const queriedAccum = await dock.accumulatorModule.getAccumulator( accumulatorId, - true + true, ); const tempAccumulator = PositiveAccumulator.fromAccumulated( - hexToU8a(queriedAccum.accumulated) + hexToU8a(queriedAccum.accumulated), ); expect( tempAccumulator.verifyMembershipWitness( encodedAttrs[attributeCount - 1], membershipWitness, new AccumulatorPublicKey(hexToU8a(queriedAccum.publicKey.bytes)), - new AccumulatorParams(hexToU8a(queriedAccum.publicKey.params.bytes)) - ) + new AccumulatorParams(hexToU8a(queriedAccum.publicKey.params.bytes)), + ), ).toEqual(true); }); - test("After witness update, prove knowledge of signature, i.e. possession of credential and accumulator membership", async () => { + test('After witness update, prove knowledge of signature, i.e. possession of credential and accumulator membership', async () => { await proveAndVerify(); }); - test("Do several updates to the accumulator and update witness", async () => { + test('Do several updates to the accumulator and update witness', async () => { const encodedAttrs = encodedAttributes(attributes); const member1 = Accumulator.encodePositiveNumberAsAccumulatorMember(100); @@ -472,18 +474,18 @@ for (const { [member3, member4], [member1, member2], accumulatorKeypair.secret_key, - accumulatorState + accumulatorState, ); let accum = await dock.accumulatorModule.getAccumulator( accumulatorId, - false + false, ); let witnessUpdInfo = WitnessUpdatePublicInfo.new( hexToU8a(accum.accumulated), [member3, member4], [member1, member2], - accumulatorKeypair.secretKey + accumulatorKeypair.secretKey, ); await dock.accumulatorModule.updateAccumulator( accumulatorId, @@ -496,7 +498,7 @@ for (const { accumulatorManagerDid, accumulatorManagerKeypair, { didModule: dock.did }, - false + false, ); const member5 = Accumulator.encodePositiveNumberAsAccumulatorMember(200); @@ -506,7 +508,7 @@ for (const { [member5, member6], [member4], accumulatorKeypair.secret_key, - accumulatorState + accumulatorState, ); accum = await dock.accumulatorModule.getAccumulator(accumulatorId, false); @@ -515,7 +517,7 @@ for (const { hexToU8a(accum.accumulated), [member5, member6], [member4], - accumulatorKeypair.secretKey + accumulatorKeypair.secretKey, ); await dock.accumulatorModule.updateAccumulator( accumulatorId, @@ -528,7 +530,7 @@ for (const { accumulatorManagerDid, accumulatorManagerKeypair, { didModule: dock.did }, - false + false, ); const member7 = Accumulator.encodePositiveNumberAsAccumulatorMember(201); @@ -538,7 +540,7 @@ for (const { await accumulator.addBatch( [member7, member8, member9], accumulatorKeypair.secret_key, - accumulatorState + accumulatorState, ); accum = await dock.accumulatorModule.getAccumulator(accumulatorId, false); @@ -546,7 +548,7 @@ for (const { hexToU8a(accum.accumulated), [member7, member8, member9], [], - accumulatorKeypair.secretKey + accumulatorKeypair.secretKey, ); await dock.accumulatorModule.updateAccumulator( accumulatorId, @@ -559,7 +561,7 @@ for (const { accumulatorManagerDid, accumulatorManagerKeypair, { didModule: dock.did }, - false + false, ); accum = await dock.accumulatorModule.getAccumulator(accumulatorId, true); @@ -572,11 +574,11 @@ for (const { const evs = await getAllEventsFromBlock( dock.api, currentBlockNo, - false + false, ); for (const event of evs) { const ret = AccumulatorModule.parseEventAsAccumulatorUpdate( - event.event + event.event, ); if (ret !== null && ret[0] === accumulatorId) { blockNosWithUpdates.push(currentBlockNo); @@ -590,10 +592,10 @@ for (const { // eslint-disable-next-line no-await-in-loop const updates = await dock.accumulatorModule.getUpdatesFromBlock( accumulatorId, - blockNo + blockNo, ); const wi = new WitnessUpdatePublicInfo( - hexToU8a(updates[0].witnessUpdateInfo) + hexToU8a(updates[0].witnessUpdateInfo), ); updateInfo.push(wi); } @@ -606,41 +608,41 @@ for (const { [member7, member8, member9], ], [[member1, member2], [member4], []], - [updateInfo[0], updateInfo[1], updateInfo[2]] + [updateInfo[0], updateInfo[1], updateInfo[2]], ); const tempAccumulator = PositiveAccumulator.fromAccumulated( - hexToU8a(accum.accumulated) + hexToU8a(accum.accumulated), ); expect( tempAccumulator.verifyMembershipWitness( encodedAttrs[attributeCount - 1], membershipWitness, new AccumulatorPublicKey(hexToU8a(accum.publicKey.bytes)), - new AccumulatorParams(hexToU8a(accum.publicKey.params.bytes)) - ) + new AccumulatorParams(hexToU8a(accum.publicKey.params.bytes)), + ), ).toEqual(true); }, 30000); - test("After another witness update, prove knowledge of signature, i.e. possession of credential and accumulator membership", async () => { + test('After another witness update, prove knowledge of signature, i.e. possession of credential and accumulator membership', async () => { await proveAndVerify(); }); - test("Revoke by removing from the accumulator", async () => { + test('Revoke by removing from the accumulator', async () => { const encodedAttrs = encodedAttributes(attributes); await accumulator.remove( encodedAttrs[attributeCount - 1], - accumulatorKeypair.secretKey + accumulatorKeypair.secretKey, ); const accum = await dock.accumulatorModule.getAccumulator( accumulatorId, - false + false, ); const witnessUpdInfo = WitnessUpdatePublicInfo.new( hexToU8a(accum.accumulated), [], [encodedAttrs[attributeCount - 1]], - accumulatorKeypair.secretKey + accumulatorKeypair.secretKey, ); await dock.accumulatorModule.updateAccumulator( accumulatorId, @@ -653,35 +655,33 @@ for (const { accumulatorManagerDid, accumulatorManagerKeypair, { didModule: dock.did }, - false + false, ); }); - test("Witness update should not be possible after removal from accumulator", async () => { + test('Witness update should not be possible after removal from accumulator', async () => { const encodedAttrs = encodedAttributes(attributes); const accum = await dock.accumulatorModule.getAccumulator( accumulatorId, - false + false, ); const updates = await dock.accumulatorModule.getUpdatesFromBlock( accumulatorId, - accum.lastModified + accum.lastModified, ); expect(updates.length).toEqual(1); const queriedWitnessInfo = new WitnessUpdatePublicInfo( - hexToU8a(updates[0].witnessUpdateInfo) + hexToU8a(updates[0].witnessUpdateInfo), ); - expect(() => - membershipWitness.updateUsingPublicInfoPostBatchUpdate( - encodedAttrs[attributeCount - 1], - [], - [hexToU8a(updates[0].removals[0])], - queriedWitnessInfo - ) - ).toThrow(); + expect(() => membershipWitness.updateUsingPublicInfoPostBatchUpdate( + encodedAttrs[attributeCount - 1], + [], + [hexToU8a(updates[0].removals[0])], + queriedWitnessInfo, + )).toThrow(); }); - test("After revocation, i.e. removing from accumulator, prove verification should fail", async () => { + test('After revocation, i.e. removing from accumulator, prove verification should fail', async () => { let failed = false; try { await proveAndVerify(); diff --git a/tests/integration/anoncreds/issuing.test.js b/tests/integration/anoncreds/issuing.test.js index 57a74ba9d..7d1ffcf74 100644 --- a/tests/integration/anoncreds/issuing.test.js +++ b/tests/integration/anoncreds/issuing.test.js @@ -11,7 +11,7 @@ import { } from '../helpers'; import { issueCredential, verifyCredential } from '../../../src/utils/vc/index'; import { getKeyDoc } from '../../../src/utils/vc/helpers'; -import { getJsonSchemaFromCredential, } from '../../../src/utils/vc/credentials'; +import { getJsonSchemaFromCredential } from '../../../src/utils/vc/credentials'; import { getResidentCardCredentialAndSchema, setupExternalSchema } from './utils'; import { FullNodeEndpoint, @@ -66,7 +66,6 @@ describe.each(Schemes)('Issuance', ({ did1, did1, pair1, - 1, { didModule: dock.did }, false, ); diff --git a/tests/integration/resolvers.test.js b/tests/integration/resolvers.test.js index 8d3689eb8..69f3d874d 100644 --- a/tests/integration/resolvers.test.js +++ b/tests/integration/resolvers.test.js @@ -1,6 +1,6 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockResolver, DockStatusList2021Resolver } from '../../src/resolver'; -import { typedHexDID, createNewDockDID } from '../../src/utils/did'; +import { typedHexDID, createNewDockDID, DidKeypair } from '../../src/utils/did'; import { DockAPI } from '../../src/index'; @@ -88,7 +88,7 @@ describe('Resolvers', () => { expect(resolver.supports('status-list2021:*:')).toBe(false); expect(resolver.supports('status-list2020:doc:')).toBe(false); expect(await resolver.resolve(ownerDID)).toEqual( - await dock.did.getDocument(typedHexDID(dock.api, ownerDID)), + await dock.did.getDocument(ownerDID), ); if (!DisableStatusListTests) { expect(await resolver.resolve(statusListCred.id)).toEqual( @@ -124,7 +124,7 @@ describe('Resolvers', () => { expect(resolver.supports('status-list2021:*:')).toBe(false); expect(resolver.supports('status-list2020:doc:')).toBe(false); expect(await resolver.resolve(ownerDID)).toEqual( - await dock.did.getDocument(typedHexDID(dock.api, ownerDID)), + await dock.did.getDocument(ownerDID), ); if (!DisableStatusListTests) { expect(resolver.resolve(statusListCred.id)).rejects.toThrowError( From dc063a80d234bb3c0d04d5200f3a7d9c6e5244db Mon Sep 17 00:00:00 2001 From: olegnn Date: Tue, 12 Dec 2023 22:46:40 +0400 Subject: [PATCH 14/32] Tweaks --- src/modules/did/did.js | 18 +++---- src/utils/codec.js | 13 ++--- src/utils/did.js | 50 +++++++++++-------- src/utils/misc.js | 2 - tests/integration/anoncreds/issuing.test.js | 5 +- tests/integration/did/controllers.test.js | 4 +- tests/integration/did/keys.test.js | 22 ++++---- .../integration/did/service-endpoint.test.js | 28 +++++------ tests/integration/master.test.js | 8 +-- tests/integration/revocation.test.js | 23 ++++++--- tests/integration/schema.test.js | 7 ++- 11 files changed, 93 insertions(+), 87 deletions(-) diff --git a/src/modules/did/did.js b/src/modules/did/did.js index 1f726c28f..d242f08d6 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -444,7 +444,7 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(this.api, targetDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; const signerHexDid = typedHexDID(this.api, signerDid); const [removeControllers, signature] = await this.createSignedRemoveControllers( controllers, @@ -1029,7 +1029,7 @@ class DIDModule { } else if (did.isDidMethodKey) { return (await this.getDidMethodKeyDetail(did.asDidMethodKey)).nonce; } else { - throw new Error('Invalid DID provided'); + return (await this.getOnchainDidDetail(did)).nonce; } } @@ -1197,13 +1197,10 @@ class DIDModule { async createSignedRemoveKeys( keyIds, did, - controllerDid, + controllerHexDid, signingKeyRef, nonce = undefined, ) { - const hexDid = typedHexDID(this.api, did).asDid; - const controllerHexDid = typedHexDID(this.api, controllerDid); - if (nonce === undefined) { // eslint-disable-next-line no-param-reassign nonce = await this.getNextNonceForDid(controllerHexDid); @@ -1213,7 +1210,7 @@ class DIDModule { keyIds.forEach((k) => { keys.add(k); }); - const removeKeys = { did: hexDid, keys, nonce }; + const removeKeys = { did, keys, nonce }; const serializedRemoveKeys = this.getSerializedRemoveKeys(removeKeys); const signature = signingKeyRef.sign(serializedRemoveKeys); const didSig = createDidSig(controllerHexDid, signingKeyRef, signature); @@ -1222,14 +1219,11 @@ class DIDModule { async createSignedRemoveControllers( controllers, - did, - controllerDid, + hexDid, + controllerHexDid, signingKeyRef, nonce = undefined, ) { - const hexDid = typedHexDID(this.api, did).asDid; - const controllerHexDid = typedHexDID(this.api, controllerDid); - if (nonce === undefined) { // eslint-disable-next-line no-param-reassign nonce = await this.getNextNonceForDid(controllerHexDid); diff --git a/src/utils/codec.js b/src/utils/codec.js index 8cbd293ad..8108dbf67 100644 --- a/src/utils/codec.js +++ b/src/utils/codec.js @@ -29,10 +29,11 @@ export function isHexWithGivenByteSize(value, byteSize = undefined) { * @return {string} Returns the hexadecimal representation of the ID. */ export function getHexIdentifier(id, qualifiers, byteSize) { + const strId = String(id); for (const qualifier of [].concat(qualifiers)) { - if (id.startsWith(qualifier)) { + if (strId.startsWith(qualifier)) { // Fully qualified ID. Remove the qualifier - const ss58Did = id.slice(qualifier.length); + const ss58Did = strId.slice(qualifier.length); try { const hex = u8aToHex(decodeAddress(ss58Did)); // 2 characters for `0x` and 2*byte size of ID @@ -41,21 +42,21 @@ export function getHexIdentifier(id, qualifiers, byteSize) { } return hex; } catch (e) { - throw new Error(`Invalid SS58 ID ${id}. ${e}`); + throw new Error(`Invalid SS58 ID ${strId}. ${e}`); } } } try { // Check if hex and of correct size and return the hex value if successful. - if (!isHexWithGivenByteSize(id, byteSize)) { + if (!isHexWithGivenByteSize(strId, byteSize)) { throw new Error(`Expected ${byteSize}-byte sequence`); } - return id; + return strId; } catch (error) { // Cannot parse as hex - throw new Error(`Invalid hex Did \`${id}\`: ${error}`); + throw new Error(`Invalid hex Did \`${id}\`, stringified \`${strId}\`: ${error}`); } } diff --git a/src/utils/did.js b/src/utils/did.js index c34d246fc..e094924c8 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -5,10 +5,14 @@ import { randomAsHex, encodeAddress } from '@polkadot/util-crypto'; import { u8aToHex } from '@polkadot/util'; import { isHexWithGivenByteSize, getHexIdentifier } from './codec'; -import { PublicKeyEd25519, PublicKeySecp256k1 } from '../public-keys'; +import { + PublicKeyEd25519, + PublicKeySecp256k1, + PublicKey, // eslint-disable-line + VerificationRelationship, // eslint-disable-line +} from '../public-keys'; import { Signature } from "../signatures"; // eslint-disable-line -import { PublicKey, VerificationRelationship } from "../public-keys"; // eslint-disable-line import { getPublicKeyFromKeyringPair, getSignatureFromKeyringPair, @@ -16,10 +20,16 @@ import { } from './misc'; export const DockDIDMethod = 'dock'; +export const Secp256k1PublicKeyPrefix = 'zQ3'; +export const Ed25519PublicKeyPrefix = 'z6Mk'; + export const DockDIDQualifier = `did:${DockDIDMethod}:`; export const DockDIDMethodKeyQualifier = `did:key:${DockDIDMethod}:`; export const DockDIDByteSize = 32; +export const DockDidMethodKeySecp256k1Prefix = `${DockDIDQualifier}${Secp256k1PublicKeyPrefix}`; +export const DockDidMethodKeyEd25519Prefix = `${DockDIDMethodKeyQualifier}${Ed25519PublicKeyPrefix}`; + export class DidKeypair { constructor(keyPair, keyId) { this.keyPair = keyPair; @@ -35,12 +45,6 @@ export class DidKeypair { } } -const SECP256K1_PUBLIC_KEY_PREFIX = 'zQ3'; -const ED_25519_PUBLIC_KEY_PREFIX = 'z6Mk'; - -const DockDidMethodKeySecp256k1Prefix = `${DockDIDQualifier}${SECP256K1_PUBLIC_KEY_PREFIX}`; -const DockDidMethodKeyEd25519Prefix = `${DockDIDMethodKeyQualifier}${ED_25519_PUBLIC_KEY_PREFIX}`; - export class DockDidOrDidMethodKey { constructor(api) { Object.defineProperty(this, 'api', { value: api }); @@ -70,11 +74,7 @@ export class DockDidOrDidMethodKey { } changeState(method, name, payload, keyRef) { - const signature = this.signStateChange( - name, - payload, - keyRef, - ); + const signature = this.signStateChange(name, payload, keyRef); return method(payload, signature); } @@ -197,18 +197,19 @@ export function validateDockDIDSS58Identifier(identifier) { * @return {string} Returns the hexadecimal representation of the DID. */ export function typedHexDID(api, did) { + const strDid = did.toString(); const hex = getHexIdentifier( did, [DockDIDQualifier, DockDIDMethodKeyQualifier], DockDIDByteSize, ); - if (did.startsWith(DockDidMethodKeySecp256k1Prefix)) { + if (strDid.startsWith(DockDidMethodKeySecp256k1Prefix)) { return new DockDidMethodKey(new PublicKeySecp256k1(hex), api); - } else if (did.startsWith(DockDidMethodKeyEd25519Prefix)) { + } else if (strDid.startsWith(DockDidMethodKeyEd25519Prefix)) { return new DockDidMethodKey(new PublicKeyEd25519(hex), api); } else { - validateDockDIDHexIdentifier(hex, 32); + validateDockDIDHexIdentifier(hex); return new DockDid(hex, api); } } @@ -235,12 +236,17 @@ export function typedHexDIDFromSubstrate(did) { /** * Return a fully qualified Dock DID id, i.e. "did:dock:" - * @param {string} hexId - The hex blob id (without the qualifier) + * @param {string} hexDid - The hex blob id (without the qualifier) * @returns {string} - The fully qualified Blob id */ -export function hexDIDToQualified(hexId) { - const ss58Id = encodeAddress(hexId); - return `${DockDIDQualifier}${ss58Id}`; +export function hexDIDToQualified(hexDid) { + if (typeof hexDid === 'object') { + return String(hexDid); + } else { + const ss58Address = encodeAddress(hexDid); + + return `${DockDIDQualifier}${ss58Address}`; + } } /** @@ -276,7 +282,7 @@ export function createDidKey(publicKey, verRel) { export function createDidSig(did, { keyId }, rawSig) { const sig = rawSig.toJSON(); - if (did instanceof DockDid) { + if (did.isDid) { return { DidSignature: { did: did.asDid, @@ -284,7 +290,7 @@ export function createDidSig(did, { keyId }, rawSig) { sig, }, }; - } else if (did instanceof DockDidMethodKey) { + } else if (did.isDidMethodKey) { return { DidMethodKeySignature: { didKey: did.asDidMethodKey, diff --git a/src/utils/misc.js b/src/utils/misc.js index db5c19c9b..6cc5b26a1 100644 --- a/src/utils/misc.js +++ b/src/utils/misc.js @@ -3,13 +3,11 @@ import { blake2AsHex } from '@polkadot/util-crypto'; import { sha256 } from 'js-sha256'; import { - PublicKey, PublicKeyEd25519, PublicKeySecp256k1, PublicKeySr25519, // eslint-disable-line } from '../public-keys'; import { - Signature, SignatureEd25519, SignatureSecp256k1, SignatureSr25519, // eslint-disable-line diff --git a/tests/integration/anoncreds/issuing.test.js b/tests/integration/anoncreds/issuing.test.js index 57a74ba9d..d934b2911 100644 --- a/tests/integration/anoncreds/issuing.test.js +++ b/tests/integration/anoncreds/issuing.test.js @@ -47,7 +47,7 @@ describe.each(Schemes)('Issuance', ({ address: FullNodeEndpoint, }); chainModule = getModule(dock); - account = new DidKeypair(dock.keyring.addFromUri(TestAccountURI), 1); + account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); pair1 = new DidKeypair(dock.keyring.addFromUri(randomAsHex(32)), 1); did1 = createNewDockDID(); @@ -66,7 +66,6 @@ describe.each(Schemes)('Issuance', ({ did1, did1, pair1, - 1, { didModule: dock.did }, false, ); @@ -81,7 +80,7 @@ describe.each(Schemes)('Issuance', ({ }, 30000); test(`Can issue+verify a ${Name} credential with external schema reference`, async () => { - const [externalSchemaEncoded, schemaId] = await setupExternalSchema(residentCardSchema, 'Resident Card Example', did1, pair1, 1, dock); + const [externalSchemaEncoded, schemaId] = await setupExternalSchema(residentCardSchema, 'Resident Card Example', did1, pair1, dock); const issuerKey = getKeyDoc(did1, keypair, keypair.type, keypair.id); const unsignedCred = { diff --git a/tests/integration/did/controllers.test.js b/tests/integration/did/controllers.test.js index 1451d3342..74173c50e 100644 --- a/tests/integration/did/controllers.test.js +++ b/tests/integration/did/controllers.test.js @@ -64,14 +64,14 @@ describe('DID controllers', () => { await expect(dock.did.isController(dockDid2, dockDid2)).resolves.toEqual(true); await expect(dock.did.isController(dockDid2, dockDid1)).resolves.toEqual(true); - for (const [newSeed, signer, pair, keyCount] of [[seed3, hexDid1, pair1, 2], [seed4, hexDid2, pair2, 3]]) { + for (const [newSeed, signer, pair, keyCount] of [[seed3, dockDid1, pair1, 2], [seed4, dockDid2, pair2, 3]]) { const newPair = dock.keyring.addFromUri(newSeed); const publicKey = getPublicKeyFromKeyringPair(newPair); const verRels = new VerificationRelationship(); verRels.setAssertion(); const didKey = new DidKey(publicKey, verRels); - await dock.did.addKeys([didKey], dockDid2, signer, new DidKeypair(pair)); + await dock.did.addKeys([didKey], dockDid2, signer, new DidKeypair(pair, 1)); const didDetail = await dock.did.getOnchainDidDetail(hexDid2.asDid); expect(didDetail.lastKeyId).toBe(keyCount); expect(didDetail.activeControllerKeys).toBe(1); diff --git a/tests/integration/did/keys.test.js b/tests/integration/did/keys.test.js index 7882d706d..102231619 100644 --- a/tests/integration/did/keys.test.js +++ b/tests/integration/did/keys.test.js @@ -1,6 +1,6 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockAPI, PublicKeySecp256k1 } from '../../../src'; -import { createNewDockDID, typedHexDID } from '../../../src/utils/did'; +import { createNewDockDID, typedHexDID, DidKeypair } from '../../../src/utils/did'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../../test-constants'; import { generateEcdsaSecp256k1Keypair, getPublicKeyFromKeyringPair } from '../../../src/utils/misc'; import { DidKey, VerificationRelationship } from '../../../src/public-keys'; @@ -51,7 +51,7 @@ describe('Key support for DIDs', () => { await dock.did.new(dockDid, [didKey1, didKey2, didKey3], [], false); - const didDetail = await dock.did.getOnchainDidDetail(hexDid); + const didDetail = await dock.did.getOnchainDidDetail(hexDid.asDid); expect(didDetail.lastKeyId).toBe(3); expect(didDetail.activeControllerKeys).toBe(2); expect(didDetail.activeControllers).toBe(1); @@ -112,10 +112,10 @@ describe('Key support for DIDs', () => { verRels1.setAssertion(); const didKey1 = new DidKey(publicKey1, verRels1); - const pair = dock.keyring.addFromUri(seed2, null, 'ed25519'); - await dock.did.addKeys([didKey1], dockDid, dockDid, pair, 2); + const pair = new DidKeypair(dock.keyring.addFromUri(seed2, null, 'ed25519'), 2); + await dock.did.addKeys([didKey1], dockDid, dockDid, pair); - const didDetail = await dock.did.getOnchainDidDetail(hexDid); + const didDetail = await dock.did.getOnchainDidDetail(hexDid.asDid); expect(didDetail.lastKeyId).toBe(4); expect(didDetail.activeControllerKeys).toBe(3); expect(didDetail.activeControllers).toBe(1); @@ -165,10 +165,10 @@ describe('Key support for DIDs', () => { }); test('Remove keys from DID', async () => { - const pair = generateEcdsaSecp256k1Keypair(seed4); - await dock.did.removeKeys([1, 3], dockDid, dockDid, pair, 4); + const pair = new DidKeypair(generateEcdsaSecp256k1Keypair(seed4), 4); + await dock.did.removeKeys([1, 3], dockDid, dockDid, pair); - const didDetail = await dock.did.getOnchainDidDetail(hexDid); + const didDetail = await dock.did.getOnchainDidDetail(hexDid.asDid); expect(didDetail.lastKeyId).toBe(4); expect(didDetail.activeControllerKeys).toBe(2); expect(didDetail.activeControllers).toBe(1); @@ -220,9 +220,9 @@ describe('Key support for DIDs', () => { const publicKey = new PublicKeyX25519(randomAsHex(32)); const didKey = new DidKey(publicKey, verRels); - const pair = dock.keyring.addFromUri(seed2, null, 'ed25519'); - await dock.did.addKeys([didKey], dockDid, dockDid, pair, 2); - const didDetail = await dock.did.getOnchainDidDetail(hexDid); + const pair = new DidKeypair(dock.keyring.addFromUri(seed2, null, 'ed25519'), 2); + await dock.did.addKeys([didKey], dockDid, dockDid, pair); + const didDetail = await dock.did.getOnchainDidDetail(hexDid.asDid); expect(didDetail.lastKeyId).toBe(5); const dk = await dock.did.getDidKey(dockDid, 5); expect(dk.publicKey).toEqual(publicKey); diff --git a/tests/integration/did/service-endpoint.test.js b/tests/integration/did/service-endpoint.test.js index 9fd8cc085..8fe1a5654 100644 --- a/tests/integration/did/service-endpoint.test.js +++ b/tests/integration/did/service-endpoint.test.js @@ -1,7 +1,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { u8aToHex } from '@polkadot/util'; import { DockAPI } from '../../../src'; -import { createNewDockDID, typedHexDID, NoDIDError } from '../../../src/utils/did'; +import { createNewDockDID, typedHexDID, NoDIDError, DidKeypair } from '../../../src/utils/did'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../../test-constants'; import { getPublicKeyFromKeyringPair } from '../../../src/utils/misc'; import { DidKey, VerificationRelationship } from '../../../src/public-keys'; @@ -47,8 +47,8 @@ describe('DID service endpoints', () => { }, 10000); test('Create DIDs and add service endpoint', async () => { - const pair1 = dock.keyring.addFromUri(seed1); - const publicKey1 = getPublicKeyFromKeyringPair(pair1); + const pair1 = new DidKeypair(dock.keyring.addFromUri(seed1), 1); + const publicKey1 = pair1.publicKey(); const didKey1 = new DidKey(publicKey1, new VerificationRelationship()); await dock.did.new(dockDid1, [didKey1], [], false); @@ -58,14 +58,14 @@ describe('DID service endpoints', () => { // `dockDid1` adds service endpoint for itself const origins1 = origins1Text.map((u) => u8aToHex(encoder.encode(u))); - await dock.did.addServiceEndpoint(spId1, spType, origins1, hexDid1, hexDid1, pair1, 1, undefined, false); + await dock.did.addServiceEndpoint(spId1, spType, origins1, hexDid1, hexDid1, pair1, undefined, false); const sp = await dock.did.getServiceEndpoint(dockDid1, spId1); expect(sp.type).toEqual(spType); expect(sp.origins).toEqual(origins1); - const pair2 = dock.keyring.addFromUri(seed2); - const publicKey2 = getPublicKeyFromKeyringPair(pair2); + const pair2 = new DidKeypair(dock.keyring.addFromUri(seed2), 1); + const publicKey2 = pair2.publicKey(); const vr = new VerificationRelationship(); vr.setAssertion(); const didKey2 = new DidKey(publicKey2, vr); @@ -74,7 +74,7 @@ describe('DID service endpoints', () => { // `dockDid1` adds service endpoint to `dockDid2` const origins2 = origins2Text.map((u) => u8aToHex(encoder.encode(u))); - await dock.did.addServiceEndpoint(spId2, spType, origins2, hexDid2, hexDid1, pair1, 1, undefined, false); + await dock.did.addServiceEndpoint(spId2, spType, origins2, hexDid2, hexDid1, pair1, undefined, false); const sp1 = await dock.did.getServiceEndpoint(dockDid2, spId2); expect(sp1.type).toEqual(spType); @@ -96,11 +96,11 @@ describe('DID service endpoints', () => { }, 10000); test('Add another service endpoint', async () => { - const pair1 = dock.keyring.addFromUri(seed1); + const pair1 = new DidKeypair(dock.keyring.addFromUri(seed1), 1); const spType = new ServiceEndpointType(); spType.setLinkedDomains(); const origins = origins3Text.map((u) => u8aToHex(encoder.encode(u))); - await dock.did.addServiceEndpoint(spId3, spType, origins, hexDid2, hexDid1, pair1, 1, undefined, false); + await dock.did.addServiceEndpoint(spId3, spType, origins, hexDid2, hexDid1, pair1, undefined, false); const sp = await dock.did.getServiceEndpoint(dockDid2, spId3); expect(sp.type).toEqual(spType); expect(sp.origins).toEqual(origins); @@ -123,18 +123,18 @@ describe('DID service endpoints', () => { }); test('Remove service endpoint', async () => { - const pair1 = dock.keyring.addFromUri(seed1); + const pair1 = new DidKeypair(dock.keyring.addFromUri(seed1), 1); // `dockDid1` removes service endpoint of `dockDid2` - await dock.did.removeServiceEndpoint(spId2, hexDid2, hexDid1, pair1, 1, undefined, false); + await dock.did.removeServiceEndpoint(spId2, hexDid2, hexDid1, pair1, undefined, false); await expect(dock.did.getServiceEndpoint(dockDid2, spId2)).rejects.toThrow(); }); test('Removing DID removes service endpoint as well', async () => { - const pair1 = dock.keyring.addFromUri(seed1); + const pair1 = new DidKeypair(dock.keyring.addFromUri(seed1), 1); - await dock.did.remove(dockDid1, dockDid1, pair1, 1); + await dock.did.remove(dockDid1, dockDid1, pair1); - await expect(dock.did.getOnchainDidDetail(hexDid1)).rejects.toThrow(NoDIDError); + await expect(dock.did.getOnchainDidDetail(hexDid1.asDid)).rejects.toThrow(NoDIDError); await expect(dock.did.getServiceEndpoint(dockDid1, spId1)).rejects.toThrow(); }); }); diff --git a/tests/integration/master.test.js b/tests/integration/master.test.js index 310140dc8..07473daa5 100644 --- a/tests/integration/master.test.js +++ b/tests/integration/master.test.js @@ -1,10 +1,11 @@ +/* import { Keyring } from '@polkadot/api'; import { cryptoWaitReady, randomAsU8a } from '@polkadot/util-crypto'; import { assert, u8aToHex, stringToU8a } from '@polkadot/util'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../test-constants'; import { DockAPI } from '../../src'; import { getSignatureFromKeyringPair, getStateChange } from '../../src/utils/misc'; -import { createDidSig } from '../../src/utils/did'; +import { createDidSig, typedHexDID } from '../../src/utils/did'; const ALICE_DID = u8aToHex(stringToU8a('Alice\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0')); const BOB_DID = u8aToHex(stringToU8a('Bob\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0')); @@ -244,12 +245,13 @@ async function allVote( const votes = []; for (const [did, key] of did_to_key) { - const nonce = await nc.didModule.getNextNonceForDid(did); + const nonce = await nc.didModule.getNextNonceForDid(typedHexDID(nc.api, did)); const vote = { nonce, data: { proposal: encodedProposal, roundNo } }; const encodedStateChange = getStateChange(nc.api, 'MasterVote', vote); const signature = getSignatureFromKeyringPair(key, encodedStateChange); - const didSig = createDidSig(did, 1, signature); + const didSig = createDidSig(typedHexDID(nc.api, did), 1, signature); votes.push({ sig: didSig, nonce }); } return votes; } +*/ diff --git a/tests/integration/revocation.test.js b/tests/integration/revocation.test.js index 549bb4206..25cbf8da5 100644 --- a/tests/integration/revocation.test.js +++ b/tests/integration/revocation.test.js @@ -7,7 +7,7 @@ import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI } from '../test-const import { OneOfPolicy, } from '../../src/utils/revocation'; -import { DidKeypair } from '../../src/utils/did' +import { DidKeypair, typedHexDID, typedHexDIDFromSubstrate } from '../../src/utils/did' import { registerNewDIDUsingPair } from './helpers'; describe('Revocation Module', () => { @@ -115,7 +115,7 @@ describe('Revocation Module', () => { // Note: Intentionally passing true and waiting for finalization as not doing that makes the multi-query check fail. // This seems like a bug since the single query check done in next loop work. Even the upgrade to @polkadot/api version 9.14 didn't fix - await dock.revocation.unrevoke(unrevoke, [[sig1, nonce1]], true); + await dock.revocation.unrevoke(unrevoke, [[nonce1, sig1]], true); for (let i = 0; i < rIdsArr.length; i++) { // eslint-disable-next-line no-await-in-loop @@ -187,15 +187,22 @@ describe('Revocation Module', () => { const reg = await dock.revocation.getRevocationRegistry(multipleControllerRegistryID); expect(reg.policy.isOneOf).toBe(true); - const controllerSet = reg.policy.toJSON().oneOf; - expect(controllerSet.length).toBe(2); + const controllerSet = reg.policy.asOneOf; + expect(controllerSet.toJSON().length).toBe(2); let hasFirstDID = false; let hasSecondDID = false; - controllerSet.forEach((controller) => { - if (controller === ownerDID) { + [...controllerSet.entries()] + .flatMap((v) => v) + .map(typedHexDIDFromSubstrate) + .forEach((controller) => { + if ( + controller.toString() === typedHexDID(dock.api, ownerDID).toString() + ) { hasFirstDID = true; - } else if (controller === ownerDID2) { + } else if ( + controller.toString() === typedHexDID(dock.api, ownerDID2).toString() + ) { hasSecondDID = true; } }); @@ -211,7 +218,7 @@ describe('Revocation Module', () => { expect(revocationStatus).toBe(true); // Unrevoke from another DID - await dock.revocation.unrevokeCredentialWithOneOfPolicy(multipleControllerRegistryID, revId, ownerDID2, pair2, 1, { didModule: dock.did }, false); + await dock.revocation.unrevokeCredentialWithOneOfPolicy(multipleControllerRegistryID, revId, ownerDID2, pair2, { didModule: dock.did }, false); const revocationStatus1 = await dock.revocation.getIsRevoked(multipleControllerRegistryID, revId); expect(revocationStatus1).toBe(false); diff --git a/tests/integration/schema.test.js b/tests/integration/schema.test.js index 11a92821c..53689906f 100644 --- a/tests/integration/schema.test.js +++ b/tests/integration/schema.test.js @@ -21,7 +21,6 @@ import { registerNewDIDUsingPair } from './helpers'; let account; let pair; let dockDID; -let hexDid; let blobId; let keyDoc; let validCredential; @@ -58,7 +57,7 @@ describe('Schema Blob Module Integration', () => { dockApi.setAccount(account); pair = new DidKeypair(dockApi.keyring.addFromUri(firstKeySeed), 1); dockDID = createNewDockDID(); - hexDid = typedHexDID(dock.api, dockDID); + hexDid = typedHexDID(dockApi.api, dockDID); await registerNewDIDUsingPair(dockApi, dockDID, pair); blobId = randomAsHex(DockBlobIdByteSize); @@ -122,11 +121,11 @@ describe('Schema Blob Module Integration', () => { test('Set and get schema', async () => { const schema = new Schema(); await schema.setJSONSchema(exampleSchema); - await dockApi.blob.new(schema.toBlob(), hexDid, pair, { didModule: dockApi.didModule }, false); + await dockApi.blob.new(schema.toBlob(), dockDID, pair, { didModule: dockApi.didModule }, false); await expect(Schema.get(blobId, dockApi)).resolves.toMatchObject({ ...exampleSchema, id: blobId, - author: hexDIDToQualified(typedHexDID(dock.api, dockDID)), + author: hexDIDToQualified(typedHexDID(dockApi.api, dockDID)), }); }, 20000); From 48059807d22bdc1c772a0ad1862dbfcb49bf1824 Mon Sep 17 00:00:00 2001 From: olegnn Date: Thu, 28 Dec 2023 17:42:12 +0400 Subject: [PATCH 15/32] Tweaks --- scripts/master_voting/vote.js | 2 +- src/modules/WithParamsAndPublicKeys.js | 10 ++-- src/modules/accumulator.js | 19 ++++--- src/modules/blob.js | 2 +- src/modules/did/did.js | 56 +++++++++---------- src/modules/offchain-signatures.js | 12 ++-- src/modules/revocation.js | 4 +- src/modules/status-list-credential.js | 2 +- src/modules/trust-registry.js | 9 ++- src/utils/did.js | 55 +++++++++--------- src/utils/revocation/one-of-policy.js | 2 +- .../integration/anoncreds/accumulator.test.js | 10 ++-- tests/integration/anoncreds/scheme.test.js | 10 ++-- tests/integration/blob.test.js | 10 ++-- tests/integration/custom-nonce.test.js | 26 ++++----- tests/integration/did/controllers.test.js | 6 +- tests/integration/did/did-basic.test.js | 2 +- tests/integration/did/keys.test.js | 2 +- tests/integration/did/offchain-did.test.js | 2 +- .../integration/did/service-endpoint.test.js | 4 +- tests/integration/master.test.js | 4 +- tests/integration/revocation.test.js | 4 +- tests/integration/schema.test.js | 4 +- .../status-list-credential-module.test.js | 4 +- .../integration/trust-registry-module.test.js | 32 +++++------ 25 files changed, 148 insertions(+), 145 deletions(-) diff --git a/scripts/master_voting/vote.js b/scripts/master_voting/vote.js index 4b2e4afc1..dbcf3eec7 100644 --- a/scripts/master_voting/vote.js +++ b/scripts/master_voting/vote.js @@ -45,7 +45,7 @@ async function main() { const round_no = parseIntChecked(process.argv[2]); - const did = typedHexDID(dock.api, did); + const did = typedHexDID(did); const proposal_filename = process.argv[3]; const proposal_unparsed = await fsp.readFile(proposal_filename); diff --git a/src/modules/WithParamsAndPublicKeys.js b/src/modules/WithParamsAndPublicKeys.js index 37eba5c05..04acb3d78 100644 --- a/src/modules/WithParamsAndPublicKeys.js +++ b/src/modules/WithParamsAndPublicKeys.js @@ -86,7 +86,7 @@ export default class WithParamsAndPublicKeys { throw new Error('Reference should be an array of 2 items'); } try { - parsed[0] = typedHexDID(this.api, ref[0]); + parsed[0] = typedHexDID(ref[0]); } catch (e) { throw new Error( `First item of reference should be a DID but was ${ref[0]}`, @@ -120,7 +120,7 @@ export default class WithParamsAndPublicKeys { { nonce = undefined, didModule = undefined }, ) { const offchainParams = this.constructor.buildParams(params); - const hexDid = typedHexDID(this.api, signerDid); + const hexDid = typedHexDID(signerDid); const [addParams, signature] = await this.createSignedAddParams( offchainParams, hexDid, @@ -147,7 +147,7 @@ export default class WithParamsAndPublicKeys { signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const hexDid = typedHexDID(this.api, signerDid); + const hexDid = typedHexDID(signerDid); const [removeParams, signature] = await this.createSignedRemoveParams( index, hexDid, @@ -252,7 +252,7 @@ export default class WithParamsAndPublicKeys { } async getParams(did, counter) { - const hexId = typedHexDID(this.api, did); + const hexId = typedHexDID(did); return this.getParamsByHexDid(hexId, counter); } @@ -265,7 +265,7 @@ export default class WithParamsAndPublicKeys { * @returns {Promise<{bytes: string}|null>} */ async getPublicKey(did, keyId, withParams = false) { - const hexId = typedHexDID(this.api, did); + const hexId = typedHexDID(did); return this.getPublicKeyByHexDid(hexId, keyId, withParams); } diff --git a/src/modules/accumulator.js b/src/modules/accumulator.js index 6e409782c..f1948b00a 100644 --- a/src/modules/accumulator.js +++ b/src/modules/accumulator.js @@ -84,7 +84,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<*>} */ async createAddPublicKeyTx(publicKey, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(this.api, signerDid); + const signerHexDid = typedHexDID(signerDid); const [addPk, signature] = await this.createSignedAddPublicKey(publicKey, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addPublicKey(addPk, signature); } @@ -100,7 +100,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<*>} */ async createRemovePublicKeyTx(removeKeyId, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(this.api, signerDid); + const signerHexDid = typedHexDID(signerDid); const [remPk, signature] = await this.createSignedRemovePublicKey(removeKeyId, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.removePublicKey(remPk, signature); } @@ -118,7 +118,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<*>} */ async createAddPositiveAccumulatorTx(id, accumulated, publicKeyRef, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(this.api, signerDid); + const signerHexDid = typedHexDID(signerDid); const [addAccumulator, signature] = await this.createSignedAddPositiveAccumulator(id, accumulated, publicKeyRef, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addAccumulator(addAccumulator, signature); } @@ -137,7 +137,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<*>} */ async createAddUniversalAccumulatorTx(id, accumulated, publicKeyRef, maxSize, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(this.api, signerDid); + const signerHexDid = typedHexDID(signerDid); const [addAccumulator, signature] = await this.createSignedAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addAccumulator(addAccumulator, signature); } @@ -160,7 +160,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { id, newAccumulated, { additions = undefined, removals = undefined, witnessUpdateInfo = undefined }, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const signerHexDid = typedHexDID(this.api, signerDid); + const signerHexDid = typedHexDID(signerDid); const [update, signature] = await this.createSignedUpdateAccumulator(id, newAccumulated, { additions, removals, witnessUpdateInfo }, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.updateAccumulator(update, signature); @@ -177,7 +177,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise} */ async removeAccumulatorTx(id, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(this.api, signerDid); + const signerHexDid = typedHexDID(signerDid); const [removal, signature] = await this.createSignedRemoveAccumulator(id, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.removeAccumulator(removal, signature); } @@ -460,7 +460,8 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<{bytes: string}|null>} */ async getLastParamsWritten(did) { - const hexId = typedHexDID(this.api, did); + const hexId = typedHexDID(did); + const counters = await this.api.query[this.moduleName].accumulatorOwnerCounters(hexId); const counter = counters.paramsCounter.toNumber(); if (counter > 0) { @@ -478,7 +479,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise} */ async getAllParamsByDid(did) { - const hexId = typedHexDID(this.api, did); + const hexId = typedHexDID(did); const params = []; const counters = await this.api.query[this.moduleName].accumulatorOwnerCounters(hexId); @@ -502,7 +503,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise< object[]>} */ async getAllPublicKeysByDid(did, withParams = false) { - const hexId = typedHexDID(this.api, did); + const hexId = typedHexDID(did); const pks = []; const counters = await this.api.query[this.moduleName].accumulatorOwnerCounters(hexId); diff --git a/src/modules/blob.js b/src/modules/blob.js index 59ed11519..8d013ab70 100644 --- a/src/modules/blob.js +++ b/src/modules/blob.js @@ -84,7 +84,7 @@ class BlobModule { * @returns {Promise<*>} */ async createNewTx(blob, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(this.api, signerDid); + const signerHexDid = typedHexDID(signerDid); const [addBlob, didSig] = await this.createSignedAddBlob(blob, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.new(addBlob, didSig); } diff --git a/src/modules/did/did.js b/src/modules/did/did.js index 9aa7a3eb7..04ba87577 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -51,7 +51,7 @@ class DIDModule { * @returns {*} */ createNewOffchainTx(did, didDocRef) { - const hexId = typedHexDID(this.api, did).asDid; + const hexId = typedHexDID(did).asDid; return this.module.newOffchain(hexId, didDocRef); } @@ -78,7 +78,7 @@ class DIDModule { * @returns {*} */ createSetOffchainDidRefTx(did, didDocRef) { - const hexId = typedHexDID(this.api, did).asDid; + const hexId = typedHexDID(did).asDid; return this.module.setOffchainDidDocRef(hexId, didDocRef); } @@ -109,7 +109,7 @@ class DIDModule { * @returns {Promise<*>} */ createRemoveOffchainDidTx(did) { - const hexId = typedHexDID(this.api, did).asDid; + const hexId = typedHexDID(did).asDid; return this.module.removeOffchainDid(hexId); } @@ -139,10 +139,10 @@ class DIDModule { const cnts = new BTreeSet(); if (controllers !== undefined) { controllers.forEach((c) => { - cnts.add(typedHexDID(this.api, c)); + cnts.add(typedHexDID(c)); }); } - const hexId = typedHexDID(this.api, did).asDid; + const hexId = typedHexDID(did).asDid; return this.module.newOnchain( hexId, didKeys.map((d) => d.toJSON()), @@ -152,7 +152,7 @@ class DIDModule { /** * Creates a new DID on the Dock chain. - * @param {string} did - The new DID. Can be a full DID or hex identifier + * @param {string} did - The new DID. Can be aw full DID or hex identifier * @param {DidKey[]} didKeys - Array of `DidKey`s as expected by the Substrate node * @param {array} controllers - Array of `Did`s as expected by the Substrate node. * @param waitForFinalization @@ -190,8 +190,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(this.api, targetDid).asDid; - const signerHexDid = typedHexDID(this.api, signerDid); + const targetHexDid = typedHexDID(targetDid).asDid; + const signerHexDid = typedHexDID(signerDid); const [addKeys, signature] = await this.createSignedAddKeys( didKeys, targetHexDid, @@ -253,8 +253,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(this.api, targetDid).asDid; - const signerHexDid = typedHexDID(this.api, signerDid); + const targetHexDid = typedHexDID(targetDid).asDid; + const signerHexDid = typedHexDID(signerDid); const [addControllers, signature] = await this.createSignedAddControllers( controllers, targetHexDid, @@ -317,8 +317,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(this.api, targetDid).asDid; - const signerHexDid = typedHexDID(this.api, signerDid); + const targetHexDid = typedHexDID(targetDid).asDid; + const signerHexDid = typedHexDID(signerDid); const [addServiceEndpoint, signature] = await this.createSignedAddServiceEndpoint( endpointId, endpointType, @@ -385,8 +385,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(this.api, targetDid).asDid; - const signerHexDid = typedHexDID(this.api, signerDid); + const targetHexDid = typedHexDID(targetDid).asDid; + const signerHexDid = typedHexDID(signerDid); const [removeKeys, signature] = await this.createSignedRemoveKeys( keyIds, targetHexDid, @@ -445,8 +445,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(this.api, targetDid).asDid; - const signerHexDid = typedHexDID(this.api, signerDid); + const targetHexDid = typedHexDID(targetDid).asDid; + const signerHexDid = typedHexDID(signerDid); const [removeControllers, signature] = await this.createSignedRemoveControllers( controllers, targetHexDid, @@ -505,8 +505,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(this.api, targetDid).asDid; - const signerHexDid = typedHexDID(this.api, signerDid); + const targetHexDid = typedHexDID(targetDid).asDid; + const signerHexDid = typedHexDID(signerDid); const [removeServiceEndpoint, signature] = await this.createSignedRemoveServiceEndpoint( endpointId, targetHexDid, @@ -558,8 +558,8 @@ class DIDModule { * @return {Promise} The extrinsic to sign and send. */ async createRemoveTx(targetDid, signerDid, signingKeyRef, nonce = undefined) { - const hexDid = typedHexDID(this.api, targetDid).asDid; - const signerHexDid = typedHexDID(this.api, signerDid); + const hexDid = typedHexDID(targetDid).asDid; + const signerHexDid = typedHexDID(signerDid); const [didRemoval, signature] = await this.createSignedDidRemoval( hexDid, signerHexDid, @@ -607,7 +607,7 @@ class DIDModule { * @returns {Promise>} */ async createSetClaimTx(priority, iri, did, signingKeyRef, nonce = undefined) { - const hexDid = typedHexDID(this.api, did); + const hexDid = typedHexDID(did); const [setAttestation, signature] = await this.createSignedAttestation( priority, iri, @@ -687,7 +687,7 @@ class DIDModule { */ // eslint-disable-next-line sonarjs/cognitive-complexity async getDocument(did, { getOffchainSigKeys = true } = {}) { - const typedDid = typedHexDID(this.api, did); + const typedDid = typedHexDID(did); const hexDid = typedDid.asDid; let didDetails = await this.getOnchainDidDetail(hexDid); didDetails = didDetails.data || didDetails; @@ -1051,7 +1051,7 @@ class DIDModule { * @returns {Promise} */ async getDidKey(did, keyIndex) { - const hexId = typedHexDID(this.api, did).asDid; + const hexId = typedHexDID(did).asDid; let resp = await this.api.query.didModule.didKeys(hexId, keyIndex); if (resp.isNone) { throw new Error(`No key for found did ${did} and key index ${keyIndex}`); @@ -1093,8 +1093,8 @@ class DIDModule { * @returns {Promise} */ async isController(controlled, controller) { - const controlledDid = typedHexDID(this.api, controlled).asDid; - const controllerDid = typedHexDID(this.api, controller); + const controlledDid = typedHexDID(controlled).asDid; + const controllerDid = typedHexDID(controller); const resp = await this.api.query.didModule.didControllers( controlledDid, controllerDid, @@ -1109,7 +1109,7 @@ class DIDModule { * @returns {Promise} */ async getServiceEndpoint(did, endpointId) { - const hexId = typedHexDID(this.api, did).asDid; + const hexId = typedHexDID(did).asDid; let resp = await this.api.query.didModule.didServiceEndpoints( hexId, endpointId, @@ -1160,7 +1160,7 @@ class DIDModule { const cnts = new BTreeSet(); controllers.forEach((c) => { - cnts.add(typedHexDID(this.api, c)); + cnts.add(typedHexDID(c)); }); const addControllers = { did: hexDid, controllers: cnts, nonce }; const serializedAddControllers = this.getSerializedAddControllers(addControllers); @@ -1233,7 +1233,7 @@ class DIDModule { const cnts = new BTreeSet(); controllers.forEach((c) => { - cnts.add(typedHexDID(this.api, c)); + cnts.add(typedHexDID(c)); }); const removeControllers = { did: hexDid, controllers: cnts, nonce }; diff --git a/src/modules/offchain-signatures.js b/src/modules/offchain-signatures.js index d0739f551..ebf830dd9 100644 --- a/src/modules/offchain-signatures.js +++ b/src/modules/offchain-signatures.js @@ -50,7 +50,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @returns {Promise<{bytes: string}|null>} */ async getLastParamsWritten(did) { - const hexId = typedHexDID(this.api, did); + const hexId = typedHexDID(did); const counter = await this.api.query[this.moduleName].paramsCounter(hexId); if (counter > 0) { const resp = await this.queryParamsFromChain(hexId, counter); @@ -67,7 +67,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @returns {Promise} */ async getAllParamsByDid(did) { - const hexId = typedHexDID(this.api, did); + const hexId = typedHexDID(did); const params = []; const counter = await this.api.query[this.moduleName].paramsCounter(hexId); @@ -128,8 +128,8 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { { nonce = undefined, didModule = undefined }, ) { const offchainPublicKey = this.constructor.buildPublicKey(publicKey); - const targetHexDid = typedHexDID(this.api, targetDid).asDid; - const signerHexDid = typedHexDID(this.api, signerDid); + const targetHexDid = typedHexDID(targetDid).asDid; + const signerHexDid = typedHexDID(signerDid); const [addPk, signature] = await this.createSignedAddPublicKey( offchainPublicKey, targetHexDid, @@ -158,8 +158,8 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const targetHexDid = typedHexDID(this.api, targetDid).asDid; - const signerHexDid = typedHexDID(this.api, signerDid); + const targetHexDid = typedHexDID(targetDid).asDid; + const signerHexDid = typedHexDID(signerDid); const [removePk, signature] = await this.createSignedRemovePublicKey( removeKeyId, targetHexDid, diff --git a/src/modules/revocation.js b/src/modules/revocation.js index f610cc2ea..5c10f7e8b 100644 --- a/src/modules/revocation.js +++ b/src/modules/revocation.js @@ -213,7 +213,7 @@ class RevocationModule { } async createSignedUpdate(updateFunc, registryId, [...revokeIds], did, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const hexDid = typedHexDID(this.api, did); + const hexDid = typedHexDID(did); // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); @@ -239,7 +239,7 @@ class RevocationModule { } async createSignedRemove(registryId, did, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const hexDid = typedHexDID(this.api, did); + const hexDid = typedHexDID(did); // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); diff --git a/src/modules/status-list-credential.js b/src/modules/status-list-credential.js index 2240b9dd9..c70cf3332 100644 --- a/src/modules/status-list-credential.js +++ b/src/modules/status-list-credential.js @@ -244,7 +244,7 @@ export default class StatusListCredentialModule { signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const hexDid = typedHexDID(this.api, did); + const hexDid = typedHexDID(did); // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); diff --git a/src/modules/trust-registry.js b/src/modules/trust-registry.js index 5f4407b12..a0b6f3c0e 100644 --- a/src/modules/trust-registry.js +++ b/src/modules/trust-registry.js @@ -37,11 +37,12 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerHexDid = typedHexDID(this.api, convenerDid); + const convenerHexDid = typedHexDID(convenerDid); const lastNonce = nonce ?? await getDidNonce(convenerHexDid, nonce, didModule); return this.signAndSend( convenerHexDid.changeState( + this.api, this.module.initTrustRegistry.bind(this.module), 'InitTrustRegistry', { registryId, name, nonce: lastNonce }, @@ -72,11 +73,12 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerHexDid = typedHexDID(this.api, convenerDid); + const convenerHexDid = typedHexDID(convenerDid); const lastNonce = nonce ?? await getDidNonce(convenerHexDid, nonce, didModule); return this.signAndSend( convenerHexDid.changeState( + this.api, this.module.addSchemaMetadata, 'AddSchemaMetadata', { registryId, schemas, nonce: lastNonce }, @@ -107,11 +109,12 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerOrIssuerOrVerifierHexDid = typedHexDID(this.api, convenerOrIssuerOrVerifierDid); + const convenerOrIssuerOrVerifierHexDid = typedHexDID(convenerOrIssuerOrVerifierDid); const lastNonce = nonce ?? await getDidNonce(convenerOrIssuerOrVerifierHexDid, nonce, didModule); return this.signAndSend( convenerOrIssuerOrVerifierHexDid.changeState( + this.api, this.module.updateSchemaMetadata, 'UpdateSchemaMetadata', { registryId, schemas, nonce: lastNonce }, diff --git a/src/utils/did.js b/src/utils/did.js index 071f578e0..9205ea462 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -24,10 +24,10 @@ export const Secp256k1PublicKeyPrefix = 'zQ3'; export const Ed25519PublicKeyPrefix = 'z6Mk'; export const DockDIDQualifier = `did:${DockDIDMethod}:`; -export const DockDIDMethodKeyQualifier = `did:key:${DockDIDMethod}:`; +export const DockDIDMethodKeyQualifier = `did:key:`; export const DockDIDByteSize = 32; -export const DockDidMethodKeySecp256k1Prefix = `${DockDIDQualifier}${Secp256k1PublicKeyPrefix}`; +export const DockDidMethodKeySecp256k1Prefix = `${DockDIDMethodKeyQualifier}${Secp256k1PublicKeyPrefix}`; export const DockDidMethodKeyEd25519Prefix = `${DockDIDMethodKeyQualifier}${Ed25519PublicKeyPrefix}`; export class DidKeypair { @@ -45,11 +45,22 @@ export class DidKeypair { } } -export class DockDidOrDidMethodKey { - constructor(api) { - Object.defineProperty(this, 'api', { value: api }); +export class DidActor { + signStateChange(api, name, payload, keyRef) { + const stateChange = getStateChange(api, name, payload); + const keySignature = keyRef.sign(stateChange); + + return createDidSig(this, keyRef, keySignature); } + changeState(api, method, name, payload, keyRef) { + const signature = this.signStateChange(api, name, payload, keyRef); + + return method(payload, signature); + } +} + +export class DockDidOrDidMethodKey extends DidActor { get asDid() { throw new Error('Not a `Did`'); } @@ -65,24 +76,11 @@ export class DockDidOrDidMethodKey { get isDidMethodKey() { return false; } - - signStateChange(name, payload, keyRef) { - const stateChange = getStateChange(this.api, name, payload); - const keySignature = keyRef.sign(stateChange); - - return createDidSig(this, keyRef, keySignature); - } - - changeState(method, name, payload, keyRef) { - const signature = this.signStateChange(name, payload, keyRef); - - return method(payload, signature); - } } export class DockDid extends DockDidOrDidMethodKey { - constructor(did, api) { - super(api); + constructor(did) { + super(); this.did = did; } @@ -108,8 +106,8 @@ export class DockDid extends DockDidOrDidMethodKey { } export class DockDidMethodKey extends DockDidOrDidMethodKey { - constructor(didMethodKey, api) { - super(api); + constructor(didMethodKey) { + super(); this.didMethodKey = didMethodKey; } @@ -199,12 +197,11 @@ export function validateDockDIDSS58Identifier(identifier) { /** * Takes a DID string, gets the hexadecimal value of that and returns a `DockDidMethodKey` or `DockDid` object. - * @param {*} api * @param {string} did - The DID can be passed as fully qualified DID like `did:dock:` or * `did:key:` or a 32 byte hex string * @return {DockDidOrDidMethodKey} Returns a `DockDidMethodKey` or `DockDid` object. */ -export function typedHexDID(api, did) { +export function typedHexDID(did) { const strDid = did.toString(); const hex = getHexIdentifier( did, @@ -213,12 +210,12 @@ export function typedHexDID(api, did) { ); if (strDid.startsWith(DockDidMethodKeySecp256k1Prefix)) { - return new DockDidMethodKey(new PublicKeySecp256k1(hex), api); + return new DockDidMethodKey(new PublicKeySecp256k1(hex)); } else if (strDid.startsWith(DockDidMethodKeyEd25519Prefix)) { - return new DockDidMethodKey(new PublicKeyEd25519(hex), api); + return new DockDidMethodKey(new PublicKeyEd25519(hex)); } else { validateDockDIDHexIdentifier(hex); - return new DockDid(hex, api); + return new DockDid(hex); } } @@ -237,8 +234,10 @@ export function typedHexDIDFromSubstrate(did) { if (did.isDid) { return new DockDid(hex); - } else { + } else if (did.isDidMethodKey) { return new DockDidMethodKey(hex); + } else { + throw new Error(`Invalid did provided: \`${did}\``) } } diff --git a/src/utils/revocation/one-of-policy.js b/src/utils/revocation/one-of-policy.js index 16ed2b47a..3c34ebe2f 100644 --- a/src/utils/revocation/one-of-policy.js +++ b/src/utils/revocation/one-of-policy.js @@ -26,7 +26,7 @@ export default class OneOfPolicy extends Policy { * @param {string} ownerDID - Owner's DID */ controllerIds() { - const controllerIds = [...this.controllers].map((controller) => typedHexDID(null, controller)); + const controllerIds = [...this.controllers].map(typedHexDID); // Sort the controller ids as the node is expecting sorted ids and keeping ids unsorted is giving a signature // verification error. This is a workaround and is needed for now. It maybe fixed later controllerIds.sort(); diff --git a/tests/integration/anoncreds/accumulator.test.js b/tests/integration/anoncreds/accumulator.test.js index 0a90a290f..22c60321e 100644 --- a/tests/integration/anoncreds/accumulator.test.js +++ b/tests/integration/anoncreds/accumulator.test.js @@ -158,7 +158,7 @@ describe("Accumulator Module", () => { const queriedPk2 = await chainModule.getPublicKey(did2, 1); expect(queriedPk2.bytes).toEqual(pk2.bytes); - expect(queriedPk2.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); + expect(queriedPk2.paramsRef).toEqual([typedHexDID(did1), 1]); const queriedPk2WithParams = await chainModule.getPublicKey(did2, 1, true); expect(queriedPk2WithParams.params).toEqual(params1); @@ -181,7 +181,7 @@ describe("Accumulator Module", () => { const queriedPk3 = await chainModule.getPublicKey(did2, 2); expect(queriedPk3.bytes).toEqual(pk3.bytes); - expect(queriedPk3.paramsRef).toEqual([typedHexDID(dock.api, did1), 2]); + expect(queriedPk3.paramsRef).toEqual([typedHexDID(did1), 2]); const queriedPk3WithParams = await chainModule.getPublicKey(did2, 2, true); expect(queriedPk3WithParams.params).toEqual(params2); @@ -234,7 +234,7 @@ describe("Accumulator Module", () => { expect(accum1.created).toEqual(accum1.lastModified); expect(accum1.type).toEqual("positive"); expect(accum1.accumulated).toEqual(accumulated1); - expect(accum1.keyRef).toEqual([typedHexDID(dock.api, did1), 1]); + expect(accum1.keyRef).toEqual([typedHexDID(did1), 1]); expect(accum1.publicKey).toBeUndefined(); const accum2 = await chainModule.getAccumulator(id2, false); @@ -243,7 +243,7 @@ describe("Accumulator Module", () => { expect(accum2.created).toEqual(accum2.lastModified); expect(accum2.type).toEqual("universal"); expect(accum2.accumulated).toEqual(accumulated2); - expect(accum2.keyRef).toEqual([typedHexDID(dock.api, did2), 1]); + expect(accum2.keyRef).toEqual([typedHexDID(did2), 1]); expect(accum2.publicKey).toBeUndefined(); const keyWithParams = await chainModule.getPublicKey(did2, 1, true); @@ -255,7 +255,7 @@ describe("Accumulator Module", () => { ); expect(accum2WithKeyAndParams.type).toEqual("universal"); expect(accum2WithKeyAndParams.accumulated).toEqual(accumulated2); - expect(accum2WithKeyAndParams.keyRef).toEqual([typedHexDID(dock.api, did2), 1]); + expect(accum2WithKeyAndParams.keyRef).toEqual([typedHexDID(did2), 1]); expect(accum2WithKeyAndParams.publicKey).toEqual(keyWithParams); await chainModule.removeAccumulator( diff --git a/tests/integration/anoncreds/scheme.test.js b/tests/integration/anoncreds/scheme.test.js index abc0152a3..0720de256 100644 --- a/tests/integration/anoncreds/scheme.test.js +++ b/tests/integration/anoncreds/scheme.test.js @@ -86,7 +86,7 @@ for (const { expect(paramsWritten1.label).toEqual(params1.label); const allParams = await getParamsByDid( dock.api, - typedHexDID(dock.api, did1), + typedHexDID(did1), ); expect(Object.values(allParams.toJSON())).toEqual([params1]); @@ -181,9 +181,9 @@ for (const { ); const queriedPk2 = await chainModule.getPublicKey(did2, 2); expect(queriedPk2.bytes).toEqual(pk2.bytes); - expect(queriedPk2.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); + expect(queriedPk2.paramsRef).toEqual([typedHexDID(did1), 1]); const keyWithParams = await getPublicKeyWithParamsByStorageKey(dock.api, [ - typedHexDID(dock.api, did2).asDid, + typedHexDID(did2).asDid, 2, ]); const jsonKeyWithParams = keyWithParams.toJSON(); @@ -222,7 +222,7 @@ for (const { const queriedPk3 = await chainModule.getPublicKey(did2, 3); expect(queriedPk3.bytes).toEqual(pk3.bytes); - expect(queriedPk3.paramsRef).toEqual([typedHexDID(dock.api, did1), 2]); + expect(queriedPk3.paramsRef).toEqual([typedHexDID(did1), 2]); const queriedPk3WithParams = await chainModule.getPublicKey( did2, @@ -232,7 +232,7 @@ for (const { expect(queriedPk3WithParams.params).toEqual(queriedParams2); const allPks = await getPublicKeysByDid( dock.api, - typedHexDID(dock.api, did2), + typedHexDID(did2), ); expect( Object.values(allPks.toJSON()).map((keyWithParams) => { diff --git a/tests/integration/blob.test.js b/tests/integration/blob.test.js index 2003f971a..73bb8f941 100644 --- a/tests/integration/blob.test.js +++ b/tests/integration/blob.test.js @@ -36,7 +36,7 @@ describe('Blob Module', () => { dock.setAccount(account); pair = new DidKeypair(dock.keyring.addFromUri(firstKeySeed), 1); dockDID = createNewDockDID(); - await registerNewDIDUsingPair(dock, typedHexDID(dock.api, dockDID), pair); + await registerNewDIDUsingPair(dock, typedHexDID(dockDID), pair); }); afterAll(async () => { @@ -61,7 +61,7 @@ describe('Blob Module', () => { const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dockDID)); expect(chainBlob[1]).toEqual(blobJSON); }, 30000); @@ -77,7 +77,7 @@ describe('Blob Module', () => { const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dockDID)); expect(u8aToString(chainBlob[1])).toEqual(blobHex); }, 30000); @@ -94,7 +94,7 @@ describe('Blob Module', () => { const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dockDID)); expect(u8aToHex(chainBlob[1])).toEqual(blobHex); }, 30000); @@ -111,7 +111,7 @@ describe('Blob Module', () => { const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dockDID)); expect(chainBlob[1]).toEqual(blobVect); }, 30000); diff --git a/tests/integration/custom-nonce.test.js b/tests/integration/custom-nonce.test.js index ae8958733..7a4523784 100644 --- a/tests/integration/custom-nonce.test.js +++ b/tests/integration/custom-nonce.test.js @@ -54,7 +54,7 @@ describe('Custom nonce', () => { }, 10000); test('Add key, controller, service endpoint, blob, BBS+ params and keys and accumulator in a batch', async () => { - const nonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); + const nonce = await dock.didModule.getNonceForDid(typedHexDID(did1)); const pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); const txs = []; @@ -148,7 +148,7 @@ describe('Custom nonce', () => { const queriedPk = await dock.bbsPlusModule.getPublicKey(did1, 3); expect(queriedPk.bytes).toEqual(pk.bytes); - expect(queriedPk.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); + expect(queriedPk.paramsRef).toEqual([typedHexDID(did1), 1]); const queriedParams1 = await dock.accumulatorModule.getParams(did1, 1); expect(queriedParams1.bytes).toEqual(addParams1.bytes); @@ -156,17 +156,17 @@ describe('Custom nonce', () => { const queriedPk1 = await dock.accumulatorModule.getPublicKey(did1, 1); expect(queriedPk1.bytes).toEqual(pk1.bytes); - expect(queriedPk1.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); + expect(queriedPk1.paramsRef).toEqual([typedHexDID(did1), 1]); const accum1 = await dock.accumulatorModule.getAccumulator(id1, true); expect(accum1.type).toEqual('positive'); expect(accum1.accumulated).toEqual(accumulated1); - expect(accum1.keyRef).toEqual([typedHexDID(dock.api, did1), 1]); + expect(accum1.keyRef).toEqual([typedHexDID(did1), 1]); const accum2 = await dock.accumulatorModule.getAccumulator(id2, true); expect(accum2.type).toEqual('universal'); expect(accum2.accumulated).toEqual(accumulated2); - expect(accum2.keyRef).toEqual([typedHexDID(dock.api, did1), 1]); + expect(accum2.keyRef).toEqual([typedHexDID(did1), 1]); expect(accum1.created).toEqual(accum2.created); expect(accum1.lastModified).toEqual(accum2.lastModified); }, 20000); @@ -193,7 +193,7 @@ describe('Custom nonce', () => { await dock.revocation.newRegistry(registryId3, policy, false, false); const pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); - let currentNonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); + let currentNonce = await dock.didModule.getNonceForDid(typedHexDID(did1)); let txs = []; // Revoke from all 3 registries in the same transaction batch @@ -218,7 +218,7 @@ describe('Custom nonce', () => { } // Remove from all 3 registries in the same transaction batch - currentNonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); + currentNonce = await dock.didModule.getNonceForDid(typedHexDID(did1)); txs = []; for (const [regId, nonce] of [[registryId1, currentNonce + 1], [registryId2, currentNonce + 2], [registryId3, currentNonce + 3]]) { const [remove, sig, computedNonce] = await dock.revocation.createSignedRemove(regId, did1, pair, { nonce }); @@ -257,7 +257,7 @@ describe('Custom nonce', () => { const pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); - let nonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); + let nonce = await dock.didModule.getNonceForDid(typedHexDID(did1)); let txs = []; // Add a key and a service endpoint to each DID @@ -295,9 +295,9 @@ describe('Custom nonce', () => { await expect(dock.did.getServiceEndpoint(did5, spId5)).resolves.toEqual({ type: spType, origins: origins[2] }); // Each DID adds 2 blobs - const nonce3 = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did3)); - const nonce4 = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did4)); - const nonce5 = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did5)); + const nonce3 = await dock.didModule.getNonceForDid(typedHexDID(did3)); + const nonce4 = await dock.didModule.getNonceForDid(typedHexDID(did4)); + const nonce5 = await dock.didModule.getNonceForDid(typedHexDID(did5)); txs = []; const [[blobId1, blobHex1, blob1], [blobId2, blobHex2, blob2], [blobId3, blobHex3, blob3], [blobId4, blobHex4, blob4], [blobId5, blobHex5, blob5], [blobId6, blobHex6, blob6]] = [1, 2, 3, 4, 5, 6].map((_) => { @@ -332,11 +332,11 @@ describe('Custom nonce', () => { const chainBlob = await dock.blob.get(bi); expect(!!chainBlob).toBe(true); expect(u8aToHex(chainBlob[1])).toEqual(bh); - expect(chainBlob[0]).toEqual(typedHexDID(dock.api, d)); + expect(chainBlob[0]).toEqual(typedHexDID(d)); } // Remove all DIDs in a batch - nonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); + nonce = await dock.didModule.getNonceForDid(typedHexDID(did1)); txs = []; const tx13 = await dock.did.createRemoveTx(did3, did1, pair, nonce + 1); diff --git a/tests/integration/did/controllers.test.js b/tests/integration/did/controllers.test.js index 74173c50e..7b7c8c0a5 100644 --- a/tests/integration/did/controllers.test.js +++ b/tests/integration/did/controllers.test.js @@ -10,15 +10,15 @@ describe('DID controllers', () => { const dock = new DockAPI(); const dockDid1 = createNewDockDID(); - const hexDid1 = typedHexDID(dock.api, dockDid1); + const hexDid1 = typedHexDID(dockDid1); // This DID will be controlled by itself and dockDid1 const dockDid2 = createNewDockDID(); - const hexDid2 = typedHexDID(dock.api, dockDid2); + const hexDid2 = typedHexDID(dockDid2); // This DID will not control itself but will be controlled by dockDid1 and dockDid2 const dockDid3 = createNewDockDID(); - const hexDid3 = typedHexDID(dock.api, dockDid3); + const hexDid3 = typedHexDID(dockDid3); const seed1 = randomAsHex(32); const seed2 = randomAsHex(32); diff --git a/tests/integration/did/did-basic.test.js b/tests/integration/did/did-basic.test.js index 6bdf209af..170458ed6 100644 --- a/tests/integration/did/did-basic.test.js +++ b/tests/integration/did/did-basic.test.js @@ -21,7 +21,7 @@ describe('Basic DID tests', () => { // Generate a random DID const dockDid = createNewDockDID(); - const typedDid = typedHexDID(dock.api, dockDid); + const typedDid = typedHexDID(dockDid); const hexDid = typedDid.asDid; // Generate first key with this seed. The key type is Sr25519 diff --git a/tests/integration/did/keys.test.js b/tests/integration/did/keys.test.js index 102231619..1a1a95d16 100644 --- a/tests/integration/did/keys.test.js +++ b/tests/integration/did/keys.test.js @@ -12,7 +12,7 @@ describe('Key support for DIDs', () => { // Generate a random DID const dockDid = createNewDockDID(); - const hexDid = typedHexDID(dock.api, dockDid); + const hexDid = typedHexDID(dockDid); const seed1 = randomAsHex(32); const seed2 = randomAsHex(32); diff --git a/tests/integration/did/offchain-did.test.js b/tests/integration/did/offchain-did.test.js index 7943ef840..9787d2329 100644 --- a/tests/integration/did/offchain-did.test.js +++ b/tests/integration/did/offchain-did.test.js @@ -13,7 +13,7 @@ describe('Off-chain DIDs', () => { // Generate a random DID const dockDID = createNewDockDID(); - const hexDID = typedHexDID(dock.api, dockDID); + const hexDID = typedHexDID(dockDID); const firstDocRef = randomAsHex(100); const secondDocRef = randomAsHex(110); diff --git a/tests/integration/did/service-endpoint.test.js b/tests/integration/did/service-endpoint.test.js index 8fe1a5654..3e5787bec 100644 --- a/tests/integration/did/service-endpoint.test.js +++ b/tests/integration/did/service-endpoint.test.js @@ -13,11 +13,11 @@ describe('DID service endpoints', () => { const dock = new DockAPI(); const dockDid1 = createNewDockDID(); - const hexDid1 = typedHexDID(dock.api, dockDid1); + const hexDid1 = typedHexDID(dockDid1); // This DID will not be controlled by itself const dockDid2 = createNewDockDID(); - const hexDid2 = typedHexDID(dock.api, dockDid2); + const hexDid2 = typedHexDID(dockDid2); const seed1 = randomAsHex(32); const seed2 = randomAsHex(32); diff --git a/tests/integration/master.test.js b/tests/integration/master.test.js index e6bb752dd..e2724ee96 100644 --- a/tests/integration/master.test.js +++ b/tests/integration/master.test.js @@ -244,11 +244,11 @@ async function allVote( const votes = []; for (const [did, key] of did_to_key) { - const nonce = await nc.didModule.getNextNonceForDid(typedHexDID(nc.api, did)); + const nonce = await nc.didModule.getNextNonceForDid(typedHexDID(did)); const vote = { nonce, data: { proposal: encodedProposal, roundNo } }; const encodedStateChange = getStateChange(nc.api, 'MasterVote', vote); const signature = getSignatureFromKeyringPair(key, encodedStateChange); - const didSig = createDidSig(typedHexDID(nc.api, did), 1, signature); + const didSig = createDidSig(typedHexDID(did), 1, signature); votes.push({ sig: didSig, nonce }); } return votes; diff --git a/tests/integration/revocation.test.js b/tests/integration/revocation.test.js index 176b0d378..636e573f1 100644 --- a/tests/integration/revocation.test.js +++ b/tests/integration/revocation.test.js @@ -197,11 +197,11 @@ describe('Revocation Module', () => { .map(typedHexDIDFromSubstrate) .forEach((controller) => { if ( - controller.toString() === typedHexDID(dock.api, ownerDID).toString() + controller.toString() === typedHexDID(ownerDID).toString() ) { hasFirstDID = true; } else if ( - controller.toString() === typedHexDID(dock.api, ownerDID2).toString() + controller.toString() === typedHexDID(ownerDID2).toString() ) { hasSecondDID = true; } diff --git a/tests/integration/schema.test.js b/tests/integration/schema.test.js index b6ef816c9..fb9041e5a 100644 --- a/tests/integration/schema.test.js +++ b/tests/integration/schema.test.js @@ -58,7 +58,7 @@ describe('Schema Blob Module Integration', () => { dockApi.setAccount(account); pair = new DidKeypair(dockApi.keyring.addFromUri(firstKeySeed), 1); dockDID = createNewDockDID(); - hexDid = typedHexDID(dockApi.api, dockDID); + hexDid = typedHexDID(dockDID); await registerNewDIDUsingPair(dockApi, dockDID, pair); blobId = randomAsHex(DockBlobIdByteSize); @@ -126,7 +126,7 @@ describe('Schema Blob Module Integration', () => { await expect(Schema.get(blobId, dockApi)).resolves.toMatchObject({ ...exampleSchema, id: blobId, - author: hexDIDToQualified(typedHexDID(dockApi.api, dockDID)), + author: hexDIDToQualified(typedHexDID(dockDID)), }); }, 20000); diff --git a/tests/integration/status-list-credential-module.test.js b/tests/integration/status-list-credential-module.test.js index 6a0ecce42..d8aced01c 100644 --- a/tests/integration/status-list-credential-module.test.js +++ b/tests/integration/status-list-credential-module.test.js @@ -278,11 +278,11 @@ buildTest("StatusListCredential Module", () => { .map(typedHexDIDFromSubstrate) .forEach((controller) => { if ( - controller.toString() === typedHexDID(dock.api, ownerDID).toString() + controller.toString() === typedHexDID(ownerDID).toString() ) { hasFirstDID = true; } else if ( - controller.toString() === typedHexDID(dock.api, ownerDID2).toString() + controller.toString() === typedHexDID(ownerDID2).toString() ) { hasSecondDID = true; } diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js index 8a68a9a97..91a4db4d0 100644 --- a/tests/integration/trust-registry-module.test.js +++ b/tests/integration/trust-registry-module.test.js @@ -109,7 +109,7 @@ buildTest("Trust Registry", () => { await dock.api.query.trustRegistry.trustRegistriesInfo(trustRegistryId) ).toJSON(); expect(registryInfo).toEqual({ - convener: typedHexDID(dock.api, convenerDID), + convener: typedHexDID(convenerDID), name: "Test Registry", }); }); @@ -127,8 +127,8 @@ buildTest("Trust Registry", () => { ); const verifiers = new BTreeSet(); - verifiers.add(typedHexDID(dock.api, issuerDID)); - verifiers.add(typedHexDID(dock.api, issuerDID2)); + verifiers.add(typedHexDID(issuerDID)); + verifiers.add(typedHexDID(issuerDID2)); const issuers = new BTreeMap(); const issuerPrices = new BTreeMap(); @@ -136,8 +136,8 @@ buildTest("Trust Registry", () => { const issuer2Prices = new BTreeMap(); issuer2Prices.set("A", 20); - issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); - issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); + issuers.set(typedHexDID(issuerDID), issuerPrices); + issuers.set(typedHexDID(issuerDID2), issuer2Prices); const schemas = new BTreeMap(); schemas.set(schemaId, { @@ -186,8 +186,8 @@ buildTest("Trust Registry", () => { ); let verifiers = new BTreeSet(); - verifiers.add(typedHexDID(dock.api, issuerDID)); - verifiers.add(typedHexDID(dock.api, issuerDID2)); + verifiers.add(typedHexDID(issuerDID)); + verifiers.add(typedHexDID(issuerDID2)); let issuers = new BTreeMap(); let issuerPrices = new BTreeMap(); @@ -195,8 +195,8 @@ buildTest("Trust Registry", () => { let issuer2Prices = new BTreeMap(); issuer2Prices.set("A", 20); - issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); - issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); + issuers.set(typedHexDID(issuerDID), issuerPrices); + issuers.set(typedHexDID(issuerDID2), issuer2Prices); let schemas = new BTreeMap(); schemas.set(schemaId, { @@ -234,8 +234,8 @@ buildTest("Trust Registry", () => { let schemasUpdate = new BTreeMap(); verifiers = new BTreeSet(); - verifiers.add(typedHexDID(dock.api, issuerDID)); - verifiers.add(typedHexDID(dock.api, issuerDID2)); + verifiers.add(typedHexDID(issuerDID)); + verifiers.add(typedHexDID(issuerDID2)); issuers = new BTreeMap(); issuerPrices = new BTreeMap(); @@ -243,8 +243,8 @@ buildTest("Trust Registry", () => { issuer2Prices = new BTreeMap(); issuer2Prices.set("A", 75); - issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); - issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); + issuers.set(typedHexDID(issuerDID), issuerPrices); + issuers.set(typedHexDID(issuerDID2), issuer2Prices); schemasUpdate.set(schemaId, { issuers: { @@ -285,15 +285,15 @@ buildTest("Trust Registry", () => { issuer2Prices.set("B", 36); let issuersUpdate = new BTreeMap(); - issuersUpdate.set(typedHexDID(dock.api, issuerDID2), { Set: issuer2Prices }); + issuersUpdate.set(typedHexDID(issuerDID2), { Set: issuer2Prices }); schemasUpdate.set(schemaId, { issuers: { Modify: issuersUpdate, }, }); issuers = new BTreeMap(); - issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); - issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); + issuers.set(typedHexDID(issuerDID2), issuer2Prices); + issuers.set(typedHexDID(issuerDID), issuerPrices); schemas.set(schemaId, { issuers, verifiers: schemas.get(schemaId).verifiers }); await dock.trustRegistry.updateSchemaMetadata( From 48e39dacf4805b4c6f86a194b41441a0fbff1a58 Mon Sep 17 00:00:00 2001 From: olegnn Date: Fri, 29 Dec 2023 16:32:30 +0400 Subject: [PATCH 16/32] Misc tweaks --- src/modules/trust-registry.js | 181 +++++++++++++++--- src/utils/did.js | 6 +- .../integration/trust-registry-module.test.js | 118 +++++++++++- 3 files changed, 273 insertions(+), 32 deletions(-) diff --git a/src/modules/trust-registry.js b/src/modules/trust-registry.js index a0b6f3c0e..e9d632360 100644 --- a/src/modules/trust-registry.js +++ b/src/modules/trust-registry.js @@ -1,3 +1,4 @@ +import { BTreeSet } from '@polkadot/types'; import { typedHexDID } from '../utils/did'; import { getDidNonce } from '../utils/misc'; @@ -19,33 +20,36 @@ export default class TrustRegistryModule { /** * Initializes Trust Registry with the supplied parameters. - * @param {*} convenerDid - * @param {*} registryId - * @param {*} name - * @param {*} signingKeyRef - * @param {*} params - * @param {bool} waitForFinalization - * @param {*} params + * @param convenerDid + * @param registryId + * @param name + * @param signingKeyRef + * @param params + * @param waitForFinalization + * @param params * @returns {Promise} */ async init( convenerDid, registryId, name, + govFramework, signingKeyRef, { nonce = undefined, didModule = undefined } = {}, waitForFinalization = true, params = {}, ) { const convenerHexDid = typedHexDID(convenerDid); - const lastNonce = nonce ?? await getDidNonce(convenerHexDid, nonce, didModule); + const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); return this.signAndSend( convenerHexDid.changeState( this.api, - this.module.initTrustRegistry.bind(this.module), - 'InitTrustRegistry', - { registryId, name, nonce: lastNonce }, + this.module.initOrUpdateTrustRegistry.bind(this.module), + 'InitOrUpdateTrustRegistry', + { + registryId, name, govFramework, nonce: lastNonce, + }, signingKeyRef, ), waitForFinalization, @@ -55,13 +59,13 @@ export default class TrustRegistryModule { /** * Appends new schemas to the registry. - * @param {*} convenerDid - * @param {*} registryId - * @param {*} schemas - * @param {*} signingKeyRef - * @param {*} params - * @param {bool} waitForFinalization - * @param {*} params + * @param convenerDid + * @param registryId + * @param schemas + * @param signingKeyRef + * @param params + * @param waitForFinalization + * @param params * @returns {Promise} */ async addSchemaMetadata( @@ -74,7 +78,7 @@ export default class TrustRegistryModule { params = {}, ) { const convenerHexDid = typedHexDID(convenerDid); - const lastNonce = nonce ?? await getDidNonce(convenerHexDid, nonce, didModule); + const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); return this.signAndSend( convenerHexDid.changeState( @@ -91,13 +95,13 @@ export default class TrustRegistryModule { /** * Updates schemas metadatas in the registry. - * @param {*} convenerDid - * @param {*} registryId - * @param {*} schemas - * @param {*} signingKeyRef - * @param {*} params - * @param {bool} waitForFinalization - * @param {*} params + * @param convenerDid + * @param registryId + * @param schemas + * @param signingKeyRef + * @param params + * @param waitForFinalization + * @param params * @returns {Promise} */ async updateSchemaMetadata( @@ -109,8 +113,11 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerOrIssuerOrVerifierHexDid = typedHexDID(convenerOrIssuerOrVerifierDid); - const lastNonce = nonce ?? await getDidNonce(convenerOrIssuerOrVerifierHexDid, nonce, didModule); + const convenerOrIssuerOrVerifierHexDid = typedHexDID( + convenerOrIssuerOrVerifierDid, + ); + const lastNonce = nonce + ?? (await getDidNonce(convenerOrIssuerOrVerifierHexDid, nonce, didModule)); return this.signAndSend( convenerOrIssuerOrVerifierHexDid.changeState( @@ -124,4 +131,122 @@ export default class TrustRegistryModule { params, ); } + + /** + * Suspends issuers in the registry. + * @param convenerDid + * @param registryId + * @param issuers + * @param signingKeyRef + * @param params + * @param waitForFinalization + * @param params + * @returns {Promise} + */ + async suspendIssuers( + convenerDid, + registryId, + issuers, + signingKeyRef, + { nonce = undefined, didModule = undefined } = {}, + waitForFinalization = true, + params = {}, + ) { + const convenerHexDid = typedHexDID(convenerDid); + const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); + + const hexIssuers = new BTreeSet(); + for (const issuer of issuers) { + hexIssuers.add(typedHexDID(issuer)); + } + + return this.signAndSend( + convenerHexDid.changeState( + this.api, + this.module.suspendIssuers, + 'SuspendIssuers', + { registryId, issuers: hexIssuers, nonce: lastNonce }, + signingKeyRef, + ), + waitForFinalization, + params, + ); + } + + /** + * Unsuspends issuers in the registry. + * @param convenerDid + * @param registryId + * @param issuers + * @param signingKeyRef + * @param params + * @param waitForFinalization + * @param params + * @returns {Promise} + */ + async unsuspendIssuers( + convenerDid, + registryId, + issuers, + signingKeyRef, + { nonce = undefined, didModule = undefined } = {}, + waitForFinalization = true, + params = {}, + ) { + const convenerHexDid = typedHexDID(convenerDid); + const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); + + const hexIssuers = new BTreeSet(); + for (const issuer of issuers) { + hexIssuers.add(typedHexDID(issuer)); + } + + return this.signAndSend( + convenerHexDid.changeState( + this.api, + this.module.unsuspendIssuers, + 'UnsuspendIssuers', + { registryId, issuers: hexIssuers, nonce: lastNonce }, + signingKeyRef, + ), + waitForFinalization, + params, + ); + } + + /** + * Unsuspends issuers in the registry. + * @param issuerDid + * @param registryId + * @param issuers + * @param signingKeyRef + * @param params + * @param waitForFinalization + * @param params + * @returns {Promise} + */ + async updateDelegatedIssuers( + issuerDid, + registryId, + delegated, + signingKeyRef, + { nonce = undefined, didModule = undefined } = {}, + waitForFinalization = true, + params = {}, + ) { + const issuerHexDid = typedHexDID(issuerDid); + const lastNonce = nonce ?? (await getDidNonce(issuerHexDid, nonce, didModule)); + + return this.signAndSend( + issuerHexDid.changeState( + this.api, + this.module.updateDelegatedIssuers, + 'UpdateDelegatedIssuers', + { registryId, delegated, nonce: lastNonce }, + signingKeyRef, + ), + waitForFinalization, + params, + ); + } } diff --git a/src/utils/did.js b/src/utils/did.js index 9205ea462..ba3da4ee7 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -20,11 +20,11 @@ import { } from './misc'; export const DockDIDMethod = 'dock'; -export const Secp256k1PublicKeyPrefix = 'zQ3'; +export const Secp256k1PublicKeyPrefix = 'zQ3s'; export const Ed25519PublicKeyPrefix = 'z6Mk'; export const DockDIDQualifier = `did:${DockDIDMethod}:`; -export const DockDIDMethodKeyQualifier = `did:key:`; +export const DockDIDMethodKeyQualifier = 'did:key:'; export const DockDIDByteSize = 32; export const DockDidMethodKeySecp256k1Prefix = `${DockDIDMethodKeyQualifier}${Secp256k1PublicKeyPrefix}`; @@ -237,7 +237,7 @@ export function typedHexDIDFromSubstrate(did) { } else if (did.isDidMethodKey) { return new DockDidMethodKey(hex); } else { - throw new Error(`Invalid did provided: \`${did}\``) + throw new Error(`Invalid did provided: \`${did}\``); } } diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js index 91a4db4d0..bbcc7dcb3 100644 --- a/tests/integration/trust-registry-module.test.js +++ b/tests/integration/trust-registry-module.test.js @@ -1,5 +1,6 @@ import { randomAsHex } from "@polkadot/util-crypto"; import { BTreeSet, BTreeMap } from "@polkadot/types"; +import { u8aToHex, stringToU8a } from '@polkadot/util'; import { DockAPI } from "../../src/index"; @@ -78,7 +79,7 @@ buildTest("Trust Registry", () => { 1 ); - // The keyring should be initialized before any test begins as this suite is testing statusListCredentialModule + // The keyring should be initialized before any test begins as this suite is testing trustRegistry const account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); @@ -101,6 +102,7 @@ buildTest("Trust Registry", () => { convenerDID, trustRegistryId, "Test Registry", + "Gov framework", convenerPair, dock ); @@ -111,6 +113,7 @@ buildTest("Trust Registry", () => { expect(registryInfo).toEqual({ convener: typedHexDID(convenerDID), name: "Test Registry", + govFramework: u8aToHex(stringToU8a("Gov framework")) }); }); @@ -122,6 +125,7 @@ buildTest("Trust Registry", () => { convenerDID, trustRegistryId, "Test Registry", + "Gov framework", convenerPair, dock ); @@ -173,6 +177,117 @@ buildTest("Trust Registry", () => { }); }); + it("Suspends issuers in the existing Trust Registry", async () => { + // Create a random status list id + const schemaId = randomAsHex(32); + + await dock.trustRegistry.init( + convenerDID, + trustRegistryId, + "Test Registry", + "Gov framework", + convenerPair, + dock + ); + + const verifiers = new BTreeSet(); + verifiers.add(typedHexDID(issuerDID)); + verifiers.add(typedHexDID(issuerDID2)); + + const issuers = new BTreeMap(); + const issuerPrices = new BTreeMap(); + issuerPrices.set("A", 20); + const issuer2Prices = new BTreeMap(); + issuer2Prices.set("A", 20); + + issuers.set(typedHexDID(issuerDID), issuerPrices); + issuers.set(typedHexDID(issuerDID2), issuer2Prices); + + const schemas = new BTreeMap(); + schemas.set(schemaId, { + issuers, + verifiers, + }); + + await dock.trustRegistry.addSchemaMetadata( + convenerDID, + trustRegistryId, + schemas, + convenerPair, + dock + ); + + await dock.trustRegistry.suspendIssuers( + convenerDID, + trustRegistryId, + [issuerDID, issuerDID2], + convenerPair, + dock + ); + + for (const issuer of [issuerDID, issuerDID2]) { + expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(issuer))).toJSON()).toEqual({ + suspended: true, + delegated: [] + }); + } + + await dock.trustRegistry.unsuspendIssuers( + convenerDID, + trustRegistryId, + [issuerDID], + convenerPair, + dock + ); + + for (const issuer of [issuerDID]) { + expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(issuer))).toJSON()).toEqual({ + suspended: false, + delegated: [] + }); + } + + for (const issuer of [issuerDID2]) { + expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(issuer))).toJSON()).toEqual({ + suspended: true, + delegated: [] + }); + } + }); + + it("Updates delegated issuers in the existing Trust Registry", async () => { + // Create a random status list id + await dock.trustRegistry.init( + convenerDID, + trustRegistryId, + "Test Registry", + "Gov framework", + convenerPair, + dock + ); + + expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(issuerDID))).toJSON()).toEqual({ + suspended: false, + delegated: [] + }); + + const issuers = new BTreeSet(); + issuers.add(typedHexDID(issuerDID2)); + + await dock.trustRegistry.updateDelegatedIssuers( + issuerDID, + trustRegistryId, + { Set: issuers }, + issuerPair, + dock + ); + + expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(issuerDID))).toJSON()).toEqual({ + suspended: false, + delegated: [typedHexDID(issuerDID2)] + }); + }); + it("Updates schemas to the existing Trust Registry", async () => { // Create a random status list id const schemaId = randomAsHex(32); @@ -181,6 +296,7 @@ buildTest("Trust Registry", () => { convenerDID, trustRegistryId, "Test Registry", + "Gov framework", convenerPair, dock ); From c2e671635997824e683ee65f9f571cab89fa1769 Mon Sep 17 00:00:00 2001 From: lovesh Date: Fri, 29 Dec 2023 20:28:38 +0530 Subject: [PATCH 17/32] Fix docs and return types Signed-off-by: lovesh --- src/modules/WithParamsAndPublicKeys.js | 2 +- src/modules/trust-registry.js | 14 +++++++++++++- src/utils/did.js | 6 +++--- src/utils/revocation/one-of-policy.js | 2 +- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/modules/WithParamsAndPublicKeys.js b/src/modules/WithParamsAndPublicKeys.js index 04acb3d78..db06b7606 100644 --- a/src/modules/WithParamsAndPublicKeys.js +++ b/src/modules/WithParamsAndPublicKeys.js @@ -259,7 +259,7 @@ export default class WithParamsAndPublicKeys { /** * * @param did - * @param signingKeyRef + * @param keyId * @param withParams - If true, return the params referenced by the public key. It will throw an error if paramsRef is null * or params were not found on chain which can happen if they were deleted after this public key was added. * @returns {Promise<{bytes: string}|null>} diff --git a/src/modules/trust-registry.js b/src/modules/trust-registry.js index e9d632360..906bc5a18 100644 --- a/src/modules/trust-registry.js +++ b/src/modules/trust-registry.js @@ -23,7 +23,10 @@ export default class TrustRegistryModule { * @param convenerDid * @param registryId * @param name + * @param govFramework * @param signingKeyRef + * @param nonce + * @param didModule * @param params * @param waitForFinalization * @param params @@ -63,6 +66,8 @@ export default class TrustRegistryModule { * @param registryId * @param schemas * @param signingKeyRef + * @param nonce + * @param didModule * @param params * @param waitForFinalization * @param params @@ -95,10 +100,12 @@ export default class TrustRegistryModule { /** * Updates schemas metadatas in the registry. - * @param convenerDid + * @param convenerOrIssuerOrVerifierDid * @param registryId * @param schemas * @param signingKeyRef + * @param nonce + * @param didModule * @param params * @param waitForFinalization * @param params @@ -138,6 +145,8 @@ export default class TrustRegistryModule { * @param registryId * @param issuers * @param signingKeyRef + * @param nonce + * @param didModule * @param params * @param waitForFinalization * @param params @@ -179,6 +188,8 @@ export default class TrustRegistryModule { * @param registryId * @param issuers * @param signingKeyRef + * @param nonce + * @param didModule * @param params * @param waitForFinalization * @param params @@ -219,6 +230,7 @@ export default class TrustRegistryModule { * @param issuerDid * @param registryId * @param issuers + * @param delegated * @param signingKeyRef * @param params * @param waitForFinalization diff --git a/src/utils/did.js b/src/utils/did.js index ba3da4ee7..e384f9f2d 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -223,7 +223,7 @@ export function typedHexDID(did) { * Gets the hexadecimal value of the given DID received from the substrate side. * @param {string} did - The DID can be passed as fully qualified DID like `did:dock:` or * a 32 byte hex string - * @return {string} Returns the hexadecimal representation of the DID. + * @return {DockDidOrDidMethodKey} Returns an object wrapping the DID. */ export function typedHexDIDFromSubstrate(did) { const hex = getHexIdentifier( @@ -243,8 +243,8 @@ export function typedHexDIDFromSubstrate(did) { /** * Return a fully qualified Dock DID id, i.e. "did:dock:" - * @param {string|object} hexDid - The hex blob id (without the qualifier) - * @returns {string} - The fully qualified Blob id + * @param {string|object} hexDid - The hex DID (without the qualifier) or wrapper on DID + * @returns {string} - The fully qualified DID */ export function hexDIDToQualified(hexDid) { if (typeof hexDid?.toStringSS58 === 'function') { diff --git a/src/utils/revocation/one-of-policy.js b/src/utils/revocation/one-of-policy.js index 3c34ebe2f..e6df2cc33 100644 --- a/src/utils/revocation/one-of-policy.js +++ b/src/utils/revocation/one-of-policy.js @@ -23,7 +23,7 @@ export default class OneOfPolicy extends Policy { /** * Returns list containing unique sorted owner DIDs. - * @param {string} ownerDID - Owner's DID + * @returns {DockDidOrDidMethodKey[]} */ controllerIds() { const controllerIds = [...this.controllers].map(typedHexDID); From 1daae35342bf10cc656dca4bad93e919c71487a9 Mon Sep 17 00:00:00 2001 From: olegnn Date: Sat, 30 Dec 2023 09:07:35 +0400 Subject: [PATCH 18/32] Minor tweaks --- .github/workflows/integrations-tests.yml | 2 ++ example/blob.js | 7 +++---- example/dock-did.js | 14 +++++++------- example/resolver.js | 4 ++-- example/revocation.js | 7 +++---- example/schema.js | 9 ++++----- example/vcdm.js | 6 +++--- src/modules/trust-registry.js | 5 ++++- 8 files changed, 28 insertions(+), 26 deletions(-) diff --git a/.github/workflows/integrations-tests.yml b/.github/workflows/integrations-tests.yml index 530a38c93..33ee7fa82 100644 --- a/.github/workflows/integrations-tests.yml +++ b/.github/workflows/integrations-tests.yml @@ -22,6 +22,7 @@ jobs: mainnet: runs-on: ubuntu-latest env: + DisableTrustRegistryTests: true CONFIG_DOCK_NODE_IMAGE_TAG: 'mainnet' steps: - uses: actions/checkout@v2 @@ -39,6 +40,7 @@ jobs: testnet: runs-on: ubuntu-latest env: + DisableTrustRegistryTests: true CONFIG_DOCK_NODE_IMAGE_TAG: 'testnet' steps: - uses: actions/checkout@v2 diff --git a/example/blob.js b/example/blob.js index e32eb40fa..60cc93f64 100644 --- a/example/blob.js +++ b/example/blob.js @@ -3,8 +3,7 @@ import { u8aToString } from '@polkadot/util'; import { DockAPI } from '../src/index'; import { DockBlobIdByteSize } from '../src/modules/blob'; -import { createNewDockDID } from '../src/utils/did'; -import { getPublicKeyFromKeyringPair } from '../src/utils/misc'; +import { createNewDockDID, DidKeypair } from '../src/utils/did'; // The following can be tweaked depending on where the node is running and what // account is to be used for sending the transaction. @@ -33,7 +32,7 @@ async function createAuthorDID(dock, pair) { console.log('Creating new author DID', dockDID); // Create an author DID to write with - const publicKey = getPublicKeyFromKeyringPair(pair); + const publicKey = pair.publicKey(); const didKey = new DidKey(publicKey, new VerificationRelationship()); await dock.did.new(dockDID, [didKey], [], false); return dockDID; @@ -57,7 +56,7 @@ async function main() { const dock = await connectToNode(); // Generate keypair for DID - const pair = dock.keyring.addFromUri(randomAsHex(32)); + const pair = new DidKeypair(dock.keyring.addFromUri(randomAsHex(32)), 1); // Generate a DID to be used as author const dockDID = await createAuthorDID(dock, pair); diff --git a/example/dock-did.js b/example/dock-did.js index 46f9acbd9..d114a4041 100644 --- a/example/dock-did.js +++ b/example/dock-did.js @@ -8,8 +8,8 @@ import dock, { } from '../src/index'; import { createNewDockDID, + DidKeypair, } from '../src/utils/did'; -import { getPublicKeyFromKeyringPair } from '../src/utils/misc'; // The following can be tweaked depending on where the node is running and what // account is to be used for sending the transaction. @@ -31,7 +31,7 @@ async function removeDID() { console.log('Removing DID now.'); // Sign the DID removal with this key pair as this is the current key of the DID - const pair = dock.keyring.addFromUri(firstKeySeed, null, 'sr25519'); + const pair = new DidKeypair(dock.keyring.addFromUri(firstKeySeed, null, 'sr25519'), 1); return dock.did.remove(dockDID, dockDID, pair, undefined, false); } @@ -41,7 +41,7 @@ async function addServiceEndpoint() { console.log('Add new service endpoint now.'); // Sign key update with this key pair as this is the current key of the DID - const pair = dock.keyring.addFromUri(firstKeySeed, null, 'sr25519'); + const pair = new DidKeypair(dock.keyring.addFromUri(firstKeySeed, null, 'sr25519'), 1); const spType = new ServiceEndpointType(); spType.setLinkedDomains(); @@ -58,7 +58,7 @@ async function addController() { console.log('Add new controller now.'); // Sign key update with this key pair as this is the current key of the DID - const pair = dock.keyring.addFromUri(firstKeySeed, null, 'sr25519'); + const pair = new DidKeypair(dock.keyring.addFromUri(firstKeySeed, null, 'sr25519'), 1); const newController = createNewDockDID(); @@ -70,12 +70,12 @@ async function addKey() { console.log('Add new key now.'); // Sign key update with this key pair as this is the current key of the DID - const pair = dock.keyring.addFromUri(firstKeySeed, null, 'sr25519'); + const pair = new DidKeypair(dock.keyring.addFromUri(firstKeySeed, null, 'sr25519'), 1); // Update DID key to the following - const newPair = dock.keyring.addFromUri(secondKeySeed, null, 'ed25519'); + const newPair = new DidKeypair(dock.keyring.addFromUri(secondKeySeed, null, 'ed25519'), 1); // the following function will figure out the correct PublicKey type from the `type` property of `newPair` - const newPk = getPublicKeyFromKeyringPair(newPair); + const newPk = newPair.publicKey(); const vr = new VerificationRelationship(); vr.setAuthentication(); diff --git a/example/resolver.js b/example/resolver.js index 5da83bf89..036706bff 100644 --- a/example/resolver.js +++ b/example/resolver.js @@ -2,7 +2,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import ethr from 'ethr-did-resolver'; import { DockAPI } from '../src/index'; -import { createNewDockDID, NoDIDError } from '../src/utils/did'; +import { createNewDockDID, NoDIDError, DidKeypair } from '../src/utils/did'; import { DIDResolver, DIDKeyResolver, UniversalResolver, WILDCARD, DockDIDResolver, } from '../src/resolver'; @@ -54,7 +54,7 @@ async function createDockDID() { dock.setAccount(account); const dockDID = createNewDockDID(); - const pair = dock.keyring.addFromUri(randomAsHex(32), null, 'sr25519'); + const pair = new DidKeypair(dock.keyring.addFromUri(randomAsHex(32), null, 'sr25519'), 1); await registerNewDIDUsingPair(dock, dockDID, pair); return dockDID; } diff --git a/example/revocation.js b/example/revocation.js index b9e5ab032..8e40719a0 100644 --- a/example/revocation.js +++ b/example/revocation.js @@ -1,8 +1,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import dock from '../src/index'; -import { createNewDockDID } from '../src/utils/did'; -import { getPublicKeyFromKeyringPair } from '../src/utils/misc'; +import { createNewDockDID, DidKeypair } from '../src/utils/did'; import { OneOfPolicy, @@ -65,13 +64,13 @@ async function main() { dock.setAccount(account); // The DID should be written before creating a registry - const pair = dock.keyring.addFromUri(controllerSeed, null, 'sr25519'); + const pair = new DidKeypair(dock.keyring.addFromUri(controllerSeed, null, 'sr25519'), 1); // Set our controller DID and associated keypair to be used for generating proof console.log(`Creating controller DID (${controllerDID}) using sr25519 pair from seed (${controllerSeed})...`); // The controller is same as the DID - const publicKey = getPublicKeyFromKeyringPair(pair); + const publicKey = pair.publicKey(); const didKey = new DidKey(publicKey, new VerificationRelationship()); await dock.did.new(controllerDID, [didKey], [], false); diff --git a/example/schema.js b/example/schema.js index 96f357f79..49f0fdf08 100644 --- a/example/schema.js +++ b/example/schema.js @@ -2,8 +2,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import Schema from '../src/modules/schema'; import { DockAPI } from '../src/index'; -import { createNewDockDID } from '../src/utils/did'; -import { getPublicKeyFromKeyringPair } from '../src/utils/misc'; +import { createNewDockDID, DidKeypair } from '../src/utils/did'; import VerifiableCredential from '../src/verifiable-credential'; import { Ed25519VerKeyName } from '../src/utils/vc/crypto/constants'; import { getKeyDoc } from '../src/utils/vc/helpers'; @@ -27,7 +26,7 @@ async function createAuthorDID(dock, pair) { console.log('Creating new author DID', dockDID); // Create an author DID to write with - const publicKey = getPublicKeyFromKeyringPair(pair); + const publicKey = pair.publicKey(); const didKey = new DidKey(publicKey, new VerificationRelationship()); await dock.did.new(dockDID, [didKey], [], false); return dockDID; @@ -47,7 +46,7 @@ async function main() { const subjectKeySeed = randomAsHex(32); // Generate first key with this seed. The key type is Sr25519 - const pair = dock.keyring.addFromUri(keySeed, null, 'ed25519'); + const pair = new DidKeypair(dock.keyring.addFromUri(keySeed, null, 'ed25519'), 1); // Generate a DID to be used as author const dockDID = await createAuthorDID(dock, pair); @@ -59,7 +58,7 @@ async function main() { Ed25519VerKeyName, ); - const subjectPair = dock.keyring.addFromUri(subjectKeySeed); + const subjectPair = new DidKeypair(dock.keyring.addFromUri(subjectKeySeed), 1); const subjectDID = createNewDockDID(); await registerNewDIDUsingPair(dock, subjectDID, subjectPair); diff --git a/example/vcdm.js b/example/vcdm.js index ebb81985e..c66f88eeb 100644 --- a/example/vcdm.js +++ b/example/vcdm.js @@ -3,7 +3,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import dock from '../src/index'; import VerifiableCredential from '../src/verifiable-credential'; import VerifiablePresentation from '../src/verifiable-presentation'; -import { createNewDockDID } from '../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../src/utils/did'; import { registerNewDIDUsingPair } from '../tests/integration/helpers'; import { createRandomRegistryId, OneOfPolicy, buildDockCredentialStatus } from '../src/utils/revocation'; import { FullNodeEndpoint, TestAccountURI } from '../tests/test-constants'; @@ -44,12 +44,12 @@ async function setup() { // Register issuer DID console.log('Registering issuer DID...'); - const pair = dock.keyring.addFromUri(issuerSeed, null, 'ed25519'); + const pair = new DidKeypair(dock.keyring.addFromUri(issuerSeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dock, issuerDID, pair); // Register holder DID console.log('Registering holder DID...'); - const pair1 = dock.keyring.addFromUri(holderSeed, null, 'ed25519'); + const pair1 = new DidKeypair(dock.keyring.addFromUri(holderSeed, null, 'ed25519'), 1); await registerNewDIDUsingPair(dock, holderDID, pair1); // Create a new policy diff --git a/src/modules/trust-registry.js b/src/modules/trust-registry.js index e9d632360..78a668056 100644 --- a/src/modules/trust-registry.js +++ b/src/modules/trust-registry.js @@ -48,7 +48,10 @@ export default class TrustRegistryModule { this.module.initOrUpdateTrustRegistry.bind(this.module), 'InitOrUpdateTrustRegistry', { - registryId, name, govFramework, nonce: lastNonce, + registryId, + name, + govFramework, + nonce: lastNonce, }, signingKeyRef, ), From 9fa3aa440c51c24488eea5a44b51812795547dd8 Mon Sep 17 00:00:00 2001 From: olegnn Date: Sat, 30 Dec 2023 10:28:36 +0400 Subject: [PATCH 19/32] Backward compatibility --- src/utils/did.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/utils/did.js b/src/utils/did.js index e384f9f2d..9e9f30195 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -296,6 +296,9 @@ export function createDidSig(did, { keyId }, rawSig) { keyId, sig, }, + did: did.asDid, + keyId, + sig, }; } else if (did.isDidMethodKey) { return { From a7b14670715896b58d8ec910edee6aafae34a849 Mon Sep 17 00:00:00 2001 From: lovesh Date: Tue, 2 Jan 2024 16:58:13 +0530 Subject: [PATCH 20/32] Add note for backward compatibilty and add helper for easier DidKeypair creation Signed-off-by: lovesh --- example/blob.js | 2 +- src/utils/did.js | 21 +++++++++++++++ tests/integration/blob.test.js | 2 +- .../integration/credential-revocation.test.js | 4 +-- tests/integration/resolvers.test.js | 4 +-- tests/integration/revocation.test.js | 26 +++++++++---------- tests/integration/schema.test.js | 2 +- 7 files changed, 41 insertions(+), 20 deletions(-) diff --git a/example/blob.js b/example/blob.js index 60cc93f64..31514fbc6 100644 --- a/example/blob.js +++ b/example/blob.js @@ -56,7 +56,7 @@ async function main() { const dock = await connectToNode(); // Generate keypair for DID - const pair = new DidKeypair(dock.keyring.addFromUri(randomAsHex(32)), 1); + const pair = DidKeypair.fromApi(dock); // Generate a DID to be used as author const dockDID = await createAuthorDID(dock, pair); diff --git a/src/utils/did.js b/src/utils/did.js index 9e9f30195..2d1e1cdba 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -43,6 +43,24 @@ export class DidKeypair { sign(message) { return getSignatureFromKeyringPair(this.keyPair, message); } + + /** + * Create a new keypair from a DockAPI object. + * @param {DockAPI} dockApi + * @param seed - Generates 32 byte random seed if not provided + * @param keypairType - Defaults to ed25519. + * @param meta + * @param keyId - Defaults to 1 + * @returns {DidKeypair} + */ + static fromApi(dockApi, { + seed = randomAsHex(32), + keypairType = 'ed25519', + meta = null, + keyId = 1, + } = {}) { + return new DidKeypair(dockApi.keyring.addFromUri(seed, meta, keypairType), keyId); + } } export class DidActor { @@ -283,6 +301,7 @@ export function createDidKey(publicKey, verRel) { * * @param {DockDidOrDidMethodKey} did - DID as hex * @param {number} keyId - + * @param rawSig * @param {Signature} sig * @returns {{sig: *, keyId, did}} */ @@ -291,6 +310,8 @@ export function createDidSig(did, { keyId }, rawSig) { if (did.isDid) { return { + // Note: The following repeats the 3 fields to ensure backward compatibility. Once nodes have been upgraded, + // fields outside `DidSignature` must be removed. DidSignature: { did: did.asDid, keyId, diff --git a/tests/integration/blob.test.js b/tests/integration/blob.test.js index 73bb8f941..35dfe7ca2 100644 --- a/tests/integration/blob.test.js +++ b/tests/integration/blob.test.js @@ -34,7 +34,7 @@ describe('Blob Module', () => { }); account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); - pair = new DidKeypair(dock.keyring.addFromUri(firstKeySeed), 1); + pair = DidKeypair.fromApi(dock, {seed: firstKeySeed}); dockDID = createNewDockDID(); await registerNewDIDUsingPair(dock, typedHexDID(dockDID), pair); }); diff --git a/tests/integration/credential-revocation.test.js b/tests/integration/credential-revocation.test.js index a219a2ceb..d3214acaa 100644 --- a/tests/integration/credential-revocation.test.js +++ b/tests/integration/credential-revocation.test.js @@ -59,11 +59,11 @@ describe('Credential revocation with issuer as the revocation authority', () => dockAPI.setAccount(account); // Register issuer DID - issuerKeyPair = new DidKeypair(dockAPI.keyring.addFromUri(issuerSeed, null, 'ed25519'), 1); + issuerKeyPair = DidKeypair.fromApi(dockAPI, {seed: issuerSeed}); await registerNewDIDUsingPair(dockAPI, issuerDID, issuerKeyPair); // Register holder DID - const pair1 = new DidKeypair(dockAPI.keyring.addFromUri(holderSeed, null, 'ed25519'), 1); + const pair1 = DidKeypair.fromApi(dockAPI, {seed: holderSeed}); await registerNewDIDUsingPair(dockAPI, holderDID, pair1); // Create a new policy diff --git a/tests/integration/resolvers.test.js b/tests/integration/resolvers.test.js index 69f3d874d..935650940 100644 --- a/tests/integration/resolvers.test.js +++ b/tests/integration/resolvers.test.js @@ -1,6 +1,6 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockResolver, DockStatusList2021Resolver } from '../../src/resolver'; -import { typedHexDID, createNewDockDID, DidKeypair } from '../../src/utils/did'; +import { createNewDockDID, DidKeypair } from '../../src/utils/did'; import { DockAPI } from '../../src/index'; @@ -54,7 +54,7 @@ describe('Resolvers', () => { dock.setAccount(account); // Thees DIDs should be written before any test begins - pair = new DidKeypair(dock.keyring.addFromUri(ownerSeed, null, 'sr25519'), 1); + pair = DidKeypair.fromApi(dock, { seed: ownerSeed, keypairType: 'sr25519' }); // The controller is same as the DID await registerNewDIDUsingPair(dock, ownerDID, pair); diff --git a/tests/integration/revocation.test.js b/tests/integration/revocation.test.js index 636e573f1..e0f48b850 100644 --- a/tests/integration/revocation.test.js +++ b/tests/integration/revocation.test.js @@ -7,7 +7,7 @@ import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI } from '../test-const import { OneOfPolicy, } from '../../src/utils/revocation'; -import { DidKeypair, typedHexDID, typedHexDIDFromSubstrate } from '../../src/utils/did' +import { DidKeypair, typedHexDID, typedHexDIDFromSubstrate } from '../../src/utils/did'; import { registerNewDIDUsingPair } from './helpers'; describe('Revocation Module', () => { @@ -50,8 +50,8 @@ describe('Revocation Module', () => { dock.setAccount(account); // Thees DIDs should be written before any test begins - pair = new DidKeypair(dock.keyring.addFromUri(ownerSeed, null, 'sr25519'), 1); - pair2 = new DidKeypair(dock.keyring.addFromUri(ownerSeed2, null, 'sr25519'), 1); + pair = DidKeypair.fromApi(dock, { seed: ownerSeed, keypairType: 'sr25519' }); + pair2 = DidKeypair.fromApi(dock, { seed: ownerSeed2, keypairType: 'sr25519' }); // The controller is same as the DID await registerNewDIDUsingPair(dock, ownerDID, pair); @@ -196,16 +196,16 @@ describe('Revocation Module', () => { .flatMap((v) => v) .map(typedHexDIDFromSubstrate) .forEach((controller) => { - if ( - controller.toString() === typedHexDID(ownerDID).toString() - ) { - hasFirstDID = true; - } else if ( - controller.toString() === typedHexDID(ownerDID2).toString() - ) { - hasSecondDID = true; - } - }); + if ( + controller.toString() === typedHexDID(ownerDID).toString() + ) { + hasFirstDID = true; + } else if ( + controller.toString() === typedHexDID(ownerDID2).toString() + ) { + hasSecondDID = true; + } + }); expect(hasFirstDID && hasSecondDID).toBe(true); }, 40000); diff --git a/tests/integration/schema.test.js b/tests/integration/schema.test.js index fb9041e5a..3344593cf 100644 --- a/tests/integration/schema.test.js +++ b/tests/integration/schema.test.js @@ -56,7 +56,7 @@ describe('Schema Blob Module Integration', () => { }); account = dockApi.keyring.addFromUri(TestAccountURI); dockApi.setAccount(account); - pair = new DidKeypair(dockApi.keyring.addFromUri(firstKeySeed), 1); + pair = DidKeypair.fromApi(dockApi); dockDID = createNewDockDID(); hexDid = typedHexDID(dockDID); await registerNewDIDUsingPair(dockApi, dockDID, pair); From 0fd3de4b49a0a70f4e73942a988fb8caf6aca3aa Mon Sep 17 00:00:00 2001 From: olegnn Date: Fri, 5 Jan 2024 15:49:48 +0400 Subject: [PATCH 21/32] WIP: backward compatibility --- scripts/txn-pricing.js | 4 +- src/modules/revocation.js | 6 +- src/modules/status-list-credential.js | 4 +- src/utils/did.js | 107 ++++++++++++------ tests/integration/custom-nonce.test.js | 4 +- tests/integration/fees.test.js | 6 +- tests/integration/revocation.test.js | 16 +-- .../status-list-credential-module.test.js | 8 +- 8 files changed, 98 insertions(+), 57 deletions(-) diff --git a/scripts/txn-pricing.js b/scripts/txn-pricing.js index 87f8ea3a3..9225e23e5 100755 --- a/scripts/txn-pricing.js +++ b/scripts/txn-pricing.js @@ -233,7 +233,7 @@ async function revocation() { } const [update, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, revokeIds, did, pair, { didModule: dock.did }); - const revTx = dock.revocation.createRevokeTx(update, [[nonce, sig]]); + const revTx = dock.revocation.createRevokeTx(update, [{ nonce, sig }]); console.info(`Payment info of ${count} revocation is ${(await revTx.paymentInfo(account.address))}`); await printFeePaid(dock.api, account.address, async () => { await dock.signAndSend(revTx, false); @@ -241,7 +241,7 @@ async function revocation() { } const [update, sig, nonce] = await dock.revocation.createSignedRemove(registryId, did, pair, { didModule: dock.did }); - const revTx = dock.revocation.createRemoveRegistryTx(update, [[nonce, sig]]); + const revTx = dock.revocation.createRemoveRegistryTx(update, [{ nonce, sig }]); console.info(`Payment info of removing registry is ${(await revTx.paymentInfo(account.address))}`); await printFeePaid(dock.api, account.address, async () => { diff --git a/src/modules/revocation.js b/src/modules/revocation.js index 5c10f7e8b..625512f25 100644 --- a/src/modules/revocation.js +++ b/src/modules/revocation.js @@ -187,7 +187,7 @@ class RevocationModule { */ async revokeCredentialWithOneOfPolicy(registryId, revId, did, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { const [revoke, sig, sigNonce] = await this.createSignedRevoke(registryId, [revId], did, signingKeyRef, { nonce, didModule }); - return this.revoke(revoke, [[sigNonce, sig]], waitForFinalization, params); + return this.revoke(revoke, [{ sig, nonce: sigNonce }], waitForFinalization, params); } /** @@ -204,12 +204,12 @@ class RevocationModule { */ async unrevokeCredentialWithOneOfPolicy(registryId, revId, did, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { const [revoke, sig, sigNonce] = await this.createSignedUnRevoke(registryId, [revId], did, signingKeyRef, { nonce, didModule }); - return this.unrevoke(revoke, [[sigNonce, sig]], waitForFinalization, params); + return this.unrevoke(revoke, [{ sig, nonce: sigNonce }], waitForFinalization, params); } async removeRegistryWithOneOfPolicy(registryId, did, signingKeyRef, { nonce = undefined, didModule = undefined }, waitForFinalization = true, params = {}) { const [removal, sig, sigNonce] = await this.createSignedRemove(registryId, did, signingKeyRef, { nonce, didModule }); - return this.removeRegistry(removal, [[sigNonce, sig]], waitForFinalization, params); + return this.removeRegistry(removal, [{ sig, nonce: sigNonce }], waitForFinalization, params); } async createSignedUpdate(updateFunc, registryId, [...revokeIds], did, signingKeyRef, { nonce = undefined, didModule = undefined }) { diff --git a/src/modules/status-list-credential.js b/src/modules/status-list-credential.js index c70cf3332..dee4e313f 100644 --- a/src/modules/status-list-credential.js +++ b/src/modules/status-list-credential.js @@ -139,7 +139,7 @@ export default class StatusListCredentialModule { ); return this.updateStatusListCredential( payload, - [[sigNonce, sig]], + [{ nonce: sigNonce, sig }], waitForFinalization, params, ); @@ -173,7 +173,7 @@ export default class StatusListCredentialModule { ); return this.removeStatusListCredential( payload, - [[sigNonce, sig]], + [{ nonce: sigNonce, sig }], waitForFinalization, params, ); diff --git a/src/utils/did.js b/src/utils/did.js index 9e9f30195..395ae194f 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -2,30 +2,32 @@ // Import some utils from Polkadot JS // eslint-disable-next-line max-classes-per-file -import { randomAsHex, encodeAddress } from '@polkadot/util-crypto'; -import { u8aToHex } from '@polkadot/util'; -import { isHexWithGivenByteSize, getHexIdentifier } from './codec'; +import { randomAsHex, encodeAddress } from "@polkadot/util-crypto"; +import { u8aToHex } from "@polkadot/util"; +import { isHexWithGivenByteSize, getHexIdentifier } from "./codec"; import { PublicKeyEd25519, PublicKeySecp256k1, PublicKey, // eslint-disable-line VerificationRelationship, // eslint-disable-line -} from '../public-keys'; +} from "../public-keys"; import { Signature } from "../signatures"; // eslint-disable-line import { getPublicKeyFromKeyringPair, getSignatureFromKeyringPair, getStateChange, -} from './misc'; +} from "./misc"; -export const DockDIDMethod = 'dock'; -export const Secp256k1PublicKeyPrefix = 'zQ3s'; -export const Ed25519PublicKeyPrefix = 'z6Mk'; +export const DockDIDMethod = "dock"; +export const Secp256k1PublicKeyPrefix = "zQ3s"; +export const Ed25519PublicKeyPrefix = "z6Mk"; export const DockDIDQualifier = `did:${DockDIDMethod}:`; -export const DockDIDMethodKeyQualifier = 'did:key:'; +export const DockDIDMethodKeyQualifier = "did:key:"; export const DockDIDByteSize = 32; +export const DockDIDMethodKeySecp256k1ByteSize = 33; +export const DockDIDMethodKeyEd25519ByteSize = 32; export const DockDidMethodKeySecp256k1Prefix = `${DockDIDMethodKeyQualifier}${Secp256k1PublicKeyPrefix}`; export const DockDidMethodKeyEd25519Prefix = `${DockDIDMethodKeyQualifier}${Ed25519PublicKeyPrefix}`; @@ -62,11 +64,11 @@ export class DidActor { export class DockDidOrDidMethodKey extends DidActor { get asDid() { - throw new Error('Not a `Did`'); + throw new Error("Not a `Did`"); } get asDidMethodKey() { - throw new Error('Not a `DidMethodKey`'); + throw new Error("Not a `DidMethodKey`"); } get isDid() { @@ -139,9 +141,10 @@ export class DockDidMethodKey extends DockDidOrDidMethodKey { export class NoDIDError extends Error { constructor(did) { super(`DID (${did}) does not exist`); - this.name = 'NoDIDError'; + this.name = "NoDIDError"; this.did = did; - this.message = 'A DID document lookup was successful, but the DID in question does not exist. This is different from a network error.'; + this.message = + "A DID document lookup was successful, but the DID in question does not exist. This is different from a network error."; } } @@ -151,9 +154,10 @@ export class NoDIDError extends Error { export class NoOnchainDIDError extends Error { constructor(did) { super(`DID (${did}) is an off-chain DID`); - this.name = 'NoOnchainDIDError'; + this.name = "NoOnchainDIDError"; this.did = did; - this.message = 'The DID exists on chain but is an off-chain DID, meaning the DID document exists off-chain.'; + this.message = + "The DID exists on chain but is an off-chain DID, meaning the DID document exists off-chain."; } } @@ -163,9 +167,10 @@ export class NoOnchainDIDError extends Error { export class NoOffchainDIDError extends Error { constructor(did) { super(`DID (${did}) is an on-chain DID`); - this.name = 'NoOffchainDIDError'; + this.name = "NoOffchainDIDError"; this.did = did; - this.message = 'The DID exists on chain and is an on-chain DID but the lookup was performed for an off-chain DID.'; + this.message = + "The DID exists on chain and is an on-chain DID but the lookup was performed for an off-chain DID."; } } @@ -191,7 +196,7 @@ export function validateDockDIDSS58Identifier(identifier) { const regex = new RegExp(/^[5KL][1-9A-HJ-NP-Za-km-z]{47}$/); const matches = regex.exec(identifier); if (!matches) { - throw new Error('The identifier must be 32 bytes and valid SS58 string'); + throw new Error("The identifier must be 32 bytes and valid SS58 string"); } } @@ -203,18 +208,26 @@ export function validateDockDIDSS58Identifier(identifier) { */ export function typedHexDID(did) { const strDid = did.toString(); - const hex = getHexIdentifier( - did, - [DockDIDQualifier, DockDIDMethodKeyQualifier], - DockDIDByteSize, - ); if (strDid.startsWith(DockDidMethodKeySecp256k1Prefix)) { + const hex = getHexIdentifier( + strDid, + DockDIDMethodKeyQualifier, + DockDIDMethodKeySecp256k1ByteSize + ); + return new DockDidMethodKey(new PublicKeySecp256k1(hex)); } else if (strDid.startsWith(DockDidMethodKeyEd25519Prefix)) { + const hex = getHexIdentifier( + strDid, + DockDIDMethodKeyQualifier, + DockDIDMethodKeyEd25519ByteSize + ); + return new DockDidMethodKey(new PublicKeyEd25519(hex)); } else { - validateDockDIDHexIdentifier(hex); + const hex = getHexIdentifier(strDid, DockDIDQualifier, DockDIDByteSize); + return new DockDid(hex); } } @@ -226,16 +239,44 @@ export function typedHexDID(did) { * @return {DockDidOrDidMethodKey} Returns an object wrapping the DID. */ export function typedHexDIDFromSubstrate(did) { - const hex = getHexIdentifier( - u8aToHex(did.isDid ? did.asDid : did.asDidMethodKey), - [], - DockDIDByteSize, - ); + if (!did.isDid) { + const hex = getHexIdentifier( + u8aToHex(did), + [], + DockDIDByteSize + ); + + return new DockDid(hex); + } else if (did.isDid) { + const hex = getHexIdentifier( + u8aToHex(did.asDid), + [], + DockDIDByteSize + ); - if (did.isDid) { return new DockDid(hex); } else if (did.isDidMethodKey) { - return new DockDidMethodKey(hex); + const key = did.asDidMethodKey; + + if (key.isSecp256k1) { + const hex = getHexIdentifier( + u8aToHex(did.asSecp256k1), + [], + DockDIDMethodKeySecp256k1ByteSize + ); + + return new DockDidMethodKey(hex); + } else if (key.isEd25519) { + const hex = getHexIdentifier( + u8aToHex(did.asEd25519), + [], + DockDIDMethodKeyEd25519ByteSize + ); + + return new DockDidMethodKey(hex); + } else { + throw new Error(`Invalid did key: provided: \`${key}\``) + } } else { throw new Error(`Invalid did provided: \`${did}\``); } @@ -247,7 +288,7 @@ export function typedHexDIDFromSubstrate(did) { * @returns {string} - The fully qualified DID */ export function hexDIDToQualified(hexDid) { - if (typeof hexDid?.toStringSS58 === 'function') { + if (typeof hexDid?.toStringSS58 === "function") { return hexDid.toStringSS58(); } else { const ss58Address = encodeAddress(hexDid); @@ -309,7 +350,7 @@ export function createDidSig(did, { keyId }, rawSig) { }; } else { throw new Error( - `Incorrect DID passed: \`${did}\`, expected instance of either \`DockDid\` or \`DockDidMethodKey\``, + `Incorrect DID passed: \`${did}\`, expected instance of either \`DockDid\` or \`DockDidMethodKey\`` ); } } diff --git a/tests/integration/custom-nonce.test.js b/tests/integration/custom-nonce.test.js index 7a4523784..33feab80d 100644 --- a/tests/integration/custom-nonce.test.js +++ b/tests/integration/custom-nonce.test.js @@ -200,7 +200,7 @@ describe('Custom nonce', () => { for (const [regId, revs, nonce] of [[registryId1, revokeIds1, currentNonce + 1], [registryId2, revokeIds2, currentNonce + 2], [registryId3, revokeIds3, currentNonce + 3]]) { const [revoke, sig, computedNonce] = await dock.revocation.createSignedRevoke(regId, revs, did1, pair, { nonce }); expect(computedNonce).toEqual(nonce); - const tx = await dock.revocation.createRevokeTx(revoke, [{ nonce, data: sig }]); + const tx = await dock.revocation.createRevokeTx(revoke, [{ nonce, sig }]); txs.push(tx); } @@ -223,7 +223,7 @@ describe('Custom nonce', () => { for (const [regId, nonce] of [[registryId1, currentNonce + 1], [registryId2, currentNonce + 2], [registryId3, currentNonce + 3]]) { const [remove, sig, computedNonce] = await dock.revocation.createSignedRemove(regId, did1, pair, { nonce }); expect(computedNonce).toEqual(nonce); - const tx = await dock.revocation.createRemoveRegistryTx(remove, [{ nonce, data: sig }]); + const tx = await dock.revocation.createRemoveRegistryTx(remove, [{ nonce, sig }]); txs.push(tx); } diff --git a/tests/integration/fees.test.js b/tests/integration/fees.test.js index c236ac161..e64095df2 100644 --- a/tests/integration/fees.test.js +++ b/tests/integration/fees.test.js @@ -303,7 +303,7 @@ describe.skip('Fees', () => { 1, { didModule: dock.did }, ); - const revTx = dock.revocation.createRevokeTx(update, [[nonce, sig]]); + const revTx = dock.revocation.createRevokeTx(update, [{ nonce, sig }]); await withPaidFeeMatchingSnapshot(async () => { await dock.signAndSend(revTx, false); @@ -318,11 +318,11 @@ describe.skip('Fees', () => { { didModule: dock.did }, ); const revTx = dock.revocation.createRemoveRegistryTx(update, [ - [nonce, sig], + { nonce, sig }, ]); await withPaidFeeMatchingSnapshot(() => dock.signAndSend(revTx, false)); - }, 40000);- + }, 40000); test('anchors', async () => { const anc = randomAsHex(32); diff --git a/tests/integration/revocation.test.js b/tests/integration/revocation.test.js index 636e573f1..f75d75f45 100644 --- a/tests/integration/revocation.test.js +++ b/tests/integration/revocation.test.js @@ -71,14 +71,14 @@ describe('Revocation Module', () => { test('Can revoke single from a registry', async () => { const [revoke, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, revokeIds, ownerDID, pair, { didModule: dock.did }); - await dock.revocation.revoke(revoke, [[nonce, sig]], false); + await dock.revocation.revoke(revoke, [{ nonce, sig }], false); const revocationStatus = await dock.revocation.getIsRevoked(registryId, revokeId); expect(revocationStatus).toBe(true); }, 40000); test('Can unrevoke single from a registry', async () => { const [unrevoke, sig, nonce] = await dock.revocation.createSignedUnRevoke(registryId, revokeIds, ownerDID, pair, { didModule: dock.did }); - await dock.revocation.unrevoke(unrevoke, [[nonce, sig]], false); + await dock.revocation.unrevoke(unrevoke, [{ nonce, sig }], false); const revocationStatus = await dock.revocation.getIsRevoked(registryId, revokeId); expect(revocationStatus).toBe(false); @@ -95,7 +95,7 @@ describe('Revocation Module', () => { const rIdsArr = Array.from(rIds); const [revoke, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, rIds, ownerDID, pair, { didModule: dock.did }); - await dock.revocation.revoke(revoke, [[nonce, sig]], false); + await dock.revocation.revoke(revoke, [{ nonce, sig }], false); console.time(`Check ${count} revocation status one by one`); for (let i = 0; i < rIdsArr.length; i++) { @@ -115,7 +115,7 @@ describe('Revocation Module', () => { // Note: Intentionally passing true and waiting for finalization as not doing that makes the multi-query check fail. // This seems like a bug since the single query check done in next loop work. Even the upgrade to @polkadot/api version 9.14 didn't fix - await dock.revocation.unrevoke(unrevoke, [[nonce1, sig1]], true); + await dock.revocation.unrevoke(unrevoke, [{ nonce: nonce1, sig: sig1 }], true); for (let i = 0; i < rIdsArr.length; i++) { // eslint-disable-next-line no-await-in-loop @@ -130,7 +130,7 @@ describe('Revocation Module', () => { test('Can remove a registry', async () => { const [remove, sig, nonce] = await dock.revocation.createSignedRemove(registryId, ownerDID, pair, { didModule: dock.did }); - await dock.revocation.removeRegistry(remove, [[nonce, sig]], false); + await dock.revocation.removeRegistry(remove, [{ nonce, sig }], false); await expect(dock.revocation.getRevocationRegistry(registryId)).rejects.toThrow(/Could not find revocation registry/); }, 40000); @@ -145,7 +145,7 @@ describe('Revocation Module', () => { expect(!!reg).toBe(true); const [revoke, sig, nonce] = await dock.revocation.createSignedRevoke(registryId, revokeIds, ownerDID, pair, { didModule: dock.did }); - await dock.revocation.revoke(revoke, [[nonce, sig]], false); + await dock.revocation.revoke(revoke, [{ nonce, sig }], false); const revocationStatus = await dock.revocation.getIsRevoked(registryId, revokeId); expect(revocationStatus).toBe(true); @@ -157,7 +157,7 @@ describe('Revocation Module', () => { const [unrevoke, sig, nonce] = await dock.revocation.createSignedUnRevoke(registryId, revokeIds, ownerDID, pair, { didModule: dock.did }); await expect( - dock.revocation.unrevoke(unrevoke, [[nonce, sig]], false), + dock.revocation.unrevoke(unrevoke, [{ nonce, sig }], false), ).rejects.toThrow(); const revocationStatus = await dock.revocation.getIsRevoked(registryId, revokeId); @@ -170,7 +170,7 @@ describe('Revocation Module', () => { const [remove, sig, nonce] = await dock.revocation.createSignedRemove(registryId, ownerDID, pair, { didModule: dock.did }); await expect( - dock.revocation.removeRegistry(remove, [[sig, nonce]], false), + dock.revocation.removeRegistry(remove, [{ nonce, sig }], false), ).rejects.toThrow(); await expect(dock.revocation.getRevocationRegistry(registryId)).resolves.toBeDefined(); diff --git a/tests/integration/status-list-credential-module.test.js b/tests/integration/status-list-credential-module.test.js index d8aced01c..01b57307c 100644 --- a/tests/integration/status-list-credential-module.test.js +++ b/tests/integration/status-list-credential-module.test.js @@ -137,7 +137,7 @@ buildTest("StatusListCredential Module", () => { ); await dock.statusListCredential.updateStatusListCredential( revoke, - [[nonce, sig]], + [{ nonce, sig }], false ); const fetchedCred = @@ -187,7 +187,7 @@ buildTest("StatusListCredential Module", () => { ); await dock.statusListCredential.updateStatusListCredential( update, - [[nonce, sig]], + [{ nonce, sig }], false ); let fetchedCred = @@ -209,7 +209,7 @@ buildTest("StatusListCredential Module", () => { ); await dock.statusListCredential.updateStatusListCredential( update, - [[nonce, sig]], + [{ nonce, sig }], false ); @@ -229,7 +229,7 @@ buildTest("StatusListCredential Module", () => { ); await dock.statusListCredential.removeStatusListCredential( remove, - [[nonce, sig]], + [{ nonce, sig }], false ); expect( From 7f7e45294690148623afe6092aa07f9d2baa08bb Mon Sep 17 00:00:00 2001 From: olegnn Date: Sat, 6 Jan 2024 11:04:46 +0400 Subject: [PATCH 22/32] Tests pass --- example/revocation.js | 4 +- example/vcdm.js | 4 +- scripts/txn-pricing.js | 8 +-- src/dock-api.js | 3 + src/modules/WithParamsAndPublicKeys.js | 17 ++--- src/modules/accumulator.js | 32 +++++----- src/modules/blob.js | 4 +- src/modules/did/did.js | 54 ++++++++-------- src/modules/offchain-signatures.js | 12 ++-- src/modules/revocation.js | 4 +- src/modules/status-list-credential.js | 2 +- src/modules/trust-registry.js | 19 +++--- src/utils/did.js | 64 +++++++++---------- src/utils/revocation/one-of-policy.js | 3 +- .../integration/anoncreds/accumulator.test.js | 16 ++--- tests/integration/anoncreds/demo.test.js | 4 +- .../anoncreds/derived-credentials.test.js | 2 +- tests/integration/anoncreds/issuing.test.js | 2 +- .../prefilled-positive-accumulator.test.js | 2 +- .../anoncreds/presentation.test.js | 2 +- .../integration/anoncreds/r1cs-circom.test.js | 2 +- .../anoncreds/saver-and-bound-check.test.js | 2 +- tests/integration/anoncreds/scheme.test.js | 16 ++--- tests/integration/blob.test.js | 10 +-- .../integration/credential-revocation.test.js | 4 +- tests/integration/custom-nonce.test.js | 32 +++++----- tests/integration/did/controllers.test.js | 10 ++- tests/integration/did/did-basic.test.js | 7 +- tests/integration/did/keys.test.js | 4 +- tests/integration/did/offchain-did.test.js | 4 +- .../integration/did/service-endpoint.test.js | 8 ++- tests/integration/fees.test.js | 8 +-- tests/integration/master.test.js | 4 +- tests/integration/resolvers.test.js | 6 +- tests/integration/revocation.test.js | 20 +++--- tests/integration/schema.test.js | 4 +- .../status-list-credential-module.test.js | 20 +++--- .../status-list-credential.test.js | 4 +- .../integration/trust-registry-module.test.js | 54 ++++++++-------- 39 files changed, 249 insertions(+), 228 deletions(-) diff --git a/example/revocation.js b/example/revocation.js index 8e40719a0..e6dc84051 100644 --- a/example/revocation.js +++ b/example/revocation.js @@ -1,7 +1,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import dock from '../src/index'; -import { createNewDockDID, DidKeypair } from '../src/utils/did'; +import { createNewDockDID, DidKeypair, typedHexDID } from '../src/utils/did'; import { OneOfPolicy, @@ -22,7 +22,7 @@ const controllerSeed = randomAsHex(32); // Create a list of controllers const controllers = new Set(); -controllers.add(controllerDID); +controllers.add(typedHexDID(dock.api, controllerDID)); // Create a registry policy const policy = new OneOfPolicy(controllers); diff --git a/example/vcdm.js b/example/vcdm.js index c66f88eeb..6368d6c39 100644 --- a/example/vcdm.js +++ b/example/vcdm.js @@ -3,7 +3,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import dock from '../src/index'; import VerifiableCredential from '../src/verifiable-credential'; import VerifiablePresentation from '../src/verifiable-presentation'; -import { createNewDockDID, DidKeypair } from '../src/utils/did'; +import { createNewDockDID, DidKeypair, typedHexDID } from '../src/utils/did'; import { registerNewDIDUsingPair } from '../tests/integration/helpers'; import { createRandomRegistryId, OneOfPolicy, buildDockCredentialStatus } from '../src/utils/revocation'; import { FullNodeEndpoint, TestAccountURI } from '../tests/test-constants'; @@ -54,7 +54,7 @@ async function setup() { // Create a new policy const policy = new OneOfPolicy(); - policy.addOwner(issuerDID); + policy.addOwner(typedHexDID(dock.api, issuerDID)); // Add a new revocation registry with above policy console.log('Creating registry...'); diff --git a/scripts/txn-pricing.js b/scripts/txn-pricing.js index 9225e23e5..cb6090cc8 100755 --- a/scripts/txn-pricing.js +++ b/scripts/txn-pricing.js @@ -5,7 +5,7 @@ import { BTreeSet } from '@polkadot/types'; import { randomAsHex } from '@polkadot/util-crypto'; import dock from '../src/index'; import { - createNewDockDID, + createNewDockDID, typedHexDID, } from '../src/utils/did'; import { getPublicKeyFromKeyringPair } from '../src/utils/misc'; import { createRandomRegistryId, OneOfPolicy } from '../src/utils/revocation'; @@ -217,7 +217,7 @@ async function revocation() { const registryId = createRandomRegistryId(); // Create owners const owners = new Set(); - owners.add(did); + owners.add(typedHexDID(dock.api, did)); const policy = new OneOfPolicy(owners); await printFeePaid(dock.api, account.address, async () => { @@ -301,7 +301,7 @@ async function bbsPlus() { // Add a public key const kp = BBSPlusKeypairG2.generate(BBSPlusSignatureParamsG1.generate(10, hexToU8a(label))); - const pk = BBSPlusModule.prepareAddPublicKey(u8aToHex(kp.publicKey.bytes), undefined, [did, 1]); + const pk = BBSPlusModule.prepareAddPublicKey(dock.api, u8aToHex(kp.publicKey.bytes), undefined, [did, 1]); await printFeePaid(dock.api, account.address, async () => { console.info('Add a BBS+ key'); await dock.bbsPlusModule.addPublicKey(pk, did, did, pair, { didModule: dock.did }, false); @@ -339,7 +339,7 @@ async function accumulator() { const kp = Accumulator.generateKeypair(new AccumulatorParams(hexToU8a(params.bytes))); - const pk = AccumulatorModule.prepareAddPublicKey(u8aToHex(kp.publicKey.bytes), undefined, [did, 1]); + const pk = AccumulatorModule.prepareAddPublicKey(dock.api, u8aToHex(kp.publicKey.bytes), undefined, [did, 1]); await printFeePaid(dock.api, account.address, async () => { console.info('Accumulator key write'); await dock.accumulatorModule.addPublicKey(pk, did, pair, { didModule: dock.did }, false); diff --git a/src/dock-api.js b/src/dock-api.js index 7dc9956dc..1eeab5b73 100644 --- a/src/dock-api.js +++ b/src/dock-api.js @@ -134,6 +134,9 @@ export default class DockAPI { this.api = await ApiPromise.create(apiOptions); + const runtimeVersion = await this.api.rpc.state.getRuntimeVersion(); + this.api.specVersion = runtimeVersion.specVersion.toNumber(); + await this.initKeyring(keyring); this.anchorModule.setApi(this.api, this.signAndSend.bind(this)); diff --git a/src/modules/WithParamsAndPublicKeys.js b/src/modules/WithParamsAndPublicKeys.js index db06b7606..4fc0b0c3e 100644 --- a/src/modules/WithParamsAndPublicKeys.js +++ b/src/modules/WithParamsAndPublicKeys.js @@ -49,6 +49,7 @@ export default class WithParamsAndPublicKeys { * @returns {{}} */ static prepareAddPublicKey( + api, bytes, curveType = undefined, paramsRef = undefined, @@ -67,7 +68,7 @@ export default class WithParamsAndPublicKeys { throw new Error(`Invalid curve type ${curveType}`); } publicKey.paramsRef = paramsRef !== undefined - ? WithParamsAndPublicKeys.parseRef(paramsRef) + ? WithParamsAndPublicKeys.parseRef(api, paramsRef) : undefined; return publicKey; } @@ -78,7 +79,7 @@ export default class WithParamsAndPublicKeys { * @param ref * @returns {any[]} */ - static parseRef(ref) { + static parseRef(api, ref) { const parsed = new Array(2); if ( !(typeof ref === 'object' && ref instanceof Array && ref.length === 2) @@ -86,7 +87,7 @@ export default class WithParamsAndPublicKeys { throw new Error('Reference should be an array of 2 items'); } try { - parsed[0] = typedHexDID(ref[0]); + parsed[0] = typedHexDID(api, ref[0]); } catch (e) { throw new Error( `First item of reference should be a DID but was ${ref[0]}`, @@ -120,7 +121,7 @@ export default class WithParamsAndPublicKeys { { nonce = undefined, didModule = undefined }, ) { const offchainParams = this.constructor.buildParams(params); - const hexDid = typedHexDID(signerDid); + const hexDid = typedHexDID(this.api, signerDid); const [addParams, signature] = await this.createSignedAddParams( offchainParams, hexDid, @@ -147,7 +148,7 @@ export default class WithParamsAndPublicKeys { signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const hexDid = typedHexDID(signerDid); + const hexDid = typedHexDID(this.api, signerDid); const [removeParams, signature] = await this.createSignedRemoveParams( index, hexDid, @@ -252,7 +253,7 @@ export default class WithParamsAndPublicKeys { } async getParams(did, counter) { - const hexId = typedHexDID(did); + const hexId = typedHexDID(this.api, did); return this.getParamsByHexDid(hexId, counter); } @@ -265,7 +266,7 @@ export default class WithParamsAndPublicKeys { * @returns {Promise<{bytes: string}|null>} */ async getPublicKey(did, keyId, withParams = false) { - const hexId = typedHexDID(did); + const hexId = typedHexDID(this.api, did); return this.getPublicKeyByHexDid(hexId, keyId, withParams); } @@ -336,7 +337,7 @@ export default class WithParamsAndPublicKeys { } if (pk.paramsRef.isSome) { const pr = pk.paramsRef.unwrap(); - pkObj.paramsRef = [typedHexDIDFromSubstrate(pr[0]), pr[1].toNumber()]; + pkObj.paramsRef = [typedHexDIDFromSubstrate(this.api, pr[0]), pr[1].toNumber()]; } else { pkObj.paramsRef = null; } diff --git a/src/modules/accumulator.js b/src/modules/accumulator.js index f1948b00a..f636b4db6 100644 --- a/src/modules/accumulator.js +++ b/src/modules/accumulator.js @@ -16,8 +16,8 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { this.signAndSend = signAndSend; } - static prepareAddPositiveAccumulator(id, accumulated, publicKeyRef) { - const keyRef = AccumulatorModule.parseRef(publicKeyRef); + static prepareAddPositiveAccumulator(api, id, accumulated, publicKeyRef) { + const keyRef = AccumulatorModule.parseRef(api, publicKeyRef); return { id, accumulator: { @@ -29,8 +29,8 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { }; } - static prepareAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize) { - const keyRef = AccumulatorModule.parseRef(publicKeyRef); + static prepareAddUniversalAccumulator(api, id, accumulated, publicKeyRef, maxSize) { + const keyRef = AccumulatorModule.parseRef(api, publicKeyRef); return { id, accumulator: { @@ -84,7 +84,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<*>} */ async createAddPublicKeyTx(publicKey, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [addPk, signature] = await this.createSignedAddPublicKey(publicKey, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addPublicKey(addPk, signature); } @@ -100,7 +100,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<*>} */ async createRemovePublicKeyTx(removeKeyId, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [remPk, signature] = await this.createSignedRemovePublicKey(removeKeyId, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.removePublicKey(remPk, signature); } @@ -118,7 +118,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<*>} */ async createAddPositiveAccumulatorTx(id, accumulated, publicKeyRef, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [addAccumulator, signature] = await this.createSignedAddPositiveAccumulator(id, accumulated, publicKeyRef, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addAccumulator(addAccumulator, signature); } @@ -137,7 +137,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<*>} */ async createAddUniversalAccumulatorTx(id, accumulated, publicKeyRef, maxSize, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [addAccumulator, signature] = await this.createSignedAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.addAccumulator(addAccumulator, signature); } @@ -160,7 +160,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { id, newAccumulated, { additions = undefined, removals = undefined, witnessUpdateInfo = undefined }, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const signerHexDid = typedHexDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [update, signature] = await this.createSignedUpdateAccumulator(id, newAccumulated, { additions, removals, witnessUpdateInfo }, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.updateAccumulator(update, signature); @@ -177,7 +177,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise} */ async removeAccumulatorTx(id, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [removal, signature] = await this.createSignedRemoveAccumulator(id, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.removeAccumulator(removal, signature); } @@ -316,7 +316,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { async createSignedAddPositiveAccumulator(id, accumulated, publicKeyRef, signerHexDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(signerHexDid, nonce, didModule); - const accum = AccumulatorModule.prepareAddPositiveAccumulator(id, accumulated, publicKeyRef); + const accum = AccumulatorModule.prepareAddPositiveAccumulator(this.api, id, accumulated, publicKeyRef); const addAccum = { ...accum, nonce }; const signature = this.signAddAccumulator(signingKeyRef, addAccum); const didSig = createDidSig(signerHexDid, signingKeyRef, signature); @@ -326,7 +326,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { async createSignedAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize, signerHexDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(signerHexDid, nonce, didModule); - const accum = AccumulatorModule.prepareAddUniversalAccumulator(id, accumulated, publicKeyRef, maxSize); + const accum = AccumulatorModule.prepareAddUniversalAccumulator(this.api, id, accumulated, publicKeyRef, maxSize); const addAccum = { ...accum, nonce }; const signature = this.signAddAccumulator(signingKeyRef, addAccum); const didSig = createDidSig(signerHexDid, signingKeyRef, signature); @@ -398,7 +398,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { accumulatorObj.accumulated = u8aToHex(common.accumulated); const owner = common.keyRef[0]; const keyId = common.keyRef[1].toNumber(); - accumulatorObj.keyRef = [typedHexDIDFromSubstrate(owner), keyId]; + accumulatorObj.keyRef = [typedHexDIDFromSubstrate(this.api, owner), keyId]; if (withKeyAndParams) { const pk = await this.getPublicKeyByHexDid(owner, keyId, true); @@ -460,7 +460,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise<{bytes: string}|null>} */ async getLastParamsWritten(did) { - const hexId = typedHexDID(did); + const hexId = typedHexDID(this.api, did); const counters = await this.api.query[this.moduleName].accumulatorOwnerCounters(hexId); const counter = counters.paramsCounter.toNumber(); @@ -479,7 +479,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise} */ async getAllParamsByDid(did) { - const hexId = typedHexDID(did); + const hexId = typedHexDID(this.api, did); const params = []; const counters = await this.api.query[this.moduleName].accumulatorOwnerCounters(hexId); @@ -503,7 +503,7 @@ export default class AccumulatorModule extends WithParamsAndPublicKeys { * @returns {Promise< object[]>} */ async getAllPublicKeysByDid(did, withParams = false) { - const hexId = typedHexDID(did); + const hexId = typedHexDID(this.api, did); const pks = []; const counters = await this.api.query[this.moduleName].accumulatorOwnerCounters(hexId); diff --git a/src/modules/blob.js b/src/modules/blob.js index 8d013ab70..05d05b33c 100644 --- a/src/modules/blob.js +++ b/src/modules/blob.js @@ -84,7 +84,7 @@ class BlobModule { * @returns {Promise<*>} */ async createNewTx(blob, signerDid, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const signerHexDid = typedHexDID(signerDid); + const signerHexDid = typedHexDID(this.api, signerDid); const [addBlob, didSig] = await this.createSignedAddBlob(blob, signerHexDid, signingKeyRef, { nonce, didModule }); return this.module.new(addBlob, didSig); } @@ -133,7 +133,7 @@ class BlobModule { // no-op, just use default Uint8 array value } - return [typedHexDIDFromSubstrate(respTuple[0]), value]; + return [typedHexDIDFromSubstrate(this.api, respTuple[0]), value]; } throw new Error(`Needed 2 items in response but got${respTuple.length}`); } diff --git a/src/modules/did/did.js b/src/modules/did/did.js index 04ba87577..ee40a1649 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -51,7 +51,7 @@ class DIDModule { * @returns {*} */ createNewOffchainTx(did, didDocRef) { - const hexId = typedHexDID(did).asDid; + const hexId = typedHexDID(this.api, did).asDid; return this.module.newOffchain(hexId, didDocRef); } @@ -78,7 +78,7 @@ class DIDModule { * @returns {*} */ createSetOffchainDidRefTx(did, didDocRef) { - const hexId = typedHexDID(did).asDid; + const hexId = typedHexDID(this.api, did).asDid; return this.module.setOffchainDidDocRef(hexId, didDocRef); } @@ -109,7 +109,7 @@ class DIDModule { * @returns {Promise<*>} */ createRemoveOffchainDidTx(did) { - const hexId = typedHexDID(did).asDid; + const hexId = typedHexDID(this.api, did).asDid; return this.module.removeOffchainDid(hexId); } @@ -139,10 +139,10 @@ class DIDModule { const cnts = new BTreeSet(); if (controllers !== undefined) { controllers.forEach((c) => { - cnts.add(typedHexDID(c)); + cnts.add(typedHexDID(this.api, c)); }); } - const hexId = typedHexDID(did).asDid; + const hexId = typedHexDID(this.api, did).asDid; return this.module.newOnchain( hexId, didKeys.map((d) => d.toJSON()), @@ -190,8 +190,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(targetDid).asDid; - const signerHexDid = typedHexDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [addKeys, signature] = await this.createSignedAddKeys( didKeys, targetHexDid, @@ -253,8 +253,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(targetDid).asDid; - const signerHexDid = typedHexDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [addControllers, signature] = await this.createSignedAddControllers( controllers, targetHexDid, @@ -317,8 +317,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(targetDid).asDid; - const signerHexDid = typedHexDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [addServiceEndpoint, signature] = await this.createSignedAddServiceEndpoint( endpointId, endpointType, @@ -385,8 +385,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(targetDid).asDid; - const signerHexDid = typedHexDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [removeKeys, signature] = await this.createSignedRemoveKeys( keyIds, targetHexDid, @@ -445,8 +445,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(targetDid).asDid; - const signerHexDid = typedHexDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [removeControllers, signature] = await this.createSignedRemoveControllers( controllers, targetHexDid, @@ -505,8 +505,8 @@ class DIDModule { signingKeyRef, nonce = undefined, ) { - const targetHexDid = typedHexDID(targetDid).asDid; - const signerHexDid = typedHexDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [removeServiceEndpoint, signature] = await this.createSignedRemoveServiceEndpoint( endpointId, targetHexDid, @@ -558,8 +558,8 @@ class DIDModule { * @return {Promise} The extrinsic to sign and send. */ async createRemoveTx(targetDid, signerDid, signingKeyRef, nonce = undefined) { - const hexDid = typedHexDID(targetDid).asDid; - const signerHexDid = typedHexDID(signerDid); + const hexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [didRemoval, signature] = await this.createSignedDidRemoval( hexDid, signerHexDid, @@ -607,7 +607,7 @@ class DIDModule { * @returns {Promise>} */ async createSetClaimTx(priority, iri, did, signingKeyRef, nonce = undefined) { - const hexDid = typedHexDID(did); + const hexDid = typedHexDID(this.api, did); const [setAttestation, signature] = await this.createSignedAttestation( priority, iri, @@ -687,7 +687,7 @@ class DIDModule { */ // eslint-disable-next-line sonarjs/cognitive-complexity async getDocument(did, { getOffchainSigKeys = true } = {}) { - const typedDid = typedHexDID(did); + const typedDid = typedHexDID(this.api, did); const hexDid = typedDid.asDid; let didDetails = await this.getOnchainDidDetail(hexDid); didDetails = didDetails.data || didDetails; @@ -1051,7 +1051,7 @@ class DIDModule { * @returns {Promise} */ async getDidKey(did, keyIndex) { - const hexId = typedHexDID(did).asDid; + const hexId = typedHexDID(this.api, did).asDid; let resp = await this.api.query.didModule.didKeys(hexId, keyIndex); if (resp.isNone) { throw new Error(`No key for found did ${did} and key index ${keyIndex}`); @@ -1093,8 +1093,8 @@ class DIDModule { * @returns {Promise} */ async isController(controlled, controller) { - const controlledDid = typedHexDID(controlled).asDid; - const controllerDid = typedHexDID(controller); + const controlledDid = typedHexDID(this.api, controlled).asDid; + const controllerDid = typedHexDID(this.api, controller); const resp = await this.api.query.didModule.didControllers( controlledDid, controllerDid, @@ -1109,7 +1109,7 @@ class DIDModule { * @returns {Promise} */ async getServiceEndpoint(did, endpointId) { - const hexId = typedHexDID(did).asDid; + const hexId = typedHexDID(this.api, did).asDid; let resp = await this.api.query.didModule.didServiceEndpoints( hexId, endpointId, @@ -1160,7 +1160,7 @@ class DIDModule { const cnts = new BTreeSet(); controllers.forEach((c) => { - cnts.add(typedHexDID(c)); + cnts.add(typedHexDID(this.api, c)); }); const addControllers = { did: hexDid, controllers: cnts, nonce }; const serializedAddControllers = this.getSerializedAddControllers(addControllers); @@ -1233,7 +1233,7 @@ class DIDModule { const cnts = new BTreeSet(); controllers.forEach((c) => { - cnts.add(typedHexDID(c)); + cnts.add(typedHexDID(this.api, c)); }); const removeControllers = { did: hexDid, controllers: cnts, nonce }; diff --git a/src/modules/offchain-signatures.js b/src/modules/offchain-signatures.js index ebf830dd9..d0739f551 100644 --- a/src/modules/offchain-signatures.js +++ b/src/modules/offchain-signatures.js @@ -50,7 +50,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @returns {Promise<{bytes: string}|null>} */ async getLastParamsWritten(did) { - const hexId = typedHexDID(did); + const hexId = typedHexDID(this.api, did); const counter = await this.api.query[this.moduleName].paramsCounter(hexId); if (counter > 0) { const resp = await this.queryParamsFromChain(hexId, counter); @@ -67,7 +67,7 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { * @returns {Promise} */ async getAllParamsByDid(did) { - const hexId = typedHexDID(did); + const hexId = typedHexDID(this.api, did); const params = []; const counter = await this.api.query[this.moduleName].paramsCounter(hexId); @@ -128,8 +128,8 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { { nonce = undefined, didModule = undefined }, ) { const offchainPublicKey = this.constructor.buildPublicKey(publicKey); - const targetHexDid = typedHexDID(targetDid).asDid; - const signerHexDid = typedHexDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [addPk, signature] = await this.createSignedAddPublicKey( offchainPublicKey, targetHexDid, @@ -158,8 +158,8 @@ export default class OffchainSignaturesModule extends WithParamsAndPublicKeys { signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const targetHexDid = typedHexDID(targetDid).asDid; - const signerHexDid = typedHexDID(signerDid); + const targetHexDid = typedHexDID(this.api, targetDid).asDid; + const signerHexDid = typedHexDID(this.api, signerDid); const [removePk, signature] = await this.createSignedRemovePublicKey( removeKeyId, targetHexDid, diff --git a/src/modules/revocation.js b/src/modules/revocation.js index 625512f25..86786100b 100644 --- a/src/modules/revocation.js +++ b/src/modules/revocation.js @@ -213,7 +213,7 @@ class RevocationModule { } async createSignedUpdate(updateFunc, registryId, [...revokeIds], did, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const hexDid = typedHexDID(did); + const hexDid = typedHexDID(this.api, did); // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); @@ -239,7 +239,7 @@ class RevocationModule { } async createSignedRemove(registryId, did, signingKeyRef, { nonce = undefined, didModule = undefined }) { - const hexDid = typedHexDID(did); + const hexDid = typedHexDID(this.api, did); // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); diff --git a/src/modules/status-list-credential.js b/src/modules/status-list-credential.js index dee4e313f..038b7de9c 100644 --- a/src/modules/status-list-credential.js +++ b/src/modules/status-list-credential.js @@ -244,7 +244,7 @@ export default class StatusListCredentialModule { signingKeyRef, { nonce = undefined, didModule = undefined }, ) { - const hexDid = typedHexDID(did); + const hexDid = typedHexDID(this.api, did); // eslint-disable-next-line no-param-reassign nonce = await getDidNonce(hexDid, nonce, didModule); diff --git a/src/modules/trust-registry.js b/src/modules/trust-registry.js index c63dd7654..3f1967cfa 100644 --- a/src/modules/trust-registry.js +++ b/src/modules/trust-registry.js @@ -42,7 +42,7 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerHexDid = typedHexDID(convenerDid); + const convenerHexDid = typedHexDID(this.api, convenerDid); const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); return this.signAndSend( @@ -85,7 +85,7 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerHexDid = typedHexDID(convenerDid); + const convenerHexDid = typedHexDID(this.api, convenerDid); const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); return this.signAndSend( @@ -123,9 +123,8 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerOrIssuerOrVerifierHexDid = typedHexDID( - convenerOrIssuerOrVerifierDid, - ); + const convenerOrIssuerOrVerifierHexDid = typedHexDID(this.api, + convenerOrIssuerOrVerifierDid); const lastNonce = nonce ?? (await getDidNonce(convenerOrIssuerOrVerifierHexDid, nonce, didModule)); @@ -164,12 +163,12 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerHexDid = typedHexDID(convenerDid); + const convenerHexDid = typedHexDID(this.api, convenerDid); const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); const hexIssuers = new BTreeSet(); for (const issuer of issuers) { - hexIssuers.add(typedHexDID(issuer)); + hexIssuers.add(typedHexDID(this.api, issuer)); } return this.signAndSend( @@ -207,12 +206,12 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerHexDid = typedHexDID(convenerDid); + const convenerHexDid = typedHexDID(this.api, convenerDid); const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); const hexIssuers = new BTreeSet(); for (const issuer of issuers) { - hexIssuers.add(typedHexDID(issuer)); + hexIssuers.add(typedHexDID(this.api, issuer)); } return this.signAndSend( @@ -249,7 +248,7 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const issuerHexDid = typedHexDID(issuerDid); + const issuerHexDid = typedHexDID(this.api, issuerDid); const lastNonce = nonce ?? (await getDidNonce(issuerHexDid, nonce, didModule)); return this.signAndSend( diff --git a/src/utils/did.js b/src/utils/did.js index 395ae194f..c8f4a53bf 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -2,29 +2,29 @@ // Import some utils from Polkadot JS // eslint-disable-next-line max-classes-per-file -import { randomAsHex, encodeAddress } from "@polkadot/util-crypto"; -import { u8aToHex } from "@polkadot/util"; -import { isHexWithGivenByteSize, getHexIdentifier } from "./codec"; +import { randomAsHex, encodeAddress } from '@polkadot/util-crypto'; +import { u8aToHex } from '@polkadot/util'; +import { isHexWithGivenByteSize, getHexIdentifier } from './codec'; import { PublicKeyEd25519, PublicKeySecp256k1, PublicKey, // eslint-disable-line VerificationRelationship, // eslint-disable-line -} from "../public-keys"; +} from '../public-keys'; import { Signature } from "../signatures"; // eslint-disable-line import { getPublicKeyFromKeyringPair, getSignatureFromKeyringPair, getStateChange, -} from "./misc"; +} from './misc'; -export const DockDIDMethod = "dock"; -export const Secp256k1PublicKeyPrefix = "zQ3s"; -export const Ed25519PublicKeyPrefix = "z6Mk"; +export const DockDIDMethod = 'dock'; +export const Secp256k1PublicKeyPrefix = 'zQ3s'; +export const Ed25519PublicKeyPrefix = 'z6Mk'; export const DockDIDQualifier = `did:${DockDIDMethod}:`; -export const DockDIDMethodKeyQualifier = "did:key:"; +export const DockDIDMethodKeyQualifier = 'did:key:'; export const DockDIDByteSize = 32; export const DockDIDMethodKeySecp256k1ByteSize = 33; export const DockDIDMethodKeyEd25519ByteSize = 32; @@ -64,11 +64,11 @@ export class DidActor { export class DockDidOrDidMethodKey extends DidActor { get asDid() { - throw new Error("Not a `Did`"); + throw new Error('Not a `Did`'); } get asDidMethodKey() { - throw new Error("Not a `DidMethodKey`"); + throw new Error('Not a `DidMethodKey`'); } get isDid() { @@ -141,10 +141,9 @@ export class DockDidMethodKey extends DockDidOrDidMethodKey { export class NoDIDError extends Error { constructor(did) { super(`DID (${did}) does not exist`); - this.name = "NoDIDError"; + this.name = 'NoDIDError'; this.did = did; - this.message = - "A DID document lookup was successful, but the DID in question does not exist. This is different from a network error."; + this.message = 'A DID document lookup was successful, but the DID in question does not exist. This is different from a network error.'; } } @@ -154,10 +153,9 @@ export class NoDIDError extends Error { export class NoOnchainDIDError extends Error { constructor(did) { super(`DID (${did}) is an off-chain DID`); - this.name = "NoOnchainDIDError"; + this.name = 'NoOnchainDIDError'; this.did = did; - this.message = - "The DID exists on chain but is an off-chain DID, meaning the DID document exists off-chain."; + this.message = 'The DID exists on chain but is an off-chain DID, meaning the DID document exists off-chain.'; } } @@ -167,10 +165,9 @@ export class NoOnchainDIDError extends Error { export class NoOffchainDIDError extends Error { constructor(did) { super(`DID (${did}) is an on-chain DID`); - this.name = "NoOffchainDIDError"; + this.name = 'NoOffchainDIDError'; this.did = did; - this.message = - "The DID exists on chain and is an on-chain DID but the lookup was performed for an off-chain DID."; + this.message = 'The DID exists on chain and is an on-chain DID but the lookup was performed for an off-chain DID.'; } } @@ -196,7 +193,7 @@ export function validateDockDIDSS58Identifier(identifier) { const regex = new RegExp(/^[5KL][1-9A-HJ-NP-Za-km-z]{47}$/); const matches = regex.exec(identifier); if (!matches) { - throw new Error("The identifier must be 32 bytes and valid SS58 string"); + throw new Error('The identifier must be 32 bytes and valid SS58 string'); } } @@ -206,14 +203,17 @@ export function validateDockDIDSS58Identifier(identifier) { * `did:key:` or a 32 byte hex string * @return {DockDidOrDidMethodKey} Returns a `DockDidMethodKey` or `DockDid` object. */ -export function typedHexDID(did) { +export function typedHexDID(api, did) { const strDid = did.toString(); + if (api.specVersion < 44) { + return getHexIdentifier(strDid, DockDIDQualifier, DockDIDByteSize); + } if (strDid.startsWith(DockDidMethodKeySecp256k1Prefix)) { const hex = getHexIdentifier( strDid, DockDIDMethodKeyQualifier, - DockDIDMethodKeySecp256k1ByteSize + DockDIDMethodKeySecp256k1ByteSize, ); return new DockDidMethodKey(new PublicKeySecp256k1(hex)); @@ -221,7 +221,7 @@ export function typedHexDID(did) { const hex = getHexIdentifier( strDid, DockDIDMethodKeyQualifier, - DockDIDMethodKeyEd25519ByteSize + DockDIDMethodKeyEd25519ByteSize, ); return new DockDidMethodKey(new PublicKeyEd25519(hex)); @@ -238,12 +238,12 @@ export function typedHexDID(did) { * a 32 byte hex string * @return {DockDidOrDidMethodKey} Returns an object wrapping the DID. */ -export function typedHexDIDFromSubstrate(did) { +export function typedHexDIDFromSubstrate(api, did) { if (!did.isDid) { const hex = getHexIdentifier( u8aToHex(did), [], - DockDIDByteSize + DockDIDByteSize, ); return new DockDid(hex); @@ -251,7 +251,7 @@ export function typedHexDIDFromSubstrate(did) { const hex = getHexIdentifier( u8aToHex(did.asDid), [], - DockDIDByteSize + DockDIDByteSize, ); return new DockDid(hex); @@ -262,7 +262,7 @@ export function typedHexDIDFromSubstrate(did) { const hex = getHexIdentifier( u8aToHex(did.asSecp256k1), [], - DockDIDMethodKeySecp256k1ByteSize + DockDIDMethodKeySecp256k1ByteSize, ); return new DockDidMethodKey(hex); @@ -270,12 +270,12 @@ export function typedHexDIDFromSubstrate(did) { const hex = getHexIdentifier( u8aToHex(did.asEd25519), [], - DockDIDMethodKeyEd25519ByteSize + DockDIDMethodKeyEd25519ByteSize, ); return new DockDidMethodKey(hex); } else { - throw new Error(`Invalid did key: provided: \`${key}\``) + throw new Error(`Invalid did key: provided: \`${key}\``); } } else { throw new Error(`Invalid did provided: \`${did}\``); @@ -288,7 +288,7 @@ export function typedHexDIDFromSubstrate(did) { * @returns {string} - The fully qualified DID */ export function hexDIDToQualified(hexDid) { - if (typeof hexDid?.toStringSS58 === "function") { + if (typeof hexDid?.toStringSS58 === 'function') { return hexDid.toStringSS58(); } else { const ss58Address = encodeAddress(hexDid); @@ -350,7 +350,7 @@ export function createDidSig(did, { keyId }, rawSig) { }; } else { throw new Error( - `Incorrect DID passed: \`${did}\`, expected instance of either \`DockDid\` or \`DockDidMethodKey\`` + `Incorrect DID passed: \`${did}\`, expected instance of either \`DockDid\` or \`DockDidMethodKey\``, ); } } diff --git a/src/utils/revocation/one-of-policy.js b/src/utils/revocation/one-of-policy.js index e6df2cc33..069ee76e8 100644 --- a/src/utils/revocation/one-of-policy.js +++ b/src/utils/revocation/one-of-policy.js @@ -1,4 +1,3 @@ -import { typedHexDID } from '../did'; import Policy from './policy'; // Revocation policy that allows one of the pre-decided controllers to update the registry. @@ -26,7 +25,7 @@ export default class OneOfPolicy extends Policy { * @returns {DockDidOrDidMethodKey[]} */ controllerIds() { - const controllerIds = [...this.controllers].map(typedHexDID); + const controllerIds = [...this.controllers]; // Sort the controller ids as the node is expecting sorted ids and keeping ids unsorted is giving a signature // verification error. This is a workaround and is needed for now. It maybe fixed later controllerIds.sort(); diff --git a/tests/integration/anoncreds/accumulator.test.js b/tests/integration/anoncreds/accumulator.test.js index 22c60321e..6fc675f67 100644 --- a/tests/integration/anoncreds/accumulator.test.js +++ b/tests/integration/anoncreds/accumulator.test.js @@ -127,7 +127,7 @@ describe("Accumulator Module", () => { const params = Accumulator.generateParams(); let keypair = Accumulator.generateKeypair(params); const bytes1 = u8aToHex(keypair.publicKey.bytes); - const pk1 = chainModuleClass.prepareAddPublicKey(bytes1); + const pk1 = chainModuleClass.prepareAddPublicKey(dock.api, bytes1); await chainModule.addPublicKey( pk1, did1, @@ -144,7 +144,7 @@ describe("Accumulator Module", () => { const aparams1 = new AccumulatorParams(hexToU8a(params1.bytes)); keypair = Accumulator.generateKeypair(aparams1, hexToU8a(seedAccum)); const bytes2 = u8aToHex(keypair.publicKey.bytes); - const pk2 = chainModuleClass.prepareAddPublicKey(bytes2, undefined, [ + const pk2 = chainModuleClass.prepareAddPublicKey(dock.api, bytes2, undefined, [ did1, 1, ]); @@ -158,7 +158,7 @@ describe("Accumulator Module", () => { const queriedPk2 = await chainModule.getPublicKey(did2, 1); expect(queriedPk2.bytes).toEqual(pk2.bytes); - expect(queriedPk2.paramsRef).toEqual([typedHexDID(did1), 1]); + expect(queriedPk2.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); const queriedPk2WithParams = await chainModule.getPublicKey(did2, 1, true); expect(queriedPk2WithParams.params).toEqual(params1); @@ -167,7 +167,7 @@ describe("Accumulator Module", () => { const aparams2 = new AccumulatorParams(hexToU8a(params2.bytes)); keypair = Accumulator.generateKeypair(aparams2); const bytes3 = u8aToHex(keypair.publicKey.bytes); - const pk3 = chainModuleClass.prepareAddPublicKey(bytes3, undefined, [ + const pk3 = chainModuleClass.prepareAddPublicKey(dock.api, bytes3, undefined, [ did1, 2, ]); @@ -181,7 +181,7 @@ describe("Accumulator Module", () => { const queriedPk3 = await chainModule.getPublicKey(did2, 2); expect(queriedPk3.bytes).toEqual(pk3.bytes); - expect(queriedPk3.paramsRef).toEqual([typedHexDID(did1), 2]); + expect(queriedPk3.paramsRef).toEqual([typedHexDID(dock.api, did1), 2]); const queriedPk3WithParams = await chainModule.getPublicKey(did2, 2, true); expect(queriedPk3WithParams.params).toEqual(params2); @@ -234,7 +234,7 @@ describe("Accumulator Module", () => { expect(accum1.created).toEqual(accum1.lastModified); expect(accum1.type).toEqual("positive"); expect(accum1.accumulated).toEqual(accumulated1); - expect(accum1.keyRef).toEqual([typedHexDID(did1), 1]); + expect(accum1.keyRef).toEqual([typedHexDID(dock.api, did1), 1]); expect(accum1.publicKey).toBeUndefined(); const accum2 = await chainModule.getAccumulator(id2, false); @@ -243,7 +243,7 @@ describe("Accumulator Module", () => { expect(accum2.created).toEqual(accum2.lastModified); expect(accum2.type).toEqual("universal"); expect(accum2.accumulated).toEqual(accumulated2); - expect(accum2.keyRef).toEqual([typedHexDID(did2), 1]); + expect(accum2.keyRef).toEqual([typedHexDID(dock.api, did2), 1]); expect(accum2.publicKey).toBeUndefined(); const keyWithParams = await chainModule.getPublicKey(did2, 1, true); @@ -255,7 +255,7 @@ describe("Accumulator Module", () => { ); expect(accum2WithKeyAndParams.type).toEqual("universal"); expect(accum2WithKeyAndParams.accumulated).toEqual(accumulated2); - expect(accum2WithKeyAndParams.keyRef).toEqual([typedHexDID(did2), 1]); + expect(accum2WithKeyAndParams.keyRef).toEqual([typedHexDID(dock.api, did2), 1]); expect(accum2WithKeyAndParams.publicKey).toEqual(keyWithParams); await chainModule.removeAccumulator( diff --git a/tests/integration/anoncreds/demo.test.js b/tests/integration/anoncreds/demo.test.js index eb906612d..f3655a58c 100644 --- a/tests/integration/anoncreds/demo.test.js +++ b/tests/integration/anoncreds/demo.test.js @@ -215,7 +215,7 @@ for (const { ); issuerBbsPlusKeypair = KeyPair.generate(params); - const pk = Module.prepareAddPublicKey( + const pk = Module.prepareAddPublicKey(dock.api, u8aToHex(issuerBbsPlusKeypair.publicKey.bytes), undefined, [issuerDid, 1], @@ -262,7 +262,7 @@ for (const { hexToU8a(seedAccum), ); - const pk = AccumulatorModule.prepareAddPublicKey( + const pk = AccumulatorModule.prepareAddPublicKey(dock.api, u8aToHex(accumulatorKeypair.publicKey.bytes), undefined, [accumulatorManagerDid, 1], diff --git a/tests/integration/anoncreds/derived-credentials.test.js b/tests/integration/anoncreds/derived-credentials.test.js index 55b56a33b..e52d44add 100644 --- a/tests/integration/anoncreds/derived-credentials.test.js +++ b/tests/integration/anoncreds/derived-credentials.test.js @@ -130,7 +130,7 @@ describe.each(Schemes)('Derived Credentials', ({ controller: did1, msgCount: 100, }); - const pk1 = Module.prepareAddPublicKey(u8aToHex(keypair.publicKeyBuffer)); + const pk1 = Module.prepareAddPublicKey(dock.api, u8aToHex(keypair.publicKeyBuffer)); await chainModule.addPublicKey( pk1, did1, diff --git a/tests/integration/anoncreds/issuing.test.js b/tests/integration/anoncreds/issuing.test.js index f29b96f7b..ed082363d 100644 --- a/tests/integration/anoncreds/issuing.test.js +++ b/tests/integration/anoncreds/issuing.test.js @@ -60,7 +60,7 @@ describe.each(Schemes)('Issuance', ({ msgCount: 100, }); - const pk1 = Module.prepareAddPublicKey(u8aToHex(keypair.publicKeyBuffer)); + const pk1 = Module.prepareAddPublicKey(dock.api, u8aToHex(keypair.publicKeyBuffer)); await chainModule.addPublicKey( pk1, did1, diff --git a/tests/integration/anoncreds/prefilled-positive-accumulator.test.js b/tests/integration/anoncreds/prefilled-positive-accumulator.test.js index db2145a64..91d3c097f 100644 --- a/tests/integration/anoncreds/prefilled-positive-accumulator.test.js +++ b/tests/integration/anoncreds/prefilled-positive-accumulator.test.js @@ -68,7 +68,7 @@ describe('Prefilled positive accumulator', () => { keypair = Accumulator.generateKeypair(params, seedAccum); const bytes2 = u8aToHex(keypair.publicKey.bytes); - const pk1 = chainModuleClass.prepareAddPublicKey(bytes2, undefined, [did, 1]); + const pk1 = chainModuleClass.prepareAddPublicKey(dock.api, bytes2, undefined, [did, 1]); await chainModule.addPublicKey(pk1, did, pair, { didModule: dock.didModule }, false); accumulator = PositiveAccumulator.initialize(params, keypair.secretKey); diff --git a/tests/integration/anoncreds/presentation.test.js b/tests/integration/anoncreds/presentation.test.js index 90a9976b1..131be205d 100644 --- a/tests/integration/anoncreds/presentation.test.js +++ b/tests/integration/anoncreds/presentation.test.js @@ -60,7 +60,7 @@ describe.each(Schemes)('Presentation', ({ chainModule = getModule(dock); - const pk1 = Module.prepareAddPublicKey(u8aToHex(keypair.publicKeyBuffer)); + const pk1 = Module.prepareAddPublicKey(dock.api, u8aToHex(keypair.publicKeyBuffer)); await chainModule.addPublicKey( pk1, did1, diff --git a/tests/integration/anoncreds/r1cs-circom.test.js b/tests/integration/anoncreds/r1cs-circom.test.js index 7a54152cf..eefc9fa4e 100644 --- a/tests/integration/anoncreds/r1cs-circom.test.js +++ b/tests/integration/anoncreds/r1cs-circom.test.js @@ -144,7 +144,7 @@ for (const { // Not writing the params on chain as its assumed that the label is hardcoded in the code as system parameter issuerSchemeKeypair = KeyPair.generate(sigParams); - const pk = Module.prepareAddPublicKey( + const pk = Module.prepareAddPublicKey(dock.api, u8aToHex(issuerSchemeKeypair.publicKey.bytes), ); await getModule(dock).addPublicKey( diff --git a/tests/integration/anoncreds/saver-and-bound-check.test.js b/tests/integration/anoncreds/saver-and-bound-check.test.js index 0a6e42611..ed3a9e419 100644 --- a/tests/integration/anoncreds/saver-and-bound-check.test.js +++ b/tests/integration/anoncreds/saver-and-bound-check.test.js @@ -126,7 +126,7 @@ for (const { expect(paramsWritten.label).toEqual(params.label); issuerSchemeKeypair = KeyPair.generate(sigParams); - const pk = Module.prepareAddPublicKey( + const pk = Module.prepareAddPublicKey(dock.api, u8aToHex(issuerSchemeKeypair.publicKey.bytes), undefined, [issuerDid, 1], diff --git a/tests/integration/anoncreds/scheme.test.js b/tests/integration/anoncreds/scheme.test.js index 0720de256..96af798dd 100644 --- a/tests/integration/anoncreds/scheme.test.js +++ b/tests/integration/anoncreds/scheme.test.js @@ -86,7 +86,7 @@ for (const { expect(paramsWritten1.label).toEqual(params1.label); const allParams = await getParamsByDid( dock.api, - typedHexDID(did1), + typedHexDID(dock.api, did1), ); expect(Object.values(allParams.toJSON())).toEqual([params1]); @@ -144,7 +144,7 @@ for (const { const params = SignatureParams.generate(5); let keypair = KeyPair.generate(params); const bytes1 = u8aToHex(keypair.publicKey.bytes); - const pk1 = chainModuleClass.prepareAddPublicKey(bytes1); + const pk1 = chainModuleClass.prepareAddPublicKey(dock.api, bytes1); await chainModule.addPublicKey( pk1, did1, @@ -167,7 +167,7 @@ for (const { ); keypair = KeyPair.generate(params1); const bytes2 = u8aToHex(keypair.publicKey.bytes); - const pk2 = chainModuleClass.prepareAddPublicKey(bytes2, undefined, [ + const pk2 = chainModuleClass.prepareAddPublicKey(dock.api, bytes2, undefined, [ did1, 1, ]); @@ -181,9 +181,9 @@ for (const { ); const queriedPk2 = await chainModule.getPublicKey(did2, 2); expect(queriedPk2.bytes).toEqual(pk2.bytes); - expect(queriedPk2.paramsRef).toEqual([typedHexDID(did1), 1]); + expect(queriedPk2.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); const keyWithParams = await getPublicKeyWithParamsByStorageKey(dock.api, [ - typedHexDID(did2).asDid, + typedHexDID(dock.api, did2).asDid, 2, ]); const jsonKeyWithParams = keyWithParams.toJSON(); @@ -207,7 +207,7 @@ for (const { ); keypair = KeyPair.generate(params2); const bytes3 = u8aToHex(keypair.publicKey.bytes); - const pk3 = chainModuleClass.prepareAddPublicKey(bytes3, undefined, [ + const pk3 = chainModuleClass.prepareAddPublicKey(dock.api, bytes3, undefined, [ did1, 2, ]); @@ -222,7 +222,7 @@ for (const { const queriedPk3 = await chainModule.getPublicKey(did2, 3); expect(queriedPk3.bytes).toEqual(pk3.bytes); - expect(queriedPk3.paramsRef).toEqual([typedHexDID(did1), 2]); + expect(queriedPk3.paramsRef).toEqual([typedHexDID(dock.api, did1), 2]); const queriedPk3WithParams = await chainModule.getPublicKey( did2, @@ -232,7 +232,7 @@ for (const { expect(queriedPk3WithParams.params).toEqual(queriedParams2); const allPks = await getPublicKeysByDid( dock.api, - typedHexDID(did2), + typedHexDID(dock.api, did2), ); expect( Object.values(allPks.toJSON()).map((keyWithParams) => { diff --git a/tests/integration/blob.test.js b/tests/integration/blob.test.js index 73bb8f941..2003f971a 100644 --- a/tests/integration/blob.test.js +++ b/tests/integration/blob.test.js @@ -36,7 +36,7 @@ describe('Blob Module', () => { dock.setAccount(account); pair = new DidKeypair(dock.keyring.addFromUri(firstKeySeed), 1); dockDID = createNewDockDID(); - await registerNewDIDUsingPair(dock, typedHexDID(dockDID), pair); + await registerNewDIDUsingPair(dock, typedHexDID(dock.api, dockDID), pair); }); afterAll(async () => { @@ -61,7 +61,7 @@ describe('Blob Module', () => { const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(typedHexDID(dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); expect(chainBlob[1]).toEqual(blobJSON); }, 30000); @@ -77,7 +77,7 @@ describe('Blob Module', () => { const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(typedHexDID(dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); expect(u8aToString(chainBlob[1])).toEqual(blobHex); }, 30000); @@ -94,7 +94,7 @@ describe('Blob Module', () => { const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(typedHexDID(dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); expect(u8aToHex(chainBlob[1])).toEqual(blobHex); }, 30000); @@ -111,7 +111,7 @@ describe('Blob Module', () => { const chainBlob = await dock.blob.get(blobId); expect(!!chainBlob).toBe(true); - expect(chainBlob[0]).toEqual(typedHexDID(dockDID)); + expect(chainBlob[0]).toEqual(typedHexDID(dock.api, dockDID)); expect(chainBlob[1]).toEqual(blobVect); }, 30000); diff --git a/tests/integration/credential-revocation.test.js b/tests/integration/credential-revocation.test.js index a219a2ceb..f1b587f6a 100644 --- a/tests/integration/credential-revocation.test.js +++ b/tests/integration/credential-revocation.test.js @@ -21,7 +21,7 @@ import { registerNewDIDUsingPair, } from './helpers'; import { getKeyDoc } from '../../src/utils/vc/helpers'; -import { createNewDockDID, DidKeypair } from '../../src/utils/did'; +import { createNewDockDID, DidKeypair, typedHexDID } from '../../src/utils/did'; import { addRevRegIdToCredential, getPrivateStatus } from '../../src/utils/vc/credentials'; import { getPrivateStatuses } from '../../src/utils/vc/presentations'; @@ -68,7 +68,7 @@ describe('Credential revocation with issuer as the revocation authority', () => // Create a new policy const policy = new OneOfPolicy(); - policy.addOwner(issuerDID); + policy.addOwner(typedHexDID(dockAPI.api, issuerDID)); // Add a new revocation registry with above policy await dockAPI.revocation.newRegistry(registryId, policy, false, false); diff --git a/tests/integration/custom-nonce.test.js b/tests/integration/custom-nonce.test.js index 33feab80d..7fd702dc4 100644 --- a/tests/integration/custom-nonce.test.js +++ b/tests/integration/custom-nonce.test.js @@ -54,7 +54,7 @@ describe('Custom nonce', () => { }, 10000); test('Add key, controller, service endpoint, blob, BBS+ params and keys and accumulator in a batch', async () => { - const nonce = await dock.didModule.getNonceForDid(typedHexDID(did1)); + const nonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); const pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); const txs = []; @@ -98,7 +98,7 @@ describe('Custom nonce', () => { txs.push(tx5); const keypair = BBSPlusKeypairG2.generate(params); - const pk = BBSPlusModule.prepareAddPublicKey(u8aToHex(keypair.publicKey.bytes), undefined, [did1, 1]); + const pk = BBSPlusModule.prepareAddPublicKey(dock.api, u8aToHex(keypair.publicKey.bytes), undefined, [did1, 1]); const tx6 = await dock.bbsPlusModule.createAddPublicKeyTx(pk, did1, did1, pair, { nonce: nonce + 6 }); txs.push(tx6); @@ -109,7 +109,7 @@ describe('Custom nonce', () => { txs.push(tx7); const keypair1 = Accumulator.generateKeypair(params1); - const pk1 = AccumulatorModule.prepareAddPublicKey(u8aToHex(keypair1.publicKey.bytes), undefined, [did1, 1]); + const pk1 = AccumulatorModule.prepareAddPublicKey(dock.api, u8aToHex(keypair1.publicKey.bytes), undefined, [did1, 1]); const tx8 = await dock.accumulatorModule.createAddPublicKeyTx(pk1, did1, pair, { nonce: nonce + 8 }); txs.push(tx8); @@ -148,7 +148,7 @@ describe('Custom nonce', () => { const queriedPk = await dock.bbsPlusModule.getPublicKey(did1, 3); expect(queriedPk.bytes).toEqual(pk.bytes); - expect(queriedPk.paramsRef).toEqual([typedHexDID(did1), 1]); + expect(queriedPk.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); const queriedParams1 = await dock.accumulatorModule.getParams(did1, 1); expect(queriedParams1.bytes).toEqual(addParams1.bytes); @@ -156,24 +156,24 @@ describe('Custom nonce', () => { const queriedPk1 = await dock.accumulatorModule.getPublicKey(did1, 1); expect(queriedPk1.bytes).toEqual(pk1.bytes); - expect(queriedPk1.paramsRef).toEqual([typedHexDID(did1), 1]); + expect(queriedPk1.paramsRef).toEqual([typedHexDID(dock.api, did1), 1]); const accum1 = await dock.accumulatorModule.getAccumulator(id1, true); expect(accum1.type).toEqual('positive'); expect(accum1.accumulated).toEqual(accumulated1); - expect(accum1.keyRef).toEqual([typedHexDID(did1), 1]); + expect(accum1.keyRef).toEqual([typedHexDID(dock.api, did1), 1]); const accum2 = await dock.accumulatorModule.getAccumulator(id2, true); expect(accum2.type).toEqual('universal'); expect(accum2.accumulated).toEqual(accumulated2); - expect(accum2.keyRef).toEqual([typedHexDID(did1), 1]); + expect(accum2.keyRef).toEqual([typedHexDID(dock.api, did1), 1]); expect(accum1.created).toEqual(accum2.created); expect(accum1.lastModified).toEqual(accum2.lastModified); }, 20000); test('Add 3 registries and submit revocations for all in a batch', async () => { const owners = new Set(); - owners.add(did1); + owners.add(typedHexDID(dock.api, did1)); const [revokeIds1, revokeIds2, revokeIds3] = [1, 2, 3].map((_) => { const r = new Set(); @@ -193,7 +193,7 @@ describe('Custom nonce', () => { await dock.revocation.newRegistry(registryId3, policy, false, false); const pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); - let currentNonce = await dock.didModule.getNonceForDid(typedHexDID(did1)); + let currentNonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); let txs = []; // Revoke from all 3 registries in the same transaction batch @@ -218,7 +218,7 @@ describe('Custom nonce', () => { } // Remove from all 3 registries in the same transaction batch - currentNonce = await dock.didModule.getNonceForDid(typedHexDID(did1)); + currentNonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); txs = []; for (const [regId, nonce] of [[registryId1, currentNonce + 1], [registryId2, currentNonce + 2], [registryId3, currentNonce + 3]]) { const [remove, sig, computedNonce] = await dock.revocation.createSignedRemove(regId, did1, pair, { nonce }); @@ -257,7 +257,7 @@ describe('Custom nonce', () => { const pair = new DidKeypair(dock.keyring.addFromUri(seed1), 1); - let nonce = await dock.didModule.getNonceForDid(typedHexDID(did1)); + let nonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); let txs = []; // Add a key and a service endpoint to each DID @@ -295,9 +295,9 @@ describe('Custom nonce', () => { await expect(dock.did.getServiceEndpoint(did5, spId5)).resolves.toEqual({ type: spType, origins: origins[2] }); // Each DID adds 2 blobs - const nonce3 = await dock.didModule.getNonceForDid(typedHexDID(did3)); - const nonce4 = await dock.didModule.getNonceForDid(typedHexDID(did4)); - const nonce5 = await dock.didModule.getNonceForDid(typedHexDID(did5)); + const nonce3 = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did3)); + const nonce4 = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did4)); + const nonce5 = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did5)); txs = []; const [[blobId1, blobHex1, blob1], [blobId2, blobHex2, blob2], [blobId3, blobHex3, blob3], [blobId4, blobHex4, blob4], [blobId5, blobHex5, blob5], [blobId6, blobHex6, blob6]] = [1, 2, 3, 4, 5, 6].map((_) => { @@ -332,11 +332,11 @@ describe('Custom nonce', () => { const chainBlob = await dock.blob.get(bi); expect(!!chainBlob).toBe(true); expect(u8aToHex(chainBlob[1])).toEqual(bh); - expect(chainBlob[0]).toEqual(typedHexDID(d)); + expect(chainBlob[0]).toEqual(typedHexDID(dock.api, d)); } // Remove all DIDs in a batch - nonce = await dock.didModule.getNonceForDid(typedHexDID(did1)); + nonce = await dock.didModule.getNonceForDid(typedHexDID(dock.api, did1)); txs = []; const tx13 = await dock.did.createRemoveTx(did3, did1, pair, nonce + 1); diff --git a/tests/integration/did/controllers.test.js b/tests/integration/did/controllers.test.js index 7b7c8c0a5..f81544b0c 100644 --- a/tests/integration/did/controllers.test.js +++ b/tests/integration/did/controllers.test.js @@ -10,15 +10,15 @@ describe('DID controllers', () => { const dock = new DockAPI(); const dockDid1 = createNewDockDID(); - const hexDid1 = typedHexDID(dockDid1); + let hexDid1; // This DID will be controlled by itself and dockDid1 const dockDid2 = createNewDockDID(); - const hexDid2 = typedHexDID(dockDid2); + let hexDid2; // This DID will not control itself but will be controlled by dockDid1 and dockDid2 const dockDid3 = createNewDockDID(); - const hexDid3 = typedHexDID(dockDid3); + let hexDid3; const seed1 = randomAsHex(32); const seed2 = randomAsHex(32); @@ -32,6 +32,10 @@ describe('DID controllers', () => { }); const account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); + + hexDid1 = typedHexDID(dock.api, dockDid1); + hexDid2 = typedHexDID(dock.api, dockDid2); + hexDid3 = typedHexDID(dock.api, dockDid3); }); afterAll(async () => { diff --git a/tests/integration/did/did-basic.test.js b/tests/integration/did/did-basic.test.js index 170458ed6..e1d643d43 100644 --- a/tests/integration/did/did-basic.test.js +++ b/tests/integration/did/did-basic.test.js @@ -21,8 +21,8 @@ describe('Basic DID tests', () => { // Generate a random DID const dockDid = createNewDockDID(); - const typedDid = typedHexDID(dockDid); - const hexDid = typedDid.asDid; + let typedDid; + let hexDid; // Generate first key with this seed. The key type is Sr25519 const seed = randomAsHex(32); @@ -32,6 +32,9 @@ describe('Basic DID tests', () => { keyring: TestKeyringOpts, address: FullNodeEndpoint, }); + + typedDid = typedHexDID(dock.api, dockDid); + hexDid = typedDid.asDid; }); afterAll(async () => { diff --git a/tests/integration/did/keys.test.js b/tests/integration/did/keys.test.js index 1a1a95d16..4e76db195 100644 --- a/tests/integration/did/keys.test.js +++ b/tests/integration/did/keys.test.js @@ -12,7 +12,7 @@ describe('Key support for DIDs', () => { // Generate a random DID const dockDid = createNewDockDID(); - const hexDid = typedHexDID(dockDid); + let hexDid; const seed1 = randomAsHex(32); const seed2 = randomAsHex(32); @@ -26,6 +26,8 @@ describe('Key support for DIDs', () => { }); const account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); + + hexDid = typedHexDID(dock.api, dockDid); }); afterAll(async () => { diff --git a/tests/integration/did/offchain-did.test.js b/tests/integration/did/offchain-did.test.js index 9787d2329..1de835b99 100644 --- a/tests/integration/did/offchain-did.test.js +++ b/tests/integration/did/offchain-did.test.js @@ -13,7 +13,7 @@ describe('Off-chain DIDs', () => { // Generate a random DID const dockDID = createNewDockDID(); - const hexDID = typedHexDID(dockDID); + let hexDID; const firstDocRef = randomAsHex(100); const secondDocRef = randomAsHex(110); @@ -26,6 +26,8 @@ describe('Off-chain DIDs', () => { }); const account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); + + hexDID = typedHexDID(dock.api, dockDID); }); afterAll(async () => { diff --git a/tests/integration/did/service-endpoint.test.js b/tests/integration/did/service-endpoint.test.js index 3e5787bec..ab0dca4e2 100644 --- a/tests/integration/did/service-endpoint.test.js +++ b/tests/integration/did/service-endpoint.test.js @@ -3,7 +3,6 @@ import { u8aToHex } from '@polkadot/util'; import { DockAPI } from '../../../src'; import { createNewDockDID, typedHexDID, NoDIDError, DidKeypair } from '../../../src/utils/did'; import { FullNodeEndpoint, TestAccountURI, TestKeyringOpts } from '../../test-constants'; -import { getPublicKeyFromKeyringPair } from '../../../src/utils/misc'; import { DidKey, VerificationRelationship } from '../../../src/public-keys'; import { ServiceEndpointType } from '../../../src/modules/did/service-endpoint'; @@ -13,11 +12,11 @@ describe('DID service endpoints', () => { const dock = new DockAPI(); const dockDid1 = createNewDockDID(); - const hexDid1 = typedHexDID(dockDid1); + let hexDid1; // This DID will not be controlled by itself const dockDid2 = createNewDockDID(); - const hexDid2 = typedHexDID(dockDid2); + let hexDid2; const seed1 = randomAsHex(32); const seed2 = randomAsHex(32); @@ -40,6 +39,9 @@ describe('DID service endpoints', () => { }); const account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); + + hexDid1 = typedHexDID(dock.api, dockDid1); + hexDid2 = typedHexDID(dock.api, dockDid2); }); afterAll(async () => { diff --git a/tests/integration/fees.test.js b/tests/integration/fees.test.js index e64095df2..d1852b8fb 100644 --- a/tests/integration/fees.test.js +++ b/tests/integration/fees.test.js @@ -13,7 +13,7 @@ import { } from '@polkadot/util'; import { randomAsHex } from '@polkadot/util-crypto'; import { DockAPI } from '../../src/index'; -import { createNewDockDID } from '../../src/utils/did'; +import { createNewDockDID, typedHexDID } from '../../src/utils/did'; import { createDidPair, getBalance } from './helpers'; import { createRandomRegistryId, @@ -283,7 +283,7 @@ describe.skip('Fees', () => { const registryId = createRandomRegistryId(); // Create owners const owners = new Set(); - owners.add(did); + owners.add(typedHexDID(dock.api, did)); const policy = new OneOfPolicy(owners); await withPaidFeeMatchingSnapshot(() => dock.revocation.newRegistry(registryId, policy, false, false)); @@ -373,7 +373,7 @@ describe.skip('Fees', () => { const kp = BBSPlusKeypairG2.generate( BBSPlusSignatureParamsG1.generate(10, hexToU8a(label)), ); - const pk = BBSPlusModule.prepareAddPublicKey( + const pk = BBSPlusModule.prepareAddPublicKey(dock.api, u8aToHex(kp.publicKey.bytes), undefined, [did, 1], @@ -434,7 +434,7 @@ describe.skip('Fees', () => { new AccumulatorParams(hexToU8a(params.bytes)), ); - const pk = AccumulatorModule.prepareAddPublicKey( + const pk = AccumulatorModule.prepareAddPublicKey(dock.api, u8aToHex(kp.publicKey.bytes), undefined, [did, 1], diff --git a/tests/integration/master.test.js b/tests/integration/master.test.js index e2724ee96..cf7017e85 100644 --- a/tests/integration/master.test.js +++ b/tests/integration/master.test.js @@ -244,11 +244,11 @@ async function allVote( const votes = []; for (const [did, key] of did_to_key) { - const nonce = await nc.didModule.getNextNonceForDid(typedHexDID(did)); + const nonce = await nc.didModule.getNextNonceForDid(typedHexDID(dock.api, did)); const vote = { nonce, data: { proposal: encodedProposal, roundNo } }; const encodedStateChange = getStateChange(nc.api, 'MasterVote', vote); const signature = getSignatureFromKeyringPair(key, encodedStateChange); - const didSig = createDidSig(typedHexDID(did), 1, signature); + const didSig = createDidSig(typedHexDID(dock.api, did), 1, signature); votes.push({ sig: didSig, nonce }); } return votes; diff --git a/tests/integration/resolvers.test.js b/tests/integration/resolvers.test.js index 69f3d874d..071ddbf0d 100644 --- a/tests/integration/resolvers.test.js +++ b/tests/integration/resolvers.test.js @@ -32,10 +32,9 @@ describe('Resolvers', () => { // Create owners const owners = new Set(); - owners.add(ownerDID); // Create a status list policy - const policy = new OneOfPolicy(owners); + let policy; beforeAll(async () => { await dock.init({ @@ -43,6 +42,9 @@ describe('Resolvers', () => { address: FullNodeEndpoint, }); + owners.add(typedHexDID(dock.api, ownerDID)); + policy = new OneOfPolicy(owners); + ownerKey = getKeyDoc( ownerDID, dock.keyring.addFromUri(ownerSeed, null, 'ed25519'), diff --git a/tests/integration/revocation.test.js b/tests/integration/revocation.test.js index f75d75f45..1cfc1332b 100644 --- a/tests/integration/revocation.test.js +++ b/tests/integration/revocation.test.js @@ -29,10 +29,7 @@ describe('Revocation Module', () => { // Create owners const owners = new Set(); - owners.add(ownerDID); - - // Create a registry policy - const policy = new OneOfPolicy(owners); + let policy; // Create revoke IDs const revokeId = randomAsHex(32); @@ -45,6 +42,11 @@ describe('Revocation Module', () => { address: FullNodeEndpoint, }); + owners.add(typedHexDID(dock.api, ownerDID)); + + // Create a registry policy + policy = new OneOfPolicy(owners); + // The keyring should be initialized before any test begins as this suite is testing revocation const account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); @@ -178,8 +180,8 @@ describe('Revocation Module', () => { test('Can create a registry with multiple owners', async () => { const controllersNew = new Set(); - controllersNew.add(ownerDID); - controllersNew.add(ownerDID2); + controllersNew.add(typedHexDID(dock.api, ownerDID)); + controllersNew.add(typedHexDID(dock.api, ownerDID2)); // Create policy and registry with multiple owners const policyNew = new OneOfPolicy(controllersNew); @@ -194,14 +196,14 @@ describe('Revocation Module', () => { let hasSecondDID = false; [...controllerSet.entries()] .flatMap((v) => v) - .map(typedHexDIDFromSubstrate) + .map(cnt => typedHexDIDFromSubstrate(dock.api, cnt)) .forEach((controller) => { if ( - controller.toString() === typedHexDID(ownerDID).toString() + controller.toString() === typedHexDID(dock.api, ownerDID).toString() ) { hasFirstDID = true; } else if ( - controller.toString() === typedHexDID(ownerDID2).toString() + controller.toString() === typedHexDID(dock.api, ownerDID2).toString() ) { hasSecondDID = true; } diff --git a/tests/integration/schema.test.js b/tests/integration/schema.test.js index fb9041e5a..b6ef816c9 100644 --- a/tests/integration/schema.test.js +++ b/tests/integration/schema.test.js @@ -58,7 +58,7 @@ describe('Schema Blob Module Integration', () => { dockApi.setAccount(account); pair = new DidKeypair(dockApi.keyring.addFromUri(firstKeySeed), 1); dockDID = createNewDockDID(); - hexDid = typedHexDID(dockDID); + hexDid = typedHexDID(dockApi.api, dockDID); await registerNewDIDUsingPair(dockApi, dockDID, pair); blobId = randomAsHex(DockBlobIdByteSize); @@ -126,7 +126,7 @@ describe('Schema Blob Module Integration', () => { await expect(Schema.get(blobId, dockApi)).resolves.toMatchObject({ ...exampleSchema, id: blobId, - author: hexDIDToQualified(typedHexDID(dockDID)), + author: hexDIDToQualified(typedHexDID(dockApi.api, dockDID)), }); }, 20000); diff --git a/tests/integration/status-list-credential-module.test.js b/tests/integration/status-list-credential-module.test.js index 01b57307c..6bd16b9da 100644 --- a/tests/integration/status-list-credential-module.test.js +++ b/tests/integration/status-list-credential-module.test.js @@ -50,10 +50,7 @@ buildTest("StatusListCredential Module", () => { // Create owners const owners = new Set(); - owners.add(ownerDID); - - // Create a status list policy - const policy = new OneOfPolicy(owners); + let policy; // Create revoke IDs const revokeId = (Math.random() * 10e3) | 0; @@ -66,6 +63,11 @@ buildTest("StatusListCredential Module", () => { address: FullNodeEndpoint, }); + // Create a status list policy + owners.add(typedHexDID(dock.api, ownerDID)); + + policy = new OneOfPolicy(owners); + ownerKey = getKeyDoc( ownerDID, dock.keyring.addFromUri(ownerSeed, null, "ed25519"), @@ -241,8 +243,8 @@ buildTest("StatusListCredential Module", () => { test("Can create a status list with multiple owners", async () => { const controllersNew = new Set(); - controllersNew.add(ownerDID); - controllersNew.add(ownerDID2); + controllersNew.add(typedHexDID(dock.api, ownerDID)); + controllersNew.add(typedHexDID(dock.api, ownerDID2)); const cred = await StatusList2021Credential.create( ownerKey, @@ -275,14 +277,14 @@ buildTest("StatusListCredential Module", () => { let hasSecondDID = false; [...controllerSet.entries()] .flatMap((v) => v) - .map(typedHexDIDFromSubstrate) + .map(cnt => typedHexDIDFromSubstrate(dock.api, cnt)) .forEach((controller) => { if ( - controller.toString() === typedHexDID(ownerDID).toString() + controller.toString() === typedHexDID(dock.api, ownerDID).toString() ) { hasFirstDID = true; } else if ( - controller.toString() === typedHexDID(ownerDID2).toString() + controller.toString() === typedHexDID(dock.api, ownerDID2).toString() ) { hasSecondDID = true; } diff --git a/tests/integration/status-list-credential.test.js b/tests/integration/status-list-credential.test.js index f1ad7f68f..f84b1be02 100644 --- a/tests/integration/status-list-credential.test.js +++ b/tests/integration/status-list-credential.test.js @@ -21,7 +21,7 @@ import { createPresentation } from '../create-presentation'; import { OneOfPolicy } from '../../src/utils/revocation'; import { getUnsignedCred, registerNewDIDUsingPair } from './helpers'; import { getKeyDoc } from '../../src/utils/vc/helpers'; -import { createNewDockDID, DidKeypair } from '../../src/utils/did'; +import { createNewDockDID, DidKeypair, typedHexDID } from '../../src/utils/did'; import StatusList2021Credential from '../../src/status-list-credential/status-list2021-credential'; import { addStatusList21EntryToCredential } from '../../src/utils/vc/credentials'; @@ -71,7 +71,7 @@ buildTest('StatusList2021Credential', () => { // Create a new policy const policy = new OneOfPolicy(); - policy.addOwner(issuerDID); + policy.addOwner(typedHexDID(dockAPI.api, issuerDID)); issuerKey = getKeyDoc( issuerDID, issuerKeyPair, diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js index bbcc7dcb3..300998fe8 100644 --- a/tests/integration/trust-registry-module.test.js +++ b/tests/integration/trust-registry-module.test.js @@ -111,7 +111,7 @@ buildTest("Trust Registry", () => { await dock.api.query.trustRegistry.trustRegistriesInfo(trustRegistryId) ).toJSON(); expect(registryInfo).toEqual({ - convener: typedHexDID(convenerDID), + convener: typedHexDID(dock.api, convenerDID), name: "Test Registry", govFramework: u8aToHex(stringToU8a("Gov framework")) }); @@ -131,8 +131,8 @@ buildTest("Trust Registry", () => { ); const verifiers = new BTreeSet(); - verifiers.add(typedHexDID(issuerDID)); - verifiers.add(typedHexDID(issuerDID2)); + verifiers.add(typedHexDID(dock.api, issuerDID)); + verifiers.add(typedHexDID(dock.api, issuerDID2)); const issuers = new BTreeMap(); const issuerPrices = new BTreeMap(); @@ -140,8 +140,8 @@ buildTest("Trust Registry", () => { const issuer2Prices = new BTreeMap(); issuer2Prices.set("A", 20); - issuers.set(typedHexDID(issuerDID), issuerPrices); - issuers.set(typedHexDID(issuerDID2), issuer2Prices); + issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); + issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); const schemas = new BTreeMap(); schemas.set(schemaId, { @@ -191,8 +191,8 @@ buildTest("Trust Registry", () => { ); const verifiers = new BTreeSet(); - verifiers.add(typedHexDID(issuerDID)); - verifiers.add(typedHexDID(issuerDID2)); + verifiers.add(typedHexDID(dock.api, issuerDID)); + verifiers.add(typedHexDID(dock.api, issuerDID2)); const issuers = new BTreeMap(); const issuerPrices = new BTreeMap(); @@ -200,8 +200,8 @@ buildTest("Trust Registry", () => { const issuer2Prices = new BTreeMap(); issuer2Prices.set("A", 20); - issuers.set(typedHexDID(issuerDID), issuerPrices); - issuers.set(typedHexDID(issuerDID2), issuer2Prices); + issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); + issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); const schemas = new BTreeMap(); schemas.set(schemaId, { @@ -226,7 +226,7 @@ buildTest("Trust Registry", () => { ); for (const issuer of [issuerDID, issuerDID2]) { - expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(issuer))).toJSON()).toEqual({ + expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(dock.api, issuer))).toJSON()).toEqual({ suspended: true, delegated: [] }); @@ -241,14 +241,14 @@ buildTest("Trust Registry", () => { ); for (const issuer of [issuerDID]) { - expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(issuer))).toJSON()).toEqual({ + expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(dock.api, issuer))).toJSON()).toEqual({ suspended: false, delegated: [] }); } for (const issuer of [issuerDID2]) { - expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(issuer))).toJSON()).toEqual({ + expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(dock.api, issuer))).toJSON()).toEqual({ suspended: true, delegated: [] }); @@ -266,13 +266,13 @@ buildTest("Trust Registry", () => { dock ); - expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(issuerDID))).toJSON()).toEqual({ + expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(dock.api, issuerDID))).toJSON()).toEqual({ suspended: false, delegated: [] }); const issuers = new BTreeSet(); - issuers.add(typedHexDID(issuerDID2)); + issuers.add(typedHexDID(dock.api, issuerDID2)); await dock.trustRegistry.updateDelegatedIssuers( issuerDID, @@ -282,9 +282,9 @@ buildTest("Trust Registry", () => { dock ); - expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(issuerDID))).toJSON()).toEqual({ + expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(dock.api, issuerDID))).toJSON()).toEqual({ suspended: false, - delegated: [typedHexDID(issuerDID2)] + delegated: [typedHexDID(dock.api, issuerDID2)] }); }); @@ -302,8 +302,8 @@ buildTest("Trust Registry", () => { ); let verifiers = new BTreeSet(); - verifiers.add(typedHexDID(issuerDID)); - verifiers.add(typedHexDID(issuerDID2)); + verifiers.add(typedHexDID(dock.api, issuerDID)); + verifiers.add(typedHexDID(dock.api, issuerDID2)); let issuers = new BTreeMap(); let issuerPrices = new BTreeMap(); @@ -311,8 +311,8 @@ buildTest("Trust Registry", () => { let issuer2Prices = new BTreeMap(); issuer2Prices.set("A", 20); - issuers.set(typedHexDID(issuerDID), issuerPrices); - issuers.set(typedHexDID(issuerDID2), issuer2Prices); + issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); + issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); let schemas = new BTreeMap(); schemas.set(schemaId, { @@ -350,8 +350,8 @@ buildTest("Trust Registry", () => { let schemasUpdate = new BTreeMap(); verifiers = new BTreeSet(); - verifiers.add(typedHexDID(issuerDID)); - verifiers.add(typedHexDID(issuerDID2)); + verifiers.add(typedHexDID(dock.api, issuerDID)); + verifiers.add(typedHexDID(dock.api, issuerDID2)); issuers = new BTreeMap(); issuerPrices = new BTreeMap(); @@ -359,8 +359,8 @@ buildTest("Trust Registry", () => { issuer2Prices = new BTreeMap(); issuer2Prices.set("A", 75); - issuers.set(typedHexDID(issuerDID), issuerPrices); - issuers.set(typedHexDID(issuerDID2), issuer2Prices); + issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); + issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); schemasUpdate.set(schemaId, { issuers: { @@ -401,15 +401,15 @@ buildTest("Trust Registry", () => { issuer2Prices.set("B", 36); let issuersUpdate = new BTreeMap(); - issuersUpdate.set(typedHexDID(issuerDID2), { Set: issuer2Prices }); + issuersUpdate.set(typedHexDID(dock.api, issuerDID2), { Set: issuer2Prices }); schemasUpdate.set(schemaId, { issuers: { Modify: issuersUpdate, }, }); issuers = new BTreeMap(); - issuers.set(typedHexDID(issuerDID2), issuer2Prices); - issuers.set(typedHexDID(issuerDID), issuerPrices); + issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); + issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); schemas.set(schemaId, { issuers, verifiers: schemas.get(schemaId).verifiers }); await dock.trustRegistry.updateSchemaMetadata( From af0f2908c3b0433adb5f35d57ef8d1bafd116e3d Mon Sep 17 00:00:00 2001 From: olegnn Date: Mon, 8 Jan 2024 03:07:51 +0400 Subject: [PATCH 23/32] Tweaks --- src/modules/WithParamsAndPublicKeys.js | 6 +- src/modules/did/did.js | 6 +- src/rpc-defs/core-mods-rpc-defs.js | 6 +- src/utils/did.js | 68 +++++++++++++------ tests/integration/schema.test.js | 2 +- .../integration/trust-registry-module.test.js | 31 ++++++--- 6 files changed, 80 insertions(+), 39 deletions(-) diff --git a/src/modules/WithParamsAndPublicKeys.js b/src/modules/WithParamsAndPublicKeys.js index 4fc0b0c3e..8fc13e300 100644 --- a/src/modules/WithParamsAndPublicKeys.js +++ b/src/modules/WithParamsAndPublicKeys.js @@ -281,7 +281,7 @@ export default class WithParamsAndPublicKeys { async getPublicKeyByHexDid(hexDid, keyId, withParams = false) { const resp = await this.queryPublicKeyFromChain(hexDid, keyId); if (resp) { - const pkObj = WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse(resp); + const pkObj = WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse(this.api, resp); if (withParams) { if (pkObj.paramsRef === null) { throw new Error('No reference to parameters for the public key'); @@ -328,7 +328,7 @@ export default class WithParamsAndPublicKeys { * @param pk * @returns {{bytes: string}} */ - static createPublicKeyObjFromChainResponse(pk) { + static createPublicKeyObjFromChainResponse(api, pk) { const pkObj = { bytes: u8aToHex(pk.bytes), }; @@ -337,7 +337,7 @@ export default class WithParamsAndPublicKeys { } if (pk.paramsRef.isSome) { const pr = pk.paramsRef.unwrap(); - pkObj.paramsRef = [typedHexDIDFromSubstrate(this.api, pr[0]), pr[1].toNumber()]; + pkObj.paramsRef = [typedHexDIDFromSubstrate(api, pr[0]), pr[1].toNumber()]; } else { pkObj.paramsRef = null; } diff --git a/src/modules/did/did.js b/src/modules/did/did.js index ee40a1649..3093cb70d 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -839,6 +839,7 @@ class DIDModule { } // Don't care about signature params for now const pkObj = WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse( + this.api, rawKey, ); if (pkObj.curveType !== 'Bls12381') { @@ -865,6 +866,7 @@ class DIDModule { // Don't care about signature params for now const pkObj = WithParamsAndPublicKeys.createPublicKeyObjFromChainResponse( + this.api, rawKey, ); if (pkObj.curveType !== 'Bls12381') { @@ -905,7 +907,9 @@ class DIDModule { id, controller: [...controllers].map((c) => (c.Did ? this.getFullyQualifiedDID(encodeAddress(c.Did)) - : this.getFullyQualifiedDIDMethodKey(encodeAddress(c.DidMethodKey)))), + : c.DidMethodKey + ? this.getFullyQualifiedDIDMethodKey(encodeAddress(c.DidMethodKey)) + : this.getFullyQualifiedDID(encodeAddress(c)))), publicKey: verificationMethod, }; diff --git a/src/rpc-defs/core-mods-rpc-defs.js b/src/rpc-defs/core-mods-rpc-defs.js index 4a7a052da..91c3188f1 100644 --- a/src/rpc-defs/core-mods-rpc-defs.js +++ b/src/rpc-defs/core-mods-rpc-defs.js @@ -17,7 +17,7 @@ export default { params: [ { name: 'did', - type: 'DidOrDidMethodKey', + type: 'Did', }, ], type: 'BTreeMap', @@ -47,7 +47,7 @@ export default { params: [ { name: 'did', - type: 'DidOrDidMethodKey', + type: 'Did', }, ], type: 'BTreeMap', @@ -77,7 +77,7 @@ export default { params: [ { name: 'did', - type: 'DidOrDidMethodKey', + type: 'Did', }, ], type: 'BTreeMap', diff --git a/src/utils/did.js b/src/utils/did.js index c8f4a53bf..f14283a85 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -126,11 +126,20 @@ export class DockDidMethodKey extends DockDidOrDidMethodKey { } toString() { - return `${DockDIDMethodKeyQualifier}${this.asDidMethodKey}`; + return this.toStringSS58(); } toStringSS58() { - return `${DockDIDMethodKeyQualifier}${encodeAddress(this.asDidMethodKey)}`; + let prefix; + if (this.didMethodKey instanceof PublicKeyEd25519) { + prefix = DockDidMethodKeyEd25519Prefix; + } else if (this.didMethodKey instanceof PublicKeySecp256k1) { + prefix = DockDidMethodKeySecp256k1Prefix; + } else { + throw new Error('Unsopported public key type'); + } + + return `${prefix}${encodeAddress(this.asDidMethodKey.toJSON())}`; } } @@ -197,6 +206,32 @@ export function validateDockDIDSS58Identifier(identifier) { } } +/** + * Temporary solution for the DID's backward compatibility. + * + * -------------------------------------------------------- + */ + +Object.defineProperty(String.prototype, 'asDid', { + get() { + if (this.isDid) { + return String(this); + } else { + throw new Error('Not a `Did`'); + } + }, +}); + +Object.defineProperty(String.prototype, 'isDid', { + get() { + return isHexWithGivenByteSize(String(this), DockDIDByteSize); + }, +}); + +/** + * -------------------------------------------------------- + */ + /** * Takes a DID string, gets the hexadecimal value of that and returns a `DockDidMethodKey` or `DockDid` object. * @param {string} did - The DID can be passed as fully qualified DID like `did:dock:` or @@ -205,7 +240,7 @@ export function validateDockDIDSS58Identifier(identifier) { */ export function typedHexDID(api, did) { const strDid = did.toString(); - if (api.specVersion < 44) { + if (api.specVersion < 50) { return getHexIdentifier(strDid, DockDIDQualifier, DockDIDByteSize); } @@ -239,20 +274,10 @@ export function typedHexDID(api, did) { * @return {DockDidOrDidMethodKey} Returns an object wrapping the DID. */ export function typedHexDIDFromSubstrate(api, did) { - if (!did.isDid) { - const hex = getHexIdentifier( - u8aToHex(did), - [], - DockDIDByteSize, - ); - - return new DockDid(hex); + if (api.specVersion < 50) { + return getHexIdentifier(did, DockDIDQualifier, DockDIDByteSize); } else if (did.isDid) { - const hex = getHexIdentifier( - u8aToHex(did.asDid), - [], - DockDIDByteSize, - ); + const hex = getHexIdentifier(u8aToHex(did.asDid), [], DockDIDByteSize); return new DockDid(hex); } else if (did.isDidMethodKey) { @@ -330,16 +355,19 @@ export function createDidKey(publicKey, verRel) { export function createDidSig(did, { keyId }, rawSig) { const sig = rawSig.toJSON(); - if (did.isDid) { + if (typeof did === 'string') { + return { + did: did.asDid, + keyId, + sig, + }; + } else if (did.isDid) { return { DidSignature: { did: did.asDid, keyId, sig, }, - did: did.asDid, - keyId, - sig, }; } else if (did.isDidMethodKey) { return { diff --git a/tests/integration/schema.test.js b/tests/integration/schema.test.js index b6ef816c9..5a0f62175 100644 --- a/tests/integration/schema.test.js +++ b/tests/integration/schema.test.js @@ -43,7 +43,7 @@ const ctx2 = { }, }; -describe('Schema Blob Module Integration', () => { +describe.skip('Schema Blob Module Integration', () => { const dockApi = new DockAPI(); // Generate first key with this seed. The key type is Sr25519 diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js index 300998fe8..3181e685d 100644 --- a/tests/integration/trust-registry-module.test.js +++ b/tests/integration/trust-registry-module.test.js @@ -11,7 +11,9 @@ import { DisableTrustRegistryTests, } from "../test-constants"; -import { createNewDockDID, DidKeypair, typedHexDID } from "../../src/utils/did"; +import { createNewDockDID, DidKeypair, DockDidMethodKey, typedHexDID } from "../../src/utils/did"; +import { generateEcdsaSecp256k1Keypair } from '../../src/utils/misc'; +import { PublicKeySecp256k1 } from "../../src"; import { registerNewDIDUsingPair } from "./helpers"; const buildTest = DisableTrustRegistryTests ? describe.skip : describe; @@ -43,6 +45,10 @@ buildTest("Trust Registry", () => { const verifierSeed2 = randomAsHex(32); let verifierPair2; + const verifierDIDMethodKeyPair = generateEcdsaSecp256k1Keypair(seed2); + const verifierDIDMethodKeyPublicKey = PublicKeySecp256k1.fromKeyringPair(verifierDIDMethodKeyPair); + const verifierDIDMethodKey = new DockDidMethodKey(verifierDIDMethodKeyPublicKey); + // Create revoke IDs const revokeId = (Math.random() * 10e3) | 0; const revokeIds = new Set(); @@ -131,8 +137,9 @@ buildTest("Trust Registry", () => { ); const verifiers = new BTreeSet(); - verifiers.add(typedHexDID(dock.api, issuerDID)); - verifiers.add(typedHexDID(dock.api, issuerDID2)); + verifiers.add(typedHexDID(dock.api, verifierDID)); + verifiers.add(typedHexDID(dock.api, verifierDID2)); + verifiers.add(verifierDIDMethodKey); const issuers = new BTreeMap(); const issuerPrices = new BTreeMap(); @@ -191,8 +198,9 @@ buildTest("Trust Registry", () => { ); const verifiers = new BTreeSet(); - verifiers.add(typedHexDID(dock.api, issuerDID)); - verifiers.add(typedHexDID(dock.api, issuerDID2)); + verifiers.add(typedHexDID(dock.api, verifierDID)); + verifiers.add(typedHexDID(dock.api, verifierDID2)); + verifiers.add(verifierDIDMethodKey); const issuers = new BTreeMap(); const issuerPrices = new BTreeMap(); @@ -272,7 +280,7 @@ buildTest("Trust Registry", () => { }); const issuers = new BTreeSet(); - issuers.add(typedHexDID(dock.api, issuerDID2)); + issuers.add(typedHexDID(dock.api, verifierDID2)); await dock.trustRegistry.updateDelegatedIssuers( issuerDID, @@ -288,7 +296,7 @@ buildTest("Trust Registry", () => { }); }); - it("Updates schemas to the existing Trust Registry", async () => { + it("Updates schemas in the existing Trust Registry", async () => { // Create a random status list id const schemaId = randomAsHex(32); @@ -302,8 +310,9 @@ buildTest("Trust Registry", () => { ); let verifiers = new BTreeSet(); - verifiers.add(typedHexDID(dock.api, issuerDID)); - verifiers.add(typedHexDID(dock.api, issuerDID2)); + verifiers.add(typedHexDID(dock.api, verifierDID)); + verifiers.add(typedHexDID(dock.api, verifierDID2)); + verifiers.add(verifierDIDMethodKey); let issuers = new BTreeMap(); let issuerPrices = new BTreeMap(); @@ -350,8 +359,8 @@ buildTest("Trust Registry", () => { let schemasUpdate = new BTreeMap(); verifiers = new BTreeSet(); - verifiers.add(typedHexDID(dock.api, issuerDID)); - verifiers.add(typedHexDID(dock.api, issuerDID2)); + verifiers.add(typedHexDID(dock.api, verifierDID)); + verifiers.add(typedHexDID(dock.api, verifierDID2)); issuers = new BTreeMap(); issuerPrices = new BTreeMap(); From c16c4e5f30ecbc246bf964eef85af2762e97dcef Mon Sep 17 00:00:00 2001 From: olegnn Date: Mon, 8 Jan 2024 03:09:23 +0400 Subject: [PATCH 24/32] Restore previous type def --- src/rpc-defs/core-mods-rpc-defs.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/rpc-defs/core-mods-rpc-defs.js b/src/rpc-defs/core-mods-rpc-defs.js index 91c3188f1..4a7a052da 100644 --- a/src/rpc-defs/core-mods-rpc-defs.js +++ b/src/rpc-defs/core-mods-rpc-defs.js @@ -17,7 +17,7 @@ export default { params: [ { name: 'did', - type: 'Did', + type: 'DidOrDidMethodKey', }, ], type: 'BTreeMap', @@ -47,7 +47,7 @@ export default { params: [ { name: 'did', - type: 'Did', + type: 'DidOrDidMethodKey', }, ], type: 'BTreeMap', @@ -77,7 +77,7 @@ export default { params: [ { name: 'did', - type: 'Did', + type: 'DidOrDidMethodKey', }, ], type: 'BTreeMap', From 8a2fbdd6e37fe010d335a0cf4c87a2414603bfed Mon Sep 17 00:00:00 2001 From: olegnn Date: Mon, 8 Jan 2024 13:00:49 +0400 Subject: [PATCH 25/32] More tweaks --- src/dock-api.js | 6 +++ src/modules/did/did.js | 14 ++++-- src/utils/did.js | 49 +++++++++++++------ tests/integration/resolvers.test.js | 2 +- .../integration/trust-registry-module.test.js | 33 +++++++------ 5 files changed, 69 insertions(+), 35 deletions(-) diff --git a/src/dock-api.js b/src/dock-api.js index 1eeab5b73..1a2a79932 100644 --- a/src/dock-api.js +++ b/src/dock-api.js @@ -137,6 +137,12 @@ export default class DockAPI { const runtimeVersion = await this.api.rpc.state.getRuntimeVersion(); this.api.specVersion = runtimeVersion.specVersion.toNumber(); + if (this.api.specVersion < 50) { + console.log('???', this.api.specVersion); + apiOptions.types = { DidOrDidMethodKey: 'Did' }; + this.api = await ApiPromise.create(apiOptions); + } + await this.initKeyring(keyring); this.anchorModule.setApi(this.api, this.signAndSend.bind(this)); diff --git a/src/modules/did/did.js b/src/modules/did/did.js index 3093cb70d..4638c4b5b 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -905,11 +905,15 @@ class DIDModule { const document = { '@context': ['https://www.w3.org/ns/did/v1'], id, - controller: [...controllers].map((c) => (c.Did - ? this.getFullyQualifiedDID(encodeAddress(c.Did)) - : c.DidMethodKey - ? this.getFullyQualifiedDIDMethodKey(encodeAddress(c.DidMethodKey)) - : this.getFullyQualifiedDID(encodeAddress(c)))), + controller: [...controllers].map((c) => { + if (c.Did) { + return this.getFullyQualifiedDID(encodeAddress(c.Did)); + } else if (c.DidMethodKey) { + return this.getFullyQualifiedDIDMethodKey(encodeAddress(c.DidMethodKey)); + } else { + return this.getFullyQualifiedDID(encodeAddress(c)); + } + }), publicKey: verificationMethod, }; diff --git a/src/utils/did.js b/src/utils/did.js index d941ad52d..f32c29545 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -55,13 +55,19 @@ export class DidKeypair { * @param keyId - Defaults to 1 * @returns {DidKeypair} */ - static fromApi(dockApi, { - seed = randomAsHex(32), - keypairType = 'ed25519', - meta = null, - keyId = 1, - } = {}) { - return new DidKeypair(dockApi.keyring.addFromUri(seed, meta, keypairType), keyId); + static fromApi( + dockApi, + { + seed = randomAsHex(32), + keypairType = 'ed25519', + meta = null, + keyId = 1, + } = {}, + ) { + return new DidKeypair( + dockApi.keyring.addFromUri(seed, meta, keypairType), + keyId, + ); } } @@ -129,6 +135,14 @@ export class DockDidMethodKey extends DockDidOrDidMethodKey { constructor(didMethodKey) { super(); this.didMethodKey = didMethodKey; + + if (didMethodKey instanceof PublicKeyEd25519) { + this.didMethodKey = { ed25519: didMethodKey.value }; + } else if (didMethodKey instanceof PublicKeySecp256k1) { + this.didMethodKey = { secp256k1: didMethodKey.value }; + } else { + throw new Error('Unsopported public key type'); + } } get isDidMethodKey() { @@ -140,7 +154,11 @@ export class DockDidMethodKey extends DockDidOrDidMethodKey { } toJSON() { - return { DidMethodKey: this.didMethodKey }; + return { + DidMethodKey: this.didMethodKey.ed25519 + ? { Ed25519: this.didMethodKey.ed25519 } + : { Secp256k1: this.didMethodKey.secp256k1 }, + }; } toString() { @@ -148,16 +166,19 @@ export class DockDidMethodKey extends DockDidOrDidMethodKey { } toStringSS58() { - let prefix; - if (this.didMethodKey instanceof PublicKeyEd25519) { + let prefix; let + address; + if (this.didMethodKey.ed25519) { prefix = DockDidMethodKeyEd25519Prefix; - } else if (this.didMethodKey instanceof PublicKeySecp256k1) { + address = this.didMethodKey.ed25519; + } else if (this.didMethodKey.secp256k1) { prefix = DockDidMethodKeySecp256k1Prefix; + address = this.didMethodKey.secp256k1; } else { throw new Error('Unsopported public key type'); } - return `${prefix}${encodeAddress(this.asDidMethodKey.toJSON())}`; + return `${prefix}${encodeAddress(address)}`; } } @@ -229,7 +250,7 @@ export function validateDockDIDSS58Identifier(identifier) { * * -------------------------------------------------------- */ - +// eslint-disable-next-line no-extend-native Object.defineProperty(String.prototype, 'asDid', { get() { if (this.isDid) { @@ -239,7 +260,7 @@ Object.defineProperty(String.prototype, 'asDid', { } }, }); - +// eslint-disable-next-line no-extend-native Object.defineProperty(String.prototype, 'isDid', { get() { return isHexWithGivenByteSize(String(this), DockDIDByteSize); diff --git a/tests/integration/resolvers.test.js b/tests/integration/resolvers.test.js index fd8076f38..9a64c2ca2 100644 --- a/tests/integration/resolvers.test.js +++ b/tests/integration/resolvers.test.js @@ -1,6 +1,6 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockResolver, DockStatusList2021Resolver } from '../../src/resolver'; -import { createNewDockDID, DidKeypair } from '../../src/utils/did'; +import { createNewDockDID, DidKeypair, typedHexDID } from '../../src/utils/did'; import { DockAPI } from '../../src/index'; diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js index 3181e685d..15bedb93d 100644 --- a/tests/integration/trust-registry-module.test.js +++ b/tests/integration/trust-registry-module.test.js @@ -45,10 +45,13 @@ buildTest("Trust Registry", () => { const verifierSeed2 = randomAsHex(32); let verifierPair2; - const verifierDIDMethodKeyPair = generateEcdsaSecp256k1Keypair(seed2); + const seed = randomAsHex(32); + const verifierDIDMethodKeyPair = generateEcdsaSecp256k1Keypair(seed); const verifierDIDMethodKeyPublicKey = PublicKeySecp256k1.fromKeyringPair(verifierDIDMethodKeyPair); const verifierDIDMethodKey = new DockDidMethodKey(verifierDIDMethodKeyPublicKey); + console.log(verifierDIDMethodKey.toStringSS58()); + // Create revoke IDs const revokeId = (Math.random() * 10e3) | 0; const revokeIds = new Set(); @@ -174,13 +177,13 @@ buildTest("Trust Registry", () => { ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify({ did: issuer.asDid }), + JSON.stringify(issuer.isDid ? { did: issuer.asDid }: { didMethodKey: issuer.asDidMethodKey }), Object.fromEntries([...prices.entries()]), ]) ), verifiers: [...verifiers.values()] - .map((verifier) => ({ did: verifier.asDid })) - .sort((a, b) => a.did.localeCompare(b.did)), + .map((verifier) => verifier.isDid ? { did: verifier.asDid }: { didMethodKey: verifier.asDidMethodKey }) + .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); }); @@ -280,7 +283,7 @@ buildTest("Trust Registry", () => { }); const issuers = new BTreeSet(); - issuers.add(typedHexDID(dock.api, verifierDID2)); + issuers.add(typedHexDID(dock.api, issuerDID2)); await dock.trustRegistry.updateDelegatedIssuers( issuerDID, @@ -312,7 +315,7 @@ buildTest("Trust Registry", () => { let verifiers = new BTreeSet(); verifiers.add(typedHexDID(dock.api, verifierDID)); verifiers.add(typedHexDID(dock.api, verifierDID2)); - verifiers.add(verifierDIDMethodKey); + // verifiers.add(verifierDIDMethodKey); let issuers = new BTreeMap(); let issuerPrices = new BTreeMap(); @@ -347,13 +350,13 @@ buildTest("Trust Registry", () => { ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify({ did: issuer.asDid }), + JSON.stringify(issuer.isDid ? { did: issuer.asDid }: { didMethodKey: issuer.asDidMethodKey }), Object.fromEntries([...prices.entries()]), ]) ), verifiers: [...verifiers.values()] - .map((verifier) => ({ did: verifier.asDid })) - .sort((a, b) => a.did.localeCompare(b.did)), + .map((verifier) => verifier.isDid ? { did: verifier.asDid }: { didMethodKey: verifier.asDidMethodKey }) + .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); let schemasUpdate = new BTreeMap(); @@ -395,13 +398,13 @@ buildTest("Trust Registry", () => { ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify({ did: issuer.asDid }), + JSON.stringify(issuer.isDid ? { did: issuer.asDid }: { didMethodKey: issuer.asDidMethodKey }), Object.fromEntries([...prices.entries()]), ]) ), verifiers: [...verifiers.values()] - .map((verifier) => ({ did: verifier.asDid })) - .sort((a, b) => a.did.localeCompare(b.did)), + .map((verifier) => verifier.isDid ? { did: verifier.asDid }: { didMethodKey: verifier.asDidMethodKey }) + .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); schemasUpdate = new BTreeMap(); @@ -439,13 +442,13 @@ buildTest("Trust Registry", () => { ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify({ did: issuer.asDid }), + JSON.stringify(issuer.isDid ? { did: issuer.asDid }: { didMethodKey: issuer.asDidMethodKey }), Object.fromEntries([...prices.entries()]), ]) ), verifiers: [...verifiers.values()] - .map((verifier) => ({ did: verifier.asDid })) - .sort((a, b) => a.did.localeCompare(b.did)), + .map((verifier) => verifier.isDid ? { did: verifier.asDid }: { didMethodKey: verifier.asDidMethodKey }) + .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); }); }); From 48b60492d4b5ffa9b6df84ba6ea54caefa96693a Mon Sep 17 00:00:00 2001 From: olegnn Date: Mon, 8 Jan 2024 13:05:49 +0400 Subject: [PATCH 26/32] More corrections --- example/revocation.js | 14 +++++++------- src/dock-api.js | 1 - 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/example/revocation.js b/example/revocation.js index e6dc84051..587d33d20 100644 --- a/example/revocation.js +++ b/example/revocation.js @@ -20,17 +20,17 @@ const registryId = createRandomRegistryId(); const controllerDID = createNewDockDID(); const controllerSeed = randomAsHex(32); -// Create a list of controllers -const controllers = new Set(); -controllers.add(typedHexDID(dock.api, controllerDID)); - -// Create a registry policy -const policy = new OneOfPolicy(controllers); - // Create revoke IDs const revokeId = randomAsHex(32); async function createRegistry() { + // Create a list of controllers + const controllers = new Set(); + + controllers.add(typedHexDID(dock.api, controllerDID)); + + // Create a registry policy + const policy = new OneOfPolicy(controllers); console.log(`Creating a registry with owner DID (${controllerDID}) with policy type:`, policy.constructor.name); await dock.revocation.newRegistry(registryId, policy, false, false); console.log('Created registry'); diff --git a/src/dock-api.js b/src/dock-api.js index 1a2a79932..6ae7d3e43 100644 --- a/src/dock-api.js +++ b/src/dock-api.js @@ -138,7 +138,6 @@ export default class DockAPI { this.api.specVersion = runtimeVersion.specVersion.toNumber(); if (this.api.specVersion < 50) { - console.log('???', this.api.specVersion); apiOptions.types = { DidOrDidMethodKey: 'Did' }; this.api = await ApiPromise.create(apiOptions); } From 46a6e2645c9b7734e33f89272026c5ccd93986b8 Mon Sep 17 00:00:00 2001 From: olegnn Date: Mon, 8 Jan 2024 13:28:05 +0400 Subject: [PATCH 27/32] Reorder assignment --- src/dock-api.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/dock-api.js b/src/dock-api.js index 6ae7d3e43..be2daba90 100644 --- a/src/dock-api.js +++ b/src/dock-api.js @@ -135,12 +135,13 @@ export default class DockAPI { this.api = await ApiPromise.create(apiOptions); const runtimeVersion = await this.api.rpc.state.getRuntimeVersion(); - this.api.specVersion = runtimeVersion.specVersion.toNumber(); + const specVersion = runtimeVersion.specVersion.toNumber(); - if (this.api.specVersion < 50) { - apiOptions.types = { DidOrDidMethodKey: 'Did' }; + if (specVersion < 50) { + apiOptions.types = { ...(apiOptions.types || {}), DidOrDidMethodKey: 'Did' }; this.api = await ApiPromise.create(apiOptions); } + this.api.specVersion = specVersion; await this.initKeyring(keyring); From 65587cd2b29a43c0fa8cae96d077792f1f723da2 Mon Sep 17 00:00:00 2001 From: olegnn Date: Mon, 8 Jan 2024 13:51:44 +0400 Subject: [PATCH 28/32] Attempts to fix tests --- src/modules/schema.js | 2 +- src/utils/did.js | 6 ++++++ src/utils/vc/schema.js | 2 +- tests/integration/schema.test.js | 9 +++++---- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/modules/schema.js b/src/modules/schema.js index 6fdd794ed..84a624fa3 100644 --- a/src/modules/schema.js +++ b/src/modules/schema.js @@ -140,7 +140,7 @@ export default class Schema { return { ...chainValue, id, - author: hexDIDToQualified(chainBlob[0].did), + author: hexDIDToQualified(chainBlob[0]), }; } throw new Error('Incorrect schema format'); diff --git a/src/utils/did.js b/src/utils/did.js index f32c29545..85b136b33 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -266,6 +266,12 @@ Object.defineProperty(String.prototype, 'isDid', { return isHexWithGivenByteSize(String(this), DockDIDByteSize); }, }); +// eslint-disable-next-line no-extend-native +Object.defineProperty(String.prototype, 'toStringSS58', { + get() { + return new DockDid(this.asDid).toStringSS58(); + }, +}); /** * -------------------------------------------------------- diff --git a/src/utils/vc/schema.js b/src/utils/vc/schema.js index 1533e2f3f..f8fc66236 100644 --- a/src/utils/vc/schema.js +++ b/src/utils/vc/schema.js @@ -89,7 +89,7 @@ export async function getAndValidateSchemaIfPresent( schemaObj = { ...data, id: schemaUri, - author: hexDIDToQualified(author.did), + author: hexDIDToQualified(author), }; } else { schemaObj = document; diff --git a/tests/integration/schema.test.js b/tests/integration/schema.test.js index 5873ed465..b01fda246 100644 --- a/tests/integration/schema.test.js +++ b/tests/integration/schema.test.js @@ -4,7 +4,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import { DockAPI } from '../../src/index'; import { - createNewDockDID, typedHexDID, hexDIDToQualified, DidKeypair, + createNewDockDID, typedHexDID, DidKeypair, hexDIDToQualified, } from '../../src/utils/did'; import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI } from '../test-constants'; import { verifyCredential, verifyPresentation } from '../../src/utils/vc/index'; @@ -43,7 +43,7 @@ const ctx2 = { }, }; -describe.skip('Schema Blob Module Integration', () => { +describe('Schema Blob Module Integration', () => { const dockApi = new DockAPI(); // Generate first key with this seed. The key type is Sr25519 @@ -123,10 +123,11 @@ describe.skip('Schema Blob Module Integration', () => { const schema = new Schema(); await schema.setJSONSchema(exampleSchema); await dockApi.blob.new(schema.toBlob(), dockDID, pair, { didModule: dockApi.didModule }, false); - await expect(Schema.get(blobId, dockApi)).resolves.toMatchObject({ + const schemaObj = await Schema.get(blobId, dockApi); + expect(schemaObj).toMatchObject({ ...exampleSchema, id: blobId, - author: hexDIDToQualified(typedHexDID(dockApi.api, dockDID)), + author: hexDIDToQualified(hexDid), }); }, 20000); From 43243c650766a856f1272ab5750f9c2bd7394523 Mon Sep 17 00:00:00 2001 From: olegnn Date: Mon, 8 Jan 2024 17:42:34 +0400 Subject: [PATCH 29/32] More tests --- src/modules/did/did.js | 21 ++- src/utils/did.js | 9 +- .../integration/trust-registry-module.test.js | 124 ++++++++++++++---- 3 files changed, 125 insertions(+), 29 deletions(-) diff --git a/src/modules/did/did.js b/src/modules/did/did.js index 4638c4b5b..8b5dc969e 100644 --- a/src/modules/did/did.js +++ b/src/modules/did/did.js @@ -152,7 +152,7 @@ class DIDModule { /** * Creates a new DID on the Dock chain. - * @param {string} did - The new DID. Can be aw full DID or hex identifier + * @param {string} did - The new DID. Can be a full DID or hex identifier * @param {DidKey[]} didKeys - Array of `DidKey`s as expected by the Substrate node * @param {array} controllers - Array of `Did`s as expected by the Substrate node. * @param waitForFinalization @@ -173,6 +173,25 @@ class DIDModule { ); } + /** + * Creates a new `did:key:` on the Dock chain. + * @param {string} did - The new DID. Can be a full DID or hex identifier + * @param waitForFinalization + * @param params + * @return {Promise} Promise to the pending transaction + */ + async newDidMethodKey( + didMethodKey, + waitForFinalization = true, + params = {}, + ) { + return this.signAndSend( + this.module.newDidMethodKey(didMethodKey), + waitForFinalization, + params, + ); + } + /** * Create transaction to add keys to an on-chain DID. * @param {DidKey[]} didKeys - Array of `DidKey`s as expected by the Substrate node diff --git a/src/utils/did.js b/src/utils/did.js index 85b136b33..4d0c64722 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -134,7 +134,6 @@ export class DockDid extends DockDidOrDidMethodKey { export class DockDidMethodKey extends DockDidOrDidMethodKey { constructor(didMethodKey) { super(); - this.didMethodKey = didMethodKey; if (didMethodKey instanceof PublicKeyEd25519) { this.didMethodKey = { ed25519: didMethodKey.value }; @@ -292,7 +291,7 @@ export function typedHexDID(api, did) { if (strDid.startsWith(DockDidMethodKeySecp256k1Prefix)) { const hex = getHexIdentifier( strDid, - DockDIDMethodKeyQualifier, + DockDidMethodKeySecp256k1Prefix, DockDIDMethodKeySecp256k1ByteSize, ); @@ -300,7 +299,7 @@ export function typedHexDID(api, did) { } else if (strDid.startsWith(DockDidMethodKeyEd25519Prefix)) { const hex = getHexIdentifier( strDid, - DockDIDMethodKeyQualifier, + DockDidMethodKeyEd25519Prefix, DockDIDMethodKeyEd25519ByteSize, ); @@ -409,8 +408,6 @@ export function createDidSig(did, { keyId }, rawSig) { }; } else if (did.isDid) { return { - // Note: The following repeats the 3 fields to ensure backward compatibility. Once nodes have been upgraded, - // fields outside `DidSignature` must be removed. DidSignature: { did: did.asDid, keyId, @@ -420,7 +417,7 @@ export function createDidSig(did, { keyId }, rawSig) { } else if (did.isDidMethodKey) { return { DidMethodKeySignature: { - didKey: did.asDidMethodKey, + didMethodKey: did.asDidMethodKey, sig, }, }; diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js index 15bedb93d..8e9c87083 100644 --- a/tests/integration/trust-registry-module.test.js +++ b/tests/integration/trust-registry-module.test.js @@ -1,6 +1,6 @@ import { randomAsHex } from "@polkadot/util-crypto"; import { BTreeSet, BTreeMap } from "@polkadot/types"; -import { u8aToHex, stringToU8a } from '@polkadot/util'; +import { u8aToHex, stringToU8a } from "@polkadot/util"; import { DockAPI } from "../../src/index"; @@ -11,8 +11,13 @@ import { DisableTrustRegistryTests, } from "../test-constants"; -import { createNewDockDID, DidKeypair, DockDidMethodKey, typedHexDID } from "../../src/utils/did"; -import { generateEcdsaSecp256k1Keypair } from '../../src/utils/misc'; +import { + createNewDockDID, + DidKeypair, + DockDidMethodKey, + typedHexDID, +} from "../../src/utils/did"; +import { generateEcdsaSecp256k1Keypair } from "../../src/utils/misc"; import { PublicKeySecp256k1 } from "../../src"; import { registerNewDIDUsingPair } from "./helpers"; @@ -45,12 +50,9 @@ buildTest("Trust Registry", () => { const verifierSeed2 = randomAsHex(32); let verifierPair2; - const seed = randomAsHex(32); - const verifierDIDMethodKeyPair = generateEcdsaSecp256k1Keypair(seed); - const verifierDIDMethodKeyPublicKey = PublicKeySecp256k1.fromKeyringPair(verifierDIDMethodKeyPair); - const verifierDIDMethodKey = new DockDidMethodKey(verifierDIDMethodKeyPublicKey); - - console.log(verifierDIDMethodKey.toStringSS58()); + const verifierDIDMethodKeySeed = randomAsHex(32); + let verifierDIDMethodKeyPair; + let verifierDIDMethodKey; // Create revoke IDs const revokeId = (Math.random() * 10e3) | 0; @@ -88,6 +90,11 @@ buildTest("Trust Registry", () => { 1 ); + verifierDIDMethodKeyPair = new DidKeypair( + dock.keyring.addFromUri(verifierDIDMethodKeySeed, null, "ed25519") + ); + verifierDIDMethodKey = new DockDidMethodKey(verifierDIDMethodKeyPair.publicKey()); + // The keyring should be initialized before any test begins as this suite is testing trustRegistry const account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); @@ -99,6 +106,7 @@ buildTest("Trust Registry", () => { await registerNewDIDUsingPair(dock, issuerDID2, issuerPair2); await registerNewDIDUsingPair(dock, verifierDID, verifierPair); await registerNewDIDUsingPair(dock, verifierDID2, verifierPair2); + await dock.did.newDidMethodKey(verifierDIDMethodKey.asDidMethodKey); }, 40000); it("Initializes Trust Registry", async () => { @@ -315,7 +323,7 @@ buildTest("Trust Registry", () => { let verifiers = new BTreeSet(); verifiers.add(typedHexDID(dock.api, verifierDID)); verifiers.add(typedHexDID(dock.api, verifierDID2)); - // verifiers.add(verifierDIDMethodKey); + verifiers.add(verifierDIDMethodKey); let issuers = new BTreeMap(); let issuerPrices = new BTreeMap(); @@ -350,21 +358,25 @@ buildTest("Trust Registry", () => { ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify(issuer.isDid ? { did: issuer.asDid }: { didMethodKey: issuer.asDidMethodKey }), + JSON.stringify( + issuer.isDid + ? { did: issuer.asDid } + : { didMethodKey: issuer.asDidMethodKey } + ), Object.fromEntries([...prices.entries()]), ]) ), verifiers: [...verifiers.values()] - .map((verifier) => verifier.isDid ? { did: verifier.asDid }: { didMethodKey: verifier.asDidMethodKey }) + .map((verifier) => + verifier.isDid + ? { did: verifier.asDid } + : { didMethodKey: verifier.asDidMethodKey } + ) .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); let schemasUpdate = new BTreeMap(); - verifiers = new BTreeSet(); - verifiers.add(typedHexDID(dock.api, verifierDID)); - verifiers.add(typedHexDID(dock.api, verifierDID2)); - issuers = new BTreeMap(); issuerPrices = new BTreeMap(); issuerPrices.set("A", 65); @@ -398,12 +410,20 @@ buildTest("Trust Registry", () => { ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify(issuer.isDid ? { did: issuer.asDid }: { didMethodKey: issuer.asDidMethodKey }), + JSON.stringify( + issuer.isDid + ? { did: issuer.asDid } + : { didMethodKey: issuer.asDidMethodKey } + ), Object.fromEntries([...prices.entries()]), ]) ), verifiers: [...verifiers.values()] - .map((verifier) => verifier.isDid ? { did: verifier.asDid }: { didMethodKey: verifier.asDidMethodKey }) + .map((verifier) => + verifier.isDid + ? { did: verifier.asDid } + : { didMethodKey: verifier.asDidMethodKey } + ) .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); @@ -413,7 +433,9 @@ buildTest("Trust Registry", () => { issuer2Prices.set("B", 36); let issuersUpdate = new BTreeMap(); - issuersUpdate.set(typedHexDID(dock.api, issuerDID2), { Set: issuer2Prices }); + issuersUpdate.set(typedHexDID(dock.api, issuerDID2), { + Set: issuer2Prices, + }); schemasUpdate.set(schemaId, { issuers: { Modify: issuersUpdate, @@ -422,7 +444,10 @@ buildTest("Trust Registry", () => { issuers = new BTreeMap(); issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); - schemas.set(schemaId, { issuers, verifiers: schemas.get(schemaId).verifiers }); + schemas.set(schemaId, { + issuers, + verifiers: schemas.get(schemaId).verifiers, + }); await dock.trustRegistry.updateSchemaMetadata( issuerDID2, @@ -442,12 +467,67 @@ buildTest("Trust Registry", () => { ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify(issuer.isDid ? { did: issuer.asDid }: { didMethodKey: issuer.asDidMethodKey }), + JSON.stringify( + issuer.isDid + ? { did: issuer.asDid } + : { didMethodKey: issuer.asDidMethodKey } + ), Object.fromEntries([...prices.entries()]), ]) ), verifiers: [...verifiers.values()] - .map((verifier) => verifier.isDid ? { did: verifier.asDid }: { didMethodKey: verifier.asDidMethodKey }) + .map((verifier) => + verifier.isDid + ? { did: verifier.asDid } + : { didMethodKey: verifier.asDidMethodKey } + ) + .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), + }); + + schemasUpdate = new BTreeMap(); + let verifiersUpdate = new BTreeMap(); + const innerUpdate = new BTreeSet(); + innerUpdate.add(verifierDIDMethodKey); + verifiersUpdate.set(verifierDIDMethodKey, { Remove: innerUpdate }); + schemasUpdate.set(schemaId, { + verifiers: { + Modify: verifiersUpdate, + }, + }); + + await dock.trustRegistry.updateSchemaMetadata( + verifierDIDMethodKey, + trustRegistryId, + schemasUpdate, + verifierDIDMethodKeyPair, + dock + ); + + verifiers.delete(verifierDIDMethodKey); + expect( + ( + await dock.api.query.trustRegistry.trustRegistrySchemasMetadata( + schemaId, + trustRegistryId + ) + ).toJSON() + ).toEqual({ + issuers: Object.fromEntries( + [...issuers.entries()].map(([issuer, prices]) => [ + JSON.stringify( + issuer.isDid + ? { did: issuer.asDid } + : { didMethodKey: issuer.asDidMethodKey } + ), + Object.fromEntries([...prices.entries()]), + ]) + ), + verifiers: [...verifiers.values()] + .map((verifier) => + verifier.isDid + ? { did: verifier.asDid } + : { didMethodKey: verifier.asDidMethodKey } + ) .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); }); From 7779131dd39169c297b682ec8690f366155baaf6 Mon Sep 17 00:00:00 2001 From: lovesh Date: Wed, 10 Jan 2024 19:58:58 +0530 Subject: [PATCH 30/32] misc small fixes Signed-off-by: lovesh --- scripts/hit_1.js | 21 +- scripts/txn-pricing.js | 4 +- .../status-list2021-credential.js | 8 +- src/utils/did.js | 10 +- tests/integration/revocation.test.js | 22 +- .../status-list-credential-module.test.js | 204 ++++++++-------- .../integration/trust-registry-module.test.js | 221 ++++++++---------- 7 files changed, 235 insertions(+), 255 deletions(-) diff --git a/scripts/hit_1.js b/scripts/hit_1.js index edf3145e6..17735e81e 100644 --- a/scripts/hit_1.js +++ b/scripts/hit_1.js @@ -1,7 +1,7 @@ import { randomAsHex } from '@polkadot/util-crypto'; import dock, { DockAPI } from '../src/index'; import { - createNewDockDID, + createNewDockDID, DidKeypair, } from '../src/utils/did'; import { getPublicKeyFromKeyringPair } from '../src/utils/misc'; import { sendBatch } from './helpers'; @@ -47,7 +47,7 @@ async function sendOnChainDIDTxns(count, waitForFinalization = true) { const didKey = new DidKey(publicKey, new VerificationRelationship()); const tx = dock.did.createNewOnchainTx(did, [didKey], []); txs.push(tx); - didPairs.push([did, pair]); + didPairs.push([did, new DidKeypair(pair, 1)]); } await sendBatch(dock, txs, account.address, waitForFinalization); @@ -77,7 +77,7 @@ async function sendAddKeyTxns(count, didPairs) { const newPair = dock.keyring.addFromUri(seed, null, 'sr25519'); const publicKey = getPublicKeyFromKeyringPair(newPair); const didKey = new DidKey(publicKey, new VerificationRelationship()); - const tx = await dock.did.createAddKeysTx([didKey], did, did, currentpair); + const tx = await dock.did.createAddKeysTx([didKey], did, did, currentPair); txs.push(tx); j++; } @@ -105,7 +105,7 @@ async function sendAddControllerTxns(count, didPairs) { while (txs.length < count) { const did = didPairs[j][0]; const currentPair = didPairs[j][1]; - const tx = await dock.did.createAddControllersTx([createNewDockDID()], did, did, currentpair); + const tx = await dock.did.createAddControllersTx([createNewDockDID()], did, did, currentPair); txs.push(tx); j++; } @@ -133,7 +133,7 @@ async function sendRemoveTxns(count, didPairs, waitForFinalization = true) { while (txs.length < count) { const did = didPairs[j][0]; const currentPair = didPairs[j][1]; - const tx = await dock.did.createRemoveTx(did, did, currentpair); + const tx = await dock.did.createRemoveTx(did, did, currentPair); txs.push(tx); j++; } @@ -207,15 +207,16 @@ async function sendAnchorTxns(count) { } async function runOnce() { - let didPairs = await sendOnChainDIDTxns(1950); + const count = 1000; + let didPairs = await sendOnChainDIDTxns(count); console.log(''); - didPairs = await sendAddKeyTxns(1950, didPairs); + didPairs = await sendAddKeyTxns(count, didPairs); console.log(''); - await sendAddControllerTxns(1950, didPairs); + await sendAddControllerTxns(count, didPairs); console.log(''); - await sendBlobTxns(1500, didPairs); + await sendBlobTxns(800, didPairs); console.log(''); - await sendRemoveTxns(1950, didPairs); + await sendRemoveTxns(count, didPairs); } async function runInLoop(limit) { diff --git a/scripts/txn-pricing.js b/scripts/txn-pricing.js index cb6090cc8..ef4537a8e 100755 --- a/scripts/txn-pricing.js +++ b/scripts/txn-pricing.js @@ -5,7 +5,7 @@ import { BTreeSet } from '@polkadot/types'; import { randomAsHex } from '@polkadot/util-crypto'; import dock from '../src/index'; import { - createNewDockDID, typedHexDID, + createNewDockDID, DidKeypair, typedHexDID, } from '../src/utils/did'; import { getPublicKeyFromKeyringPair } from '../src/utils/misc'; import { createRandomRegistryId, OneOfPolicy } from '../src/utils/revocation'; @@ -34,7 +34,7 @@ function getDidPair() { const pair = dock.keyring.addFromUri(seed, null, 'sr25519'); const publicKey = getPublicKeyFromKeyringPair(pair); const didKey = new DidKey(publicKey, new VerificationRelationship()); - return [did, pair, didKey]; + return [did, new DidKeypair(pair, 1), didKey]; } async function printFeePaid(dockApi, address, fn) { diff --git a/src/status-list-credential/status-list2021-credential.js b/src/status-list-credential/status-list2021-credential.js index 0f31dd1ca..0e9c7d2f8 100644 --- a/src/status-list-credential/status-list2021-credential.js +++ b/src/status-list-credential/status-list2021-credential.js @@ -27,14 +27,14 @@ export default class StatusList2021Credential extends VerifiableCredential { // Caches decoded status list. Object.defineProperty(this, 'decodedStatusList', { - value: function decodedStatusList() { + value: async function decodedStatusList() { if ( encodedStatusList === this.credentialSubject.encodedList && cachedDecodedStatusList !== void 0 ) { return cachedDecodedStatusList; } else { - cachedDecodedStatusList = decodeList(this.credentialSubject); + cachedDecodedStatusList = await decodeList(this.credentialSubject); encodedStatusList = this.credentialSubject.encodedList; return cachedDecodedStatusList; @@ -122,7 +122,7 @@ export default class StatusList2021Credential extends VerifiableCredential { * Throws an error if the underlying status list can't be decoded or supplied index is out of range. * * @param {number} index - * @returns {boolean} + * @returns {Promise} */ async revoked(index) { const decodedStatusList = await this.decodedStatusList(); @@ -136,7 +136,7 @@ export default class StatusList2021Credential extends VerifiableCredential { * Throws an error if the underlying status list can't be decoded or any of supplied indices is out of range. * * @param {Iterable} indices - * @returns {Array} + * @returns {Promise>} */ async revokedBatch(indices) { const decodedStatusList = await this.decodedStatusList(); diff --git a/src/utils/did.js b/src/utils/did.js index 4d0c64722..9f3a6bea9 100644 --- a/src/utils/did.js +++ b/src/utils/did.js @@ -278,9 +278,10 @@ Object.defineProperty(String.prototype, 'toStringSS58', { /** * Takes a DID string, gets the hexadecimal value of that and returns a `DockDidMethodKey` or `DockDid` object. + * @param api * @param {string} did - The DID can be passed as fully qualified DID like `did:dock:` or * `did:key:` or a 32 byte hex string - * @return {DockDidOrDidMethodKey} Returns a `DockDidMethodKey` or `DockDid` object. + * @return {string|DockDidOrDidMethodKey} Returns a `string` or `DockDidMethodKey` or `DockDid` object. */ export function typedHexDID(api, did) { const strDid = did.toString(); @@ -313,9 +314,10 @@ export function typedHexDID(api, did) { /** * Gets the hexadecimal value of the given DID received from the substrate side. + * @param api * @param {string} did - The DID can be passed as fully qualified DID like `did:dock:` or * a 32 byte hex string - * @return {DockDidOrDidMethodKey} Returns an object wrapping the DID. + * @return {string|DockDidOrDidMethodKey} Returns an object wrapping the DID. */ export function typedHexDIDFromSubstrate(api, did) { if (api.specVersion < 50) { @@ -391,7 +393,7 @@ export function createDidKey(publicKey, verRel) { /** * - * @param {DockDidOrDidMethodKey} did - DID as hex + * @param {string|DockDidOrDidMethodKey} did - DID as string or an object * @param {number} keyId - * @param rawSig * @param {Signature} sig @@ -402,7 +404,7 @@ export function createDidSig(did, { keyId }, rawSig) { if (typeof did === 'string') { return { - did: did.asDid, + did, keyId, sig, }; diff --git a/tests/integration/revocation.test.js b/tests/integration/revocation.test.js index 6c50355fe..c034535ba 100644 --- a/tests/integration/revocation.test.js +++ b/tests/integration/revocation.test.js @@ -196,18 +196,18 @@ describe('Revocation Module', () => { let hasSecondDID = false; [...controllerSet.entries()] .flatMap((v) => v) - .map(cnt => typedHexDIDFromSubstrate(dock.api, cnt)) + .map((cnt) => typedHexDIDFromSubstrate(dock.api, cnt)) .forEach((controller) => { - if ( - controller.toString() === typedHexDID(dock.api, ownerDID).toString() - ) { - hasFirstDID = true; - } else if ( - controller.toString() === typedHexDID(dock.api, ownerDID2).toString() - ) { - hasSecondDID = true; - } - }); + if ( + controller.toString() === typedHexDID(dock.api, ownerDID).toString() + ) { + hasFirstDID = true; + } else if ( + controller.toString() === typedHexDID(dock.api, ownerDID2).toString() + ) { + hasSecondDID = true; + } + }); expect(hasFirstDID && hasSecondDID).toBe(true); }, 40000); diff --git a/tests/integration/status-list-credential-module.test.js b/tests/integration/status-list-credential-module.test.js index 6bd16b9da..ac3890156 100644 --- a/tests/integration/status-list-credential-module.test.js +++ b/tests/integration/status-list-credential-module.test.js @@ -1,35 +1,35 @@ -import { randomAsHex } from "@polkadot/util-crypto"; +import { randomAsHex } from '@polkadot/util-crypto'; -import { DockAPI } from "../../src/index"; +import { DockAPI } from '../../src/index'; import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI, DisableStatusListTests, -} from "../test-constants"; +} from '../test-constants'; import { typedHexDID, createNewDockDID, DidKeypair, typedHexDIDFromSubstrate, -} from "../../src/utils/did"; -import { OneOfPolicy } from "../../src/utils/revocation"; -import { registerNewDIDUsingPair } from "./helpers"; -import { getKeyDoc } from "../../src/utils/vc/helpers"; -import StatusList2021Credential from "../../src/status-list-credential/status-list2021-credential"; +} from '../../src/utils/did'; +import { OneOfPolicy } from '../../src/utils/revocation'; +import { registerNewDIDUsingPair } from './helpers'; +import { getKeyDoc } from '../../src/utils/vc/helpers'; +import StatusList2021Credential from '../../src/status-list-credential/status-list2021-credential'; const expectEqualCreds = (cred1, cred2) => { expect(cred1).toEqual(cred2); expect(cred1.toJSON()).toEqual(cred2.toJSON()); expect(StatusList2021Credential.fromJSON(cred1.toJSON())).toEqual( - StatusList2021Credential.fromJSON(cred2.toJSON()) + StatusList2021Credential.fromJSON(cred2.toJSON()), ); }; const buildTest = DisableStatusListTests ? describe.skip : describe; -buildTest("StatusListCredential Module", () => { +buildTest('StatusListCredential Module', () => { const dock = new DockAPI(); let pair; let pair2; @@ -70,14 +70,14 @@ buildTest("StatusListCredential Module", () => { ownerKey = getKeyDoc( ownerDID, - dock.keyring.addFromUri(ownerSeed, null, "ed25519"), - "Ed25519VerificationKey2018" + dock.keyring.addFromUri(ownerSeed, null, 'ed25519'), + 'Ed25519VerificationKey2018', ); ownerKey2 = getKeyDoc( ownerDID2, - dock.keyring.addFromUri(ownerSeed2, null, "ed25519"), - "Ed25519VerificationKey2018" + dock.keyring.addFromUri(ownerSeed2, null, 'ed25519'), + 'Ed25519VerificationKey2018', ); // The keyring should be initialized before any test begins as this suite is testing statusListCredentialModule @@ -86,12 +86,12 @@ buildTest("StatusListCredential Module", () => { // Thees DIDs should be written before any test begins pair = new DidKeypair( - dock.keyring.addFromUri(ownerSeed, null, "sr25519"), - 1 + dock.keyring.addFromUri(ownerSeed, null, 'sr25519'), + 1, ); pair2 = new DidKeypair( - dock.keyring.addFromUri(ownerSeed2, null, "sr25519"), - 1 + dock.keyring.addFromUri(ownerSeed2, null, 'sr25519'), + 1, ); // The controller is same as the DID @@ -104,144 +104,137 @@ buildTest("StatusListCredential Module", () => { await dock.disconnect(); }, 10000); - test("Can create a status list with a OneOf policy", async () => { + test('Can create a status list with a OneOf policy', async () => { const cred = await StatusList2021Credential.create( ownerKey, - statusListCredId + statusListCredId, ); await expect( dock.statusListCredential.createStatusListCredential( statusListCredId, cred, policy, - false - ) + false, + ), ).resolves.toBeDefined(); - const fetchedCred = - await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId - ); + const fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( + statusListCredId, + ); expectEqualCreds(cred, fetchedCred); }, 40000); - test("Can revoke index from a status list credential", async () => { + test('Can revoke index from a status list credential', async () => { const cred = await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId + statusListCredId, ); await cred.update(ownerKey, { revokeIndices: revokeIds }); - const [revoke, sig, nonce] = - await dock.statusListCredential.createSignedUpdateStatusListCredential( - statusListCredId, - cred, - ownerDID, - pair, - { didModule: dock.did } - ); + const [revoke, sig, nonce] = await dock.statusListCredential.createSignedUpdateStatusListCredential( + statusListCredId, + cred, + ownerDID, + pair, + { didModule: dock.did }, + ); await dock.statusListCredential.updateStatusListCredential( revoke, [{ nonce, sig }], - false + false, + ); + const fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( + statusListCredId, ); - const fetchedCred = - await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId - ); expectEqualCreds(cred, fetchedCred); expect(await fetchedCred.revoked(revokeId)).toBe(true); }, 40000); - test("Cant unsuspend from a status list credential with `statusPurpose` = `revocation`", async () => { + test('Cant unsuspend from a status list credential with `statusPurpose` = `revocation`', async () => { const cred = await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId + statusListCredId, ); - expect( - cred.update(ownerKey, { unsuspendIndices: revokeIds }) + await expect( + cred.update(ownerKey, { unsuspendIndices: revokeIds }), ).rejects.toEqual( new Error( - "Can't unsuspend indices for credential with `statusPurpose` = `revocation`, it's only possible with `statusPurpose` = `suspension`" - ) + "Can't unsuspend indices for credential with `statusPurpose` = `revocation`, it's only possible with `statusPurpose` = `suspension`", + ), ); - expect( - cred.update(ownerKey, { unsuspendIndices: revokeIds }) + await expect( + cred.update(ownerKey, { unsuspendIndices: revokeIds }), ).rejects.toEqual( new Error( - "Can't unsuspend indices for credential with `statusPurpose` = `revocation`, it's only possible with `statusPurpose` = `suspension`" - ) + "Can't unsuspend indices for credential with `statusPurpose` = `revocation`, it's only possible with `statusPurpose` = `suspension`", + ), ); expect(await cred.revokedBatch(revokeIds)).toEqual( - Array.from(revokeIds, () => true) + Array.from(revokeIds, () => true), ); }, 40000); - test("Can unsuspend from a status list credential", async () => { + test('Can unsuspend from a status list credential', async () => { const credential = await StatusList2021Credential.create( ownerKey, statusListCredId, - { statusPurpose: "suspension", revokeIndices: revokeIds } + { statusPurpose: 'suspension', revokeIndices: revokeIds }, + ); + let [update, sig, nonce] = await dock.statusListCredential.createSignedUpdateStatusListCredential( + statusListCredId, + credential, + ownerDID, + pair, + { didModule: dock.did }, ); - let [update, sig, nonce] = - await dock.statusListCredential.createSignedUpdateStatusListCredential( - statusListCredId, - credential, - ownerDID, - pair, - { didModule: dock.did } - ); await dock.statusListCredential.updateStatusListCredential( update, [{ nonce, sig }], - false + false, + ); + let fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( + statusListCredId, ); - let fetchedCred = - await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId - ); expectEqualCreds(credential, fetchedCred); await fetchedCred.update(ownerKey, { unsuspendIndices: revokeIds }); expect(await fetchedCred.revokedBatch(revokeIds)).toEqual( - Array.from(revokeIds, () => false) + Array.from(revokeIds, () => false), + ); + [update, sig, nonce] = await dock.statusListCredential.createSignedUpdateStatusListCredential( + statusListCredId, + fetchedCred, + ownerDID, + pair, + { didModule: dock.did }, ); - [update, sig, nonce] = - await dock.statusListCredential.createSignedUpdateStatusListCredential( - statusListCredId, - fetchedCred, - ownerDID, - pair, - { didModule: dock.did } - ); await dock.statusListCredential.updateStatusListCredential( update, [{ nonce, sig }], - false + false, ); fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId + statusListCredId, ); expect(await fetchedCred.revoked(revokeId)).toBe(false); }, 40000); - test("Can remove a status list", async () => { - const [remove, sig, nonce] = - await dock.statusListCredential.createSignedRemoveStatusListCredential( - statusListCredId, - ownerDID, - pair, - { didModule: dock.did } - ); + test('Can remove a status list', async () => { + const [remove, sig, nonce] = await dock.statusListCredential.createSignedRemoveStatusListCredential( + statusListCredId, + ownerDID, + pair, + { didModule: dock.did }, + ); await dock.statusListCredential.removeStatusListCredential( remove, [{ nonce, sig }], - false + false, ); expect( await dock.statusListCredential.fetchStatusList2021Credential( - statusListCredId - ) + statusListCredId, + ), ).toBe(null); }, 40000); - test("Can create a status list with multiple owners", async () => { + test('Can create a status list with multiple owners', async () => { const controllersNew = new Set(); controllersNew.add(typedHexDID(dock.api, ownerDID)); controllersNew.add(typedHexDID(dock.api, ownerDID2)); @@ -249,7 +242,7 @@ buildTest("StatusListCredential Module", () => { const cred = await StatusList2021Credential.create( ownerKey, multipleControllerstatusListCredID, - { statusPurpose: "suspension" } + { statusPurpose: 'suspension' }, ); // Create policy and status list with multiple owners @@ -260,12 +253,12 @@ buildTest("StatusListCredential Module", () => { cred, policyNew, false, - false - ) + false, + ), ).resolves.toBeDefined(); const fetchedCred = ( await dock.api.query.statusListCredential.statusListCredentials( - multipleControllerstatusListCredID + multipleControllerstatusListCredID, ) ).unwrap(); expect(fetchedCred.policy.isOneOf).toBe(true); @@ -277,7 +270,7 @@ buildTest("StatusListCredential Module", () => { let hasSecondDID = false; [...controllerSet.entries()] .flatMap((v) => v) - .map(cnt => typedHexDIDFromSubstrate(dock.api, cnt)) + .map((cnt) => typedHexDIDFromSubstrate(dock.api, cnt)) .forEach((controller) => { if ( controller.toString() === typedHexDID(dock.api, ownerDID).toString() @@ -292,13 +285,12 @@ buildTest("StatusListCredential Module", () => { expect(hasFirstDID && hasSecondDID).toBe(true); }, 40000); - test("Can revoke, unsuspend and remove status list with multiple owners", async () => { + test('Can revoke, unsuspend and remove status list with multiple owners', async () => { const revId = (Math.random() * 10e3) | 0; - let fetchedCred = - await dock.statusListCredential.fetchStatusList2021Credential( - multipleControllerstatusListCredID - ); + let fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( + multipleControllerstatusListCredID, + ); await fetchedCred.update(ownerKey, { revokeIndices: [revId] }); // Revoke await dock.statusListCredential.updateStatusListCredentialWithOneOfPolicy( @@ -307,11 +299,11 @@ buildTest("StatusListCredential Module", () => { ownerDID, pair, { didModule: dock.did }, - false + false, ); fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( multipleControllerstatusListCredID, - revId + revId, ); expect(await fetchedCred.revoked(revId)).toBe(true); @@ -324,10 +316,10 @@ buildTest("StatusListCredential Module", () => { ownerDID2, pair2, { didModule: dock.did }, - false + false, ); fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( - multipleControllerstatusListCredID + multipleControllerstatusListCredID, ); expect(await fetchedCred.revoked(revId)).toBe(false); @@ -337,10 +329,10 @@ buildTest("StatusListCredential Module", () => { ownerDID, pair, { didModule: dock.did }, - false + false, ); fetchedCred = await dock.statusListCredential.fetchStatusList2021Credential( - multipleControllerstatusListCredID + multipleControllerstatusListCredID, ); expect(fetchedCred).toBe(null); }, 30000); diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js index 8e9c87083..3e699bac1 100644 --- a/tests/integration/trust-registry-module.test.js +++ b/tests/integration/trust-registry-module.test.js @@ -1,29 +1,27 @@ -import { randomAsHex } from "@polkadot/util-crypto"; -import { BTreeSet, BTreeMap } from "@polkadot/types"; -import { u8aToHex, stringToU8a } from "@polkadot/util"; +import { randomAsHex } from '@polkadot/util-crypto'; +import { BTreeSet, BTreeMap } from '@polkadot/types'; +import { u8aToHex, stringToU8a } from '@polkadot/util'; -import { DockAPI } from "../../src/index"; +import { DockAPI } from '../../src/index'; import { FullNodeEndpoint, TestKeyringOpts, TestAccountURI, DisableTrustRegistryTests, -} from "../test-constants"; +} from '../test-constants'; import { createNewDockDID, DidKeypair, DockDidMethodKey, typedHexDID, -} from "../../src/utils/did"; -import { generateEcdsaSecp256k1Keypair } from "../../src/utils/misc"; -import { PublicKeySecp256k1 } from "../../src"; -import { registerNewDIDUsingPair } from "./helpers"; +} from '../../src/utils/did'; +import { registerNewDIDUsingPair } from './helpers'; const buildTest = DisableTrustRegistryTests ? describe.skip : describe; -buildTest("Trust Registry", () => { +buildTest('Trust Registry', () => { const dock = new DockAPI(); // Create a random status list id @@ -54,11 +52,6 @@ buildTest("Trust Registry", () => { let verifierDIDMethodKeyPair; let verifierDIDMethodKey; - // Create revoke IDs - const revokeId = (Math.random() * 10e3) | 0; - const revokeIds = new Set(); - revokeIds.add(revokeId); - beforeAll(async () => { await dock.init({ keyring: TestKeyringOpts, @@ -66,32 +59,32 @@ buildTest("Trust Registry", () => { }); convenerPair = new DidKeypair( - dock.keyring.addFromUri(ownerSeed, null, "ed25519"), - 1 + dock.keyring.addFromUri(ownerSeed, null, 'ed25519'), + 1, ); issuerPair = new DidKeypair( - dock.keyring.addFromUri(issuerSeed, null, "ed25519"), - 1 + dock.keyring.addFromUri(issuerSeed, null, 'ed25519'), + 1, ); issuerPair2 = new DidKeypair( - dock.keyring.addFromUri(issuerSeed2, null, "ed25519"), - 1 + dock.keyring.addFromUri(issuerSeed2, null, 'ed25519'), + 1, ); verifierPair = new DidKeypair( - dock.keyring.addFromUri(verifierSeed, null, "ed25519"), - 1 + dock.keyring.addFromUri(verifierSeed, null, 'ed25519'), + 1, ); verifierPair2 = new DidKeypair( - dock.keyring.addFromUri(verifierSeed2, null, "ed25519"), - 1 + dock.keyring.addFromUri(verifierSeed2, null, 'ed25519'), + 1, ); verifierDIDMethodKeyPair = new DidKeypair( - dock.keyring.addFromUri(verifierDIDMethodKeySeed, null, "ed25519") + dock.keyring.addFromUri(verifierDIDMethodKeySeed, null, 'ed25519'), ); verifierDIDMethodKey = new DockDidMethodKey(verifierDIDMethodKeyPair.publicKey()); @@ -109,19 +102,19 @@ buildTest("Trust Registry", () => { await dock.did.newDidMethodKey(verifierDIDMethodKey.asDidMethodKey); }, 40000); - it("Initializes Trust Registry", async () => { + it('Initializes Trust Registry', async () => { expect( (await dock.api.query.trustRegistry.trustRegistriesInfo(trustRegistryId)) - .isNone + .isNone, ).toEqual(true); await dock.trustRegistry.init( convenerDID, trustRegistryId, - "Test Registry", - "Gov framework", + 'Test Registry', + 'Gov framework', convenerPair, - dock + dock, ); const registryInfo = ( @@ -129,22 +122,22 @@ buildTest("Trust Registry", () => { ).toJSON(); expect(registryInfo).toEqual({ convener: typedHexDID(dock.api, convenerDID), - name: "Test Registry", - govFramework: u8aToHex(stringToU8a("Gov framework")) + name: 'Test Registry', + govFramework: u8aToHex(stringToU8a('Gov framework')), }); }); - it("Adds schemas to the existing Trust Registry", async () => { + it('Adds schemas to the existing Trust Registry', async () => { // Create a random status list id const schemaId = randomAsHex(32); await dock.trustRegistry.init( convenerDID, trustRegistryId, - "Test Registry", - "Gov framework", + 'Test Registry', + 'Gov framework', convenerPair, - dock + dock, ); const verifiers = new BTreeSet(); @@ -154,9 +147,9 @@ buildTest("Trust Registry", () => { const issuers = new BTreeMap(); const issuerPrices = new BTreeMap(); - issuerPrices.set("A", 20); + issuerPrices.set('A', 20); const issuer2Prices = new BTreeMap(); - issuer2Prices.set("A", 20); + issuer2Prices.set('A', 20); issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); @@ -172,40 +165,40 @@ buildTest("Trust Registry", () => { trustRegistryId, schemas, convenerPair, - dock + dock, ); expect( ( await dock.api.query.trustRegistry.trustRegistrySchemasMetadata( schemaId, - trustRegistryId + trustRegistryId, ) - ).toJSON() + ).toJSON(), ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify(issuer.isDid ? { did: issuer.asDid }: { didMethodKey: issuer.asDidMethodKey }), + JSON.stringify(issuer.isDid ? { did: issuer.asDid } : { didMethodKey: issuer.asDidMethodKey }), Object.fromEntries([...prices.entries()]), - ]) + ]), ), verifiers: [...verifiers.values()] - .map((verifier) => verifier.isDid ? { did: verifier.asDid }: { didMethodKey: verifier.asDidMethodKey }) + .map((verifier) => (verifier.isDid ? { did: verifier.asDid } : { didMethodKey: verifier.asDidMethodKey })) .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); }); - it("Suspends issuers in the existing Trust Registry", async () => { + it('Suspends issuers in the existing Trust Registry', async () => { // Create a random status list id const schemaId = randomAsHex(32); await dock.trustRegistry.init( convenerDID, trustRegistryId, - "Test Registry", - "Gov framework", + 'Test Registry', + 'Gov framework', convenerPair, - dock + dock, ); const verifiers = new BTreeSet(); @@ -215,9 +208,9 @@ buildTest("Trust Registry", () => { const issuers = new BTreeMap(); const issuerPrices = new BTreeMap(); - issuerPrices.set("A", 20); + issuerPrices.set('A', 20); const issuer2Prices = new BTreeMap(); - issuer2Prices.set("A", 20); + issuer2Prices.set('A', 20); issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); @@ -233,7 +226,7 @@ buildTest("Trust Registry", () => { trustRegistryId, schemas, convenerPair, - dock + dock, ); await dock.trustRegistry.suspendIssuers( @@ -241,13 +234,13 @@ buildTest("Trust Registry", () => { trustRegistryId, [issuerDID, issuerDID2], convenerPair, - dock + dock, ); for (const issuer of [issuerDID, issuerDID2]) { expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(dock.api, issuer))).toJSON()).toEqual({ suspended: true, - delegated: [] + delegated: [], }); } @@ -256,38 +249,38 @@ buildTest("Trust Registry", () => { trustRegistryId, [issuerDID], convenerPair, - dock + dock, ); for (const issuer of [issuerDID]) { expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(dock.api, issuer))).toJSON()).toEqual({ suspended: false, - delegated: [] + delegated: [], }); } for (const issuer of [issuerDID2]) { expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(dock.api, issuer))).toJSON()).toEqual({ suspended: true, - delegated: [] + delegated: [], }); } }); - it("Updates delegated issuers in the existing Trust Registry", async () => { + it('Updates delegated issuers in the existing Trust Registry', async () => { // Create a random status list id await dock.trustRegistry.init( convenerDID, trustRegistryId, - "Test Registry", - "Gov framework", + 'Test Registry', + 'Gov framework', convenerPair, - dock + dock, ); expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(dock.api, issuerDID))).toJSON()).toEqual({ suspended: false, - delegated: [] + delegated: [], }); const issuers = new BTreeSet(); @@ -298,43 +291,43 @@ buildTest("Trust Registry", () => { trustRegistryId, { Set: issuers }, issuerPair, - dock + dock, ); expect((await dock.api.query.trustRegistry.trustRegistryIssuerConfigurations(trustRegistryId, typedHexDID(dock.api, issuerDID))).toJSON()).toEqual({ suspended: false, - delegated: [typedHexDID(dock.api, issuerDID2)] + delegated: [typedHexDID(dock.api, issuerDID2)], }); }); - it("Updates schemas in the existing Trust Registry", async () => { + it('Updates schemas in the existing Trust Registry', async () => { // Create a random status list id const schemaId = randomAsHex(32); await dock.trustRegistry.init( convenerDID, trustRegistryId, - "Test Registry", - "Gov framework", + 'Test Registry', + 'Gov framework', convenerPair, - dock + dock, ); - let verifiers = new BTreeSet(); + const verifiers = new BTreeSet(); verifiers.add(typedHexDID(dock.api, verifierDID)); verifiers.add(typedHexDID(dock.api, verifierDID2)); verifiers.add(verifierDIDMethodKey); let issuers = new BTreeMap(); let issuerPrices = new BTreeMap(); - issuerPrices.set("A", 20); + issuerPrices.set('A', 20); let issuer2Prices = new BTreeMap(); - issuer2Prices.set("A", 20); + issuer2Prices.set('A', 20); issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); - let schemas = new BTreeMap(); + const schemas = new BTreeMap(); schemas.set(schemaId, { issuers, verifiers, @@ -345,33 +338,31 @@ buildTest("Trust Registry", () => { trustRegistryId, schemas, convenerPair, - dock + dock, ); expect( ( await dock.api.query.trustRegistry.trustRegistrySchemasMetadata( schemaId, - trustRegistryId + trustRegistryId, ) - ).toJSON() + ).toJSON(), ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ JSON.stringify( issuer.isDid ? { did: issuer.asDid } - : { didMethodKey: issuer.asDidMethodKey } + : { didMethodKey: issuer.asDidMethodKey }, ), Object.fromEntries([...prices.entries()]), - ]) + ]), ), verifiers: [...verifiers.values()] - .map((verifier) => - verifier.isDid - ? { did: verifier.asDid } - : { didMethodKey: verifier.asDidMethodKey } - ) + .map((verifier) => (verifier.isDid + ? { did: verifier.asDid } + : { didMethodKey: verifier.asDidMethodKey })) .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); @@ -379,9 +370,9 @@ buildTest("Trust Registry", () => { issuers = new BTreeMap(); issuerPrices = new BTreeMap(); - issuerPrices.set("A", 65); + issuerPrices.set('A', 65); issuer2Prices = new BTreeMap(); - issuer2Prices.set("A", 75); + issuer2Prices.set('A', 75); issuers.set(typedHexDID(dock.api, issuerDID), issuerPrices); issuers.set(typedHexDID(dock.api, issuerDID2), issuer2Prices); @@ -397,42 +388,40 @@ buildTest("Trust Registry", () => { trustRegistryId, schemasUpdate, convenerPair, - dock + dock, ); expect( ( await dock.api.query.trustRegistry.trustRegistrySchemasMetadata( schemaId, - trustRegistryId + trustRegistryId, ) - ).toJSON() + ).toJSON(), ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ JSON.stringify( issuer.isDid ? { did: issuer.asDid } - : { didMethodKey: issuer.asDidMethodKey } + : { didMethodKey: issuer.asDidMethodKey }, ), Object.fromEntries([...prices.entries()]), - ]) + ]), ), verifiers: [...verifiers.values()] - .map((verifier) => - verifier.isDid - ? { did: verifier.asDid } - : { didMethodKey: verifier.asDidMethodKey } - ) + .map((verifier) => (verifier.isDid + ? { did: verifier.asDid } + : { didMethodKey: verifier.asDidMethodKey })) .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); schemasUpdate = new BTreeMap(); issuer2Prices = new BTreeMap(); - issuer2Prices.set("A", 25); - issuer2Prices.set("B", 36); + issuer2Prices.set('A', 25); + issuer2Prices.set('B', 36); - let issuersUpdate = new BTreeMap(); + const issuersUpdate = new BTreeMap(); issuersUpdate.set(typedHexDID(dock.api, issuerDID2), { Set: issuer2Prices, }); @@ -454,38 +443,36 @@ buildTest("Trust Registry", () => { trustRegistryId, schemasUpdate, issuerPair2, - dock + dock, ); expect( ( await dock.api.query.trustRegistry.trustRegistrySchemasMetadata( schemaId, - trustRegistryId + trustRegistryId, ) - ).toJSON() + ).toJSON(), ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ JSON.stringify( issuer.isDid ? { did: issuer.asDid } - : { didMethodKey: issuer.asDidMethodKey } + : { didMethodKey: issuer.asDidMethodKey }, ), Object.fromEntries([...prices.entries()]), - ]) + ]), ), verifiers: [...verifiers.values()] - .map((verifier) => - verifier.isDid - ? { did: verifier.asDid } - : { didMethodKey: verifier.asDidMethodKey } - ) + .map((verifier) => (verifier.isDid + ? { did: verifier.asDid } + : { didMethodKey: verifier.asDidMethodKey })) .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); schemasUpdate = new BTreeMap(); - let verifiersUpdate = new BTreeMap(); + const verifiersUpdate = new BTreeMap(); const innerUpdate = new BTreeSet(); innerUpdate.add(verifierDIDMethodKey); verifiersUpdate.set(verifierDIDMethodKey, { Remove: innerUpdate }); @@ -500,7 +487,7 @@ buildTest("Trust Registry", () => { trustRegistryId, schemasUpdate, verifierDIDMethodKeyPair, - dock + dock, ); verifiers.delete(verifierDIDMethodKey); @@ -508,26 +495,24 @@ buildTest("Trust Registry", () => { ( await dock.api.query.trustRegistry.trustRegistrySchemasMetadata( schemaId, - trustRegistryId + trustRegistryId, ) - ).toJSON() + ).toJSON(), ).toEqual({ issuers: Object.fromEntries( [...issuers.entries()].map(([issuer, prices]) => [ JSON.stringify( issuer.isDid ? { did: issuer.asDid } - : { didMethodKey: issuer.asDidMethodKey } + : { didMethodKey: issuer.asDidMethodKey }, ), Object.fromEntries([...prices.entries()]), - ]) + ]), ), verifiers: [...verifiers.values()] - .map((verifier) => - verifier.isDid - ? { did: verifier.asDid } - : { didMethodKey: verifier.asDidMethodKey } - ) + .map((verifier) => (verifier.isDid + ? { did: verifier.asDid } + : { didMethodKey: verifier.asDidMethodKey })) .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), }); }); From d5baea2ad24e32ac9455ed061df14eab230566c1 Mon Sep 17 00:00:00 2001 From: lovesh Date: Wed, 10 Jan 2024 20:44:28 +0530 Subject: [PATCH 31/32] remove duplicate code Signed-off-by: lovesh --- .../integration/trust-registry-module.test.js | 112 ++++++------------ 1 file changed, 36 insertions(+), 76 deletions(-) diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js index 3e699bac1..31300d024 100644 --- a/tests/integration/trust-registry-module.test.js +++ b/tests/integration/trust-registry-module.test.js @@ -24,10 +24,10 @@ const buildTest = DisableTrustRegistryTests ? describe.skip : describe; buildTest('Trust Registry', () => { const dock = new DockAPI(); - // Create a random status list id + // Create a random trust registry id const trustRegistryId = randomAsHex(32); - // Create a new owner DID, the DID will be registered on the network and own the status list + // Create a new convener DID, the DID will be registered on the network and own the trust registry const convenerDID = createNewDockDID(); const ownerSeed = randomAsHex(32); let convenerPair; @@ -88,7 +88,7 @@ buildTest('Trust Registry', () => { ); verifierDIDMethodKey = new DockDidMethodKey(verifierDIDMethodKeyPair.publicKey()); - // The keyring should be initialized before any test begins as this suite is testing trustRegistry + // The keyring should be initialized before any test begins as this suite is testing trust registry const account = dock.keyring.addFromUri(TestAccountURI); dock.setAccount(account); @@ -128,7 +128,7 @@ buildTest('Trust Registry', () => { }); it('Adds schemas to the existing Trust Registry', async () => { - // Create a random status list id + // Create a random trust registry id const schemaId = randomAsHex(32); await dock.trustRegistry.init( @@ -176,20 +176,13 @@ buildTest('Trust Registry', () => { ) ).toJSON(), ).toEqual({ - issuers: Object.fromEntries( - [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify(issuer.isDid ? { did: issuer.asDid } : { didMethodKey: issuer.asDidMethodKey }), - Object.fromEntries([...prices.entries()]), - ]), - ), - verifiers: [...verifiers.values()] - .map((verifier) => (verifier.isDid ? { did: verifier.asDid } : { didMethodKey: verifier.asDidMethodKey })) - .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), + issuers: expectedFormattedIssuers(issuers), + verifiers: expectedFormattedVerifiers(verifiers), }); }); it('Suspends issuers in the existing Trust Registry', async () => { - // Create a random status list id + // Create a random trust registry id const schemaId = randomAsHex(32); await dock.trustRegistry.init( @@ -268,7 +261,7 @@ buildTest('Trust Registry', () => { }); it('Updates delegated issuers in the existing Trust Registry', async () => { - // Create a random status list id + // Create a random trust registry id await dock.trustRegistry.init( convenerDID, trustRegistryId, @@ -301,7 +294,7 @@ buildTest('Trust Registry', () => { }); it('Updates schemas in the existing Trust Registry', async () => { - // Create a random status list id + // Create a random trust registry id const schemaId = randomAsHex(32); await dock.trustRegistry.init( @@ -349,21 +342,8 @@ buildTest('Trust Registry', () => { ) ).toJSON(), ).toEqual({ - issuers: Object.fromEntries( - [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify( - issuer.isDid - ? { did: issuer.asDid } - : { didMethodKey: issuer.asDidMethodKey }, - ), - Object.fromEntries([...prices.entries()]), - ]), - ), - verifiers: [...verifiers.values()] - .map((verifier) => (verifier.isDid - ? { did: verifier.asDid } - : { didMethodKey: verifier.asDidMethodKey })) - .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), + issuers: expectedFormattedIssuers(issuers), + verifiers: expectedFormattedVerifiers(verifiers), }); let schemasUpdate = new BTreeMap(); @@ -399,21 +379,8 @@ buildTest('Trust Registry', () => { ) ).toJSON(), ).toEqual({ - issuers: Object.fromEntries( - [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify( - issuer.isDid - ? { did: issuer.asDid } - : { didMethodKey: issuer.asDidMethodKey }, - ), - Object.fromEntries([...prices.entries()]), - ]), - ), - verifiers: [...verifiers.values()] - .map((verifier) => (verifier.isDid - ? { did: verifier.asDid } - : { didMethodKey: verifier.asDidMethodKey })) - .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), + issuers: expectedFormattedIssuers(issuers), + verifiers: expectedFormattedVerifiers(verifiers), }); schemasUpdate = new BTreeMap(); @@ -454,21 +421,8 @@ buildTest('Trust Registry', () => { ) ).toJSON(), ).toEqual({ - issuers: Object.fromEntries( - [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify( - issuer.isDid - ? { did: issuer.asDid } - : { didMethodKey: issuer.asDidMethodKey }, - ), - Object.fromEntries([...prices.entries()]), - ]), - ), - verifiers: [...verifiers.values()] - .map((verifier) => (verifier.isDid - ? { did: verifier.asDid } - : { didMethodKey: verifier.asDidMethodKey })) - .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), + issuers: expectedFormattedIssuers(issuers), + verifiers: expectedFormattedVerifiers(verifiers), }); schemasUpdate = new BTreeMap(); @@ -499,21 +453,27 @@ buildTest('Trust Registry', () => { ) ).toJSON(), ).toEqual({ - issuers: Object.fromEntries( - [...issuers.entries()].map(([issuer, prices]) => [ - JSON.stringify( - issuer.isDid - ? { did: issuer.asDid } - : { didMethodKey: issuer.asDidMethodKey }, - ), - Object.fromEntries([...prices.entries()]), - ]), - ), - verifiers: [...verifiers.values()] - .map((verifier) => (verifier.isDid - ? { did: verifier.asDid } - : { didMethodKey: verifier.asDidMethodKey })) - .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), + issuers: expectedFormattedIssuers(issuers), + verifiers: expectedFormattedVerifiers(verifiers), }); }); }); + +function expectedFormattedIssuers(issuers) { + return Object.fromEntries( + [...issuers.entries()].map(([issuer, prices]) => [ + JSON.stringify( + issuer.isDid + ? { did: issuer.asDid } + : { didMethodKey: issuer.asDidMethodKey }, + ), + Object.fromEntries([...prices.entries()]), + ]), + ); +} + +function expectedFormattedVerifiers(verifiers) { + return [...verifiers.values()] + .map((verifier) => (verifier.isDid ? { did: verifier.asDid } : { didMethodKey: verifier.asDidMethodKey })) + .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))); +} From e8c615e322310e4fdbf35279119a11ed52efa335 Mon Sep 17 00:00:00 2001 From: lovesh Date: Wed, 10 Jan 2024 21:44:38 +0530 Subject: [PATCH 32/32] remove duplicate code Signed-off-by: lovesh --- src/modules/trust-registry.js | 33 +++++++++++-------- .../integration/trust-registry-module.test.js | 4 +++ 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/modules/trust-registry.js b/src/modules/trust-registry.js index 3f1967cfa..1596312b4 100644 --- a/src/modules/trust-registry.js +++ b/src/modules/trust-registry.js @@ -42,8 +42,7 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerHexDid = typedHexDID(this.api, convenerDid); - const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); + const [convenerHexDid, lastNonce] = await this.getActorDidAndNonce(convenerDid, { nonce, didModule }); return this.signAndSend( convenerHexDid.changeState( @@ -85,8 +84,7 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerHexDid = typedHexDID(this.api, convenerDid); - const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); + const [convenerHexDid, lastNonce] = await this.getActorDidAndNonce(convenerDid, { nonce, didModule }); return this.signAndSend( convenerHexDid.changeState( @@ -123,10 +121,7 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerOrIssuerOrVerifierHexDid = typedHexDID(this.api, - convenerOrIssuerOrVerifierDid); - const lastNonce = nonce - ?? (await getDidNonce(convenerOrIssuerOrVerifierHexDid, nonce, didModule)); + const [convenerOrIssuerOrVerifierHexDid, lastNonce] = await this.getActorDidAndNonce(convenerOrIssuerOrVerifierDid, { nonce, didModule }); return this.signAndSend( convenerOrIssuerOrVerifierHexDid.changeState( @@ -163,8 +158,7 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerHexDid = typedHexDID(this.api, convenerDid); - const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); + const [convenerHexDid, lastNonce] = await this.getActorDidAndNonce(convenerDid, { nonce, didModule }); const hexIssuers = new BTreeSet(); for (const issuer of issuers) { @@ -206,8 +200,7 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const convenerHexDid = typedHexDID(this.api, convenerDid); - const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); + const [convenerHexDid, lastNonce] = await this.getActorDidAndNonce(convenerDid, { nonce, didModule }); const hexIssuers = new BTreeSet(); for (const issuer of issuers) { @@ -248,8 +241,7 @@ export default class TrustRegistryModule { waitForFinalization = true, params = {}, ) { - const issuerHexDid = typedHexDID(this.api, issuerDid); - const lastNonce = nonce ?? (await getDidNonce(issuerHexDid, nonce, didModule)); + const [issuerHexDid, lastNonce] = await this.getActorDidAndNonce(issuerDid, { nonce, didModule }); return this.signAndSend( issuerHexDid.changeState( @@ -263,4 +255,17 @@ export default class TrustRegistryModule { params, ); } + + /** + * Get the DID doing the action and its corresponding nonce. + * @param actorDid + * @param nonce + * @param didModule + * @returns {Promise} + */ + async getActorDidAndNonce(actorDid, { nonce = undefined, didModule = undefined } = {}) { + const convenerHexDid = typedHexDID(this.api, actorDid); + const lastNonce = nonce ?? (await getDidNonce(convenerHexDid, nonce, didModule)); + return [convenerHexDid, lastNonce]; + } } diff --git a/tests/integration/trust-registry-module.test.js b/tests/integration/trust-registry-module.test.js index 31300d024..dd7f2784b 100644 --- a/tests/integration/trust-registry-module.test.js +++ b/tests/integration/trust-registry-module.test.js @@ -102,6 +102,10 @@ buildTest('Trust Registry', () => { await dock.did.newDidMethodKey(verifierDIDMethodKey.asDidMethodKey); }, 40000); + afterAll(async () => { + await dock.disconnect(); + }, 10000); + it('Initializes Trust Registry', async () => { expect( (await dock.api.query.trustRegistry.trustRegistriesInfo(trustRegistryId))