Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: did doc methods #15

Merged
merged 5 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
"dependencies": {
"@aries-framework/askar": "0.4.2",
"@aries-framework/core": "0.4.2",
"@ayanworks/polygon-did-registrar": "0.0.16-alpha.7",
"@ayanworks/polygon-did-resolver": "0.0.16-alpha.8",
"@ayanworks/polygon-did-registrar": "0.0.16-alpha.10",
"@ayanworks/polygon-did-resolver": "0.0.16-alpha.10",
"@ayanworks/polygon-schema-manager": "0.0.2-alpha.2",
"@sphereon/pex": "^2.2.2",
"@sphereon/pex-models": "^2.1.2",
Expand Down
102 changes: 65 additions & 37 deletions patches/@aries-framework+core+0.4.2.patch

Large diffs are not rendered by default.

127 changes: 114 additions & 13 deletions src/dids/PolygonDidRegistrar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import type {
Buffer,
Wallet,
} from '@aries-framework/core'
import type { ResolverRegistry } from 'did-resolver'

import { AskarWallet } from '@aries-framework/askar'
import {
Expand All @@ -22,18 +21,21 @@ import {
DidDocument,
AriesFrameworkError,
WalletError,
isValidPrivateKey,
getEcdsaSecp256k1VerificationKey2019,
DidDocumentBuilder,
} from '@aries-framework/core'
import { getResolver } from '@ayanworks/polygon-did-resolver'
import { Resolver } from 'did-resolver'
import { SigningKey } from 'ethers'

import { PolygonLedgerService } from '../ledger'

import { buildDid, validateSpecCompliantPayload } from './didPolygonUtil'
import { buildDid, getSecp256k1DidDoc, validateSpecCompliantPayload } from './didPolygonUtil'

export class PolygonDidRegistrar implements DidRegistrar {
public readonly supportedMethods = ['polygon']
private resolver = new Resolver(getResolver() as ResolverRegistry)
private resolver = new Resolver(getResolver())

public async create(agentContext: AgentContext, options: PolygonDidCreateOptions): Promise<DidCreateResult> {
const ledgerService = agentContext.dependencyManager.resolve(PolygonLedgerService)
Expand All @@ -53,11 +55,10 @@ export class PolygonDidRegistrar implements DidRegistrar {

const didRegistry = ledgerService.createDidRegistryInstance(signingKey)

const response = await didRegistry.create({
did,
publicKeyBase58: key.publicKeyBase58,
serviceEndpoint: options.options.endpoint,
})
// Create did document
const secpDidDoc = getSecp256k1DidDoc(did, key, options.options.endpoint)

const response = await didRegistry.create(did, secpDidDoc)

agentContext.config.logger.info(`Published did on ledger: ${did}`)

Expand Down Expand Up @@ -111,8 +112,7 @@ export class PolygonDidRegistrar implements DidRegistrar {
didDocument = options.didDocument
const resolvedDocument = await this.resolver.resolve(didDocument.id)
didRecord = await didRepository.findCreatedDid(agentContext, didDocument.id)
// TODO: Add condition to check if did is deactivated
if (!resolvedDocument.didDocument || !didRecord) {
if (!resolvedDocument.didDocument || resolvedDocument.didDocumentMetadata.deactivated || !didRecord) {
return {
didDocumentMetadata: {},
didRegistrationMetadata: {},
Expand All @@ -122,6 +122,35 @@ export class PolygonDidRegistrar implements DidRegistrar {
},
}
}

if (options?.secret?.privateKey) {
const privateKey = options?.secret?.privateKey
if (privateKey && !isValidPrivateKey(privateKey, KeyType.K256)) {
return {
didDocumentMetadata: {},
didRegistrationMetadata: {},
didState: {
state: 'failed',
reason: 'Invalid private key provided',
},
}
}

const key = await agentContext.wallet.createKey({
keyType: KeyType.K256,
privateKey: privateKey,
})

const verificationMethodCount = didDocument?.verificationMethod?.length ?? 0

const verificationMethod = getEcdsaSecp256k1VerificationKey2019({
id: `${didDocument.id}#key-${verificationMethodCount + 1}`,
key,
controller: didDocument.id,
})

didDocument.verificationMethod = [...(didDocument?.verificationMethod ?? []), verificationMethod]
}
} else {
return {
didDocumentMetadata: {},
Expand All @@ -134,7 +163,14 @@ export class PolygonDidRegistrar implements DidRegistrar {
}

if (!didRecord) {
throw new AriesFrameworkError('')
return {
didDocumentMetadata: {},
didRegistrationMetadata: {},
didState: {
state: 'failed',
reason: 'DidRecord not found in wallet',
},
}
}

const publicKeyBase58 = await this.getPublicKeyFromDid(agentContext, options.did)
Expand Down Expand Up @@ -180,9 +216,71 @@ export class PolygonDidRegistrar implements DidRegistrar {
}
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async deactivate(agentContext: AgentContext, options: DidDeactivateOptions): Promise<DidDeactivateResult> {
throw new Error('Method not implemented.')
const didRepository = agentContext.dependencyManager.resolve(DidRepository)
const ledgerService = agentContext.dependencyManager.resolve(PolygonLedgerService)

const did = options.did

try {
const { didDocument, didDocumentMetadata } = await this.resolver.resolve(did)

const didRecord = await didRepository.findCreatedDid(agentContext, did)
if (!didDocument || didDocumentMetadata.deactivated || !didRecord) {
return {
didDocumentMetadata: {},
didRegistrationMetadata: {},
didState: {
state: 'failed',
reason: 'Did not found',
},
}
}

const publicKeyBase58 = await this.getPublicKeyFromDid(agentContext, options.did)

if (!publicKeyBase58) {
throw new AriesFrameworkError('Public Key not found in wallet')
}

const signingKey = await this.getSigningKey(agentContext.wallet, publicKeyBase58)

const didRegistry = ledgerService.createDidRegistryInstance(signingKey)

const updatedDidDocument = new DidDocumentBuilder(options.did).addContext('https://www.w3.org/ns/did/v1').build()

const response = await didRegistry.update(didDocument.id, updatedDidDocument)

if (!response) {
throw new AriesFrameworkError(`Unable to deactivate did document for did : ${did}`)
}

await didRepository.update(agentContext, didRecord)

return {
didDocumentMetadata: {
deactivated: true,
},
didRegistrationMetadata: {},
didState: {
state: 'finished',
did: didDocument.id,
didDocument: JsonTransformer.fromJSON(didDocument, DidDocument),
secret: options.secret,
},
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
agentContext.config.logger.error(`Error deactivating DID ${errorMessage}`)
return {
didDocumentMetadata: {},
didRegistrationMetadata: {},
didState: {
state: 'failed',
reason: `unknownError: ${errorMessage}`,
},
}
}
}

private async getSigningKey(wallet: Wallet, publicKeyBase58: string): Promise<SigningKey> {
Expand Down Expand Up @@ -237,4 +335,7 @@ export interface PolygonDidUpdateOptions extends DidUpdateOptions {
method: 'polygon'
did: string
didDocument: DidDocument
secret?: {
privateKey: Buffer
}
}
52 changes: 49 additions & 3 deletions src/dids/didPolygonUtil.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import type { DidCreateResult, DidDocument } from '@aries-framework/core'

import type { DidCreateResult, DidDocument, Key } from '@aries-framework/core'

import {
AriesFrameworkError,
DidDocumentBuilder,
DidDocumentService,
VERIFICATION_METHOD_TYPE_ECDSA_SECP256K1_VERIFICATION_KEY_2019,
getEcdsaSecp256k1VerificationKey2019,
} from '@aries-framework/core'
import { computeAddress } from 'ethers'

export const VERIFICATION_METHOD_TYPE_ECDSA_SECP256K1_VERIFICATION_KEY_2019 = 'EcdsaSecp256k1VerificationKey2019'
import { SECURITY_CONTEXT_SECP256k1_URL } from '../signature-suites/EcdsaSecp256k1Signature2019'

export const polygonDidRegex = new RegExp(/^did:polygon(:testnet)?:0x[0-9a-fA-F]{40}$/)

Expand All @@ -29,6 +36,45 @@ export function failedResult(reason: string): DidCreateResult {
}
}

export function getSecp256k1DidDoc(did: string, key: Key, serviceEndpoint?: string): DidDocument {
const verificationMethod = getEcdsaSecp256k1VerificationKey2019({
id: `${did}#key-1`,
key,
controller: did,
})

const didDocumentBuilder = new DidDocumentBuilder(did)
didDocumentBuilder.addContext(SECURITY_CONTEXT_SECP256k1_URL).addVerificationMethod(verificationMethod)

if (serviceEndpoint) {
const service = new DidDocumentService({
id: `${did}#linked-domain`,
serviceEndpoint,
type: 'LinkedDomains',
})

didDocumentBuilder.addService(service)
}

if (!key.supportsEncrypting && !key.supportsSigning) {
throw new AriesFrameworkError('Key must support at least signing or encrypting')
}

if (key.supportsSigning) {
didDocumentBuilder
.addAuthentication(verificationMethod.id)
.addAssertionMethod(verificationMethod.id)
.addCapabilityDelegation(verificationMethod.id)
.addCapabilityInvocation(verificationMethod.id)
}

if (key.supportsEncrypting) {
didDocumentBuilder.addKeyAgreement(verificationMethod.id)
}

return didDocumentBuilder.build()
}

export function validateSpecCompliantPayload(didDocument: DidDocument): string | null {
// id is required, validated on both compile and runtime
if (!didDocument.id && !didDocument.id.startsWith('did:polygon:')) return 'id is required'
Expand Down
5 changes: 3 additions & 2 deletions src/dids/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { PolygonDidResolver } from './PolygonDidResolver'
export { PolygonDidRegistrar } from './PolygonDidRegistrar'
export * from './PolygonDidRegistrar'
export * from './PolygonDidResolver'
export * from './didPolygonUtil'
2 changes: 1 addition & 1 deletion src/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { PolygonDID } from '@ayanworks/polygon-did-registrar'

export const generateSecp256k1KeyPair = async () => {
const { privateKey, publicKeyBase58, address } = await PolygonDID.createKeyPair()
const { privateKey, publicKeyBase58, address } = await PolygonDID.createKeyPair('testnet')
return { privateKey, publicKeyBase58, address }
}
35 changes: 11 additions & 24 deletions tests/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,39 +180,26 @@ export const EcdsaSecp256k1Signature2019Fixtures = {
export const PolygonDIDFixtures = {
VALID_DID_DOCUMENT: {
'@context': ['https://w3id.org/did/v1', 'https://w3id.org/security/suites/secp256k1-2019/v1'],
id: 'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771',
id: 'did:polygon:testnet:0x186f462430f90fee2b58609Dcf0539F08c400A72',
verificationMethod: [
{
id: 'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771#key-1',
id: 'did:polygon:testnet:0x186f462430f90fee2b58609Dcf0539F08c400A72#$key-1',
type: 'EcdsaSecp256k1VerificationKey2019',
controller: 'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771',
publicKeyBase58: 'ygG9PXu9eooJHivLv192iyY1mNQyU7nqeUqDpw6vwWum',
},
],
authentication: [
'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771',
{
id: 'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771#key-1',
type: 'EcdsaSecp256k1VerificationKey2019',
controller: 'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771',
publicKeyBase58: 'ygG9PXu9eooJHivLv192iyY1mNQyU7nqeUqDpw6vwWum',
},
],
assertionMethod: [
'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771',
{
id: 'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771#key-1',
type: 'EcdsaSecp256k1VerificationKey2019',
controller: 'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771',
publicKeyBase58: 'ygG9PXu9eooJHivLv192iyY1mNQyU7nqeUqDpw6vwWum',
controller: 'did:polygon:testnet:0x186f462430f90fee2b58609Dcf0539F08c400A72',
publicKeyBase58: 'uWa49bYNSW9JSdcYJbXRjYw2a5nFW8MLusUYjWKjKoay',
},
],
service: [
{
id: 'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771#linked-domain',
type: 'LinkedDomains',
id: 'did:polygon:testnet:0x186f462430f90fee2b58609Dcf0539F08c400A72#linked-domain',
serviceEndpoint: 'https://example.com',
type: 'LinkedDomains',
},
],
authentication: ['did:polygon:testnet:0x186f462430f90fee2b58609Dcf0539F08c400A72#$key-1'],
assertionMethod: ['did:polygon:testnet:0x186f462430f90fee2b58609Dcf0539F08c400A72#$key-1'],
keyAgreement: ['did:polygon:testnet:0x186f462430f90fee2b58609Dcf0539F08c400A72#$key-1'],
capabilityInvocation: ['did:polygon:testnet:0x186f462430f90fee2b58609Dcf0539F08c400A72#$key-1'],
capabilityDelegation: ['did:polygon:testnet:0x186f462430f90fee2b58609Dcf0539F08c400A72#$key-1'],
},
}
36 changes: 2 additions & 34 deletions tests/polygon-did.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
import type { EncryptedMessage } from '@aries-framework/core'

import { AskarModule } from '@aries-framework/askar'
import {
Agent,
ConsoleLogger,
DidDocument,
DidsModule,
JsonTransformer,
KeyType,
LogLevel,
TypedArrayEncoder,
utils,
} from '@aries-framework/core'
import { Agent, ConsoleLogger, DidsModule, KeyType, LogLevel, TypedArrayEncoder, utils } from '@aries-framework/core'
import { agentDependencies } from '@aries-framework/node'
import { ariesAskar } from '@hyperledger/aries-askar-nodejs'
import { Subject } from 'rxjs'
Expand All @@ -27,7 +17,7 @@ const logger = new ConsoleLogger(LogLevel.info)

export type SubjectMessage = { message: EncryptedMessage; replySubject?: Subject<SubjectMessage> }

const did = 'did:polygon:testnet:0x50e775B5c3050e8B2Cfa404C3dE95ab97E43e771'
const did = 'did:polygon:testnet:0x186f462430f90fee2b58609Dcf0539F08c400A72'

describe('Polygon Module did resolver', () => {
let aliceAgent: Agent<{ askar: AskarModule; polygon: PolygonModule; dids: DidsModule }>
Expand Down Expand Up @@ -142,27 +132,5 @@ describe('Polygon Module did resolver', () => {
expect(result.didDocument).toEqual(null)
expect(result.didResolutionMetadata.error).toEqual('notFound')
})

it('should update the DID doc when new DIDDoc is passed', async () => {
const didDocument = JsonTransformer.fromJSON(PolygonDIDFixtures.VALID_DID_DOCUMENT, DidDocument)

const response = await aliceAgent.dids.update({
did,
didDocument,
secret: {
privateKey: TypedArrayEncoder.fromHex('393a414a50885766089b0d33ddc22276e141a71a6a1dded4f224e67a0a43cc99'),
},
})

expect(response).toEqual({
didDocumentMetadata: {},
didRegistrationMetadata: {},
didState: {
state: 'finished',
did: didDocument.id,
didDocument,
},
})
})
})
})
Loading
Loading