@ayanworks/credo-polygon-w3c-module 2.0.0-alpha.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/PolygonApi.d.mts +53 -0
- package/build/PolygonApi.d.mts.map +1 -0
- package/build/PolygonApi.mjs +41 -0
- package/build/PolygonApi.mjs.map +1 -0
- package/build/PolygonModule.d.mts +14 -0
- package/build/PolygonModule.d.mts.map +1 -0
- package/build/PolygonModule.mjs +31 -0
- package/build/PolygonModule.mjs.map +1 -0
- package/build/PolygonModuleConfig.d.mts +28 -0
- package/build/PolygonModuleConfig.d.mts.map +1 -0
- package/build/PolygonModuleConfig.mjs +14 -0
- package/build/PolygonModuleConfig.mjs.map +1 -0
- package/build/_virtual/_@oxc-project_runtime@0.110.0/helpers/decorate.mjs +10 -0
- package/build/_virtual/_@oxc-project_runtime@0.110.0/helpers/decorateMetadata.mjs +7 -0
- package/build/_virtual/_@oxc-project_runtime@0.110.0/helpers/decorateParam.mjs +9 -0
- package/build/dids/PolygonDidRegistrar.d.mts +39 -0
- package/build/dids/PolygonDidRegistrar.d.mts.map +1 -0
- package/build/dids/PolygonDidRegistrar.mjs +260 -0
- package/build/dids/PolygonDidRegistrar.mjs.map +1 -0
- package/build/dids/PolygonDidResolver.d.mts +14 -0
- package/build/dids/PolygonDidResolver.d.mts.map +1 -0
- package/build/dids/PolygonDidResolver.mjs +38 -0
- package/build/dids/PolygonDidResolver.mjs.map +1 -0
- package/build/dids/didPolygonUtil.d.mts +2 -0
- package/build/dids/didPolygonUtil.mjs +64 -0
- package/build/dids/didPolygonUtil.mjs.map +1 -0
- package/build/dids/index.d.mts +3 -0
- package/build/dids/index.mjs +3 -0
- package/build/index.d.mts +10 -0
- package/build/index.mjs +11 -0
- package/build/ledger/PolygonLedgerService.d.mts +116 -0
- package/build/ledger/PolygonLedgerService.d.mts.map +1 -0
- package/build/ledger/PolygonLedgerService.mjs +172 -0
- package/build/ledger/PolygonLedgerService.mjs.map +1 -0
- package/build/ledger/index.d.mts +1 -0
- package/build/ledger/index.mjs +1 -0
- package/build/signature-suites/EcdsaSecp256k1Signature2019.mjs +117 -0
- package/build/signature-suites/EcdsaSecp256k1Signature2019.mjs.map +1 -0
- package/build/signature-suites/index.mjs +1 -0
- package/build/utils/index.d.mts +1 -0
- package/build/utils/index.mjs +1 -0
- package/build/utils/utils.d.mts +12 -0
- package/build/utils/utils.d.mts.map +1 -0
- package/build/utils/utils.mjs +39 -0
- package/build/utils/utils.mjs.map +1 -0
- package/package.json +26 -47
- package/README.md +0 -30
- package/build/PolygonApi.d.ts +0 -35
- package/build/PolygonApi.js +0 -42
- package/build/PolygonApi.js.map +0 -1
- package/build/PolygonModule.d.ts +0 -10
- package/build/PolygonModule.js +0 -31
- package/build/PolygonModule.js.map +0 -1
- package/build/PolygonModuleConfig.d.ts +0 -18
- package/build/PolygonModuleConfig.js +0 -14
- package/build/PolygonModuleConfig.js.map +0 -1
- package/build/dids/PolygonDidRegistrar.d.ts +0 -30
- package/build/dids/PolygonDidRegistrar.js +0 -267
- package/build/dids/PolygonDidRegistrar.js.map +0 -1
- package/build/dids/PolygonDidResolver.d.ts +0 -9
- package/build/dids/PolygonDidResolver.js +0 -40
- package/build/dids/PolygonDidResolver.js.map +0 -1
- package/build/dids/didPolygonUtil.d.ts +0 -7
- package/build/dids/didPolygonUtil.js +0 -98
- package/build/dids/didPolygonUtil.js.map +0 -1
- package/build/dids/index.d.ts +0 -3
- package/build/dids/index.js +0 -20
- package/build/dids/index.js.map +0 -1
- package/build/index.d.ts +0 -5
- package/build/index.js +0 -28
- package/build/index.js.map +0 -1
- package/build/ledger/PolygonLedgerService.d.ts +0 -87
- package/build/ledger/PolygonLedgerService.js +0 -210
- package/build/ledger/PolygonLedgerService.js.map +0 -1
- package/build/ledger/index.d.ts +0 -1
- package/build/ledger/index.js +0 -18
- package/build/ledger/index.js.map +0 -1
- package/build/signature-suites/EcdsaSecp256k1Signature2019.d.ts +0 -60
- package/build/signature-suites/EcdsaSecp256k1Signature2019.js +0 -126
- package/build/signature-suites/EcdsaSecp256k1Signature2019.js.map +0 -1
- package/build/signature-suites/index.d.ts +0 -1
- package/build/signature-suites/index.js +0 -18
- package/build/signature-suites/index.js.map +0 -1
- package/build/utils/index.d.ts +0 -1
- package/build/utils/index.js +0 -18
- package/build/utils/index.js.map +0 -1
- package/build/utils/utils.d.ts +0 -7
- package/build/utils/utils.js +0 -38
- package/build/utils/utils.js.map +0 -1
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { isValidPolygonDid } from "./didPolygonUtil.mjs";
|
|
2
|
+
import { DidDocument, JsonTransformer } from "@credo-ts/core";
|
|
3
|
+
import { getResolver } from "@ayanworks/polygon-did-resolver";
|
|
4
|
+
import { Resolver } from "did-resolver";
|
|
5
|
+
|
|
6
|
+
//#region src/dids/PolygonDidResolver.ts
|
|
7
|
+
var PolygonDidResolver = class {
|
|
8
|
+
constructor() {
|
|
9
|
+
this.allowsCaching = true;
|
|
10
|
+
this.supportedMethods = ["polygon"];
|
|
11
|
+
this.resolver = new Resolver(getResolver());
|
|
12
|
+
}
|
|
13
|
+
async resolve(agentContext, did) {
|
|
14
|
+
const didDocumentMetadata = {};
|
|
15
|
+
if (!isValidPolygonDid(did)) throw new Error("Invalid DID");
|
|
16
|
+
try {
|
|
17
|
+
const { didDocument, didDocumentMetadata, didResolutionMetadata } = await this.resolver.resolve(did);
|
|
18
|
+
return {
|
|
19
|
+
didDocument: JsonTransformer.fromJSON(didDocument, DidDocument),
|
|
20
|
+
didDocumentMetadata,
|
|
21
|
+
didResolutionMetadata
|
|
22
|
+
};
|
|
23
|
+
} catch (error) {
|
|
24
|
+
return {
|
|
25
|
+
didDocument: null,
|
|
26
|
+
didDocumentMetadata,
|
|
27
|
+
didResolutionMetadata: {
|
|
28
|
+
error: "notFound",
|
|
29
|
+
message: `resolver_error: Unable to resolve did '${did}': ${error}`
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
//#endregion
|
|
37
|
+
export { PolygonDidResolver };
|
|
38
|
+
//# sourceMappingURL=PolygonDidResolver.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PolygonDidResolver.mjs","names":[],"sources":["../../src/dids/PolygonDidResolver.ts"],"sourcesContent":["import { getResolver } from '@ayanworks/polygon-did-resolver'\nimport {\n type AgentContext,\n DidDocument,\n type DidResolutionResult,\n type DidResolver,\n JsonTransformer,\n} from '@credo-ts/core'\nimport type { ResolverRegistry } from 'did-resolver'\nimport { Resolver } from 'did-resolver'\n\nimport { isValidPolygonDid } from './didPolygonUtil'\n\nexport class PolygonDidResolver implements DidResolver {\n public readonly allowsCaching = true\n\n public readonly supportedMethods = ['polygon']\n\n public resolver: Resolver\n\n public constructor() {\n this.resolver = new Resolver(getResolver() as ResolverRegistry)\n }\n\n public async resolve(agentContext: AgentContext, did: string): Promise<DidResolutionResult> {\n const didDocumentMetadata = {}\n\n if (!isValidPolygonDid(did)) {\n throw new Error('Invalid DID')\n }\n try {\n const { didDocument, didDocumentMetadata, didResolutionMetadata } = await this.resolver.resolve(did)\n\n return {\n didDocument: JsonTransformer.fromJSON(didDocument, DidDocument),\n didDocumentMetadata,\n didResolutionMetadata,\n }\n } catch (error) {\n return {\n didDocument: null,\n didDocumentMetadata,\n didResolutionMetadata: {\n error: 'notFound',\n message: `resolver_error: Unable to resolve did '${did}': ${error}`,\n },\n }\n }\n }\n}\n"],"mappings":";;;;;;AAaA,IAAa,qBAAb,MAAuD;CAOrD,AAAO,cAAc;OANL,gBAAgB;OAEhB,mBAAmB,CAAC,UAAU;AAK5C,OAAK,WAAW,IAAI,SAAS,aAAa,CAAqB;;CAGjE,MAAa,QAAQ,cAA4B,KAA2C;EAC1F,MAAM,sBAAsB,EAAE;AAE9B,MAAI,CAAC,kBAAkB,IAAI,CACzB,OAAM,IAAI,MAAM,cAAc;AAEhC,MAAI;GACF,MAAM,EAAE,aAAa,qBAAqB,0BAA0B,MAAM,KAAK,SAAS,QAAQ,IAAI;AAEpG,UAAO;IACL,aAAa,gBAAgB,SAAS,aAAa,YAAY;IAC/D;IACA;IACD;WACM,OAAO;AACd,UAAO;IACL,aAAa;IACb;IACA,uBAAuB;KACrB,OAAO;KACP,SAAS,0CAA0C,IAAI,KAAK;KAC7D;IACF"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { SECURITY_CONTEXT_SECP256k1_URL } from "../signature-suites/EcdsaSecp256k1Signature2019.mjs";
|
|
2
|
+
import { DidDocumentBuilder, DidDocumentService, VERIFICATION_METHOD_TYPE_ECDSA_SECP256K1_VERIFICATION_KEY_2019, getEcdsaSecp256k1VerificationKey2019 } from "@credo-ts/core";
|
|
3
|
+
import { Secp256k1PublicJwk } from "@credo-ts/core/kms";
|
|
4
|
+
import { computeAddress } from "ethers";
|
|
5
|
+
|
|
6
|
+
//#region src/dids/didPolygonUtil.ts
|
|
7
|
+
/**
|
|
8
|
+
* Helper to create Secp256k1PublicJwk from base64url-encoded x and y coordinates.
|
|
9
|
+
* Uses compressed SEC1 format (33 bytes: prefix 02/03 + X coordinate).
|
|
10
|
+
*/
|
|
11
|
+
function createSecp256k1PublicJwk(publicJwk) {
|
|
12
|
+
const xBytes = Buffer.from(publicJwk.x, "base64url");
|
|
13
|
+
const yBytes = Buffer.from(publicJwk.y, "base64url");
|
|
14
|
+
const compressedKeyHex = (yBytes[yBytes.length - 1] % 2 === 0 ? "02" : "03") + xBytes.toString("hex");
|
|
15
|
+
return Secp256k1PublicJwk.fromPublicKey(Buffer.from(compressedKeyHex, "hex"));
|
|
16
|
+
}
|
|
17
|
+
const polygonDidRegex = /* @__PURE__ */ new RegExp(/^did:polygon(:testnet)?:0x[0-9a-fA-F]{40}$/);
|
|
18
|
+
const isValidPolygonDid = (did) => polygonDidRegex.test(did);
|
|
19
|
+
function buildDid(method, network, publicKey) {
|
|
20
|
+
const address = computeAddress(`0x${publicKey}`);
|
|
21
|
+
if (network === "mainnet") return `did:${method}:${address}`;
|
|
22
|
+
return `did:${method}:${network}:${address}`;
|
|
23
|
+
}
|
|
24
|
+
function getSecp256k1DidDoc(did, publicJwk, serviceEndpoint) {
|
|
25
|
+
const verificationMethod = getEcdsaSecp256k1VerificationKey2019({
|
|
26
|
+
id: `${did}#key-1`,
|
|
27
|
+
publicJwk,
|
|
28
|
+
controller: did
|
|
29
|
+
});
|
|
30
|
+
const didDocumentBuilder = new DidDocumentBuilder(did);
|
|
31
|
+
didDocumentBuilder.addContext(SECURITY_CONTEXT_SECP256k1_URL).addVerificationMethod(verificationMethod);
|
|
32
|
+
if (serviceEndpoint) {
|
|
33
|
+
const service = new DidDocumentService({
|
|
34
|
+
id: `${did}#linked-domain`,
|
|
35
|
+
serviceEndpoint,
|
|
36
|
+
type: "LinkedDomains"
|
|
37
|
+
});
|
|
38
|
+
didDocumentBuilder.addService(service);
|
|
39
|
+
}
|
|
40
|
+
didDocumentBuilder.addAuthentication(verificationMethod.id).addAssertionMethod(verificationMethod.id).addCapabilityDelegation(verificationMethod.id).addCapabilityInvocation(verificationMethod.id).addKeyAgreement(verificationMethod.id);
|
|
41
|
+
return didDocumentBuilder.build();
|
|
42
|
+
}
|
|
43
|
+
function validateSpecCompliantPayload(didDocument) {
|
|
44
|
+
if (!didDocument.id && !didDocument.id.startsWith("did:polygon:")) return "id is required";
|
|
45
|
+
if (!didDocument.verificationMethod) return "verificationMethod is required";
|
|
46
|
+
if (!Array.isArray(didDocument.verificationMethod)) return "verificationMethod must be an array";
|
|
47
|
+
if (!didDocument.verificationMethod.length) return "verificationMethod must be not be empty";
|
|
48
|
+
if (!didDocument.verificationMethod.every((vm) => {
|
|
49
|
+
switch (vm.type) {
|
|
50
|
+
case VERIFICATION_METHOD_TYPE_ECDSA_SECP256K1_VERIFICATION_KEY_2019: return vm?.publicKeyBase58 && vm?.controller && vm?.id;
|
|
51
|
+
default: return false;
|
|
52
|
+
}
|
|
53
|
+
})) return "verificationMethod is Invalid";
|
|
54
|
+
if (didDocument.service) {
|
|
55
|
+
if (!(didDocument.service ? didDocument?.service?.every((s) => {
|
|
56
|
+
return s?.serviceEndpoint && s?.id && s?.type;
|
|
57
|
+
}) : true)) return "Service is Invalid";
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
//#endregion
|
|
63
|
+
export { buildDid, createSecp256k1PublicJwk, getSecp256k1DidDoc, isValidPolygonDid, polygonDidRegex, validateSpecCompliantPayload };
|
|
64
|
+
//# sourceMappingURL=didPolygonUtil.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"didPolygonUtil.mjs","names":["Secp256k1PublicJwkClass"],"sources":["../../src/dids/didPolygonUtil.ts"],"sourcesContent":["import type { DidCreateResult, DidDocument } from '@credo-ts/core'\n\nimport {\n DidDocumentBuilder,\n DidDocumentService,\n getEcdsaSecp256k1VerificationKey2019,\n VERIFICATION_METHOD_TYPE_ECDSA_SECP256K1_VERIFICATION_KEY_2019,\n} from '@credo-ts/core'\nimport type { PublicJwk, Secp256k1PublicJwk } from '@credo-ts/core/kms'\nimport { Secp256k1PublicJwk as Secp256k1PublicJwkClass } from '@credo-ts/core/kms'\nimport { computeAddress } from 'ethers'\nimport { SECURITY_CONTEXT_SECP256k1_URL } from '../signature-suites/EcdsaSecp256k1Signature2019'\n\n/**\n * Helper to create Secp256k1PublicJwk from base64url-encoded x and y coordinates.\n * Uses compressed SEC1 format (33 bytes: prefix 02/03 + X coordinate).\n */\nexport function createSecp256k1PublicJwk(publicJwk: { x: string; y: string }): Secp256k1PublicJwk {\n const xBytes = Buffer.from(publicJwk.x, 'base64url')\n const yBytes = Buffer.from(publicJwk.y, 'base64url')\n const prefix = yBytes[yBytes.length - 1] % 2 === 0 ? '02' : '03'\n const compressedKeyHex = prefix + xBytes.toString('hex')\n\n return Secp256k1PublicJwkClass.fromPublicKey(Buffer.from(compressedKeyHex, 'hex'))\n}\n\nexport const polygonDidRegex = new RegExp(/^did:polygon(:testnet)?:0x[0-9a-fA-F]{40}$/)\n\nexport const isValidPolygonDid = (did: string) => polygonDidRegex.test(did)\n\nexport function buildDid(method: string, network: string, publicKey: string): string {\n const address = computeAddress(`0x${publicKey}`)\n\n if (network === 'mainnet') {\n return `did:${method}:${address}`\n }\n\n return `did:${method}:${network}:${address}`\n}\n\nexport function failedResult(reason: string): DidCreateResult {\n return {\n didDocumentMetadata: {},\n didRegistrationMetadata: {},\n didState: {\n state: 'failed',\n reason: reason,\n },\n }\n}\n\nexport function getSecp256k1DidDoc(\n did: string,\n publicJwk: PublicJwk<Secp256k1PublicJwk>,\n serviceEndpoint?: string\n): DidDocument {\n const verificationMethod = getEcdsaSecp256k1VerificationKey2019({\n id: `${did}#key-1`,\n publicJwk,\n controller: did,\n })\n\n const didDocumentBuilder = new DidDocumentBuilder(did)\n didDocumentBuilder.addContext(SECURITY_CONTEXT_SECP256k1_URL).addVerificationMethod(verificationMethod)\n\n if (serviceEndpoint) {\n const service = new DidDocumentService({\n id: `${did}#linked-domain`,\n serviceEndpoint,\n type: 'LinkedDomains',\n })\n didDocumentBuilder.addService(service)\n }\n\n didDocumentBuilder\n .addAuthentication(verificationMethod.id)\n .addAssertionMethod(verificationMethod.id)\n .addCapabilityDelegation(verificationMethod.id)\n .addCapabilityInvocation(verificationMethod.id)\n .addKeyAgreement(verificationMethod.id)\n\n return didDocumentBuilder.build()\n}\n\nexport function validateSpecCompliantPayload(didDocument: DidDocument): string | null {\n // id is required, validated on both compile and runtime\n if (!didDocument.id && !didDocument.id.startsWith('did:polygon:')) return 'id is required'\n\n // verificationMethod is required\n if (!didDocument.verificationMethod) return 'verificationMethod is required'\n\n // verificationMethod must be an array\n if (!Array.isArray(didDocument.verificationMethod)) return 'verificationMethod must be an array'\n\n // verificationMethod must be not be empty\n if (!didDocument.verificationMethod.length) return 'verificationMethod must be not be empty'\n\n // verificationMethod types must be supported\n const isValidVerificationMethod = didDocument.verificationMethod.every((vm) => {\n switch (vm.type) {\n case VERIFICATION_METHOD_TYPE_ECDSA_SECP256K1_VERIFICATION_KEY_2019:\n return vm?.publicKeyBase58 && vm?.controller && vm?.id\n default:\n return false\n }\n })\n\n if (!isValidVerificationMethod) return 'verificationMethod is Invalid'\n\n if (didDocument.service) {\n const isValidService = didDocument.service\n ? didDocument?.service?.every((s) => {\n return s?.serviceEndpoint && s?.id && s?.type\n })\n : true\n\n if (!isValidService) return 'Service is Invalid'\n }\n\n return null\n}\n"],"mappings":";;;;;;;;;;AAiBA,SAAgB,yBAAyB,WAAyD;CAChG,MAAM,SAAS,OAAO,KAAK,UAAU,GAAG,YAAY;CACpD,MAAM,SAAS,OAAO,KAAK,UAAU,GAAG,YAAY;CAEpD,MAAM,oBADS,OAAO,OAAO,SAAS,KAAK,MAAM,IAAI,OAAO,QAC1B,OAAO,SAAS,MAAM;AAExD,QAAOA,mBAAwB,cAAc,OAAO,KAAK,kBAAkB,MAAM,CAAC;;AAGpF,MAAa,kCAAkB,IAAI,OAAO,6CAA6C;AAEvF,MAAa,qBAAqB,QAAgB,gBAAgB,KAAK,IAAI;AAE3E,SAAgB,SAAS,QAAgB,SAAiB,WAA2B;CACnF,MAAM,UAAU,eAAe,KAAK,YAAY;AAEhD,KAAI,YAAY,UACd,QAAO,OAAO,OAAO,GAAG;AAG1B,QAAO,OAAO,OAAO,GAAG,QAAQ,GAAG;;AAcrC,SAAgB,mBACd,KACA,WACA,iBACa;CACb,MAAM,qBAAqB,qCAAqC;EAC9D,IAAI,GAAG,IAAI;EACX;EACA,YAAY;EACb,CAAC;CAEF,MAAM,qBAAqB,IAAI,mBAAmB,IAAI;AACtD,oBAAmB,WAAW,+BAA+B,CAAC,sBAAsB,mBAAmB;AAEvG,KAAI,iBAAiB;EACnB,MAAM,UAAU,IAAI,mBAAmB;GACrC,IAAI,GAAG,IAAI;GACX;GACA,MAAM;GACP,CAAC;AACF,qBAAmB,WAAW,QAAQ;;AAGxC,oBACG,kBAAkB,mBAAmB,GAAG,CACxC,mBAAmB,mBAAmB,GAAG,CACzC,wBAAwB,mBAAmB,GAAG,CAC9C,wBAAwB,mBAAmB,GAAG,CAC9C,gBAAgB,mBAAmB,GAAG;AAEzC,QAAO,mBAAmB,OAAO;;AAGnC,SAAgB,6BAA6B,aAAyC;AAEpF,KAAI,CAAC,YAAY,MAAM,CAAC,YAAY,GAAG,WAAW,eAAe,CAAE,QAAO;AAG1E,KAAI,CAAC,YAAY,mBAAoB,QAAO;AAG5C,KAAI,CAAC,MAAM,QAAQ,YAAY,mBAAmB,CAAE,QAAO;AAG3D,KAAI,CAAC,YAAY,mBAAmB,OAAQ,QAAO;AAYnD,KAAI,CAT8B,YAAY,mBAAmB,OAAO,OAAO;AAC7E,UAAQ,GAAG,MAAX;GACE,KAAK,+DACH,QAAO,IAAI,mBAAmB,IAAI,cAAc,IAAI;GACtD,QACE,QAAO;;GAEX,CAE8B,QAAO;AAEvC,KAAI,YAAY,SAOd;MAAI,EANmB,YAAY,UAC/B,aAAa,SAAS,OAAO,MAAM;AACjC,UAAO,GAAG,mBAAmB,GAAG,MAAM,GAAG;IACzC,GACF,MAEiB,QAAO;;AAG9B,QAAO"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { buildDid, createSecp256k1PublicJwk, getSecp256k1DidDoc, isValidPolygonDid, polygonDidRegex, validateSpecCompliantPayload } from "./didPolygonUtil.mjs";
|
|
2
|
+
import { PolygonDidRegistrar } from "./PolygonDidRegistrar.mjs";
|
|
3
|
+
import { PolygonDidResolver } from "./PolygonDidResolver.mjs";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { PolygonDidRegistrar } from "./dids/PolygonDidRegistrar.mjs";
|
|
2
|
+
import { PolygonDidResolver } from "./dids/PolygonDidResolver.mjs";
|
|
3
|
+
import "./dids/index.mjs";
|
|
4
|
+
import { PolygonModuleConfig, PolygonModuleConfigOptions } from "./PolygonModuleConfig.mjs";
|
|
5
|
+
import { PolygonLedgerService } from "./ledger/PolygonLedgerService.mjs";
|
|
6
|
+
import "./ledger/index.mjs";
|
|
7
|
+
import { PolygonModule } from "./PolygonModule.mjs";
|
|
8
|
+
import { generateSecp256k1KeyPair, getSecp256k1DidDocWithPublicKey } from "./utils/utils.mjs";
|
|
9
|
+
import "./utils/index.mjs";
|
|
10
|
+
export { PolygonDidRegistrar, PolygonDidResolver, PolygonLedgerService, PolygonModule, PolygonModuleConfig, type PolygonModuleConfigOptions, generateSecp256k1KeyPair, getSecp256k1DidDocWithPublicKey };
|
package/build/index.mjs
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { PolygonModuleConfig } from "./PolygonModuleConfig.mjs";
|
|
2
|
+
import { generateSecp256k1KeyPair, getSecp256k1DidDocWithPublicKey } from "./utils/utils.mjs";
|
|
3
|
+
import "./utils/index.mjs";
|
|
4
|
+
import { PolygonLedgerService } from "./ledger/PolygonLedgerService.mjs";
|
|
5
|
+
import "./ledger/index.mjs";
|
|
6
|
+
import { PolygonDidRegistrar } from "./dids/PolygonDidRegistrar.mjs";
|
|
7
|
+
import { PolygonDidResolver } from "./dids/PolygonDidResolver.mjs";
|
|
8
|
+
import "./dids/index.mjs";
|
|
9
|
+
import { PolygonModule } from "./PolygonModule.mjs";
|
|
10
|
+
|
|
11
|
+
export { PolygonDidRegistrar, PolygonDidResolver, PolygonLedgerService, PolygonModule, PolygonModuleConfig, generateSecp256k1KeyPair, getSecp256k1DidDocWithPublicKey };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { PolygonModuleConfig } from "../PolygonModuleConfig.mjs";
|
|
2
|
+
import { AgentContext, DidDocument } from "@credo-ts/core";
|
|
3
|
+
import { SigningKey } from "ethers";
|
|
4
|
+
import { PolygonDID } from "@ayanworks/polygon-did-registrar";
|
|
5
|
+
|
|
6
|
+
//#region src/ledger/PolygonLedgerService.d.ts
|
|
7
|
+
interface SchemaRegistryConfig {
|
|
8
|
+
didRegistrarContractAddress: string;
|
|
9
|
+
rpcUrl: string;
|
|
10
|
+
fileServerToken: string;
|
|
11
|
+
privateKey: string;
|
|
12
|
+
schemaManagerContractAddress: string;
|
|
13
|
+
serverUrl: string;
|
|
14
|
+
}
|
|
15
|
+
type CreateDidOperationOptions = {
|
|
16
|
+
operation: DidOperation.Create;
|
|
17
|
+
serviceEndpoint?: string;
|
|
18
|
+
};
|
|
19
|
+
type UpdateDidOperationOptions = {
|
|
20
|
+
operation: DidOperation.Update;
|
|
21
|
+
didDocument: DidDocument;
|
|
22
|
+
did: string;
|
|
23
|
+
};
|
|
24
|
+
type DeactivateDidOperationOptions = {
|
|
25
|
+
operation: DidOperation.Deactivate;
|
|
26
|
+
did: string;
|
|
27
|
+
};
|
|
28
|
+
type AddResourceDidOperationOptions = {
|
|
29
|
+
operation: DidOperation.AddResource;
|
|
30
|
+
resourceId: string;
|
|
31
|
+
resource: object;
|
|
32
|
+
did: string;
|
|
33
|
+
};
|
|
34
|
+
declare enum DidOperation {
|
|
35
|
+
Create = "createDID",
|
|
36
|
+
Update = "updateDIDDoc",
|
|
37
|
+
Deactivate = "deactivate",
|
|
38
|
+
AddResource = "addResource"
|
|
39
|
+
}
|
|
40
|
+
type DidOperationOptions = CreateDidOperationOptions | UpdateDidOperationOptions | DeactivateDidOperationOptions | AddResourceDidOperationOptions;
|
|
41
|
+
type SchemaOperationOptions = CreateSchemaOperationOptions;
|
|
42
|
+
type CreateSchemaOperationOptions = {
|
|
43
|
+
operation: SchemaOperation.CreateSchema;
|
|
44
|
+
did: string;
|
|
45
|
+
};
|
|
46
|
+
declare enum SchemaOperation {
|
|
47
|
+
CreateSchema = "createSchema"
|
|
48
|
+
}
|
|
49
|
+
declare class PolygonLedgerService {
|
|
50
|
+
rpcUrl: string | undefined;
|
|
51
|
+
private didContractAddress;
|
|
52
|
+
private schemaManagerContractAddress;
|
|
53
|
+
private fileServerToken;
|
|
54
|
+
private fileServerUrl;
|
|
55
|
+
constructor({
|
|
56
|
+
didContractAddress,
|
|
57
|
+
rpcUrl,
|
|
58
|
+
fileServerToken,
|
|
59
|
+
schemaManagerContractAddress,
|
|
60
|
+
serverUrl
|
|
61
|
+
}: PolygonModuleConfig);
|
|
62
|
+
createSchema(agentContext: AgentContext, {
|
|
63
|
+
did,
|
|
64
|
+
schemaName,
|
|
65
|
+
schema
|
|
66
|
+
}: {
|
|
67
|
+
did: string;
|
|
68
|
+
schemaName: string;
|
|
69
|
+
schema: object;
|
|
70
|
+
}): Promise<{
|
|
71
|
+
did: string;
|
|
72
|
+
schemaId: string;
|
|
73
|
+
schemaTxnHash: any;
|
|
74
|
+
resourceTxnHash: any;
|
|
75
|
+
tnxSchemaId?: undefined;
|
|
76
|
+
schemaTxhash?: undefined;
|
|
77
|
+
schemaState?: undefined;
|
|
78
|
+
} | {
|
|
79
|
+
tnxSchemaId: string;
|
|
80
|
+
schemaTxhash: string;
|
|
81
|
+
schemaState: {
|
|
82
|
+
state: string;
|
|
83
|
+
reason: string;
|
|
84
|
+
};
|
|
85
|
+
did?: undefined;
|
|
86
|
+
schemaId?: undefined;
|
|
87
|
+
schemaTxnHash?: undefined;
|
|
88
|
+
resourceTxnHash?: undefined;
|
|
89
|
+
}>;
|
|
90
|
+
getSchemaByDidAndSchemaId(agentContext: AgentContext, did: string, schemaId: string): Promise<any>;
|
|
91
|
+
estimateFeeForDidOperation(agentContext: AgentContext, options: DidOperationOptions): Promise<{
|
|
92
|
+
transactionFee: string;
|
|
93
|
+
gasLimit: string;
|
|
94
|
+
gasPrice: string;
|
|
95
|
+
maxFeePerGas: number;
|
|
96
|
+
maxPriorityFeePerGas: number;
|
|
97
|
+
network: string;
|
|
98
|
+
chainId: string;
|
|
99
|
+
method: string;
|
|
100
|
+
} | null | undefined>;
|
|
101
|
+
estimateFeeForSchemaOperation(agentContext: AgentContext, options: SchemaOperationOptions): Promise<{} | undefined>;
|
|
102
|
+
createDidRegistryInstance(signingKey: SigningKey): PolygonDID;
|
|
103
|
+
private createSchemaRegistryInstance;
|
|
104
|
+
private getSigningKey;
|
|
105
|
+
private getPublicKeyFromDid;
|
|
106
|
+
updateModuleConfig({
|
|
107
|
+
didRegistrarContractAddress,
|
|
108
|
+
fileServerToken,
|
|
109
|
+
rpcUrl,
|
|
110
|
+
schemaManagerContractAddress,
|
|
111
|
+
serverUrl
|
|
112
|
+
}: SchemaRegistryConfig): void;
|
|
113
|
+
}
|
|
114
|
+
//#endregion
|
|
115
|
+
export { AddResourceDidOperationOptions, CreateDidOperationOptions, CreateSchemaOperationOptions, DeactivateDidOperationOptions, DidOperation, DidOperationOptions, PolygonLedgerService, SchemaOperation, SchemaOperationOptions, UpdateDidOperationOptions };
|
|
116
|
+
//# sourceMappingURL=PolygonLedgerService.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PolygonLedgerService.d.mts","names":[],"sources":["../../src/ledger/PolygonLedgerService.ts"],"mappings":";;;;;;UASU,oBAAA;EACR,2BAAA;EACA,MAAA;EACA,eAAA;EACA,UAAA;EACA,4BAAA;EACA,SAAA;AAAA;AAAA,KAGU,yBAAA;EACV,SAAA,EAAW,YAAA,CAAa,MAAA;EACxB,eAAA;AAAA;AAAA,KAGU,yBAAA;EACV,SAAA,EAAW,YAAA,CAAa,MAAA;EACxB,WAAA,EAAa,WAAA;EACb,GAAA;AAAA;AAAA,KAGU,6BAAA;EACV,SAAA,EAAW,YAAA,CAAa,UAAA;EACxB,GAAA;AAAA;AAAA,KAGU,8BAAA;EACV,SAAA,EAAW,YAAA,CAAa,WAAA;EACxB,UAAA;EACA,QAAA;EACA,GAAA;AAAA;AAAA,aAGU,YAAA;EACV,MAAA;EACA,MAAA;EACA,UAAA;EACA,WAAA;AAAA;AAAA,KAGU,mBAAA,GACR,yBAAA,GACA,yBAAA,GACA,6BAAA,GACA,8BAAA;AAAA,KAEQ,sBAAA,GAAyB,4BAAA;AAAA,KAEzB,4BAAA;EACV,SAAA,EAAW,eAAA,CAAgB,YAAA;EAC3B,GAAA;AAAA;AAAA,aAGU,eAAA;EACV,YAAA;AAAA;AAAA,cAIW,oBAAA;EACJ,MAAA;EAAA,QACC,kBAAA;EAAA,QACA,4BAAA;EAAA,QACA,eAAA;EAAA,QACA,aAAA;;IAGN,kBAAA;IACA,MAAA;IACA,eAAA;IACA,4BAAA;IACA;EAAA,GACC,mBAAA;EAQU,YAAA,CACX,YAAA,EAAc,YAAA;IACZ,GAAA;IAAK,UAAA;IAAY;EAAA;IAAY,GAAA;IAAa,UAAA;IAAoB,MAAA;EAAA,IAAgB,OAAA;;;;;;;;;;;;;;;;;;;;EAuBrE,yBAAA,CAA0B,YAAA,EAAc,YAAA,EAAc,GAAA,UAAa,QAAA,WAAgB,OAAA;EAuBnF,0BAAA,CAA2B,YAAA,EAAc,YAAA,EAAc,OAAA,EAAS,mBAAA,GAAmB,OAAA;;;;;;;;;;EAsDnF,6BAAA,CAA8B,YAAA,EAAc,YAAA,EAAc,OAAA,EAAS,sBAAA,GAAsB,OAAA;EAkD/F,yBAAA,CAA0B,UAAA,EAAY,UAAA,GAAU,UAAA;EAAA,QAY/C,4BAAA;EAAA,QAqBM,aAAA;EAAA,QAmBA,mBAAA;EAiBP,kBAAA,CAAA;IACL,2BAAA;IACA,eAAA;IACA,MAAA;IACA,4BAAA;IACA;EAAA,GACC,oBAAA;AAAA"}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { PolygonModuleConfig } from "../PolygonModuleConfig.mjs";
|
|
2
|
+
import { generateSecp256k1KeyPair, getSecp256k1DidDocWithPublicKey } from "../utils/utils.mjs";
|
|
3
|
+
import "../utils/index.mjs";
|
|
4
|
+
import { __decorateMetadata } from "../_virtual/_@oxc-project_runtime@0.110.0/helpers/decorateMetadata.mjs";
|
|
5
|
+
import { __decorate } from "../_virtual/_@oxc-project_runtime@0.110.0/helpers/decorate.mjs";
|
|
6
|
+
import { CredoError, DidDocumentBuilder, DidRepository, injectable, utils } from "@credo-ts/core";
|
|
7
|
+
import { SigningKey } from "ethers";
|
|
8
|
+
import { AskarStoreManager } from "@credo-ts/askar";
|
|
9
|
+
import { PolygonDID } from "@ayanworks/polygon-did-registrar";
|
|
10
|
+
import { PolygonSchema } from "@ayanworks/polygon-schema-manager";
|
|
11
|
+
|
|
12
|
+
//#region src/ledger/PolygonLedgerService.ts
|
|
13
|
+
var _ref;
|
|
14
|
+
let DidOperation = /* @__PURE__ */ function(DidOperation) {
|
|
15
|
+
DidOperation["Create"] = "createDID";
|
|
16
|
+
DidOperation["Update"] = "updateDIDDoc";
|
|
17
|
+
DidOperation["Deactivate"] = "deactivate";
|
|
18
|
+
DidOperation["AddResource"] = "addResource";
|
|
19
|
+
return DidOperation;
|
|
20
|
+
}({});
|
|
21
|
+
let SchemaOperation = /* @__PURE__ */ function(SchemaOperation) {
|
|
22
|
+
SchemaOperation["CreateSchema"] = "createSchema";
|
|
23
|
+
return SchemaOperation;
|
|
24
|
+
}({});
|
|
25
|
+
let PolygonLedgerService = class PolygonLedgerService {
|
|
26
|
+
constructor({ didContractAddress, rpcUrl, fileServerToken, schemaManagerContractAddress, serverUrl }) {
|
|
27
|
+
this.rpcUrl = rpcUrl;
|
|
28
|
+
this.didContractAddress = didContractAddress;
|
|
29
|
+
this.schemaManagerContractAddress = schemaManagerContractAddress;
|
|
30
|
+
this.fileServerToken = fileServerToken;
|
|
31
|
+
this.fileServerUrl = serverUrl;
|
|
32
|
+
}
|
|
33
|
+
async createSchema(agentContext, { did, schemaName, schema }) {
|
|
34
|
+
const publicKeyBase58 = await this.getPublicKeyFromDid(agentContext, did);
|
|
35
|
+
if (!publicKeyBase58) throw new CredoError("Public Key not found in wallet");
|
|
36
|
+
const signingKey = await this.getSigningKey(agentContext, publicKeyBase58);
|
|
37
|
+
const schemaRegistry = this.createSchemaRegistryInstance(signingKey);
|
|
38
|
+
agentContext.config.logger.info(`Creating schema on ledger: ${did}`);
|
|
39
|
+
const response = await schemaRegistry.createSchema(did, schemaName, schema);
|
|
40
|
+
if (!response) {
|
|
41
|
+
agentContext.config.logger.error(`Schema creation failed for did: ${did} and schema: ${schema}`);
|
|
42
|
+
throw new CredoError(`Schema creation failed for did: ${did} and schema: ${schema}`);
|
|
43
|
+
}
|
|
44
|
+
agentContext.config.logger.info(`Published schema on ledger: ${did}`);
|
|
45
|
+
return response;
|
|
46
|
+
}
|
|
47
|
+
async getSchemaByDidAndSchemaId(agentContext, did, schemaId) {
|
|
48
|
+
agentContext.config.logger.info(`Getting schema from ledger: ${did} and schemaId: ${schemaId}`);
|
|
49
|
+
const publicKeyBase58 = await this.getPublicKeyFromDid(agentContext, did);
|
|
50
|
+
if (!publicKeyBase58) throw new CredoError("Public Key not found in wallet");
|
|
51
|
+
const signingKey = await this.getSigningKey(agentContext, publicKeyBase58);
|
|
52
|
+
const response = await this.createSchemaRegistryInstance(signingKey).getSchemaById(did, schemaId);
|
|
53
|
+
if (!response) {
|
|
54
|
+
agentContext.config.logger.error(`Schema not found for did: ${did} and schemaId: ${schemaId} Error: ${response}`);
|
|
55
|
+
throw new CredoError(`Schema not found for did: ${did} and schemaId: ${schemaId}`);
|
|
56
|
+
}
|
|
57
|
+
agentContext.config.logger.info(`Got schema from ledger: ${did} and schemaId: ${schemaId}`);
|
|
58
|
+
return response;
|
|
59
|
+
}
|
|
60
|
+
async estimateFeeForDidOperation(agentContext, options) {
|
|
61
|
+
const keyPair = await generateSecp256k1KeyPair();
|
|
62
|
+
const didRegistry = this.createDidRegistryInstance(new SigningKey(keyPair.privateKey));
|
|
63
|
+
const { operation } = options;
|
|
64
|
+
if (operation === DidOperation.Create) {
|
|
65
|
+
agentContext.config.logger.info(`Getting estimated fee for operation: ${operation} `);
|
|
66
|
+
const didDoc = getSecp256k1DidDocWithPublicKey(`did:polygon:testnet${keyPair.address}`, keyPair.publicKeyBase58, options?.serviceEndpoint);
|
|
67
|
+
return await didRegistry.estimateTxFee(DidOperation.Create, [keyPair.address, JSON.stringify(didDoc)]);
|
|
68
|
+
}
|
|
69
|
+
if (operation === DidOperation.Update) {
|
|
70
|
+
agentContext.config.logger.info(`Getting estimated fee for operation: ${operation} `);
|
|
71
|
+
const address = options.did.split(":").pop() || "";
|
|
72
|
+
return await didRegistry.estimateTxFee(DidOperation.Update, [address, JSON.stringify(options.didDocument)], address);
|
|
73
|
+
}
|
|
74
|
+
if (operation === DidOperation.Deactivate) {
|
|
75
|
+
agentContext.config.logger.info(`Getting estimated fee for operation: ${operation} `);
|
|
76
|
+
const address = options.did.split(":").pop() || "";
|
|
77
|
+
const deactivatedDidDocument = new DidDocumentBuilder(options.did).addContext("https://www.w3.org/ns/did/v1").build();
|
|
78
|
+
return await didRegistry.estimateTxFee(DidOperation.Update, [address, JSON.stringify(deactivatedDidDocument)], address);
|
|
79
|
+
}
|
|
80
|
+
if (operation === DidOperation.AddResource) {
|
|
81
|
+
agentContext.config.logger.info(`Getting estimated fee for operation: ${operation} `);
|
|
82
|
+
const address = options.did.split(":").pop() || "";
|
|
83
|
+
return await didRegistry.estimateTxFee(DidOperation.AddResource, [
|
|
84
|
+
address,
|
|
85
|
+
options.resourceId,
|
|
86
|
+
JSON.stringify(options.resource)
|
|
87
|
+
], address);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async estimateFeeForSchemaOperation(agentContext, options) {
|
|
91
|
+
const keyPair = await generateSecp256k1KeyPair();
|
|
92
|
+
const schemaRegistry = this.createSchemaRegistryInstance(new SigningKey(keyPair.privateKey));
|
|
93
|
+
const { operation } = options;
|
|
94
|
+
const testResourceBody = {
|
|
95
|
+
resourceURI: "did:polygon:testnet:0x13cd23928Ae515b86592C630f56C138aE4c7B79a/resources/398cee0a-efac-4643-9f4c-74c48c72a14b",
|
|
96
|
+
resourceCollectionId: "55dbc8bf-fba3-4117-855c-1e0dc1d3bb47",
|
|
97
|
+
resourceId: "398cee0a-efac-4643-9f4c-74c48c72a14b",
|
|
98
|
+
resourceName: "Eventbrite1 Logo",
|
|
99
|
+
resourceType: "W3C-schema",
|
|
100
|
+
mediaType: "image/svg+xml",
|
|
101
|
+
created: "2022-11-17T08:10:36Z",
|
|
102
|
+
checksum: "a95380f460e63ad939541a57aecbfd795fcd37c6d78ee86c885340e33a91b559",
|
|
103
|
+
previousVersionId: null,
|
|
104
|
+
nextVersionId: null
|
|
105
|
+
};
|
|
106
|
+
if (operation === SchemaOperation.CreateSchema) {
|
|
107
|
+
agentContext.config.logger.info(`Getting estimated fee for operation: ${operation} `);
|
|
108
|
+
const schemaEstimatedFee = await schemaRegistry.estimateTxFee(SchemaOperation.CreateSchema, [
|
|
109
|
+
keyPair.address,
|
|
110
|
+
utils.uuid(),
|
|
111
|
+
JSON.stringify(testResourceBody)
|
|
112
|
+
]);
|
|
113
|
+
const resourceEstimatedFee = await this.estimateFeeForDidOperation(agentContext, {
|
|
114
|
+
operation: DidOperation.AddResource,
|
|
115
|
+
resourceId: utils.uuid(),
|
|
116
|
+
resource: testResourceBody,
|
|
117
|
+
did: options.did
|
|
118
|
+
});
|
|
119
|
+
let feeParameters = {};
|
|
120
|
+
if (schemaEstimatedFee && resourceEstimatedFee) feeParameters = {
|
|
121
|
+
estimatedTotalTxFee: Number(schemaEstimatedFee.transactionFee) + Number(resourceEstimatedFee.transactionFee),
|
|
122
|
+
estimatedSchemaTxFee: schemaEstimatedFee,
|
|
123
|
+
estimatedResourceTxFee: resourceEstimatedFee
|
|
124
|
+
};
|
|
125
|
+
return feeParameters;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
createDidRegistryInstance(signingKey) {
|
|
129
|
+
if (!this.rpcUrl || !this.didContractAddress) throw new CredoError("Ledger config not found");
|
|
130
|
+
return new PolygonDID({
|
|
131
|
+
rpcUrl: this.rpcUrl,
|
|
132
|
+
contractAddress: this.didContractAddress,
|
|
133
|
+
signingKey
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
createSchemaRegistryInstance(signingKey) {
|
|
137
|
+
if (!this.rpcUrl || !this.schemaManagerContractAddress || !this.fileServerToken || !this.fileServerUrl || !this.didContractAddress) throw new CredoError("Polygon schema module config not found");
|
|
138
|
+
return new PolygonSchema({
|
|
139
|
+
rpcUrl: this.rpcUrl,
|
|
140
|
+
didRegistrarContractAddress: this.didContractAddress,
|
|
141
|
+
schemaManagerContractAddress: this.schemaManagerContractAddress,
|
|
142
|
+
fileServerToken: this.fileServerToken,
|
|
143
|
+
serverUrl: this.fileServerUrl,
|
|
144
|
+
signingKey
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
async getSigningKey(agentContext, publicKeyBase58) {
|
|
148
|
+
const keyEntry = await agentContext.dependencyManager.resolve(AskarStoreManager).withSession(agentContext, async (session) => await session.fetchKey({ name: publicKeyBase58 }));
|
|
149
|
+
if (!keyEntry) throw new CredoError("Key not found in wallet");
|
|
150
|
+
const signingKey = new SigningKey(keyEntry.key.secretBytes);
|
|
151
|
+
keyEntry.key.handle.free();
|
|
152
|
+
return signingKey;
|
|
153
|
+
}
|
|
154
|
+
async getPublicKeyFromDid(agentContext, did) {
|
|
155
|
+
const didRecord = await agentContext.dependencyManager.resolve(DidRepository).findCreatedDid(agentContext, did);
|
|
156
|
+
if (!didRecord) throw new CredoError("DidRecord not found");
|
|
157
|
+
if (!didRecord.didDocument?.verificationMethod) throw new CredoError("VerificationMethod not found cannot get public key");
|
|
158
|
+
return didRecord.didDocument.verificationMethod[0].publicKeyBase58;
|
|
159
|
+
}
|
|
160
|
+
updateModuleConfig({ didRegistrarContractAddress, fileServerToken, rpcUrl, schemaManagerContractAddress, serverUrl }) {
|
|
161
|
+
this.rpcUrl = rpcUrl;
|
|
162
|
+
this.didContractAddress = didRegistrarContractAddress;
|
|
163
|
+
this.schemaManagerContractAddress = schemaManagerContractAddress;
|
|
164
|
+
this.fileServerToken = fileServerToken;
|
|
165
|
+
this.fileServerUrl = serverUrl;
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
PolygonLedgerService = __decorate([injectable(), __decorateMetadata("design:paramtypes", [typeof (_ref = typeof PolygonModuleConfig !== "undefined" && PolygonModuleConfig) === "function" ? _ref : Object])], PolygonLedgerService);
|
|
169
|
+
|
|
170
|
+
//#endregion
|
|
171
|
+
export { DidOperation, PolygonLedgerService, SchemaOperation };
|
|
172
|
+
//# sourceMappingURL=PolygonLedgerService.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PolygonLedgerService.mjs","names":[],"sources":["../../src/ledger/PolygonLedgerService.ts"],"sourcesContent":["import { PolygonDID } from '@ayanworks/polygon-did-registrar'\nimport { PolygonSchema } from '@ayanworks/polygon-schema-manager'\nimport { AskarStoreManager } from '@credo-ts/askar'\nimport type { AgentContext, DidDocument } from '@credo-ts/core'\nimport { CredoError, DidDocumentBuilder, DidRepository, injectable, utils } from '@credo-ts/core'\nimport { SigningKey } from 'ethers'\nimport { PolygonModuleConfig } from '../PolygonModuleConfig'\nimport { generateSecp256k1KeyPair, getSecp256k1DidDocWithPublicKey } from '../utils'\n\ninterface SchemaRegistryConfig {\n didRegistrarContractAddress: string\n rpcUrl: string\n fileServerToken: string\n privateKey: string\n schemaManagerContractAddress: string\n serverUrl: string\n}\n\nexport type CreateDidOperationOptions = {\n operation: DidOperation.Create\n serviceEndpoint?: string\n}\n\nexport type UpdateDidOperationOptions = {\n operation: DidOperation.Update\n didDocument: DidDocument\n did: string\n}\n\nexport type DeactivateDidOperationOptions = {\n operation: DidOperation.Deactivate\n did: string\n}\n\nexport type AddResourceDidOperationOptions = {\n operation: DidOperation.AddResource\n resourceId: string\n resource: object\n did: string\n}\n\nexport enum DidOperation {\n Create = 'createDID',\n Update = 'updateDIDDoc',\n Deactivate = 'deactivate',\n AddResource = 'addResource',\n}\n\nexport type DidOperationOptions =\n | CreateDidOperationOptions\n | UpdateDidOperationOptions\n | DeactivateDidOperationOptions\n | AddResourceDidOperationOptions\n\nexport type SchemaOperationOptions = CreateSchemaOperationOptions\n\nexport type CreateSchemaOperationOptions = {\n operation: SchemaOperation.CreateSchema\n did: string\n}\n\nexport enum SchemaOperation {\n CreateSchema = 'createSchema',\n}\n\n@injectable()\nexport class PolygonLedgerService {\n public rpcUrl: string | undefined\n private didContractAddress: string | undefined\n private schemaManagerContractAddress: string | undefined\n private fileServerToken: string | undefined\n private fileServerUrl: string | undefined\n\n public constructor({\n didContractAddress,\n rpcUrl,\n fileServerToken,\n schemaManagerContractAddress,\n serverUrl,\n }: PolygonModuleConfig) {\n this.rpcUrl = rpcUrl\n this.didContractAddress = didContractAddress\n this.schemaManagerContractAddress = schemaManagerContractAddress\n this.fileServerToken = fileServerToken\n this.fileServerUrl = serverUrl\n }\n\n public async createSchema(\n agentContext: AgentContext,\n { did, schemaName, schema }: { did: string; schemaName: string; schema: object }\n ) {\n const publicKeyBase58 = await this.getPublicKeyFromDid(agentContext, did)\n\n if (!publicKeyBase58) {\n throw new CredoError('Public Key not found in wallet')\n }\n\n const signingKey = await this.getSigningKey(agentContext, publicKeyBase58)\n\n const schemaRegistry = this.createSchemaRegistryInstance(signingKey)\n\n agentContext.config.logger.info(`Creating schema on ledger: ${did}`)\n\n const response = await schemaRegistry.createSchema(did, schemaName, schema)\n if (!response) {\n agentContext.config.logger.error(`Schema creation failed for did: ${did} and schema: ${schema}`)\n throw new CredoError(`Schema creation failed for did: ${did} and schema: ${schema}`)\n }\n agentContext.config.logger.info(`Published schema on ledger: ${did}`)\n return response\n }\n\n public async getSchemaByDidAndSchemaId(agentContext: AgentContext, did: string, schemaId: string) {\n agentContext.config.logger.info(`Getting schema from ledger: ${did} and schemaId: ${schemaId}`)\n\n const publicKeyBase58 = await this.getPublicKeyFromDid(agentContext, did)\n\n if (!publicKeyBase58) {\n throw new CredoError('Public Key not found in wallet')\n }\n\n const signingKey = await this.getSigningKey(agentContext, publicKeyBase58)\n\n const schemaRegistry = this.createSchemaRegistryInstance(signingKey)\n\n const response = await schemaRegistry.getSchemaById(did, schemaId)\n\n if (!response) {\n agentContext.config.logger.error(`Schema not found for did: ${did} and schemaId: ${schemaId} Error: ${response}`)\n throw new CredoError(`Schema not found for did: ${did} and schemaId: ${schemaId}`)\n }\n agentContext.config.logger.info(`Got schema from ledger: ${did} and schemaId: ${schemaId}`)\n return response\n }\n\n public async estimateFeeForDidOperation(agentContext: AgentContext, options: DidOperationOptions) {\n const keyPair = await generateSecp256k1KeyPair()\n\n const didRegistry = this.createDidRegistryInstance(new SigningKey(keyPair.privateKey))\n\n const { operation } = options\n\n if (operation === DidOperation.Create) {\n agentContext.config.logger.info(`Getting estimated fee for operation: ${operation} `)\n const did = `did:polygon:testnet${keyPair.address}`\n const didDoc = getSecp256k1DidDocWithPublicKey(did, keyPair.publicKeyBase58, options?.serviceEndpoint)\n\n const response = await didRegistry.estimateTxFee(DidOperation.Create, [keyPair.address, JSON.stringify(didDoc)])\n return response\n }\n\n if (operation === DidOperation.Update) {\n agentContext.config.logger.info(`Getting estimated fee for operation: ${operation} `)\n const address = options.did.split(':').pop() || ''\n\n const response = await didRegistry.estimateTxFee(\n DidOperation.Update,\n [address, JSON.stringify(options.didDocument)],\n address\n )\n return response\n }\n\n if (operation === DidOperation.Deactivate) {\n agentContext.config.logger.info(`Getting estimated fee for operation: ${operation} `)\n const address = options.did.split(':').pop() || ''\n const deactivatedDidDocument = new DidDocumentBuilder(options.did)\n .addContext('https://www.w3.org/ns/did/v1')\n .build()\n const response = await didRegistry.estimateTxFee(\n DidOperation.Update,\n [address, JSON.stringify(deactivatedDidDocument)],\n address\n )\n return response\n }\n\n if (operation === DidOperation.AddResource) {\n agentContext.config.logger.info(`Getting estimated fee for operation: ${operation} `)\n const address = options.did.split(':').pop() || ''\n const response = await didRegistry.estimateTxFee(\n DidOperation.AddResource,\n [address, options.resourceId, JSON.stringify(options.resource)],\n address\n )\n return response\n }\n }\n\n public async estimateFeeForSchemaOperation(agentContext: AgentContext, options: SchemaOperationOptions) {\n const keyPair = await generateSecp256k1KeyPair()\n\n const schemaRegistry = this.createSchemaRegistryInstance(new SigningKey(keyPair.privateKey))\n\n const { operation } = options\n\n const testResourceBody = {\n resourceURI:\n 'did:polygon:testnet:0x13cd23928Ae515b86592C630f56C138aE4c7B79a/resources/398cee0a-efac-4643-9f4c-74c48c72a14b',\n resourceCollectionId: '55dbc8bf-fba3-4117-855c-1e0dc1d3bb47',\n resourceId: '398cee0a-efac-4643-9f4c-74c48c72a14b',\n resourceName: 'Eventbrite1 Logo',\n resourceType: 'W3C-schema',\n mediaType: 'image/svg+xml',\n created: '2022-11-17T08:10:36Z',\n checksum: 'a95380f460e63ad939541a57aecbfd795fcd37c6d78ee86c885340e33a91b559',\n previousVersionId: null,\n nextVersionId: null,\n }\n\n if (operation === SchemaOperation.CreateSchema) {\n agentContext.config.logger.info(`Getting estimated fee for operation: ${operation} `)\n const schemaEstimatedFee = await schemaRegistry.estimateTxFee(SchemaOperation.CreateSchema, [\n keyPair.address,\n utils.uuid(),\n JSON.stringify(testResourceBody),\n ])\n\n const resourceEstimatedFee = await this.estimateFeeForDidOperation(agentContext, {\n operation: DidOperation.AddResource,\n resourceId: utils.uuid(),\n resource: testResourceBody,\n did: options.did,\n })\n\n let feeParameters = {}\n\n if (schemaEstimatedFee && resourceEstimatedFee) {\n feeParameters = {\n estimatedTotalTxFee: Number(schemaEstimatedFee.transactionFee) + Number(resourceEstimatedFee.transactionFee),\n estimatedSchemaTxFee: schemaEstimatedFee,\n estimatedResourceTxFee: resourceEstimatedFee,\n }\n }\n\n return feeParameters\n }\n }\n\n public createDidRegistryInstance(signingKey: SigningKey) {\n if (!this.rpcUrl || !this.didContractAddress) {\n throw new CredoError('Ledger config not found')\n }\n\n return new PolygonDID({\n rpcUrl: this.rpcUrl,\n contractAddress: this.didContractAddress,\n signingKey,\n })\n }\n\n private createSchemaRegistryInstance(signingKey: SigningKey) {\n if (\n !this.rpcUrl ||\n !this.schemaManagerContractAddress ||\n !this.fileServerToken ||\n !this.fileServerUrl ||\n !this.didContractAddress\n ) {\n throw new CredoError('Polygon schema module config not found')\n }\n\n return new PolygonSchema({\n rpcUrl: this.rpcUrl,\n didRegistrarContractAddress: this.didContractAddress,\n schemaManagerContractAddress: this.schemaManagerContractAddress,\n fileServerToken: this.fileServerToken,\n serverUrl: this.fileServerUrl,\n signingKey,\n })\n }\n\n private async getSigningKey(agentContext: AgentContext, publicKeyBase58: string): Promise<SigningKey> {\n const askarStoreManager = agentContext.dependencyManager.resolve(AskarStoreManager)\n\n const keyEntry = await askarStoreManager.withSession(\n agentContext,\n async (session) => await session.fetchKey({ name: publicKeyBase58 })\n )\n\n if (!keyEntry) {\n throw new CredoError('Key not found in wallet')\n }\n\n const signingKey = new SigningKey(keyEntry.key.secretBytes)\n\n keyEntry.key.handle.free()\n\n return signingKey\n }\n\n private async getPublicKeyFromDid(agentContext: AgentContext, did: string) {\n const didRepository = agentContext.dependencyManager.resolve(DidRepository)\n\n const didRecord = await didRepository.findCreatedDid(agentContext, did)\n if (!didRecord) {\n throw new CredoError('DidRecord not found')\n }\n\n if (!didRecord.didDocument?.verificationMethod) {\n throw new CredoError('VerificationMethod not found cannot get public key')\n }\n\n const publicKeyBase58 = didRecord.didDocument.verificationMethod[0].publicKeyBase58\n\n return publicKeyBase58\n }\n\n public updateModuleConfig({\n didRegistrarContractAddress,\n fileServerToken,\n rpcUrl,\n schemaManagerContractAddress,\n serverUrl,\n }: SchemaRegistryConfig) {\n this.rpcUrl = rpcUrl\n this.didContractAddress = didRegistrarContractAddress\n this.schemaManagerContractAddress = schemaManagerContractAddress\n this.fileServerToken = fileServerToken\n this.fileServerUrl = serverUrl\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAyCA,IAAY,sDAAL;AACL;AACA;AACA;AACA;;;AAgBF,IAAY,4DAAL;AACL;;;AAIK,iCAAM,qBAAqB;CAOhC,AAAO,YAAY,EACjB,oBACA,QACA,iBACA,8BACA,aACsB;AACtB,OAAK,SAAS;AACd,OAAK,qBAAqB;AAC1B,OAAK,+BAA+B;AACpC,OAAK,kBAAkB;AACvB,OAAK,gBAAgB;;CAGvB,MAAa,aACX,cACA,EAAE,KAAK,YA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AO,YAAY,MAAM,QAAQ,SAAS,EAAE,MAAM,iBAAiB,CAAC,CACrE;AAED,MAAI,CAAC,SACH,OAAM,IAAI,WAAW,0BAA0B;EAGjD,MAAM,aAAa,IAAI,WAAW,SAAS,IAAI,YAAY;AAE3D,WAAS,IAAI,OAAO,MAAM;AAE1B,SAAO;;CAGT,MAAc,oBAAoB,cAA4B,KAAa;EAGzE,MAAM,YAAY,MAFI,aAAa,kBAAkB,QAAQ,cAAc,CAErC,eAAe,cAAc,IAAI;AACvE,MAAI,CAAC,UACH,OAAM,IAAI,WAAW,sBAAsB;AAG7C,MAAI,CAAC,UAAU,aAAa,mBAC1B,OAAM,IAAI,WAAW,qDAAqD;AAK5E,SAFwB,UAAU,YAAY,mBAAmB,GAAG;;CAKtE,AAAO,mBAAmB,EACxB,6BACA,iBACA,QACA,8BACA,aACuB;AACvB,OAAK,SAAS;AACd,OAAK,qBAAqB;AAC1B,OAAK,+BAA+B;AACpC,OAAK,kBAAkB;AACvB,OAAK,gBAAgB;;;mCA9PxB,YAAY"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { AddResourceDidOperationOptions, CreateDidOperationOptions, CreateSchemaOperationOptions, DeactivateDidOperationOptions, DidOperation, DidOperationOptions, PolygonLedgerService, SchemaOperation, SchemaOperationOptions, UpdateDidOperationOptions } from "./PolygonLedgerService.mjs";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { DidOperation, PolygonLedgerService, SchemaOperation } from "./PolygonLedgerService.mjs";
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { CREDENTIALS_CONTEXT_V1_URL, JwsLinkedDataSignature, SECURITY_CONTEXT_URL, vcLibraries } from "@credo-ts/core";
|
|
2
|
+
|
|
3
|
+
//#region src/signature-suites/EcdsaSecp256k1Signature2019.ts
|
|
4
|
+
const { jsonld } = vcLibraries;
|
|
5
|
+
const SECURITY_CONTEXT_SECP256k1_URL = "https://w3id.org/security/suites/secp256k1-2019/v1";
|
|
6
|
+
const _includesContext = (options) => {
|
|
7
|
+
const context = options.document["@context"];
|
|
8
|
+
return context === options.contextUrl || Array.isArray(context) && context.includes(options.contextUrl);
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* A secp256k1 signature suite for use with k251 key pairs
|
|
12
|
+
*/
|
|
13
|
+
var EcdsaSecp256k1Signature2019 = class extends JwsLinkedDataSignature {
|
|
14
|
+
/**
|
|
15
|
+
* @param {object} options - Options hashmap.
|
|
16
|
+
*
|
|
17
|
+
* Either a `key` OR at least one of `signer`/`verifier` is required.
|
|
18
|
+
*
|
|
19
|
+
* @param {object} [options.key] - An optional key object (containing an
|
|
20
|
+
* `id` property, and either `signer` or `verifier`, depending on the
|
|
21
|
+
* intended operation. Useful for when the application is managing keys
|
|
22
|
+
* itself (when using a KMS, you never have access to the private key,
|
|
23
|
+
* and so should use the `signer` param instead).
|
|
24
|
+
* @param {Function} [options.signer] - Signer function that returns an
|
|
25
|
+
* object with an async sign() method. This is useful when interfacing
|
|
26
|
+
* with a KMS (since you don't get access to the private key and its
|
|
27
|
+
* `signer()`, the KMS client gives you only the signer function to use).
|
|
28
|
+
* @param {Function} [options.verifier] - Verifier function that returns
|
|
29
|
+
* an object with an async `verify()` method. Useful when working with a
|
|
30
|
+
* KMS-provided verifier function.
|
|
31
|
+
*
|
|
32
|
+
* Advanced optional parameters and overrides.
|
|
33
|
+
*
|
|
34
|
+
* @param {object} [options.proof] - A JSON-LD document with options to use
|
|
35
|
+
* for the `proof` node. Any other custom fields can be provided here
|
|
36
|
+
* using a context different from security-v2).
|
|
37
|
+
* @param {string|Date} [options.date] - Signing date to use if not passed.
|
|
38
|
+
* @param {boolean} [options.useNativeCanonize] - Whether to use a native
|
|
39
|
+
* canonize algorithm.
|
|
40
|
+
*/
|
|
41
|
+
constructor(options) {
|
|
42
|
+
super({
|
|
43
|
+
type: "EcdsaSecp256k1Signature2019",
|
|
44
|
+
algorithm: "EcDSA",
|
|
45
|
+
LDKeyClass: options.LDKeyClass,
|
|
46
|
+
contextUrl: SECURITY_CONTEXT_SECP256k1_URL,
|
|
47
|
+
key: options.key,
|
|
48
|
+
proof: options.proof,
|
|
49
|
+
date: options.date,
|
|
50
|
+
useNativeCanonize: options.useNativeCanonize
|
|
51
|
+
});
|
|
52
|
+
this.requiredKeyType = "EcdsaSecp256k1VerificationKey2019";
|
|
53
|
+
}
|
|
54
|
+
async assertVerificationMethod(document) {
|
|
55
|
+
if (!_includesCompatibleContext({ document })) throw new TypeError(`The '@context' of the verification method (key) MUST contain the context url "${this.contextUrl}".`);
|
|
56
|
+
if (!_isSecp256k12019Key(document)) {
|
|
57
|
+
const verificationMethodType = jsonld.getValues(document, "type")[0];
|
|
58
|
+
throw new Error(`Unsupported verification method type '${verificationMethodType}'. Verification method type MUST be 'EcdsaSecp256k1VerificationKey2019'.`);
|
|
59
|
+
} else if (_isSecp256k12019Key(document) && !_includesSecp256k12019Context(document)) throw new Error(`For verification method type 'EcdsaSecp256k1VerificationKey2019' the '@context' MUST contain the context url "${SECURITY_CONTEXT_SECP256k1_URL}".`);
|
|
60
|
+
if (document.revoked !== void 0) throw new Error("The verification method has been revoked.");
|
|
61
|
+
}
|
|
62
|
+
async getVerificationMethod(options) {
|
|
63
|
+
return await super.getVerificationMethod({
|
|
64
|
+
proof: options.proof,
|
|
65
|
+
documentLoader: options.documentLoader
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Ensures the document to be signed contains the required signature suite
|
|
70
|
+
* specific `@context`, by either adding it (if `addSuiteContext` is true),
|
|
71
|
+
* or throwing an error if it's missing.
|
|
72
|
+
*
|
|
73
|
+
* @override
|
|
74
|
+
*
|
|
75
|
+
* @param {object} options - Options hashmap.
|
|
76
|
+
* @param {object} options.document - JSON-LD document to be signed.
|
|
77
|
+
* @param {boolean} options.addSuiteContext - Add suite context?
|
|
78
|
+
*/
|
|
79
|
+
ensureSuiteContext(options) {
|
|
80
|
+
if (_includesCompatibleContext({ document: options.document })) return;
|
|
81
|
+
super.ensureSuiteContext({
|
|
82
|
+
document: options.document,
|
|
83
|
+
addSuiteContext: options.addSuiteContext
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
EcdsaSecp256k1Signature2019.CONTEXT_URL = SECURITY_CONTEXT_SECP256k1_URL;
|
|
88
|
+
function _includesCompatibleContext(options) {
|
|
89
|
+
const hasSecp256k1 = _includesContext({
|
|
90
|
+
document: options.document,
|
|
91
|
+
contextUrl: SECURITY_CONTEXT_SECP256k1_URL
|
|
92
|
+
});
|
|
93
|
+
const hasCred = _includesContext({
|
|
94
|
+
document: options.document,
|
|
95
|
+
contextUrl: CREDENTIALS_CONTEXT_V1_URL
|
|
96
|
+
});
|
|
97
|
+
const hasSecV2 = _includesContext({
|
|
98
|
+
document: options.document,
|
|
99
|
+
contextUrl: SECURITY_CONTEXT_URL
|
|
100
|
+
});
|
|
101
|
+
if (hasSecp256k1 && hasCred) return false;
|
|
102
|
+
if (hasSecp256k1 && hasSecV2) return false;
|
|
103
|
+
return hasSecp256k1 || hasCred || hasSecV2;
|
|
104
|
+
}
|
|
105
|
+
function _isSecp256k12019Key(verificationMethod) {
|
|
106
|
+
return jsonld.hasValue(verificationMethod, "type", "EcdsaSecp256k1VerificationKey2019");
|
|
107
|
+
}
|
|
108
|
+
function _includesSecp256k12019Context(document) {
|
|
109
|
+
return _includesContext({
|
|
110
|
+
document,
|
|
111
|
+
contextUrl: SECURITY_CONTEXT_SECP256k1_URL
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
//#endregion
|
|
116
|
+
export { EcdsaSecp256k1Signature2019, SECURITY_CONTEXT_SECP256k1_URL, _includesContext };
|
|
117
|
+
//# sourceMappingURL=EcdsaSecp256k1Signature2019.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EcdsaSecp256k1Signature2019.mjs","names":[],"sources":["../../src/signature-suites/EcdsaSecp256k1Signature2019.ts"],"sourcesContent":["import type { DocumentLoader, JwsLinkedDataSignatureOptions, Proof } from '@credo-ts/core'\n\nimport { CREDENTIALS_CONTEXT_V1_URL, JwsLinkedDataSignature, SECURITY_CONTEXT_URL, vcLibraries } from '@credo-ts/core'\n\nconst { jsonld } = vcLibraries\n\nexport const SECURITY_CONTEXT_SECP256k1_URL = 'https://w3id.org/security/suites/secp256k1-2019/v1'\n\ntype EcdsaSecp256k1Signature2019Options = Pick<\n JwsLinkedDataSignatureOptions,\n 'key' | 'proof' | 'date' | 'useNativeCanonize' | 'LDKeyClass'\n>\n\nexport type JsonLdDoc = Record<string, unknown>\n\nexport const _includesContext = (options: { document: JsonLdDoc; contextUrl: string }) => {\n const context = options.document['@context']\n\n return context === options.contextUrl || (Array.isArray(context) && context.includes(options.contextUrl))\n}\n\n/**\n * A secp256k1 signature suite for use with k251 key pairs\n */\nexport class EcdsaSecp256k1Signature2019 extends JwsLinkedDataSignature {\n public static CONTEXT_URL = SECURITY_CONTEXT_SECP256k1_URL\n\n /**\n * @param {object} options - Options hashmap.\n *\n * Either a `key` OR at least one of `signer`/`verifier` is required.\n *\n * @param {object} [options.key] - An optional key object (containing an\n * `id` property, and either `signer` or `verifier`, depending on the\n * intended operation. Useful for when the application is managing keys\n * itself (when using a KMS, you never have access to the private key,\n * and so should use the `signer` param instead).\n * @param {Function} [options.signer] - Signer function that returns an\n * object with an async sign() method. This is useful when interfacing\n * with a KMS (since you don't get access to the private key and its\n * `signer()`, the KMS client gives you only the signer function to use).\n * @param {Function} [options.verifier] - Verifier function that returns\n * an object with an async `verify()` method. Useful when working with a\n * KMS-provided verifier function.\n *\n * Advanced optional parameters and overrides.\n *\n * @param {object} [options.proof] - A JSON-LD document with options to use\n * for the `proof` node. Any other custom fields can be provided here\n * using a context different from security-v2).\n * @param {string|Date} [options.date] - Signing date to use if not passed.\n * @param {boolean} [options.useNativeCanonize] - Whether to use a native\n * canonize algorithm.\n */\n public constructor(options: EcdsaSecp256k1Signature2019Options) {\n super({\n type: 'EcdsaSecp256k1Signature2019',\n algorithm: 'EcDSA',\n LDKeyClass: options.LDKeyClass,\n contextUrl: SECURITY_CONTEXT_SECP256k1_URL,\n key: options.key,\n proof: options.proof,\n date: options.date,\n useNativeCanonize: options.useNativeCanonize,\n })\n this.requiredKeyType = 'EcdsaSecp256k1VerificationKey2019'\n }\n\n public async assertVerificationMethod(document: JsonLdDoc) {\n if (!_includesCompatibleContext({ document: document })) {\n // For DID Documents, since keys do not have their own contexts,\n // the suite context is usually provided by the documentLoader logic\n throw new TypeError(\n `The '@context' of the verification method (key) MUST contain the context url \"${this.contextUrl}\".`\n )\n }\n\n if (!_isSecp256k12019Key(document)) {\n const verificationMethodType = jsonld.getValues(document, 'type')[0]\n throw new Error(\n `Unsupported verification method type '${verificationMethodType}'. Verification method type MUST be 'EcdsaSecp256k1VerificationKey2019'.`\n )\n } else if (_isSecp256k12019Key(document) && !_includesSecp256k12019Context(document)) {\n throw new Error(\n `For verification method type 'EcdsaSecp256k1VerificationKey2019' the '@context' MUST contain the context url \"${SECURITY_CONTEXT_SECP256k1_URL}\".`\n )\n }\n\n // ensure verification method has not been revoked\n if (document.revoked !== undefined) {\n throw new Error('The verification method has been revoked.')\n }\n }\n\n public async getVerificationMethod(options: { proof: Proof; documentLoader?: DocumentLoader }) {\n const verificationMethod = await super.getVerificationMethod({\n proof: options.proof,\n documentLoader: options.documentLoader,\n })\n\n return verificationMethod\n }\n\n /**\n * Ensures the document to be signed contains the required signature suite\n * specific `@context`, by either adding it (if `addSuiteContext` is true),\n * or throwing an error if it's missing.\n *\n * @override\n *\n * @param {object} options - Options hashmap.\n * @param {object} options.document - JSON-LD document to be signed.\n * @param {boolean} options.addSuiteContext - Add suite context?\n */\n public ensureSuiteContext(options: { document: JsonLdDoc; addSuiteContext: boolean }) {\n if (_includesCompatibleContext({ document: options.document })) {\n return\n }\n\n super.ensureSuiteContext({ document: options.document, addSuiteContext: options.addSuiteContext })\n }\n}\n\nfunction _includesCompatibleContext(options: { document: JsonLdDoc }) {\n // Handle the EcdsaSecp256k1Signature2019 / credentials/v1 collision\n const hasSecp256k1 = _includesContext({\n document: options.document,\n contextUrl: SECURITY_CONTEXT_SECP256k1_URL,\n })\n const hasCred = _includesContext({ document: options.document, contextUrl: CREDENTIALS_CONTEXT_V1_URL })\n const hasSecV2 = _includesContext({ document: options.document, contextUrl: SECURITY_CONTEXT_URL })\n\n if (hasSecp256k1 && hasCred) {\n // The secp256k1-2019/v1 and credentials/v1 contexts are incompatible.\n // For VCs using EcdsaSecp256k1Signature2019 suite using the credentials/v1 context is sufficient\n return false\n }\n\n if (hasSecp256k1 && hasSecV2) {\n // The secp256k1-2019/v1 and security/v2 contexts are incompatible.\n // For VCs using EcdsaSecp256k1Signature2019 suite, using the security/v2 context is sufficient.\n return false\n }\n\n // Either one by itself is fine, for this suite\n return hasSecp256k1 || hasCred || hasSecV2\n}\n\nfunction _isSecp256k12019Key(verificationMethod: JsonLdDoc) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-expect-error - .hasValue is not part of the public API\n return jsonld.hasValue(verificationMethod, 'type', 'EcdsaSecp256k1VerificationKey2019')\n}\n\nfunction _includesSecp256k12019Context(document: JsonLdDoc) {\n return _includesContext({ document, contextUrl: SECURITY_CONTEXT_SECP256k1_URL })\n}\n"],"mappings":";;;AAIA,MAAM,EAAE,WAAW;AAEnB,MAAa,iCAAiC;AAS9C,MAAa,oBAAoB,YAAyD;CACxF,MAAM,UAAU,QAAQ,SAAS;AAEjC,QAAO,YAAY,QAAQ,cAAe,MAAM,QAAQ,QAAQ,IAAI,QAAQ,SAAS,QAAQ,WAAW;;;;;AAM1G,IAAa,8BAAb,cAAiD,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BtE,AAAO,YAAY,SAA6C;AAC9D,QAAM;GACJ,MAAM;GACN,WAAW;GACX,YAAY,QAAQ;GACpB,YAAY;GACZ,KAAK,QAAQ;GACb,OAAO,QAAQ;GACf,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AAqB;AAC1D,QAAO,iBAAiB;EAAE;EAAU,YAAY;EAAgC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { EcdsaSecp256k1Signature2019, SECURITY_CONTEXT_SECP256k1_URL, _includesContext } from "./EcdsaSecp256k1Signature2019.mjs";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { generateSecp256k1KeyPair, getSecp256k1DidDocWithPublicKey } from "./utils.mjs";
|