├── .changeset └── config.json ├── .editorconfig ├── .eslintrc.json ├── .github └── workflows │ ├── cheqd-api-tests.yml │ ├── cheqd-modules-tests.yml │ ├── credential-sdk-tests.yml │ ├── docs.yml │ ├── examples.yml │ ├── lint.yml │ ├── npm-audit.yml │ └── npm-publish.yml ├── .gitignore ├── .jsdoc ├── LICENSE.md ├── README.md ├── babel.config.json ├── examples ├── CHANGELOG.md ├── README.md ├── package.json └── src │ ├── bbs-dock.js │ ├── blob.js │ ├── chain-ops.js │ ├── claim-deduction.js │ ├── dock-did.js │ ├── env.js │ ├── open-badges.js │ ├── resolver.js │ ├── schema-validation.js │ ├── schema.js │ ├── schemas │ ├── bol.js │ ├── health_worker_passport.js │ ├── immunity_event_record.js │ ├── infection_diagnosis.js │ ├── non_infection_check.js │ ├── pr_card.js │ ├── proof_of_health_core.js │ └── qp_inbond.js │ └── standard-schemas.js ├── package.json ├── packages ├── cheqd-blockchain-api │ ├── CHANGELOG.md │ ├── LICENSE │ ├── README.md │ ├── index.js │ ├── jest.config.js │ ├── package.json │ ├── rollup.config.mjs │ ├── src │ │ ├── api │ │ │ ├── gas.js │ │ │ ├── index.js │ │ │ └── type-url.js │ │ ├── index.js │ │ ├── multi-sender │ │ │ ├── api.js │ │ │ ├── index.js │ │ │ └── multi-sender.js │ │ ├── utils │ │ │ ├── index.js │ │ │ ├── transfer.js │ │ │ └── tx.js │ │ └── wallet │ │ │ └── index.js │ └── tests │ │ ├── constants.js │ │ ├── multi-sender.test.js │ │ └── test-environment.js ├── cheqd-blockchain-modules │ ├── .npmignore │ ├── CHANGELOG.md │ ├── LICENSE │ ├── README.md │ ├── index.js │ ├── jest.config.js │ ├── package.json │ ├── rollup.config.mjs │ ├── src │ │ ├── accumulator │ │ │ ├── internal.js │ │ │ └── module.js │ │ ├── attest │ │ │ ├── internal.js │ │ │ └── module.js │ │ ├── blob │ │ │ ├── internal.js │ │ │ ├── module.js │ │ │ └── types.js │ │ ├── common │ │ │ ├── create-internal-cheqd-module.js │ │ │ ├── index.js │ │ │ ├── inject-params.js │ │ │ ├── inject-public-keys.js │ │ │ ├── resource.js │ │ │ ├── with-cheqd.js │ │ │ ├── with-params.js │ │ │ └── with-public-keys.js │ │ ├── did │ │ │ ├── internal.js │ │ │ └── module.js │ │ ├── index.js │ │ ├── offchain-signatures │ │ │ ├── bbs-plus.js │ │ │ ├── bbs.js │ │ │ ├── internal.js │ │ │ ├── module.js │ │ │ └── ps.js │ │ └── status-list-credential │ │ │ ├── internal.js │ │ │ └── module.js │ └── tests │ │ ├── accumulator-module.test.js │ │ ├── attest-module.test.js │ │ ├── blob-module.test.js │ │ ├── common.js │ │ ├── did-module.test.js │ │ ├── env.js │ │ ├── offchain-signatures-module.test.js │ │ ├── status-list-credential-module.test.js │ │ └── test-environment.js └── credential-sdk │ ├── .npmignore │ ├── CHANGELOG.md │ ├── LICENSE │ ├── README.md │ ├── jest.config.js │ ├── package.json │ ├── rollup.config.mjs │ ├── src │ ├── crypto │ │ └── index.js │ ├── keypairs │ │ ├── did-keypair.js │ │ ├── dock-keypair.js │ │ ├── index.js │ │ ├── keypair-ed25519.js │ │ └── keypair-secp256k1.js │ ├── modules │ │ ├── abstract │ │ │ ├── accumulator │ │ │ │ ├── index.js │ │ │ │ └── module.js │ │ │ ├── anchor │ │ │ │ ├── errors.js │ │ │ │ ├── index.js │ │ │ │ └── module.js │ │ │ ├── attest │ │ │ │ ├── index.js │ │ │ │ └── module.js │ │ │ ├── blob │ │ │ │ ├── errors.js │ │ │ │ ├── index.js │ │ │ │ └── module.js │ │ │ ├── common │ │ │ │ ├── abstract-api-provider.js │ │ │ │ ├── abstract-base-module.js │ │ │ │ ├── index.js │ │ │ │ ├── with-abstract-params.js │ │ │ │ └── with-abstract-public-keys.js │ │ │ ├── did │ │ │ │ ├── errors.js │ │ │ │ ├── index.js │ │ │ │ └── module.js │ │ │ ├── index.js │ │ │ ├── offchain-signatures │ │ │ │ ├── index.js │ │ │ │ └── module.js │ │ │ ├── schema │ │ │ │ ├── index.js │ │ │ │ └── module.js │ │ │ ├── status-list-credential │ │ │ │ ├── index.js │ │ │ │ └── module.js │ │ │ └── trust-registry │ │ │ │ ├── index.js │ │ │ │ └── module.js │ │ ├── index.js │ │ ├── multi-api │ │ │ ├── accumulator.js │ │ │ ├── attest.js │ │ │ ├── blob.js │ │ │ ├── common.js │ │ │ ├── did.js │ │ │ ├── index.js │ │ │ ├── offchain-signatures.js │ │ │ ├── status-list-credential.js │ │ │ └── trust-registry.js │ │ └── tests │ │ │ ├── accumulator-module.js │ │ │ ├── attest-module.js │ │ │ ├── blob-module.js │ │ │ ├── common.js │ │ │ ├── did-module.js │ │ │ ├── index.js │ │ │ ├── offchain-signatures-module.js │ │ │ └── status-list-credential-module.js │ ├── rdf-and-cd │ │ ├── canonicalize.js │ │ ├── cd.js │ │ ├── claimgraph.js │ │ ├── common.js │ │ ├── crawl.js │ │ ├── index.js │ │ ├── rdf-defs.js │ │ └── rdf.js │ ├── resolver │ │ ├── blob │ │ │ ├── blob-resolver.js │ │ │ └── index.js │ │ ├── core-resolver.js │ │ ├── did │ │ │ ├── did-jwk-resolver.js │ │ │ ├── did-key-resolver.js │ │ │ ├── did-resolver-with-did-replacement.js │ │ │ ├── did-resolver.js │ │ │ ├── index.js │ │ │ └── universal-resolver.js │ │ ├── generic │ │ │ ├── const.js │ │ │ ├── helpers.js │ │ │ ├── index.js │ │ │ ├── resolver-router.js │ │ │ ├── resolver.js │ │ │ └── wildcard-resolver-router.js │ │ ├── index.js │ │ ├── status-list2021 │ │ │ ├── index.js │ │ │ └── status-list2021-resolver.js │ │ └── utils.js │ ├── types │ │ ├── accumulator │ │ │ ├── accumulator.js │ │ │ ├── counters.js │ │ │ ├── id.js │ │ │ ├── index.js │ │ │ ├── keys.js │ │ │ ├── params.js │ │ │ ├── public-key.js │ │ │ └── variants.js │ │ ├── anchor │ │ │ └── index.js │ │ ├── attest │ │ │ └── index.js │ │ ├── blob │ │ │ ├── blob.js │ │ │ ├── const.js │ │ │ ├── id.js │ │ │ └── index.js │ │ ├── did │ │ │ ├── document │ │ │ │ ├── const.js │ │ │ │ ├── ident-ref.js │ │ │ │ ├── index.js │ │ │ │ ├── service-endpoint.js │ │ │ │ ├── verification-method-ref-or-cheqd-verification-method.js │ │ │ │ ├── verification-method-ref-or-ident-ref.js │ │ │ │ ├── verification-method-ref.js │ │ │ │ ├── verification-method-type.js │ │ │ │ └── verification-method.js │ │ │ ├── index.js │ │ │ ├── offchain │ │ │ │ ├── doc-ref.js │ │ │ │ └── index.js │ │ │ └── onchain │ │ │ │ ├── constants.js │ │ │ │ ├── controllers.js │ │ │ │ ├── did-key.js │ │ │ │ ├── index.js │ │ │ │ ├── typed-did │ │ │ │ ├── cheqd-did.js │ │ │ │ ├── did-method-key │ │ │ │ │ ├── did-method-key-public-key.js │ │ │ │ │ ├── did-method-key-signature.js │ │ │ │ │ └── index.js │ │ │ │ ├── dock-did-value.js │ │ │ │ ├── index.js │ │ │ │ └── signature.js │ │ │ │ ├── verification-method-signature.js │ │ │ │ └── verification-relationship.js │ │ ├── generic │ │ │ ├── any-of.js │ │ │ ├── create-placeholder.js │ │ │ ├── index.js │ │ │ ├── option.js │ │ │ ├── sized.js │ │ │ ├── typed-array.js │ │ │ ├── typed-bytes-array.js │ │ │ ├── typed-bytes.js │ │ │ ├── typed-enum.js │ │ │ ├── typed-map.js │ │ │ ├── typed-null.js │ │ │ ├── typed-number.js │ │ │ ├── typed-set.js │ │ │ ├── typed-string.js │ │ │ ├── typed-struct.js │ │ │ ├── typed-tuple.js │ │ │ ├── typed-uuid.js │ │ │ ├── utils.js │ │ │ ├── with-base.js │ │ │ ├── with-base58.js │ │ │ ├── with-base58btc.js │ │ │ ├── with-base64.js │ │ │ ├── with-catch-null.js │ │ │ ├── with-eq.js │ │ │ ├── with-from-dock-id.js │ │ │ ├── with-from-json-bytes.js │ │ │ ├── with-from.js │ │ │ ├── with-null-if-not-a-variant.js │ │ │ ├── with-prop.js │ │ │ ├── with-props.js │ │ │ ├── with-qualifier.js │ │ │ └── without-prop.js │ │ ├── index.js │ │ ├── offchain-signatures │ │ │ ├── curve-type.js │ │ │ ├── index.js │ │ │ ├── params │ │ │ │ ├── id.js │ │ │ │ ├── index.js │ │ │ │ └── value.js │ │ │ └── public-keys │ │ │ │ ├── id.js │ │ │ │ ├── index.js │ │ │ │ ├── ref.js │ │ │ │ └── value.js │ │ ├── payload │ │ │ ├── cheqd.js │ │ │ └── index.js │ │ ├── policy │ │ │ ├── index.js │ │ │ └── one-of-policy-value.js │ │ ├── public-keys │ │ │ ├── index.js │ │ │ ├── public-key-ed25519-value.js │ │ │ ├── public-key-secp256k1-value.js │ │ │ ├── public-key-sr25519-value.js │ │ │ ├── public-key-x25519-value.js │ │ │ └── public-key.js │ │ ├── signatures │ │ │ ├── index.js │ │ │ ├── signature-ed25519-value.js │ │ │ ├── signature-secp256k1-value.js │ │ │ ├── signature-sr25519-value.js │ │ │ ├── signature-value.js │ │ │ └── signature.js │ │ ├── status-list-credential │ │ │ ├── id.js │ │ │ ├── index.js │ │ │ └── status-list-credential-value.js │ │ └── trust-registry │ │ │ ├── id.js │ │ │ ├── index.js │ │ │ ├── issuer.js │ │ │ ├── schema.js │ │ │ └── verifier.js │ ├── utils │ │ ├── assert.js │ │ ├── async │ │ │ ├── index.js │ │ │ ├── memoized-promise-map.js │ │ │ ├── memoized-promise.js │ │ │ ├── merge.js │ │ │ ├── retry.js │ │ │ └── timeout.js │ │ ├── encoding │ │ │ ├── base-58-btc.js │ │ │ ├── base-58.js │ │ │ ├── base-64.js │ │ │ ├── index.js │ │ │ └── ss-58.js │ │ ├── error.js │ │ ├── ident │ │ │ ├── ensure-ident.js │ │ │ ├── index.js │ │ │ ├── matchers.js │ │ │ └── parsers.js │ │ ├── index.js │ │ ├── inheritance.js │ │ ├── interfaces.js │ │ ├── json-fetch.js │ │ ├── mappings │ │ │ └── dock-did-by-id.js │ │ ├── pattern-matcher.js │ │ └── types │ │ │ ├── array.js │ │ │ ├── bigint.js │ │ │ ├── bytes.js │ │ │ ├── index.js │ │ │ ├── iterable.js │ │ │ ├── map.js │ │ │ ├── number.js │ │ │ ├── object.js │ │ │ ├── promise.js │ │ │ ├── set.js │ │ │ └── string.js │ └── vc │ │ ├── CredentialIssuancePurpose.js │ │ ├── constants.js │ │ ├── contexts.js │ │ ├── contexts │ │ ├── bbs-v1.json │ │ ├── credential-v1-updated.json │ │ ├── did-v1-updated.json │ │ ├── dock-bbdt16-v1.json │ │ ├── dock-bbs-v1.json │ │ ├── dock-bbs23-v1.json │ │ ├── dock-ps-v1.json │ │ ├── ed25519-2020-v1-context.json │ │ ├── jws-2020-v1.json │ │ ├── odrl.json │ │ ├── prettyvc.json │ │ ├── private-status-list-21.js │ │ ├── schema.json │ │ ├── security-v1.json │ │ ├── security_context.js │ │ ├── sphereon-wallet-identity-v1.json │ │ ├── sr25519-context.json │ │ ├── status-list-21.js │ │ └── vc-examples-v1.js │ │ ├── credentials.js │ │ ├── crypto │ │ ├── Bls12381BBDT16KeyPairDock2024.js │ │ ├── Bls12381BBDT16MACDock2024.js │ │ ├── Bls12381BBDT16MACProofDock2024.js │ │ ├── Bls12381BBSKeyPairDock2023.js │ │ ├── Bls12381BBSSignatureDock2022.js │ │ ├── Bls12381BBSSignatureDock2023.js │ │ ├── Bls12381BBSSignatureProofDock2022.js │ │ ├── Bls12381BBSSignatureProofDock2023.js │ │ ├── Bls12381BDDT16KeyPairDock2024.js │ │ ├── Bls12381BDDT16MACDock2024.js │ │ ├── Bls12381BDDT16MACProofDock2024.js │ │ ├── Bls12381G2KeyPairDock2022.js │ │ ├── Bls12381PSKeyPairDock2023.js │ │ ├── Bls12381PSSignatureDock2023.js │ │ ├── Bls12381PSSignatureProofDock2023.js │ │ ├── EcdsaSecp256k1Signature2019.js │ │ ├── EcdsaSecp256k1VerificationKey2019.js │ │ ├── Ed25519Signature2018.js │ │ ├── Ed25519Signature2020.js │ │ ├── Ed25519VerificationKey2018.js │ │ ├── Ed25519VerificationKey2020.js │ │ ├── JsonWebSignature2020.js │ │ ├── common │ │ │ ├── CustomLinkedDataSignature.js │ │ │ ├── DockCryptoKeyPair.js │ │ │ ├── DockCryptoSignature.js │ │ │ └── DockCryptoSignatureProof.js │ │ ├── constants.js │ │ └── index.js │ │ ├── document-loader.js │ │ ├── helpers.js │ │ ├── index.js │ │ ├── jws.js │ │ ├── presentation.js │ │ ├── presentations.js │ │ ├── private-status-list2021-credential.js │ │ ├── revocation.js │ │ ├── schema.js │ │ ├── schemas │ │ └── schema-draft-07.js │ │ ├── status-list2021-credential.js │ │ ├── verifiable-credential.js │ │ └── verifiable-presentation.js │ └── tests │ ├── __snapshots__ │ ├── did.test.js.snap │ ├── document.test.js.snap │ ├── pattern.test.js.snap │ ├── resolvers.test.js.snap │ └── utils.test.js.snap │ ├── base-x.test.js │ ├── canonicalize.test.js │ ├── claim-deduction.test.js │ ├── claimgraph.test.js │ ├── crawl.test.js │ ├── data │ ├── static-bbs-cred-610.json │ ├── static-bbs-cred-630.json │ ├── static-did-dock.json │ └── test-keys.js │ ├── did.test.js │ ├── document.test.js │ ├── ipfs │ ├── crawl.test.disabled.js │ └── ipfs.test.disabled.js │ ├── issuing.test.js │ ├── jwt-vc.test.js │ ├── keypairs.test.js │ ├── logic.test.js │ ├── mocks │ └── fetch.js │ ├── pattern.test.js │ ├── presigned-validation.test.js │ ├── rdf-turtle.test.js │ ├── resolvers.test.js │ ├── schema.test.js │ ├── serialize.test.js │ ├── setup-test-env.js │ ├── static-bbs.test.js │ ├── test-environment.js │ ├── types.test.js │ ├── utils.test.js │ └── utils │ ├── cached-document-loader.js │ ├── create-presentation.js │ ├── example-credential.js │ ├── example-schema.js │ ├── network-cache.js │ ├── test-keys.js │ └── type-helpers.test.js ├── scripts ├── bench │ ├── CHANGELOG.md │ ├── package.json │ └── src │ │ └── main.js ├── check-licenses.sh ├── cheqd_config.toml ├── cheqd_entrypoint ├── config ├── run_cheqd_node_in_docker ├── run_dock_node_in_docker ├── wait_for_node_rpc_http ├── with_all_dock_docker_test_nodes ├── with_cheqd_docker_test_node └── with_dock_docker_test_node ├── turbo.json ├── tutorials ├── .gitignore ├── README.md ├── book.toml └── src │ ├── SUMMARY.md │ ├── concepts.md │ ├── concepts_blobs_schemas.md │ ├── concepts_claim_deduction.md │ ├── concepts_did.md │ ├── concepts_poe_anchors.md │ ├── concepts_private_delegation.md │ ├── concepts_public_attestation.md │ ├── concepts_public_delegation.md │ ├── concepts_vcdm.md │ ├── introduction.md │ ├── tutorial_anoncreds.md │ ├── tutorial_blobs_schemas.md │ ├── tutorial_claim_deduction.md │ ├── tutorial_did.md │ ├── tutorial_ipv.md │ ├── tutorial_poe_anchors.md │ ├── tutorial_private_delegation.md │ ├── tutorial_public_delegation.md │ ├── tutorial_resolver.md │ ├── tutorial_revocation.md │ └── tutorials.md └── yarn.lock /.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@3.0.3/schema.json", 3 | "changelog": "@changesets/cli/changelog", 4 | "commit": false, 5 | "fixed": [], 6 | "linked": [], 7 | "access": "public", 8 | "baseBranch": "master", 9 | "updateInternalDependencies": "patch", 10 | "ignore": [] 11 | } 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.github/workflows/credential-sdk-tests.yml: -------------------------------------------------------------------------------- 1 | name: Credential SDK tests 2 | 3 | on: [pull_request] 4 | jobs: 5 | test: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | - uses: actions/setup-node@v1 10 | with: 11 | node-version: "20.x" 12 | - run: yarn install --frozen-lockfile --ignore-scripts 13 | - run: npm install -g turbo@2.0.5 14 | - run: turbo telemetry disable 15 | - run: turbo run test --filter @docknetwork/credential-sdk 16 | -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Documentation 2 | on: 3 | push: 4 | branches: 5 | - master 6 | 7 | jobs: 8 | build-and-deploy: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout 🛎️ 12 | uses: actions/checkout@v2 # If you're using actions/checkout@v2 you must set persist-credentials to false in most cases for the deployment to work correctly. 13 | with: 14 | persist-credentials: false 15 | 16 | - name: Setup Node JS 17 | uses: actions/setup-node@v1 18 | with: 19 | node-version: "20.x" 20 | 21 | - name: Install and Build 🔧 # Only need to install jsdoc package here and then run docs script 22 | run: | 23 | npm install -g turbo 24 | yarn install --frozen-lockfile --ignore-scripts 25 | turbo run docs 26 | 27 | - name: Setup mdBook 28 | uses: peaceiris/actions-mdbook@v1 29 | with: 30 | mdbook-version: "latest" 31 | 32 | - name: Generate mdBook 33 | run: yarn run mdbook 34 | 35 | - name: Install SSH Client 🔑 36 | uses: webfactory/ssh-agent@v0.4.1 37 | with: 38 | ssh-private-key: ${{ secrets.DEPLOY_KEY }} 39 | 40 | - name: Deploy 🚀 41 | uses: JamesIves/github-pages-deploy-action@releases/v3 42 | with: 43 | SSH: true 44 | BRANCH: gh-pages # The branch the action should deploy to. 45 | FOLDER: out # The folder the action should deploy. 46 | -------------------------------------------------------------------------------- /.github/workflows/examples.yml: -------------------------------------------------------------------------------- 1 | name: Examples 2 | 3 | on: [pull_request] 4 | jobs: 5 | testnet: 6 | runs-on: ubuntu-latest 7 | env: 8 | CHEQD_MNEMONIC: "steak come surprise obvious remain black trouble measure design volume retreat float coach amused match album moment radio stuff crack orphan ranch dose endorse" 9 | CHEQD_IMAGE_TAG: 3.1.5 10 | CHEQD_NETWORK: "testnet" 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions/setup-node@v1 14 | with: 15 | node-version: "20.x" 16 | - run: yarn install --frozen-lockfile --ignore-scripts 17 | - run: npm install -g turbo@2.0.5 18 | - run: turbo telemetry disable 19 | - run: CHEQD_MNEMONIC=$CHEQD_MNEMONIC CHEQD_IMAGE_TAG=$CHEQD_IMAGE_TAG CHEQD_NETWORK=$CHEQD_NETWORK turbo run examples-with-node 20 | 21 | mainnet: 22 | runs-on: ubuntu-latest 23 | env: 24 | CHEQD_MNEMONIC: "steak come surprise obvious remain black trouble measure design volume retreat float coach amused match album moment radio stuff crack orphan ranch dose endorse" 25 | CHEQD_IMAGE_TAG: 3.1.5 26 | CHEQD_NETWORK: "mainnet" 27 | steps: 28 | - uses: actions/checkout@v2 29 | - uses: actions/setup-node@v1 30 | with: 31 | node-version: "20.x" 32 | - run: yarn install --frozen-lockfile --ignore-scripts 33 | - run: npm install -g turbo@2.0.5 34 | - run: turbo telemetry disable 35 | - run: CHEQD_MNEMONIC=$CHEQD_MNEMONIC CHEQD_IMAGE_TAG=$CHEQD_IMAGE_TAG CHEQD_NETWORK=$CHEQD_NETWORK turbo run examples-with-node 36 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Linting and check docs generation 2 | on: [push, pull_request] 3 | jobs: 4 | lint: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Checkout 8 | uses: actions/checkout@v2 # If you're using actions/checkout@v2 you must set persist-credentials to false in most cases for the deployment to work correctly. 9 | with: 10 | persist-credentials: false 11 | 12 | - name: Setup node 13 | uses: actions/setup-node@v1 14 | with: 15 | node-version: "20.x" 16 | 17 | - name: Install, lint, type check and generate docs # Not uploading the docs. 18 | run: | 19 | yarn install --frozen-lockfile --ignore-scripts 20 | npm install -g turbo@2.0.5 21 | turbo run lint --parallel 22 | turbo run docs --parallel 23 | -------------------------------------------------------------------------------- /.github/workflows/npm-audit.yml: -------------------------------------------------------------------------------- 1 | name: npm audit 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | pull_request: 7 | branches: 8 | - master 9 | paths: 10 | - "yarn.lock" 11 | - ".github/workflows/**" 12 | 13 | schedule: 14 | - cron: "0 0 * * 0" # Every sunday at midnight 15 | 16 | jobs: 17 | audit: 18 | runs-on: ubuntu-latest 19 | env: 20 | NODE_VERSION: 20.x 21 | AVOID_LICENSES: "AGPL;GPL;AGPL-3.0" 22 | IGNORE_PACKAGES: "" 23 | 24 | steps: 25 | - name: Checkout 26 | uses: actions/checkout@v2 27 | with: 28 | persist-credentials: false 29 | - name: Use Node.js ${{ env.NODE_VERSION }} 30 | uses: actions/setup-node@v1 31 | with: 32 | node-version: ${{ env.NODE_VERSION }} 33 | 34 | - name: Install dependencies 35 | run: | 36 | yarn install --frozen-lockfile --ignore-scripts 37 | 38 | - name: Check licenses 39 | run: npx --yes license-checker --production --failOn "${{ env.AVOID_LICENSES }}" --excludePackages "${{ env.IGNORE_PACKAGES }}" 40 | 41 | - name: Run audit 42 | run: /bin/bash -c "(yarn audit --groups 'dependencies' --level critical; [[ $? -ge 16 ]] && exit 1 || exit 0)" 43 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | name: npm Publish 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | build-and-publish: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v1 12 | - uses: actions/setup-node@v1 13 | with: 14 | node-version: "20.x" 15 | registry-url: https://registry.npmjs.org/ 16 | - run: yarn install --frozen-lockfile --ignore-scripts 17 | - run: yarn changeset publish 18 | env: 19 | NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | _book/ 2 | build/ 3 | dist/ 4 | build-*/ 5 | coverage/ 6 | node_modules/ 7 | tmp/ 8 | out/ 9 | /import_map.json 10 | /mod.ts 11 | NOTES.md 12 | .zed 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | .npmrc 19 | .rpt2_cache 20 | .yarn/* 21 | .turbo* 22 | !.yarn/releases 23 | !.yarn/plugins 24 | .pnp.* 25 | .vscode/ 26 | .idea/ 27 | cc-test-reporter 28 | turbo-debug.log* 29 | npm-debug.log* 30 | package-lock.json 31 | tsconfig*buildinfo 32 | out/ 33 | *.log 34 | -------------------------------------------------------------------------------- /.jsdoc: -------------------------------------------------------------------------------- 1 | { 2 | "recurseDepth": 10, 3 | "source": { 4 | "includePattern": ".+\\.js(doc|x)?$", 5 | "excludePattern": "(^|\\/|\\\\)_" 6 | }, 7 | "sourceType": "module", 8 | "tags": { 9 | "allowUnknownTags": true, 10 | "dictionaries": ["jsdoc","closure"] 11 | }, 12 | "plugins": ["node_modules/jsdoc-typeof-plugin"], 13 | "templates": { 14 | "cleverLinks": false, 15 | "monospaceLinks": false 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2019 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /babel.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": ["@babel/plugin-transform-modules-commonjs"], 3 | "presets": [ 4 | [ 5 | "@babel/preset-env", 6 | { 7 | "targets": { 8 | "node": "current" 9 | } 10 | } 11 | ] 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | - Run example to create a new DID, register it, update its key and remove the DID. 4 | 5 | ```bash 6 | yarn dock-did-example 7 | ``` 8 | 9 | - Run example to resolve DID 10 | 11 | ```bash 12 | yarn did-resolver-example 13 | ``` 14 | 15 | - Run example to see revocation 16 | 17 | ```bash 18 | yarn revocation-example 19 | ``` 20 | 21 | - Run exbashample to see verifiable credentials 22 | 23 | ```bash 24 | yarn vcdm-example 25 | ``` 26 | -------------------------------------------------------------------------------- /examples/src/env.js: -------------------------------------------------------------------------------- 1 | import { DirectSecp256k1HdWallet } from '@docknetwork/cheqd-blockchain-api/wallet'; 2 | import { CheqdNetwork } from '@docknetwork/cheqd-blockchain-api'; 3 | 4 | export const faucet = { 5 | prefix: 'cheqd', 6 | minimalDenom: 'ncheq', 7 | mnemonic: 8 | process.env.CHEQD_MNEMONIC 9 | || 'steak come surprise obvious remain black trouble measure design volume retreat float coach amused match album moment radio stuff crack orphan ranch dose endorse', 10 | async wallet() { 11 | return await DirectSecp256k1HdWallet.fromMnemonic(this.mnemonic, { 12 | prefix: this.prefix, 13 | }); 14 | }, 15 | }; 16 | 17 | export const url = process.env.CHEQD_RPC_URL || 'http://localhost:26657'; 18 | export const network = process.env.CHEQD_NETWORK || CheqdNetwork.Testnet; 19 | -------------------------------------------------------------------------------- /examples/src/schema-validation.js: -------------------------------------------------------------------------------- 1 | import { Schema } from '@docknetwork/credential-sdk/modules/abstract/schema'; 2 | 3 | // BOL Schema, its valid 4 | import bolSchema from './schemas/bol.js'; 5 | 6 | // Invalid example schema 7 | const invalidSchema = { 8 | invalid: true, 9 | }; 10 | 11 | async function main() { 12 | // Run validation for example BOL schema 13 | console.log('Example schema should be valid:', bolSchema); 14 | 15 | // This method would throw an error if its invalid 16 | await Schema.validateSchema(bolSchema); 17 | 18 | // Run validation for invalid schema 19 | console.log('Example schema should be invalid:', invalidSchema); 20 | 21 | let success = false; 22 | try { 23 | // This method will throw an error as schema is invalid 24 | await Schema.validateSchema(invalidSchema); 25 | } catch (e) { 26 | success = true; 27 | console.log('As expected, schema validation failed with error:', e); 28 | } 29 | 30 | if (success === false) { 31 | throw new Error('Invalid schema passed validation, something went wrong!'); 32 | } 33 | } 34 | 35 | main() 36 | .then(() => { 37 | process.exit(0); 38 | }) 39 | .catch((error) => { 40 | console.error('Error occurred somewhere, it was caught!', error); 41 | process.exit(1); 42 | }); 43 | -------------------------------------------------------------------------------- /examples/src/schemas/immunity_event_record.js: -------------------------------------------------------------------------------- 1 | import proofOfHealthCoreSchema from './proof_of_health_core.js'; 2 | 3 | const schema = { 4 | $schema: 'http://json-schema.org/draft-07/schema#', 5 | description: 'Show if immunity by vaccination or testing', 6 | type: 'object', 7 | $defs: { 8 | uri: { 9 | type: 'string', 10 | format: 'uri', 11 | }, 12 | }, 13 | properties: { 14 | eventType: { 15 | type: 'string', 16 | enum: ['vaccination', 'antibody test'], 17 | }, 18 | eventTime: { 19 | type: 'string', 20 | format: 'date-time', 21 | }, 22 | eventBy: { 23 | type: 'string', 24 | }, 25 | eventFacility: { 26 | type: 'string', 27 | }, 28 | eventName: { 29 | type: 'string', 30 | enum: ['X-trans-23 vaccine', 'Serological Assay COVID-19'], 31 | }, 32 | potencyDate: { 33 | type: 'string', 34 | format: 'date', 35 | }, 36 | }, 37 | required: [ 38 | 'firstName', 39 | 'firstInitial', 40 | 'lastName', 41 | 'lastInitial', 42 | 'photo', 43 | 'biometricTemplate', 44 | 'yearOfBirth', 45 | 'eventType', 46 | 'eventTime', 47 | 'eventBy', 48 | 'eventFacility', 49 | 'eventName', 50 | 'potencyDate', 51 | ], 52 | }; 53 | 54 | // TODO: Use `$ref` instead. Some of the changes already done in other branch. 55 | const properties = { 56 | ...proofOfHealthCoreSchema.properties, 57 | ...schema.properties, 58 | }; 59 | schema.properties = properties; 60 | export default schema; 61 | -------------------------------------------------------------------------------- /examples/src/schemas/non_infection_check.js: -------------------------------------------------------------------------------- 1 | import proofOfHealthCoreSchema from './proof_of_health_core.js'; 2 | 3 | const schema = { 4 | $schema: 'http://json-schema.org/draft-07/schema#', 5 | description: 'Found virus free after testing', 6 | type: 'object', 7 | $defs: { 8 | uri: { 9 | type: 'string', 10 | format: 'uri', 11 | }, 12 | }, 13 | properties: { 14 | virus: { 15 | type: 'array', 16 | minItems: 1, 17 | items: { 18 | type: 'string', 19 | }, 20 | }, 21 | checkTime: { 22 | type: 'string', 23 | format: 'date-time', 24 | }, 25 | checkLocation: { 26 | type: 'string', 27 | }, 28 | checkedBy: { 29 | type: 'string', 30 | }, 31 | checkFacility: { 32 | type: 'string', 33 | }, 34 | diagnosisMethods: { 35 | type: 'array', 36 | minItems: 1, 37 | items: { 38 | type: 'string', 39 | }, 40 | }, 41 | }, 42 | required: [ 43 | 'firstName', 44 | 'firstInitial', 45 | 'lastName', 46 | 'lastInitial', 47 | 'photo', 48 | 'biometricTemplate', 49 | 'yearOfBirth', 50 | 'virus', 51 | 'checkTime', 52 | 'checkLocation', 53 | 'checkedBy', 54 | 'checkFacility', 55 | 'diagnosisMethods', 56 | ], 57 | }; 58 | 59 | // TODO: Use `$ref` instead. Some of the changes already done in other branch. 60 | const properties = { 61 | ...proofOfHealthCoreSchema.properties, 62 | ...schema.properties, 63 | }; 64 | schema.properties = properties; 65 | export default schema; 66 | -------------------------------------------------------------------------------- /examples/src/schemas/pr_card.js: -------------------------------------------------------------------------------- 1 | export default { 2 | $schema: 'http://json-schema.org/draft-07/schema#', 3 | description: 'Permanent Resident Card', 4 | type: 'object', 5 | $defs: { 6 | uri: { 7 | type: 'string', 8 | format: 'uri', 9 | }, 10 | }, 11 | properties: { 12 | id: { $ref: '#/$defs/uri' }, 13 | type: { 14 | type: 'array', 15 | items: { type: 'string' }, 16 | }, 17 | givenName: { 18 | type: 'string', 19 | }, 20 | familyName: { 21 | type: 'string', 22 | }, 23 | gender: { 24 | type: 'string', 25 | }, 26 | image: { $ref: '#/$defs/uri' }, 27 | lprCategory: { 28 | type: 'string', 29 | }, 30 | commuterClassification: { 31 | type: 'string', 32 | }, 33 | lprNumber: { 34 | type: 'string', 35 | }, 36 | residentSince: { 37 | type: 'string', 38 | format: 'date', 39 | }, 40 | birthDate: { 41 | type: 'string', 42 | format: 'date', 43 | }, 44 | }, 45 | required: [ 46 | 'id', 47 | 'type', 48 | 'givenName', 49 | 'familyName', 50 | 'gender', 51 | 'image', 52 | 'lprCategory', 53 | 'commuterClassification', 54 | 'lprNumber', 55 | 'residentSince', 56 | 'birthDate', 57 | ], 58 | }; 59 | -------------------------------------------------------------------------------- /examples/src/schemas/proof_of_health_core.js: -------------------------------------------------------------------------------- 1 | export default { 2 | $schema: 'http://json-schema.org/draft-07/schema#', 3 | description: 'Common fields of proof of health schemas', 4 | type: 'object', 5 | $defs: { 6 | uri: { 7 | type: 'string', 8 | format: 'uri', 9 | }, 10 | }, 11 | properties: { 12 | firstName: { 13 | type: 'string', 14 | }, 15 | firstInitial: { 16 | type: 'string', 17 | }, 18 | lastName: { 19 | type: 'string', 20 | }, 21 | lastInitial: { 22 | type: 'string', 23 | }, 24 | yearOfBirth: { 25 | type: 'integer', 26 | minimum: 1920, 27 | maximum: 2015, 28 | }, 29 | photo: { $ref: '#/$defs/uri' }, 30 | biometricTemplate: { 31 | type: 'object', 32 | minProperties: 1, 33 | properties: { 34 | fingerprint: { 35 | type: 'string', 36 | }, 37 | retina: { 38 | type: 'string', 39 | }, 40 | voice: { 41 | type: 'string', 42 | }, 43 | }, 44 | additionalProperties: false, 45 | }, 46 | }, 47 | required: [ 48 | 'firstName', 49 | 'firstInitial', 50 | 'lastName', 51 | 'lastInitial', 52 | 'photo', 53 | 'biometricTemplate', 54 | 'yearOfBirth', 55 | ], 56 | }; 57 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "root", 3 | "version": "0.51.0", 4 | "private": true, 5 | "workspaces": [ 6 | "packages/*", 7 | "examples", 8 | "scripts/migration", 9 | "scripts/bench" 10 | ], 11 | "dependencies": {}, 12 | "devDependencies": { 13 | "@babel/cli": "^7.24.1", 14 | "@babel/core": "^7.24.3", 15 | "@babel/node": "^7.23.9", 16 | "@babel/plugin-transform-modules-commonjs": "^7.24.1", 17 | "@babel/preset-env": "^7.24.3", 18 | "@changesets/cli": "^2.x.x", 19 | "turbo": "2.0.5" 20 | }, 21 | "packageManager": "yarn@1.22.22", 22 | "scripts": { 23 | "mdbook": "mdbook build tutorials --dest-dir ../out/tutorials", 24 | "publish-packages": "changeset version && changeset publish" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2019 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/README.md: -------------------------------------------------------------------------------- 1 | # @docknetwork/cheqd-blockchain-api 2 | 3 | This JavaScript library is developed on top of the `@cheqd/sdk` and provides a suite of tools and functionalities to seamlessly interact with the Cheqd blockchain. 4 | It simplifies the process of connecting with the Cheqd network, enabling developers to efficiently manage digital identities and verifiable credentials within decentralized ecosystems. 5 | 6 | ## Initialize 7 | 8 | ```javascript 9 | import { CheqdAPI } from "@docknetwork/cheqd-blockchain-api"; 10 | 11 | const cheqd = new CheqdAPI(); 12 | cheqd.init(...); 13 | ``` 14 | 15 | ## Use 16 | 17 | ```javascript 18 | import { CheqdCoreModules } from "@docknetwork/cheqd-blockchain-modules"; 19 | 20 | const modules = new CheqdCoreModules(cheqd); 21 | ... 22 | ``` 23 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/index.js: -------------------------------------------------------------------------------- 1 | module.exports = require("./dist/cjs/index.cjs"); 2 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/jest.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | bail: true, 3 | moduleNameMapper: { 4 | "^@docknetwork/credential-sdk/(.*)$": 5 | "/../credential-sdk/dist/esm/$1", 6 | "^@cheqd/sdk(.*)$": "/../../node_modules/@cheqd/sdk/build/cjs/$1", 7 | "^uint8arrays$": "/../../node_modules/uint8arrays/dist/src", 8 | "^file-type$": "/../../node_modules/file-type/index.js", 9 | "^multiformats/(.*)$": 10 | "/../../node_modules/multiformats/dist/src/$1", 11 | }, 12 | clearMocks: true, 13 | testTimeout: 30000, 14 | testEnvironment: "./tests/test-environment", 15 | transform: { 16 | "^.+\\.(ts|js)$": ["babel-jest", { rootMode: "upward" }], 17 | }, 18 | transformIgnorePatterns: [ 19 | "/node_modules/(?!@polkadot|@babel|multiformats|@docknetwork|@stablelib|@cheqd|file-type|uint8arrays|multiformats|strtok3|peek-readable|token-types|uint8array-extra|p-limit|yocto-queue)", 20 | ], 21 | workerIdleMemoryLimit: "1G", 22 | verbose: true, 23 | globals: { 24 | Uint8Array, 25 | Uint32Array, 26 | ArrayBuffer, 27 | TextDecoder, 28 | TextEncoder, 29 | Buffer, 30 | }, 31 | }; 32 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/rollup.config.mjs: -------------------------------------------------------------------------------- 1 | import json from "@rollup/plugin-json"; 2 | import multiInput from "rollup-plugin-multi-input"; 3 | import commonjs from "@rollup/plugin-commonjs"; 4 | import { terser } from "rollup-plugin-terser"; 5 | // import { wasm } from '@rollup/plugin-wasm'; 6 | // import pkg from './package.json'; 7 | 8 | export default async function () { 9 | return [ 10 | { 11 | plugins: [ 12 | multiInput(), 13 | json(), 14 | // terser(), 15 | commonjs(), 16 | // Temporarily disabled, not sure if required 17 | // since rify is a node module doesnt seem to work 18 | // but would be nice to try embed it 19 | // wasm({ 20 | // sync: ['*.wasm'], 21 | // }), 22 | ], 23 | input: ["src/**/*.js"], 24 | output: [ 25 | { 26 | sourcemap: true, 27 | dir: "dist/esm", 28 | format: "esm", 29 | entryFileNames: "[name].js", 30 | }, 31 | { 32 | sourcemap: true, 33 | dir: "dist/cjs", 34 | format: "cjs", 35 | entryFileNames: "[name].cjs", 36 | }, 37 | ], 38 | }, 39 | ]; 40 | } 41 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/src/index.js: -------------------------------------------------------------------------------- 1 | export * from './api'; 2 | export { sendNcheq } from './utils'; 3 | export { CheqdMultiSenderAPI } from './multi-sender'; 4 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/src/multi-sender/api.js: -------------------------------------------------------------------------------- 1 | import { CheqdAPI } from '../api'; 2 | import MultiSender from './multi-sender'; 3 | 4 | export default class CheqdMultiSenderAPI extends CheqdAPI { 5 | constructor(params) { 6 | super(); 7 | 8 | this.sender = new MultiSender({ ...params, api: this }); 9 | } 10 | 11 | async init(...args) { 12 | await super.init(...args); 13 | await this.sender.init(...args); 14 | 15 | return this; 16 | } 17 | 18 | async disconnect() { 19 | await this.sender.shutdown(); 20 | await super.disconnect(); 21 | 22 | return this; 23 | } 24 | 25 | async signAndSend(...args) { 26 | return await this.sender.signAndSend(...args); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/src/multi-sender/index.js: -------------------------------------------------------------------------------- 1 | export { default as MultiSender } from './multi-sender'; 2 | export { default as CheqdMultiSenderAPI } from './api'; 3 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/src/utils/index.js: -------------------------------------------------------------------------------- 1 | export * from './transfer'; 2 | export * from './tx'; 3 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/src/utils/tx.js: -------------------------------------------------------------------------------- 1 | import { u8aToHex, normalizeToU8a } from '@docknetwork/credential-sdk/utils'; 2 | import { sha256 } from 'js-sha256'; 3 | 4 | /** 5 | * Calculates a hash for the signed transaction. 6 | * 7 | * @param {Uint8Array} signedTx 8 | * @returns {string} 9 | */ 10 | export const signedTxHash = (bytes) => u8aToHex(sha256.digest(normalizeToU8a(bytes))) 11 | .slice(2) 12 | .toUpperCase(); 13 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/src/wallet/index.js: -------------------------------------------------------------------------------- 1 | export * from '@cosmjs/proto-signing'; 2 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/tests/constants.js: -------------------------------------------------------------------------------- 1 | import { DirectSecp256k1HdWallet } from "../src/wallet"; 2 | import { CheqdNetwork } from "../src"; 3 | 4 | export const faucet = { 5 | prefix: "cheqd", 6 | minimalDenom: "ncheq", 7 | mnemonic: 8 | process.env.CHEQD_MNEMONIC || 9 | "steak come surprise obvious remain black trouble measure design volume retreat float coach amused match album moment radio stuff crack orphan ranch dose endorse", 10 | async wallet() { 11 | return await DirectSecp256k1HdWallet.fromMnemonic(this.mnemonic, { 12 | prefix: this.prefix, 13 | }); 14 | }, 15 | }; 16 | 17 | export const url = process.env.CHEQD_RPC_URL || "http://localhost:26657"; 18 | export const network = process.env.CHEQD_NETWORK || CheqdNetwork.Testnet; 19 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-api/tests/test-environment.js: -------------------------------------------------------------------------------- 1 | import { TestEnvironment as NodeEnvironment } from "jest-environment-node"; 2 | 3 | class MyEnvironment extends NodeEnvironment { 4 | constructor(config, context) { 5 | super( 6 | { 7 | ...config, 8 | globals: { 9 | ...config.globals, 10 | Uint32Array, 11 | Uint8Array, 12 | ArrayBuffer, 13 | TextDecoder, 14 | TextEncoder, 15 | Buffer, 16 | }, 17 | }, 18 | context 19 | ); 20 | } 21 | 22 | async setup() {} 23 | 24 | async teardown() {} 25 | } 26 | 27 | export default MyEnvironment; 28 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/.npmignore: -------------------------------------------------------------------------------- 1 | src/ 2 | scripts/ 3 | jest.config.js 4 | rollup.config.mjs 5 | out/ 6 | node_modules/ 7 | .vscode/ 8 | .turbo/ 9 | tests/ 10 | *.log 11 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2019 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/index.js: -------------------------------------------------------------------------------- 1 | module.exports = require("./dist/cjs/index.cjs"); 2 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/jest.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | bail: true, 3 | moduleNameMapper: { 4 | "^@docknetwork/credential-sdk/(.*)$": 5 | "/../credential-sdk/dist/esm/$1", 6 | "^@docknetwork/cheqd-blockchain-api/(.*)$": 7 | "/../cheqd-blockchain-api/dist/esm/$1", 8 | "^@docknetwork/cheqd-blockchain-api$": 9 | "/../cheqd-blockchain-api/dist/esm/index.js", 10 | "^@cheqd/sdk(.*)$": "/../../node_modules/@cheqd/sdk/build/cjs/$1", 11 | "^uint8arrays$": "/../../node_modules/uint8arrays/dist/src", 12 | "^file-type$": "/../../node_modules/file-type/index.js", 13 | "^multiformats/(.*)$": 14 | "/../../node_modules/multiformats/dist/src/$1", 15 | }, 16 | clearMocks: true, 17 | testTimeout: 30000, 18 | testEnvironment: "./tests/test-environment", 19 | transform: { 20 | "^.+\\.(ts|js)$": ["babel-jest", { rootMode: "upward" }], 21 | }, 22 | transformIgnorePatterns: [ 23 | "/node_modules/(?!@polkadot|@babel|multiformats|@docknetwork|@stablelib|@cheqd|file-type|uint8arrays|multiformats|strtok3|peek-readable|token-types|uint8array-extra|p-limit|yocto-queue)", 24 | ], 25 | workerIdleMemoryLimit: "1G", 26 | verbose: true, 27 | globals: { 28 | Uint8Array, 29 | Uint32Array, 30 | ArrayBuffer, 31 | TextDecoder, 32 | TextEncoder, 33 | Buffer, 34 | }, 35 | }; 36 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/rollup.config.mjs: -------------------------------------------------------------------------------- 1 | import json from "@rollup/plugin-json"; 2 | import multiInput from "rollup-plugin-multi-input"; 3 | import commonjs from "@rollup/plugin-commonjs"; 4 | 5 | export default async function () { 6 | return [ 7 | { 8 | plugins: [ 9 | multiInput(), 10 | json(), 11 | // terser(), 12 | commonjs(), 13 | // Temporarily disabled, not sure if required 14 | // since rify is a node module doesnt seem to work 15 | // but would be nice to try embed it 16 | // wasm({ 17 | // sync: ['*.wasm'], 18 | // }), 19 | ], 20 | input: ["src/**/*.js"], 21 | output: [ 22 | { 23 | sourcemap: true, 24 | dir: "dist/esm", 25 | format: "esm", 26 | entryFileNames: "[name].js", 27 | }, 28 | { 29 | sourcemap: true, 30 | dir: "dist/cjs", 31 | format: "cjs", 32 | entryFileNames: "[name].cjs", 33 | }, 34 | ], 35 | }, 36 | ]; 37 | } 38 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/attest/internal.js: -------------------------------------------------------------------------------- 1 | import { Iri, CheqdCreateResource } from '@docknetwork/credential-sdk/types'; 2 | import { TypedUUID } from '@docknetwork/credential-sdk/types/generic'; 3 | import { createInternalCheqdModule, validateResource } from '../common'; 4 | 5 | const Name = 'Attestation'; 6 | const Type = 'attest'; 7 | 8 | const methods = { 9 | setClaim(iri, targetDid) { 10 | return new CheqdCreateResource( 11 | this.types.Did.from(targetDid).value, 12 | TypedUUID.random(), 13 | '1.0', 14 | [], 15 | Name, 16 | Type, 17 | Iri.from(iri), 18 | ); 19 | }, 20 | }; 21 | 22 | export default class CheqdInternalAttestModule extends createInternalCheqdModule( 23 | methods, 24 | ) { 25 | static MsgNames = { 26 | setClaim: 'MsgCreateResource', 27 | }; 28 | 29 | async attest(did, attestId) { 30 | return Iri.from( 31 | validateResource(await this.resource(did, attestId), Name, Type), 32 | ); 33 | } 34 | 35 | async attestId(did) { 36 | const res = await this.latestResourceMetadataBy( 37 | did, 38 | (meta) => meta.resourceType === 'attest', 39 | ); 40 | 41 | return res?.id; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/attest/module.js: -------------------------------------------------------------------------------- 1 | import { AbstractAttestModule } from '@docknetwork/credential-sdk/modules'; 2 | import { withCheqd } from '../common'; 3 | import CheqdInternalAttestModule from './internal'; 4 | 5 | export default class CheqdAttestModule extends withCheqd(AbstractAttestModule) { 6 | static CheqdOnly = CheqdInternalAttestModule; 7 | 8 | /** 9 | * Fetches the DIDs attestations IRI from the chain 10 | * @param {*} did 11 | * @return {Promise} The DID's attestation, if any 12 | */ 13 | async getAttests(did) { 14 | const id = await this.cheqdOnly.attestId(did); 15 | if (id == null) { 16 | return null; 17 | } 18 | 19 | return await this.cheqdOnly.attest(did, id); 20 | } 21 | 22 | /** 23 | * Creates an attestation claim on chain for a specific DID 24 | * @param iri 25 | * @param did 26 | * @param didKeypair 27 | */ 28 | async setClaimTx(iri, targetDid, didKeypair) { 29 | return await this.cheqdOnly.tx.setClaim(iri, targetDid, didKeypair); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/blob/internal.js: -------------------------------------------------------------------------------- 1 | import { 2 | Blob, 3 | CheqdBlobWithId, 4 | CheqdCreateResource, 5 | } from '@docknetwork/credential-sdk/types'; 6 | import { createInternalCheqdModule, validateResource } from '../common'; 7 | 8 | const Name = 'Blob'; 9 | const Type = 'blob'; 10 | 11 | const methods = { 12 | new: (blobWithId) => { 13 | const { 14 | blob, 15 | id: [did, uuid], 16 | } = CheqdBlobWithId.from(blobWithId); 17 | 18 | return new CheqdCreateResource( 19 | did.value.value, 20 | uuid, 21 | '1.0', 22 | [], 23 | Name, 24 | Type, 25 | blob, 26 | ); 27 | }, 28 | }; 29 | 30 | export default class CheqdInternalBlobModule extends createInternalCheqdModule( 31 | methods, 32 | ) { 33 | static MsgNames = { 34 | new: 'MsgCreateResource', 35 | }; 36 | 37 | async blob(blobId) { 38 | const { BlobId } = this.types; 39 | 40 | return Blob.from( 41 | validateResource( 42 | await this.resource(...BlobId.from(blobId).value), 43 | Name, 44 | Type, 45 | ), 46 | ); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/blob/module.js: -------------------------------------------------------------------------------- 1 | import { AbstractBlobModule } from '@docknetwork/credential-sdk/modules'; 2 | import { NoBlobError } from '@docknetwork/credential-sdk/modules/abstract/blob'; 3 | import { NoResourceError, withCheqd } from '../common'; 4 | import CheqdInternalBlobModule from './internal'; 5 | import { OwnerWithBlob } from './types'; 6 | 7 | export default class CheqdBlobModule extends withCheqd(AbstractBlobModule) { 8 | static CheqdOnly = CheqdInternalBlobModule; 9 | 10 | /** 11 | * Write a new blob on chain. 12 | * @param blobWithId 13 | * @param didKeypair - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification 14 | * @returns {Promise<*>} 15 | */ 16 | async newTx(blobWithId, didKeypair) { 17 | return await this.cheqdOnly.tx.new(blobWithId, didKeypair); 18 | } 19 | 20 | /** 21 | * Retrieves blob with owner from chain. 22 | * Throws an error in case if blob with supplied identifier doesn't exist. 23 | * @param {*} blobId 24 | * @returns {OwnerWithBlob} 25 | */ 26 | async get(blobId) { 27 | const { BlobId } = this.types; 28 | 29 | const id = BlobId.from(blobId); 30 | 31 | try { 32 | return new OwnerWithBlob(id.value[0], await this.cheqdOnly.blob(id)); 33 | } catch (err) { 34 | throw err instanceof NoResourceError ? new NoBlobError(id) : err; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/blob/types.js: -------------------------------------------------------------------------------- 1 | import { CheqdDid, Blob } from '@docknetwork/credential-sdk/types'; 2 | import { TypedTuple } from '@docknetwork/credential-sdk/types/generic'; 3 | 4 | export class OwnerWithBlob extends TypedTuple { 5 | static Classes = [CheqdDid, Blob]; 6 | } 7 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/common/index.js: -------------------------------------------------------------------------------- 1 | export { default as createInternalCheqdModule } from './create-internal-cheqd-module'; 2 | export { default as withCheqd } from './with-cheqd'; 3 | export { default as injectParams } from './inject-params'; 4 | export { default as injectPublicKeys } from './inject-public-keys'; 5 | export { default as withParams } from './with-params'; 6 | export { default as withPublicKeys } from './with-public-keys'; 7 | export * from './resource'; 8 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/common/with-cheqd.js: -------------------------------------------------------------------------------- 1 | import { 2 | withExtendedStaticProperties, 3 | ensureInstanceOf, 4 | } from '@docknetwork/credential-sdk/utils'; 5 | import { AbstractApiProvider } from '@docknetwork/credential-sdk/modules/abstract'; 6 | 7 | export default function withCheqd(klass) { 8 | const name = `withCheqd(${klass.name})`; 9 | 10 | const obj = { 11 | [name]: class extends klass { 12 | /** 13 | * Associated class which's only available when interacting with the cheqd blockchain. 14 | * Instance of this class is assigned to `cheqdOnly` property of the object. 15 | */ 16 | static CheqdOnly; 17 | 18 | constructor(cheqd) { 19 | super(ensureInstanceOf(cheqd, AbstractApiProvider)); 20 | 21 | this.cheqdOnly = new this.constructor.CheqdOnly(this.apiProvider); 22 | } 23 | 24 | supportsIdentifier(id) { 25 | return this.apiProvider.supportsIdentifier(id); 26 | } 27 | 28 | methods() { 29 | return this.apiProvider.methods(); 30 | } 31 | 32 | get types() { 33 | return this.apiProvider.types(); 34 | } 35 | }, 36 | }; 37 | 38 | return withExtendedStaticProperties(['CheqdOnly'], obj[name]); 39 | } 40 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/did/internal.js: -------------------------------------------------------------------------------- 1 | import { 2 | DIDDocument, 3 | CheqdDeactivateDidDocument, 4 | } from '@docknetwork/credential-sdk/types'; 5 | import { TypedUUID } from '@docknetwork/credential-sdk/types/generic'; 6 | import { createInternalCheqdModule } from '../common'; 7 | 8 | function createOrUpdateDidDocument(document) { 9 | return DIDDocument.from(document).toCheqd(this.types.DidDocument); 10 | } 11 | function deactivateDidDocument(id) { 12 | return new CheqdDeactivateDidDocument( 13 | this.types.Did.from(id), 14 | TypedUUID.random(), 15 | ); 16 | } 17 | 18 | const methods = { 19 | createDidDocument: createOrUpdateDidDocument, 20 | updateDidDocument: createOrUpdateDidDocument, 21 | deactivateDidDocument, 22 | }; 23 | 24 | export class CheqdDIDModuleInternal extends createInternalCheqdModule(methods) { 25 | static MsgNames = { 26 | createDidDocument: 'MsgCreateDidDoc', 27 | updateDidDocument: 'MsgUpdateDidDoc', 28 | deactivateDidDocument: 'MsgDeactivateDidDoc', 29 | }; 30 | 31 | async getDidDocumentWithMetadata(did) { 32 | return await this.apiProvider.sdk.querier.did.didDoc( 33 | String(this.types.Did.from(did)), 34 | ); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/offchain-signatures/bbs-plus.js: -------------------------------------------------------------------------------- 1 | import { BBSPlusParams } from '@docknetwork/credential-sdk/types'; 2 | import CheqdOffchainSignaturesInternalModule from './internal'; 3 | import CheqdOffchainSignaturesModule from './module'; 4 | 5 | export default class CheqdBBSPlusModule extends CheqdOffchainSignaturesModule { 6 | static CheqdOnly = class extends CheqdOffchainSignaturesInternalModule { 7 | static Params = BBSPlusParams; 8 | }; 9 | } 10 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/offchain-signatures/bbs.js: -------------------------------------------------------------------------------- 1 | import { BBSParams } from '@docknetwork/credential-sdk/types'; 2 | import CheqdOffchainSignaturesInternalModule from './internal'; 3 | import CheqdOffchainSignaturesModule from './module'; 4 | 5 | export default class CheqdBBSModule extends CheqdOffchainSignaturesModule { 6 | static CheqdOnly = class extends CheqdOffchainSignaturesInternalModule { 7 | static Params = BBSParams; 8 | }; 9 | } 10 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/offchain-signatures/internal.js: -------------------------------------------------------------------------------- 1 | import { CheqdParamsId } from '@docknetwork/credential-sdk/types'; 2 | import { createInternalCheqdModule, injectParams } from '../common'; 3 | 4 | export default class CheqdOffchainSignaturesInternalModule extends injectParams( 5 | createInternalCheqdModule(), 6 | ) { 7 | static ParamsId = CheqdParamsId; 8 | 9 | static ParamsName = 'OffchainParams'; 10 | 11 | static ParamsType = 'offchain-signature-params'; 12 | } 13 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/offchain-signatures/module.js: -------------------------------------------------------------------------------- 1 | import { AbstractOffchainSignaturesModule } from '@docknetwork/credential-sdk/modules/abstract'; 2 | import { OffchainSignatureParams } from '@docknetwork/credential-sdk/types'; 3 | import { withCheqd, withParams } from '../common'; 4 | import CheqdOffchainSignaturesInternalModule from './internal'; 5 | 6 | export default class CheqdOffchainSignaturesModule extends withParams( 7 | withCheqd(AbstractOffchainSignaturesModule), 8 | ) { 9 | static CheqdOnly = class extends CheqdOffchainSignaturesInternalModule { 10 | static Params = OffchainSignatureParams; 11 | }; 12 | } 13 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/src/offchain-signatures/ps.js: -------------------------------------------------------------------------------- 1 | import { PSParams } from '@docknetwork/credential-sdk/types'; 2 | import CheqdOffchainSignaturesInternalModule from './internal'; 3 | import CheqdOffchainSignaturesModule from './module'; 4 | 5 | export default class CheqdPSModule extends CheqdOffchainSignaturesModule { 6 | static CheqdOnly = class extends CheqdOffchainSignaturesInternalModule { 7 | static Params = PSParams; 8 | }; 9 | } 10 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/tests/accumulator-module.test.js: -------------------------------------------------------------------------------- 1 | import { generateAccumulatorModuleTests } from "@docknetwork/credential-sdk/modules/tests"; 2 | import { tests } from "./common"; 3 | 4 | tests("AccumulatorModule", generateAccumulatorModuleTests); 5 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/tests/attest-module.test.js: -------------------------------------------------------------------------------- 1 | import { generateAttestModuleTests } from "@docknetwork/credential-sdk/modules/tests"; 2 | import { tests } from "./common"; 3 | 4 | tests("AttestModule", generateAttestModuleTests); 5 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/tests/blob-module.test.js: -------------------------------------------------------------------------------- 1 | import { generateBlobModuleTests } from "@docknetwork/credential-sdk/modules/tests"; 2 | import { tests } from "./common"; 3 | 4 | tests("BlobModule", generateBlobModuleTests); 5 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/tests/did-module.test.js: -------------------------------------------------------------------------------- 1 | import { generateDIDModuleTests } from "@docknetwork/credential-sdk/modules/tests"; 2 | import { CheqdParamsId } from "@docknetwork/credential-sdk/types"; 3 | import { tests } from "./common"; 4 | 5 | tests("DIDModule", generateDIDModuleTests, { ParamsId: CheqdParamsId }); 6 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/tests/env.js: -------------------------------------------------------------------------------- 1 | import { DirectSecp256k1HdWallet } from "@docknetwork/cheqd-blockchain-api/wallet"; 2 | import { CheqdNetwork } from "@docknetwork/cheqd-blockchain-api"; 3 | 4 | export const faucet = { 5 | prefix: "cheqd", 6 | minimalDenom: "ncheq", 7 | mnemonic: 8 | process.env.CHEQD_MNEMONIC || 9 | "steak come surprise obvious remain black trouble measure design volume retreat float coach amused match album moment radio stuff crack orphan ranch dose endorse", 10 | async wallet() { 11 | return await DirectSecp256k1HdWallet.fromMnemonic(this.mnemonic, { 12 | prefix: this.prefix, 13 | }); 14 | }, 15 | }; 16 | 17 | export const url = process.env.CHEQD_RPC_URL || "http://localhost:26657"; 18 | export const network = process.env.CHEQD_NETWORK || CheqdNetwork.Testnet; 19 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/tests/offchain-signatures-module.test.js: -------------------------------------------------------------------------------- 1 | import { generateOffchainSignatureModuleTests } from "@docknetwork/credential-sdk/modules/tests"; 2 | import { tests } from "./common"; 3 | 4 | tests("OffchainSignatureModule", generateOffchainSignatureModuleTests); 5 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/tests/status-list-credential-module.test.js: -------------------------------------------------------------------------------- 1 | import { generateStatusListCredentialModuleTests } from "@docknetwork/credential-sdk/modules/tests"; 2 | import { tests } from "./common"; 3 | 4 | tests("StatusListCredentialModule", generateStatusListCredentialModuleTests); 5 | -------------------------------------------------------------------------------- /packages/cheqd-blockchain-modules/tests/test-environment.js: -------------------------------------------------------------------------------- 1 | import { TestEnvironment as NodeEnvironment } from "jest-environment-node"; 2 | 3 | class MyEnvironment extends NodeEnvironment { 4 | constructor(config, context) { 5 | super( 6 | { 7 | ...config, 8 | globals: { 9 | ...config.globals, 10 | Uint32Array, 11 | Uint8Array, 12 | ArrayBuffer, 13 | TextDecoder, 14 | TextEncoder, 15 | Buffer, 16 | }, 17 | }, 18 | context 19 | ); 20 | } 21 | 22 | async setup() {} 23 | 24 | async teardown() {} 25 | } 26 | 27 | export default MyEnvironment; 28 | -------------------------------------------------------------------------------- /packages/credential-sdk/.npmignore: -------------------------------------------------------------------------------- 1 | src/ 2 | scripts/ 3 | jest.config.js 4 | rollup.config.mjs 5 | out/ 6 | node_modules/ 7 | .vscode/ 8 | .turbo/ 9 | tests/ 10 | *.log 11 | -------------------------------------------------------------------------------- /packages/credential-sdk/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2019 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /packages/credential-sdk/jest.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | bail: true, 3 | moduleNameMapper: {}, 4 | clearMocks: true, 5 | testTimeout: 30000, 6 | testEnvironment: "./tests/test-environment", 7 | transform: { 8 | "^.+\\.(ts|js)$": ["babel-jest", { rootMode: "upward" }], 9 | }, 10 | transformIgnorePatterns: [ 11 | "/node_modules/(?!@polkadot|@babel|multiformats|@docknetwork|@stablelib)", 12 | ], 13 | workerIdleMemoryLimit: "1G", 14 | verbose: true, 15 | globals: { 16 | Uint8Array, 17 | Uint32Array, 18 | ArrayBuffer, 19 | TextDecoder, 20 | TextEncoder, 21 | Buffer, 22 | }, 23 | }; 24 | -------------------------------------------------------------------------------- /packages/credential-sdk/rollup.config.mjs: -------------------------------------------------------------------------------- 1 | import json from "@rollup/plugin-json"; 2 | import multiInput from "rollup-plugin-multi-input"; 3 | import commonjs from "@rollup/plugin-commonjs"; 4 | 5 | export default async function () { 6 | return [ 7 | { 8 | plugins: [ 9 | multiInput(), 10 | json(), 11 | // terser(), 12 | commonjs(), 13 | // Temporarily disabled, not sure if required 14 | // since rify is a node module doesnt seem to work 15 | // but would be nice to try embed it 16 | // wasm({ 17 | // sync: ['*.wasm'], 18 | // }), 19 | ], 20 | input: ["src/**/*.js"], 21 | output: [ 22 | { 23 | sourcemap: true, 24 | dir: "dist/esm", 25 | format: "esm", 26 | entryFileNames: "[name].js", 27 | }, 28 | { 29 | sourcemap: true, 30 | dir: "dist/cjs", 31 | format: "cjs", 32 | entryFileNames: "[name].cjs", 33 | }, 34 | ], 35 | }, 36 | ]; 37 | } 38 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/crypto/index.js: -------------------------------------------------------------------------------- 1 | export * from '@docknetwork/crypto-wasm-ts/lib/index.js'; 2 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/keypairs/index.js: -------------------------------------------------------------------------------- 1 | export { default as DockKeypair } from './dock-keypair'; 2 | export { default as Ed25519Keypair } from './keypair-ed25519'; 3 | export { default as Secp256k1Keypair } from './keypair-secp256k1'; 4 | export { default as DidKeypair } from './did-keypair'; 5 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/accumulator/index.js: -------------------------------------------------------------------------------- 1 | export { default as AbstractAccumulatorModule } from './module'; 2 | export * from './module'; 3 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/anchor/errors.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Anchor wasn't found on chain 3 | */ 4 | export class NoAnchorError extends Error { 5 | constructor(anchor) { 6 | super(`Anchor (${anchor}) does not exist`); 7 | this.name = 'NoAnchorError'; 8 | this.anchor = anchor; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/anchor/index.js: -------------------------------------------------------------------------------- 1 | export { default as AbstractAnchorModule } from './module'; 2 | export * from './errors'; 3 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/attest/index.js: -------------------------------------------------------------------------------- 1 | export { default as AbstractAttestModule } from './module'; 2 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/attest/module.js: -------------------------------------------------------------------------------- 1 | import { withExtendedPrototypeProperties } from '../../../utils'; 2 | import { AbstractBaseModule } from '../common'; 3 | 4 | class AbstractAttestModule extends AbstractBaseModule { 5 | /** 6 | * Fetches the DIDs attestations IRI from the chain 7 | * @param {*} did - DID 8 | * @return {Promise} The DID's attestation 9 | */ 10 | async getAttests(_did) { 11 | throw new Error('Unimplemented'); 12 | } 13 | 14 | /** 15 | * Creates an attestation claim on chain for a specific DID 16 | * @param iri 17 | * @param signerDid 18 | * @param didKeypair 19 | * @param params 20 | */ 21 | async setClaim(iri, targetDid, didKeypair, params) { 22 | return await this.signAndSend( 23 | await this.setClaimTx(iri, targetDid, didKeypair), 24 | params, 25 | ); 26 | } 27 | 28 | /** 29 | * Creates an attestation claim on chain for a specific DID 30 | * @param iri 31 | * @param targetDid 32 | * @param didKeypair 33 | */ 34 | async setClaimTx(_iri, _targetDid, _didKeypair) { 35 | throw new Error('Unimplemented'); 36 | } 37 | } 38 | 39 | export default withExtendedPrototypeProperties( 40 | ['getAttests', 'setClaimTx'], 41 | AbstractAttestModule, 42 | ); 43 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/blob/errors.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Error thrown when a Blob lookup was successful, but the Blob in question does not exist. 3 | * This is different from a network error. 4 | */ 5 | export class NoBlobError extends Error { 6 | constructor(id) { 7 | super(`Blob ID (${id}) does not exist`); 8 | this.name = 'NoBlobError'; 9 | this.id = id; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/blob/index.js: -------------------------------------------------------------------------------- 1 | export { default as AbstractBlobModule } from './module'; 2 | export * from './errors'; 3 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/blob/module.js: -------------------------------------------------------------------------------- 1 | import { AbstractBaseModule } from '../common'; 2 | import { withExtendedPrototypeProperties } from '../../../utils'; 3 | 4 | /** Class to create and update Blobs on chain. */ 5 | class AbstractBlobModule extends AbstractBaseModule { 6 | /** 7 | * Write a new blob on chain. 8 | * @param blobWithId 9 | * @param targetDid - Signer of the blob 10 | * @param signingKeyRef - The key id used by the signer. This will be used by the verifier (node) to fetch the public key for verification 11 | * @returns {Promise<*>} 12 | */ 13 | async new(blobWithId, didKeypair, params = {}) { 14 | return await this.signAndSend( 15 | await this.newTx(blobWithId, didKeypair), 16 | params, 17 | ); 18 | } 19 | 20 | /** 21 | * Get blob with given id from the chain. Throws if the blob can't be found. 22 | * @param {string} id - Can either be a full blob id like blob:dock:0x... or just the hex identifier 23 | * @returns {Promise} - A 2-element array where the first is the author and the second is the blob contents. 24 | */ 25 | async get(_id) { 26 | throw new Error('Unimplemented'); 27 | } 28 | } 29 | 30 | export default withExtendedPrototypeProperties( 31 | ['newTx', 'get'], 32 | AbstractBlobModule, 33 | ); 34 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/common/abstract-base-module.js: -------------------------------------------------------------------------------- 1 | import AbstractApiProvider from './abstract-api-provider'; 2 | import { 3 | ensureInstanceOf, 4 | withExtendedPrototypeProperties, 5 | } from '../../../utils'; 6 | 7 | class AbstractBaseModule { 8 | constructor(apiProvider) { 9 | if (apiProvider != null) { 10 | this.apiProvider = ensureInstanceOf(apiProvider, AbstractApiProvider); 11 | } 12 | } 13 | 14 | /** 15 | * Signs and sends provided extrinsic. 16 | * 17 | * @param {*} extrinsic 18 | * @param {*} params 19 | * @returns {Promise<*>} 20 | */ 21 | async signAndSend(extrinsic, params) { 22 | if (this.apiProvider == null) { 23 | throw new Error( 24 | `Can't sign transaction because \`${this.constructor.name}\` doesn't have an associated \`apiProvider\``, 25 | ); 26 | } 27 | 28 | return await this.apiProvider.signAndSend(extrinsic, params); 29 | } 30 | } 31 | 32 | /** 33 | * Base module class that must be extended by all modules. 34 | */ 35 | export default withExtendedPrototypeProperties(['methods'], AbstractBaseModule); 36 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/common/index.js: -------------------------------------------------------------------------------- 1 | export { default as AbstractApiProvider } from './abstract-api-provider'; 2 | export { default as AbstractBaseModule } from './abstract-base-module'; 3 | export { default as withAbstractParams } from './with-abstract-params'; 4 | export { default as withAbstractPublicKeys } from './with-abstract-public-keys'; 5 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/did/errors.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Error thrown when a DID document lookup was successful, but the DID in question does not exist. 3 | * This is different from a network error. 4 | */ 5 | export class NoDIDError extends Error { 6 | constructor(did) { 7 | super(`DID (${did}) does not exist`); 8 | this.name = 'NoDIDError'; 9 | this.did = did; 10 | this.message = `A DID document lookup was successful, but the DID in question does not exist (${did}). This is different from a network error.`; 11 | } 12 | } 13 | 14 | /** 15 | * Error thrown when a DID exists on chain but is an off-chain DID, meaning the DID document exists off-chain. 16 | */ 17 | export class NoOnchainDIDError extends Error { 18 | constructor(did) { 19 | super(`DID (${did}) is an off-chain DID`); 20 | this.name = 'NoOnchainDIDError'; 21 | this.did = did; 22 | this.message = 'The DID exists on chain but is an off-chain DID, meaning the DID document exists off-chain.'; 23 | } 24 | } 25 | 26 | /** 27 | * Error thrown when a DID exists on chain and is an on-chain DID but the lookup was performed for an off-chain DID. 28 | */ 29 | export class NoOffchainDIDError extends Error { 30 | constructor(did) { 31 | super(`DID (${did}) is an on-chain DID`); 32 | this.name = 'NoOffchainDIDError'; 33 | this.did = did; 34 | this.message = 'The DID exists on chain and is an on-chain DID but the lookup was performed for an off-chain DID.'; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/did/index.js: -------------------------------------------------------------------------------- 1 | export { default as AbstractDIDModule } from './module'; 2 | export * from './errors'; 3 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/offchain-signatures/index.js: -------------------------------------------------------------------------------- 1 | export { default as AbstractOffchainSignaturesModule } from './module'; 2 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/offchain-signatures/module.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable camelcase */ 2 | 3 | import { OffchainSignatureParams } from '../../../types'; 4 | import { AbstractBaseModule, withAbstractParams } from '../common'; 5 | 6 | /** Class to write offchain signature parameters on chain */ 7 | export default class AbstractOffchainSignaturesModule extends withAbstractParams( 8 | AbstractBaseModule, 9 | ) { 10 | static Params = OffchainSignatureParams; 11 | 12 | static prepareAddParameters(bytes, label, curveType) { 13 | return super.prepareAddParameters( 14 | new this.Params.Class(bytes, label, curveType), 15 | ); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/schema/index.js: -------------------------------------------------------------------------------- 1 | export { default as Schema } from './module'; 2 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/status-list-credential/index.js: -------------------------------------------------------------------------------- 1 | export { default as AbstractStatusListCredentialModule } from './module'; 2 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/abstract/trust-registry/index.js: -------------------------------------------------------------------------------- 1 | export { default as AbstractTrustRegistryModule } from './module'; 2 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/index.js: -------------------------------------------------------------------------------- 1 | export * from './abstract'; 2 | export * from './multi-api'; 3 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/multi-api/attest.js: -------------------------------------------------------------------------------- 1 | import { AbstractAttestModule } from '../abstract'; 2 | import { NamespaceDid } from '../../types'; 3 | import { injectModuleRouter } from './common'; 4 | 5 | export default class MultiApiAttestModule extends injectModuleRouter( 6 | AbstractAttestModule, 7 | ) { 8 | /** 9 | * Fetches the DIDs attestations IRI from the chain 10 | * @param {*} did - DID 11 | * @return {Promise} The DID's attestation 12 | */ 13 | async getAttests(did) { 14 | const parsedDid = NamespaceDid.from(did); 15 | 16 | return await this.moduleById(parsedDid).getAttests(parsedDid); 17 | } 18 | 19 | /** 20 | * Creates an attestation claim on chain for a specific DID 21 | * @param iri 22 | * @param signerDid 23 | * @param didKeypair 24 | * @param params 25 | */ 26 | async setClaim(iri, targetDid, didKeypair, params) { 27 | const did = NamespaceDid.from(targetDid); 28 | 29 | return await this.moduleById(did).setClaim(iri, did, didKeypair, params); 30 | } 31 | 32 | /** 33 | * Creates an attestation claim on chain for a specific DID 34 | * @param iri 35 | * @param targetDid 36 | * @param didKeypair 37 | */ 38 | async setClaimTx(iri, targetDid, didKeypair) { 39 | const did = NamespaceDid.from(targetDid); 40 | 41 | return await this.moduleById(did).setClaimTx(iri, did, didKeypair); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/multi-api/common.js: -------------------------------------------------------------------------------- 1 | import { ensureArray, ensureInstanceOf, fmtIterable } from '../../utils'; 2 | 3 | export function injectModuleRouter(klass) { 4 | const name = `withModuleRouter(${klass.name})`; 5 | 6 | const classes = { 7 | [name]: class extends klass { 8 | constructor(modules) { 9 | super(); 10 | 11 | for (const module of ensureArray(modules)) { 12 | ensureInstanceOf(module, klass); 13 | } 14 | 15 | this.modules = modules; 16 | } 17 | 18 | moduleById(id) { 19 | for (const module of this.modules) { 20 | if (module.supportsIdentifier(id)) { 21 | return module; 22 | } 23 | } 24 | 25 | throw new Error( 26 | `Identifier \`${id}\` is not supported by any of ${fmtIterable( 27 | this.modules.map((module) => module.constructor.name), 28 | )}`, 29 | ); 30 | } 31 | 32 | dispatchById(id, fn) { 33 | return fn(this.moduleById(id)); 34 | } 35 | 36 | supportsIdentifier(id) { 37 | return this.modules.some((module) => module.supportsIdentifier(id)); 38 | } 39 | 40 | methods() { 41 | return this.modules.flatMap((module) => module.methods()); 42 | } 43 | }, 44 | }; 45 | 46 | return classes[name]; 47 | } 48 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/tests/common.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | export const testIf = 3 | (filter) => 4 | (...args) => 5 | filter(...args) ? test(...args, 6e4) : test.skip(...args); 6 | /* eslint-enable */ 7 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/modules/tests/index.js: -------------------------------------------------------------------------------- 1 | export { default as generateAccumulatorModuleTests } from './accumulator-module'; 2 | export { default as generateAttestModuleTests } from './attest-module'; 3 | export { default as generateBlobModuleTests } from './blob-module'; 4 | export { default as generateDIDModuleTests } from './did-module'; 5 | export { default as generateOffchainSignatureModuleTests } from './offchain-signatures-module'; 6 | export { default as generateStatusListCredentialModuleTests } from './status-list-credential-module'; 7 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/rdf-and-cd/index.js: -------------------------------------------------------------------------------- 1 | export * from './canonicalize'; 2 | export * from './cd'; 3 | export * from './claimgraph'; 4 | export * from './common'; 5 | export * from './rdf'; 6 | export * from './crawl'; 7 | export * from './rdf-defs'; 8 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/blob/blob-resolver.js: -------------------------------------------------------------------------------- 1 | import { ensureInstanceOf } from '../../utils'; 2 | import { AbstractBlobModule } from '../../modules/abstract/blob'; 3 | import { Resolver } from '../generic'; 4 | 5 | class DockBlobResolver extends Resolver { 6 | prefix = 'blob'; 7 | 8 | get method() { 9 | return this.blobModule.methods(); 10 | } 11 | 12 | /** 13 | * @param {AbstractBlobModule} 14 | * @constructor 15 | */ 16 | constructor(blobModule) { 17 | super(); 18 | 19 | /** 20 | * @type {AbstractBlobModule} 21 | */ 22 | this.blobModule = ensureInstanceOf(blobModule, AbstractBlobModule); 23 | } 24 | 25 | async resolve(blobUri) { 26 | const [author, blob] = await this.blobModule.get(blobUri); 27 | 28 | return [String(author), blob.toObjectOrBytes()]; 29 | } 30 | } 31 | 32 | /** 33 | * Resolves `Blob`s with identifier `blob:dock:*`. 34 | * @type {DockBlobResolver} 35 | */ 36 | export default DockBlobResolver; 37 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/blob/index.js: -------------------------------------------------------------------------------- 1 | export { default as BlobResolver } from './blob-resolver'; 2 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/core-resolver.js: -------------------------------------------------------------------------------- 1 | import { DIDResolverWithDIDReplacement } from './did'; 2 | import { StatusList2021Resolver } from './status-list2021'; 3 | import { BlobResolver } from './blob'; 4 | import { ResolverRouter } from './generic'; 5 | import { ensureInstanceOf } from '../utils'; 6 | import { AbstractCoreModules } from '../modules'; 7 | 8 | /** 9 | * Resolves dock-hosted entities such us `did:dock:*` and `status-list2021:dock:*`, `rev-reg:dock:*`, `blob:dock:*`. 10 | */ 11 | export default class CoreResolver extends ResolverRouter { 12 | constructor(modules) { 13 | const { did, statusListCredential, blob } = ensureInstanceOf( 14 | modules, 15 | AbstractCoreModules, 16 | ); 17 | 18 | super([ 19 | new DIDResolverWithDIDReplacement(did), 20 | new StatusList2021Resolver(statusListCredential), 21 | new BlobResolver(blob), 22 | ]); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/did/did-jwk-resolver.js: -------------------------------------------------------------------------------- 1 | import { getDidJwkResolver } from '@sphereon/ssi-sdk-ext.did-resolver-jwk'; 2 | import { Resolver } from '../generic'; 3 | 4 | const jwkResolver = getDidJwkResolver(); 5 | 6 | /** 7 | * Resolves `DID` keys with identifier `did:jwk:*`. 8 | */ 9 | export default class DIDJWKResolver extends Resolver { 10 | prefix = 'did'; 11 | 12 | method = 'jwk'; 13 | 14 | constructor() { 15 | super(void 0); 16 | } 17 | 18 | async resolve(did) { 19 | const { didDocument } = await jwkResolver.jwk(did); 20 | return { 21 | '@context': 'https://www.w3.org/ns/did/v1', 22 | ...didDocument, 23 | }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/did/did-key-resolver.js: -------------------------------------------------------------------------------- 1 | import { getResolver } from 'key-did-resolver'; 2 | import { Resolver } from '../generic'; 3 | import { parseDIDUrl } from '../../utils'; 4 | 5 | const resolveMethod = getResolver().key; 6 | 7 | /** 8 | * Resolves `DID` keys with identifier `did:key:*`. 9 | */ 10 | export default class DIDKeyResolver extends Resolver { 11 | prefix = 'did'; 12 | 13 | method = 'key'; 14 | 15 | constructor() { 16 | super(void 0); 17 | } 18 | 19 | async resolve(did) { 20 | const parsed = parseDIDUrl(did); 21 | const { didDocument } = await resolveMethod(did, parsed, null, {}); 22 | 23 | return { 24 | '@context': 'https://www.w3.org/ns/did/v1', 25 | ...didDocument, 26 | }; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/did/did-resolver-with-did-replacement.js: -------------------------------------------------------------------------------- 1 | import { parseDIDUrl } from '../../utils'; 2 | import DIDResolver from './did-resolver'; 3 | 4 | /** 5 | * Class DIDResolverWithDIDReplacement extends DIDResolver. 6 | * 7 | * This class provides an implementation of the resolve method that replaces a specific did in a document if it does not match the didURL. 8 | * The replacement is done by parsing the document into JSON, finding and replacing all instances of 'doc.id' with 'did', and then converting it back to an object. 9 | */ 10 | export default class DIDResolverWithDIDReplacement extends DIDResolver { 11 | async resolve(didURL) { 12 | const { did } = parseDIDUrl(didURL); 13 | const doc = await super.resolve(did); 14 | 15 | if (doc.id !== did) { 16 | return JSON.parse(JSON.stringify(doc).split(doc.id).join(did)); 17 | } else { 18 | return doc; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/did/did-resolver.js: -------------------------------------------------------------------------------- 1 | import { AbstractDIDModule } from '../../modules/abstract/did'; 2 | import { ensureInstanceOf, parseDIDUrl } from '../../utils'; 3 | import { Resolver } from '../generic'; 4 | 5 | class DIDResolver extends Resolver { 6 | prefix = 'did'; 7 | 8 | get method() { 9 | return this.didModule.methods(); 10 | } 11 | 12 | /** 13 | * @param {AbstractDIDModule} 14 | * @constructor 15 | */ 16 | constructor(didModule) { 17 | super(); 18 | 19 | /** 20 | * @type {AbstractDIDModule} 21 | */ 22 | this.didModule = ensureInstanceOf(didModule, AbstractDIDModule); 23 | } 24 | 25 | async resolve(didURL) { 26 | const { did } = parseDIDUrl(didURL); 27 | const document = await this.didModule.getDocument(did); 28 | 29 | return document.toJSON(); 30 | } 31 | } 32 | 33 | /** 34 | * Resolves `DID`s with identifier `did:dock:*`. 35 | * @type {DIDResolver} 36 | */ 37 | export default DIDResolver; 38 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/did/index.js: -------------------------------------------------------------------------------- 1 | export { default as DIDKeyResolver } from './did-key-resolver'; 2 | export { default as DIDJWKResolver } from './did-jwk-resolver'; 3 | export { default as DIDResolver } from './did-resolver'; 4 | export { default as DIDResolverWithDIDReplacement } from './did-resolver-with-did-replacement'; 5 | export { default as UniversalResolver } from './universal-resolver'; 6 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/generic/const.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Use to specify `prefix`/`method` that will be dispatched in case no direct matches are found. 3 | */ 4 | export const WILDCARD = Symbol.for( 5 | '@docknetwork/credential-sdk/resolver/wildcard-resolver', 6 | ); 7 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/generic/helpers.js: -------------------------------------------------------------------------------- 1 | import Resolver from './resolver'; 2 | import { WILDCARD } from './const'; 3 | import { ensureItemsAllowed } from '../utils'; 4 | 5 | /** 6 | * Creates a resolver. 7 | * 8 | * @template T 9 | * @param {Resolver | function(string): Promise} resolverOrFn 10 | * @param {object} [config={}] 11 | * @param {Array | string | symbol} [config.prefix=WILDCARD] 12 | * @param {Array | string | symbol} [config.method=WILDCARD] 13 | * @returns {Resolver | ResolverRouter} 14 | */ 15 | export const createResolver = ( 16 | resolverOrFn, 17 | { prefix = WILDCARD, method = WILDCARD } = {}, 18 | ) => new (class ResolverCreatedUsingCreateResolver extends Resolver { 19 | prefix = prefix; 20 | 21 | method = method; 22 | 23 | constructor() { 24 | super(); 25 | 26 | const isFn = typeof resolverOrFn === 'function'; 27 | if (!isFn && resolverOrFn instanceof Resolver) { 28 | ensureItemsAllowed( 29 | [].concat(resolverOrFn.prefix), 30 | [].concat(this.prefix), 31 | WILDCARD, 32 | ); 33 | ensureItemsAllowed( 34 | [].concat(resolverOrFn.method), 35 | [].concat(this.method), 36 | WILDCARD, 37 | ); 38 | } 39 | 40 | this.resolve = isFn 41 | ? resolverOrFn 42 | : resolverOrFn.resolve.bind(resolverOrFn); 43 | } 44 | 45 | async resolve(_id) { 46 | throw new Error('Unimplemented'); 47 | } 48 | })(); 49 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/generic/index.js: -------------------------------------------------------------------------------- 1 | export { default as ResolverRouter } from './resolver-router'; 2 | export { default as Resolver } from './resolver'; 3 | export { default as WildcardResolverRouter } from './wildcard-resolver-router'; 4 | export * from './helpers'; 5 | export * from './const'; 6 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/generic/wildcard-resolver-router.js: -------------------------------------------------------------------------------- 1 | import ResolverRouter from './resolver-router'; 2 | import { WILDCARD } from './const'; 3 | 4 | /** 5 | * Wildcard `prefix`/`method` resolver. Used primarily as a router to combine different resolvers together. 6 | */ 7 | export default class WildcardResolverRouter extends ResolverRouter { 8 | prefix = WILDCARD; 9 | 10 | method = WILDCARD; 11 | } 12 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/index.js: -------------------------------------------------------------------------------- 1 | export * from './did'; 2 | export * from './blob'; 3 | export * from './generic'; 4 | export * from './status-list2021'; 5 | export { default as CoreResolver } from './core-resolver'; 6 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/status-list2021/index.js: -------------------------------------------------------------------------------- 1 | export { default as StatusList2021Resolver } from './status-list2021-resolver'; 2 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/resolver/status-list2021/status-list2021-resolver.js: -------------------------------------------------------------------------------- 1 | import { ensureInstanceOf, ensureString } from '../../utils'; 2 | import AbstractStatusListCredentialModule from '../../modules/abstract/status-list-credential/module'; 3 | import { Resolver } from '../generic'; 4 | 5 | class StatusListResolver extends Resolver { 6 | prefix = 'status-list2021'; 7 | 8 | get method() { 9 | return this.statusListCredentialModule.methods(); 10 | } 11 | 12 | /** 13 | * @param {AbstractStatusListCredentialModule} statusListCredentialModule 14 | * @constructor 15 | */ 16 | constructor(statusListCredentialModule) { 17 | super(); 18 | 19 | /** 20 | * @type {AbstractStatusListCredentialModule} 21 | */ 22 | this.statusListCredentialModule = ensureInstanceOf( 23 | statusListCredentialModule, 24 | AbstractStatusListCredentialModule, 25 | ); 26 | } 27 | 28 | async resolve(id) { 29 | const cred = await this.statusListCredentialModule.getStatusListCredential(ensureString(id)); 30 | 31 | return cred?.toJSON(); 32 | } 33 | } 34 | 35 | /** 36 | * Resolves `StatusList2021Credential`s with identifier `status-list2021:dock:*`. 37 | * @type {StatusListResolver} 38 | */ 39 | export default StatusListResolver; 40 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/accumulator/counters.js: -------------------------------------------------------------------------------- 1 | import { TypedStruct } from '../generic'; 2 | import { DockAccumulatorPublicKeyId } from './keys'; 3 | import { DockAccumulatorParamsId } from './params'; 4 | 5 | export class DockAccumulatorCounters extends TypedStruct { 6 | static Classes = { 7 | paramsCounter: DockAccumulatorParamsId, 8 | keyCounter: DockAccumulatorPublicKeyId, 9 | }; 10 | } 11 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/accumulator/index.js: -------------------------------------------------------------------------------- 1 | export * from './keys'; 2 | export * from './params'; 3 | export * from './public-key'; 4 | export * from './accumulator'; 5 | export * from './counters'; 6 | export * from './id'; 7 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/accumulator/params.js: -------------------------------------------------------------------------------- 1 | import { 2 | option, 3 | TypedBytes, 4 | TypedNumber, 5 | TypedStruct, 6 | TypedUUID, 7 | } from '../generic'; 8 | import withFromDockId from '../generic/with-from-dock-id'; 9 | import { 10 | CurveType, 11 | CurveTypeBls12381, 12 | } from '../offchain-signatures/curve-type'; 13 | 14 | export class AccumulatorParams extends TypedStruct { 15 | static Classes = { 16 | bytes: class Bytes extends TypedBytes {}, 17 | label: option(class Label extends TypedBytes {}), 18 | curveType: CurveType, 19 | }; 20 | 21 | constructor(bytes, label, curveType = new CurveTypeBls12381()) { 22 | super(bytes, label, curveType); 23 | } 24 | } 25 | 26 | export class DockAccumulatorParamsId extends TypedNumber {} 27 | 28 | export class CheqdAccumulatorParamsId extends withFromDockId( 29 | TypedUUID, 30 | DockAccumulatorParamsId, 31 | 'accumulator-params', 32 | ) {} 33 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/anchor/index.js: -------------------------------------------------------------------------------- 1 | import BLAKE2b from 'blake2b'; 2 | import { sized, TypedBytes } from '../generic'; 3 | import { normalizeToU8a } from '../../utils'; 4 | 5 | export class AnchorHash extends sized(TypedBytes) { 6 | static Size = 32; 7 | } 8 | 9 | export class Anchor extends TypedBytes { 10 | /** 11 | * Returns new anchor produced by hashing given data using Blake2b. 12 | * @param anchor 13 | * @returns {AnchorHash} 14 | */ 15 | static hash(bytes) { 16 | const hash = BLAKE2b(32); 17 | hash.update(normalizeToU8a(bytes)); 18 | 19 | return new AnchorHash(hash.digest()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/attest/index.js: -------------------------------------------------------------------------------- 1 | import { 2 | TypedStruct, option, TypedNumber, TypedString, 3 | } from '../generic'; 4 | 5 | export class Iri extends TypedString {} 6 | 7 | export class Attest extends TypedStruct { 8 | static Classes = { 9 | priority: class Priority extends TypedNumber {}, 10 | iri: option(Iri), 11 | }; 12 | } 13 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/blob/blob.js: -------------------------------------------------------------------------------- 1 | import { TypedBytes } from '../generic'; 2 | import { 3 | hexToU8a, 4 | isHex, 5 | stringToU8a, 6 | u8aToString, 7 | u8aToU8a, 8 | } from '../../utils'; 9 | 10 | export default class Blob extends TypedBytes { 11 | constructor(value) { 12 | let bytes; 13 | if (value instanceof Uint8Array) { 14 | bytes = value; 15 | } else if (value && typeof value === 'object') { 16 | if (typeof value[Symbol.iterator] !== 'function') { 17 | bytes = stringToU8a(JSON.stringify(value)); 18 | } else { 19 | bytes = u8aToU8a(value); 20 | } 21 | } else if (typeof value === 'string') { 22 | if (!isHex(value)) { 23 | bytes = stringToU8a(value); 24 | } else { 25 | bytes = hexToU8a(value); 26 | } 27 | } 28 | 29 | super(bytes); 30 | } 31 | 32 | static fromApi(value) { 33 | return new this(value); 34 | } 35 | 36 | static fromJSON(value) { 37 | return new this(value); 38 | } 39 | 40 | toUTF8String() { 41 | return u8aToString(this); 42 | } 43 | 44 | toObject() { 45 | try { 46 | return JSON.parse(u8aToString(this.bytes)); 47 | } catch (err) { 48 | throw new Error(`Underlying value is not a valid JSON: ${err}`); 49 | } 50 | } 51 | 52 | toObjectOrBytes() { 53 | try { 54 | return this.toObject(); 55 | } catch (err) { 56 | console.error('Failed to convert blob to JSON:', err); 57 | 58 | return this.bytes; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/blob/const.js: -------------------------------------------------------------------------------- 1 | export const DockBlobQualifier = 'blob:dock:'; 2 | export const CheqdBlobQualifier = 'blob:cheqd:'; 3 | export const DockBlobIdByteSize = 32; 4 | export const CheqdBlobIdByteSize = 16; 5 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/blob/index.js: -------------------------------------------------------------------------------- 1 | import { TypedStruct, withProp } from '../generic'; 2 | import { 3 | BlobId, 4 | CheqdBlobIdValue, 5 | CheqdMainnetBlobIdValue, 6 | CheqdTestnetBlobIdValue, 7 | DockBlobIdValue, 8 | } from './id'; 9 | import Blob from './blob'; 10 | 11 | export * from './id'; 12 | export { default as Blob } from './blob'; 13 | 14 | export class BlobWithId extends TypedStruct { 15 | static Classes = { 16 | id: BlobId, 17 | blob: Blob, 18 | }; 19 | } 20 | 21 | export class CheqdBlobWithId extends withProp( 22 | BlobWithId, 23 | 'id', 24 | CheqdBlobIdValue, 25 | ) {} 26 | export class CheqdTestnetBlobWithId extends withProp( 27 | CheqdBlobWithId, 28 | 'id', 29 | CheqdTestnetBlobIdValue, 30 | ) {} 31 | export class CheqdMainnetBlobWithId extends withProp( 32 | CheqdBlobWithId, 33 | 'id', 34 | CheqdMainnetBlobIdValue, 35 | ) {} 36 | export class DockBlobWithId extends withProp( 37 | BlobWithId, 38 | 'id', 39 | DockBlobIdValue, 40 | ) {} 41 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/document/const.js: -------------------------------------------------------------------------------- 1 | export const ATTESTS_IRI = 'https://rdf.dock.io/alpha/2021#attestsDocumentContents'; 2 | 3 | export const CONTEXT_URI = 'https://www.w3.org/ns/did/v1'; 4 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/document/ident-ref.js: -------------------------------------------------------------------------------- 1 | import { withQualifier, TypedTuple, TypedString } from '../../generic'; 2 | import { NamespaceDid } from '../onchain/typed-did'; 3 | 4 | export default class IdentRef extends withQualifier(TypedTuple) { 5 | static Qualifier = ''; 6 | 7 | static Did = NamespaceDid; 8 | 9 | static Ident = TypedString; 10 | 11 | static get Classes() { 12 | return [this.Did, this.Ident]; 13 | } 14 | 15 | static random(did) { 16 | return new this(did, this.Ident.random()); 17 | } 18 | 19 | get did() { 20 | return this[0]; 21 | } 22 | 23 | get value() { 24 | return this[1]; 25 | } 26 | 27 | static fromUnqualifiedString(str) { 28 | const regex = new RegExp(`^${this.Qualifier}([^#]+)#(.+)$`); 29 | const match = str.match(regex); 30 | 31 | if (!match) { 32 | throw new Error(`Invalid format for IdentRef: \`${str}\``); 33 | } 34 | 35 | const [, did, value] = match; 36 | return new this(did, value); 37 | } 38 | 39 | toEncodedString() { 40 | const { did, value } = this; 41 | 42 | return `${did}#${value}`; 43 | } 44 | 45 | toCheqdPayload() { 46 | return this.toString(); 47 | } 48 | 49 | toJSON() { 50 | return this.toString(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/document/verification-method-ref-or-cheqd-verification-method.js: -------------------------------------------------------------------------------- 1 | import { 2 | CheqdVerificationMethodAssertion, 3 | CheqdMainnetVerificationMethodAssertion, 4 | CheqdTestnetVerificationMethodAssertion, 5 | CheqdVerificationMethodAssertionLegacy, 6 | CheqdTestnetVerificationMethodAssertionLegacy, 7 | CheqdMainnetVerificationMethodAssertionLegacy, 8 | } from './verification-method'; 9 | import { 10 | CheqdMainnetVerificationMethodRef, 11 | CheqdTestnetVerificationMethodRef, 12 | CheqdVerificationMethodRef, 13 | } from './verification-method-ref'; 14 | import { anyOf } from '../../generic'; 15 | 16 | export class CheqdVerificationMethodRefOrCheqdVerificationMethod extends anyOf( 17 | CheqdVerificationMethodAssertion, 18 | CheqdVerificationMethodAssertionLegacy, 19 | CheqdVerificationMethodRef, 20 | ) {} 21 | 22 | export class CheqdTestnetVerificationMethodOrCheqdTestnetVerificationMethodRef extends anyOf( 23 | CheqdTestnetVerificationMethodAssertion, 24 | CheqdTestnetVerificationMethodAssertionLegacy, 25 | CheqdTestnetVerificationMethodRef, 26 | ) {} 27 | 28 | export class CheqdMainnetVerificationMethodOrCheqdMainnetVerificationMethodRef extends anyOf( 29 | CheqdMainnetVerificationMethodAssertion, 30 | CheqdMainnetVerificationMethodAssertionLegacy, 31 | CheqdMainnetVerificationMethodRef, 32 | ) {} 33 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/document/verification-method-ref-or-ident-ref.js: -------------------------------------------------------------------------------- 1 | import { VerificationMethodRef } from './verification-method-ref'; 2 | import IdentRef from './ident-ref'; 3 | import { anyOf } from '../../generic'; 4 | 5 | export default class VerificationMethodRefOrIdentRef extends anyOf( 6 | VerificationMethodRef, 7 | IdentRef, 8 | ) {} 9 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/index.js: -------------------------------------------------------------------------------- 1 | import { TypedEnum } from '../generic'; 2 | import { OffchainDidDetailsValue } from './offchain'; 3 | import { StoredOnchainDidDetailsValue } from './onchain'; 4 | 5 | export * from './onchain'; 6 | export * from './offchain'; 7 | export * from './document'; 8 | 9 | export class StoredDidDetails extends TypedEnum {} 10 | 11 | export class StoredOnchainDidDetails extends StoredDidDetails { 12 | static Type = 'onChain'; 13 | 14 | static Class = StoredOnchainDidDetailsValue; 15 | } 16 | export class StoredOffchainDidDetails extends StoredDidDetails { 17 | static Type = 'offChain'; 18 | 19 | static Class = OffchainDidDetailsValue; 20 | } 21 | 22 | StoredDidDetails.bindVariants( 23 | StoredOnchainDidDetails, 24 | StoredOffchainDidDetails, 25 | ); 26 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/offchain/doc-ref.js: -------------------------------------------------------------------------------- 1 | import { TypedEnum, TypedBytes } from '../../generic'; 2 | 3 | /** 4 | * An off-chain DID Doc reference stored on-chain. The reference may be 5 | * - a CID, https://docs.ipfs.io/concepts/content-addressing/#identifier-formats 6 | * - a URL 7 | * - any other format 8 | */ 9 | export class OffChainDidDocRef extends TypedEnum {} 10 | 11 | class DocValue extends TypedBytes {} 12 | 13 | export class CIDOffchainDocRef extends OffChainDidDocRef { 14 | static Type = 'cid'; 15 | 16 | static Class = DocValue; 17 | } 18 | export class URLOffchainDocRef extends OffChainDidDocRef { 19 | static Type = 'url'; 20 | 21 | static Class = DocValue; 22 | } 23 | export class CustomOffchainDocRef extends OffChainDidDocRef { 24 | static Type = 'custom'; 25 | 26 | static Class = DocValue; 27 | } 28 | 29 | OffChainDidDocRef.bindVariants( 30 | CIDOffchainDocRef, 31 | URLOffchainDocRef, 32 | CustomOffchainDocRef, 33 | ); 34 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/offchain/index.js: -------------------------------------------------------------------------------- 1 | import { sized, TypedBytes, TypedStruct } from '../../generic'; 2 | import { OffChainDidDocRef } from './doc-ref'; 3 | 4 | export * from './doc-ref'; 5 | 6 | export class OffchainDidDetailsValue extends TypedStruct { 7 | static Classes = { 8 | accountId: class AccountId extends sized(TypedBytes) { 9 | static Size = 32; 10 | }, 11 | docRef: OffChainDidDocRef, 12 | }; 13 | } 14 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/onchain/constants.js: -------------------------------------------------------------------------------- 1 | export const DockDIDMethod = 'dock'; 2 | export const CheqdDIDMethod = 'cheqd'; 3 | export const Secp256k1PublicKeyPrefix = 'zQ3s'; 4 | export const Ed25519PublicKeyPrefix = 'z6Mk'; 5 | 6 | export const DockDIDQualifier = `did:${DockDIDMethod}:`; 7 | export const DockDIDByteSize = 32; 8 | 9 | export const CheqdDIDQualifier = `did:${CheqdDIDMethod}:`; 10 | export const CheqdDIDTestnetQualifier = `${CheqdDIDQualifier}testnet:`; 11 | export const CheqdDIDMainnetQualifier = `${CheqdDIDQualifier}mainnet:`; 12 | export const CheqdDIDByteSize = 16; 13 | 14 | export const DidMethodKeyQualifier = 'did:key:'; 15 | export const DidMethodKeySecp256k1ByteSize = 33; 16 | export const DidMethodKeyEd25519ByteSize = 32; 17 | 18 | export const DidMethodKeySecp256k1Prefix = `${DidMethodKeyQualifier}${Secp256k1PublicKeyPrefix}`; 19 | export const DidMethodKeyEd25519Prefix = `${DidMethodKeyQualifier}${Ed25519PublicKeyPrefix}`; 20 | 21 | export const DidMethodKeyBytePrefixEd25519 = new Uint8Array([0xed, 0x01]); 22 | export const DidMethodKeyBytePrefixSecp256k1 = new Uint8Array([0xe7, 0x01]); 23 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/onchain/controllers.js: -------------------------------------------------------------------------------- 1 | import { TypedArray } from '../../generic'; 2 | import { DockDidOrDidMethodKey } from './typed-did'; 3 | 4 | export class Controllers extends TypedArray { 5 | static Class = DockDidOrDidMethodKey; 6 | } 7 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/onchain/index.js: -------------------------------------------------------------------------------- 1 | import { Null, TypedNumber, TypedStruct } from '../../generic'; 2 | 3 | export * from './constants'; 4 | export * from './typed-did'; 5 | export * from './controllers'; 6 | export * from './verification-relationship'; 7 | export * from './did-key'; 8 | export * from './verification-method-signature'; 9 | 10 | export class DidMethodKeyDetails extends TypedStruct { 11 | static Classes = { 12 | nonce: TypedNumber, 13 | data: Null, 14 | }; 15 | 16 | constructor(nonce) { 17 | super(nonce, null); 18 | } 19 | } 20 | 21 | export class OnchainDidDetailsValue extends TypedStruct { 22 | static Classes = { 23 | lastKeyId: TypedNumber, 24 | activeControllerKeys: TypedNumber, 25 | activeControllers: TypedNumber, 26 | }; 27 | } 28 | 29 | export class StoredOnchainDidDetailsValue extends TypedStruct { 30 | static Classes = { 31 | nonce: TypedNumber, 32 | data: OnchainDidDetailsValue, 33 | }; 34 | 35 | constructor(nonce, data) { 36 | super(nonce, data); 37 | } 38 | 39 | get lastKeyId() { 40 | return this.data.lastKeyId.value; 41 | } 42 | 43 | get activeControllerKeys() { 44 | return this.data.activeControllerKeys.value; 45 | } 46 | 47 | get activeControllers() { 48 | return this.data.activeControllers.value; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/onchain/typed-did/did-method-key/did-method-key-signature.js: -------------------------------------------------------------------------------- 1 | import { TypedEnum } from '../../../../generic'; 2 | import { 3 | SignatureEd25519Value, 4 | SignatureSecp256k1Value, 5 | } from '../../../../signatures'; 6 | 7 | export class DidMethodKeySignatureValue extends TypedEnum {} 8 | export class DidMethodKeySignatureValueEd25519 extends DidMethodKeySignatureValue { 9 | static Class = SignatureEd25519Value; 10 | } 11 | export class DidMethodKeySignatureValueSecp256k1 extends DidMethodKeySignatureValue { 12 | static Class = SignatureSecp256k1Value; 13 | } 14 | 15 | DidMethodKeySignatureValue.bindVariants( 16 | DidMethodKeySignatureValueEd25519, 17 | DidMethodKeySignatureValueSecp256k1, 18 | ); 19 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/onchain/typed-did/did-method-key/index.js: -------------------------------------------------------------------------------- 1 | // export { default as DidMethodKeyValue } from "./did-method-key-value"; 2 | export * from './did-method-key-public-key'; 3 | export * from './did-method-key-signature'; 4 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/onchain/typed-did/dock-did-value.js: -------------------------------------------------------------------------------- 1 | import { DockDIDQualifier } from '../constants'; 2 | import { decodeFromSS58, encodeAsSS58, isHex } from '../../../../utils'; 3 | import { 4 | withQualifier, 5 | TypedBytes, 6 | sized, 7 | TypedNumber, 8 | TypedStruct, 9 | } from '../../../generic'; 10 | import DidOrDidMethodKeySignature from './signature'; 11 | import { Signature } from '../../../signatures'; 12 | 13 | /** 14 | * `did:dock:*` 15 | */ 16 | export default class DockDidValue extends sized(withQualifier(TypedBytes)) { 17 | static Qualifier = DockDIDQualifier; 18 | 19 | static Type = 'did'; 20 | 21 | static Size = 32; 22 | 23 | static fromUnqualifiedString(did) { 24 | return new this(isHex(did) ? did : decodeFromSS58(did)); 25 | } 26 | 27 | /** 28 | * Returns unqualified DID encoded as a `SS58` address. 29 | */ 30 | toEncodedString() { 31 | return encodeAsSS58(this.value); 32 | } 33 | 34 | signWith(keyPair, bytes) { 35 | // eslint-disable-next-line no-use-before-define 36 | return new DockDidSignature( 37 | // eslint-disable-next-line no-use-before-define 38 | new DockDidSignatureValue(this, keyPair.keyId, keyPair.sign(bytes)), 39 | ); 40 | } 41 | } 42 | 43 | export class DockDidSignatureValue extends TypedStruct { 44 | static Classes = { 45 | did: DockDidValue, 46 | keyId: class KeyId extends TypedNumber {}, 47 | sig: Signature, 48 | }; 49 | } 50 | 51 | export class DockDidSignature extends DidOrDidMethodKeySignature { 52 | static Type = 'didSignature'; 53 | 54 | static Class = DockDidSignatureValue; 55 | } 56 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/onchain/typed-did/signature.js: -------------------------------------------------------------------------------- 1 | import { TypedEnum } from '../../../generic'; 2 | 3 | export default class DidOrDidMethodKeySignature extends TypedEnum {} 4 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/onchain/verification-method-signature.js: -------------------------------------------------------------------------------- 1 | import { valueBytes, ensureInstanceOf } from '../../../utils'; 2 | import { TypedStruct, withProp } from '../../generic'; 3 | import { SignatureEd25519Value } from '../../signatures'; 4 | import { DidKeypair } from '../../../keypairs'; 5 | import { 6 | CheqdMainnetVerificationMethodRef, 7 | CheqdTestnetVerificationMethodRef, 8 | CheqdVerificationMethodRef, 9 | } from '../document/verification-method-ref'; 10 | 11 | class BytesSignatureEd25519Value extends SignatureEd25519Value { 12 | toCheqdPayload() { 13 | return this.bytes; 14 | } 15 | } 16 | 17 | export class VerificationMethodSignature extends TypedStruct { 18 | static Classes = { 19 | verificationMethodId: CheqdVerificationMethodRef, 20 | signature: BytesSignatureEd25519Value, 21 | }; 22 | 23 | static fromDidKeypair(signer, bytes) { 24 | ensureInstanceOf(signer, DidKeypair); 25 | 26 | return new this( 27 | signer.verificationMethodId, 28 | valueBytes(signer.sign(bytes)), 29 | ); 30 | } 31 | } 32 | 33 | export class CheqdTestnetVerificationMethodSignature extends withProp( 34 | VerificationMethodSignature, 35 | 'verificationMethodId', 36 | CheqdTestnetVerificationMethodRef, 37 | ) {} 38 | 39 | export class CheqdMainnetVerificationMethodSignature extends withProp( 40 | VerificationMethodSignature, 41 | 'verificationMethodId', 42 | CheqdMainnetVerificationMethodRef, 43 | ) {} 44 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/did/onchain/verification-relationship.js: -------------------------------------------------------------------------------- 1 | import { TypedNumber } from '../../generic'; 2 | 3 | export class VerificationRelationship extends TypedNumber { 4 | constructor(value = 0) { 5 | super(value); 6 | } 7 | 8 | setAuthentication() { 9 | // eslint-disable-next-line no-bitwise 10 | this.value |= 0b0001; 11 | return this; 12 | } 13 | 14 | setAssertion() { 15 | // eslint-disable-next-line no-bitwise 16 | this.value |= 0b0010; 17 | return this; 18 | } 19 | 20 | setCapabilityInvocation() { 21 | // eslint-disable-next-line no-bitwise 22 | this.value |= 0b0100; 23 | return this; 24 | } 25 | 26 | setKeyAgreement() { 27 | // eslint-disable-next-line no-bitwise 28 | this.value |= 0b1000; 29 | return this; 30 | } 31 | 32 | setAllSigning() { 33 | // eslint-disable-next-line no-bitwise 34 | this.value |= 0b0111; 35 | return this; 36 | } 37 | 38 | isAuthentication() { 39 | // eslint-disable-next-line no-bitwise 40 | return !!(this.value & 0b0001); 41 | } 42 | 43 | isAssertion() { 44 | // eslint-disable-next-line no-bitwise 45 | return !!(this.value & 0b0010); 46 | } 47 | 48 | isCapabilityInvocation() { 49 | // eslint-disable-next-line no-bitwise 50 | return !!(this.value & 0b0100); 51 | } 52 | 53 | isKeyAgreement() { 54 | // eslint-disable-next-line no-bitwise 55 | return !!(this.value & 0b1000); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/any-of.js: -------------------------------------------------------------------------------- 1 | import { fmtIterable } from '../../utils'; 2 | import withFrom from './with-from'; 3 | 4 | class NeverInstantiated { 5 | constructor() { 6 | throw new Error('Should never be instantiated'); 7 | } 8 | } 9 | 10 | /** 11 | * Creates a new type that can be constructed from any of the provided types. 12 | * The resulting type will attempt to parse a value using each provided type in order, 13 | * returning the first successful construction or throwing an error if none succeed. 14 | * 15 | * @template T 16 | * @param {...T[]} classes - Array of types to try constructing from 17 | * @returns {anyOfTypes} A new type that can be constructed from any of the provided types 18 | */ 19 | export default function anyOf(...classes) { 20 | const name = `anyOf(${fmtIterable(classes.map((klass) => klass.name))})`; 21 | 22 | const obj = { 23 | [name]: class extends withFrom(NeverInstantiated, (value) => { 24 | let err; 25 | 26 | for (const klass of classes) { 27 | try { 28 | return klass.from(value); 29 | } catch (e) { 30 | if (err != null) { 31 | e.message = `${err.message}; ${e.message}`; 32 | } 33 | 34 | err = e; 35 | } 36 | } 37 | 38 | throw err; 39 | }) {}, 40 | }; 41 | 42 | return obj[name]; 43 | } 44 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/create-placeholder.js: -------------------------------------------------------------------------------- 1 | import { NotAConstructor } from '../../utils/interfaces'; 2 | 3 | /** 4 | * Creates a typed placeholder that implements `from`/`fromJSON`/`fromApi` and creates a value from the supplied 5 | * argument using `makePlacholder` function. 6 | * 7 | * @template P 8 | * @param {function(*): P} makePlaceholder 9 | * @returns {function(*): P} 10 | */ 11 | export default function createPlaceholder(makePlaceholder) { 12 | const name = `placeholder(${makePlaceholder.name})`; 13 | const obj = { 14 | [name]: (...args) => makePlaceholder(...args), 15 | }; 16 | 17 | obj[name][NotAConstructor] = true; 18 | obj[name].from = obj[name]; 19 | obj[name].fromApi = obj[name]; 20 | obj[name].fromJSON = obj[name]; 21 | 22 | return obj[name]; 23 | } 24 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/index.js: -------------------------------------------------------------------------------- 1 | export { default as TypedEnum } from './typed-enum'; 2 | export { default as TypedBytes } from './typed-bytes'; 3 | export { default as TypedString } from './typed-string'; 4 | export { default as createPlaceholder } from './create-placeholder'; 5 | export { default as TypedArray } from './typed-array'; 6 | export { default as TypedTuple } from './typed-tuple'; 7 | export { default as Null } from './typed-null'; 8 | export { default as option } from './option'; 9 | export { default as sized } from './sized'; 10 | export { default as TypedNumber } from './typed-number'; 11 | export { default as TypedSet } from './typed-set'; 12 | export { default as TypedMap } from './typed-map'; 13 | export { default as TypedStruct } from './typed-struct'; 14 | export { default as TypedBytesArray } from './typed-bytes-array'; 15 | export { default as TypedUUID } from './typed-uuid'; 16 | export { default as withQualifier } from './with-qualifier'; 17 | export { default as withBase } from './with-base'; 18 | export { default as withProp } from './with-prop'; 19 | export { default as withProps } from './with-props'; 20 | export { default as anyOf } from './any-of'; 21 | export { default as withFrom } from './with-from'; 22 | export { default as withNullIfNotAVariant } from './with-null-if-not-a-variant'; 23 | export { default as withBase58 } from './with-base58'; 24 | export { default as withBase64 } from './with-base64'; 25 | export { default as withBase58btc } from './with-base58btc'; 26 | export { default as withFromJSONBytes } from './with-from-json-bytes'; 27 | export * from './utils'; 28 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/typed-bytes-array.js: -------------------------------------------------------------------------------- 1 | import TypedBytes from './typed-bytes'; 2 | 3 | /** 4 | * Same as `TypedBytes` but will be converted to `Array` during JSON serialization instead of hex. 5 | */ 6 | export default class TypedBytesArray extends TypedBytes { 7 | get value() { 8 | return this.bytes; 9 | } 10 | 11 | toJSON() { 12 | return Array.from(this); 13 | } 14 | 15 | toCheqdPayload() { 16 | return this.value; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/typed-null.js: -------------------------------------------------------------------------------- 1 | import createPlaceholder from './create-placeholder'; 2 | 3 | const Null = (value) => { 4 | if (value == null || !String(value).length) { 5 | return null; 6 | } else { 7 | throw new Error(`Unexpected value received: \`${value}\``); 8 | } 9 | }; 10 | 11 | export default createPlaceholder(Null); 12 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/typed-string.js: -------------------------------------------------------------------------------- 1 | import { 2 | normalizeOrConvertStringToU8a, 3 | u8aToString, 4 | } from '../../utils/types/bytes'; 5 | import TypedBytes from './typed-bytes'; 6 | import withCatchNull from './with-catch-null'; 7 | 8 | class TypedString extends TypedBytes { 9 | constructor(value) { 10 | super(normalizeOrConvertStringToU8a(value)); 11 | } 12 | 13 | get value() { 14 | return u8aToString(this.bytes); 15 | } 16 | 17 | toJSON() { 18 | return String(this); 19 | } 20 | 21 | toString() { 22 | return this.value; 23 | } 24 | 25 | static fromApi(value) { 26 | if ( 27 | !Array.isArray(value) 28 | && !(value instanceof Uint8Array) 29 | && typeof value !== 'string' 30 | ) { 31 | return new this(String(value)); 32 | } else { 33 | return super.fromApi(value); 34 | } 35 | } 36 | 37 | eq(other) { 38 | return String(this) === String(other); 39 | } 40 | } 41 | 42 | export default withCatchNull(TypedString); 43 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/utils.js: -------------------------------------------------------------------------------- 1 | import TypedBytes from './typed-bytes'; 2 | import TypedArray from './typed-array'; 3 | import TypedBytesArray from './typed-bytes-array'; 4 | 5 | export class TypedArrayOfTypedBytes extends TypedArray { 6 | static Class = TypedBytes; 7 | } 8 | 9 | export class TypedArrayOfBytesArrays extends TypedArray { 10 | static Class = TypedBytesArray; 11 | } 12 | 13 | /** 14 | * Creates a converter function that processes an item through multiple parsers. 15 | * 16 | * @param {Function} finalize - Function to apply to each processed item 17 | * @param {Class} parserClass - Primary parser class used to parse the initial item 18 | * @param {...Function} parsers - Additional parser functions to apply 19 | * @returns {Function} A function that takes an item and returns processed results 20 | */ 21 | export const createConverter = (finalize, parserClass, ...parsers) => (item) => { 22 | // Initialize result array with original item 23 | const res = [item]; 24 | 25 | try { 26 | // First parse the item using primary parser 27 | const parsedDid = parserClass.from(item); 28 | 29 | // Then pass the parsed result through additional parsers 30 | for (const parser of parsers) { 31 | try { 32 | res.push(parser.from(parsedDid)); 33 | } catch { 34 | // Error is intentionally ignored 35 | } 36 | } 37 | } catch { 38 | // Initial parsing error is intentionally ignored 39 | } 40 | 41 | // Apply finalization to all processed results 42 | return res.map(finalize); 43 | }; 44 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/with-base58btc.js: -------------------------------------------------------------------------------- 1 | import withFrom from './with-from'; 2 | import { decodeFromBase58btc, encodeAsBase58btc } from '../../utils/encoding'; 3 | import { withExtendedStaticProperties } from '../../utils/inheritance'; 4 | 5 | export default function withBase58btc(klass) { 6 | const name = `withBase58btc(${klass.name})`; 7 | const obj = { 8 | [name]: class extends klass { 9 | // Define the static prefix as a class variable 10 | static Prefix; 11 | 12 | toString() { 13 | return this.toBase58btc(); 14 | } 15 | 16 | toJSON() { 17 | return String(this); 18 | } 19 | 20 | get value() { 21 | return this.toBase58btc(); 22 | } 23 | 24 | static fromBase58btc(str) { 25 | return this.from(decodeFromBase58btc(str)); 26 | } 27 | 28 | toBase58btc() { 29 | const { 30 | constructor: { Prefix }, 31 | } = this; 32 | 33 | return encodeAsBase58btc(Prefix, this.bytes); 34 | } 35 | }, 36 | }; 37 | 38 | return withExtendedStaticProperties( 39 | ['Prefix'], 40 | withFrom(obj[name], (value, from) => (typeof value === 'string' ? this.fromBase58btc(value) : from(value))), 41 | ); 42 | } 43 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/with-catch-null.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Wraps supplied klass into a class that catches `null`ish values in `from`/`fromJSON`/`fromApi` methods. 3 | * @template C 4 | * @param {C} klass 5 | * @returns {C} 6 | */ 7 | export default function withCatchNull(klass) { 8 | const name = `withCatchNull(${klass.name})`; 9 | 10 | const obj = { 11 | [name]: class extends klass { 12 | static from(value) { 13 | if (value == null) { 14 | throw new Error( 15 | `Unexpected \`null\`ish value received by \`${this.name}\``, 16 | ); 17 | } else { 18 | return super.from(value); 19 | } 20 | } 21 | 22 | static fromJSON(value) { 23 | if (value == null) { 24 | throw new Error( 25 | `Unexpected \`null\`ish value received by \`${this.name}\``, 26 | ); 27 | } else { 28 | return super.fromJSON(value); 29 | } 30 | } 31 | 32 | static fromApi(value) { 33 | if (value == null) { 34 | throw new Error( 35 | `Unexpected \`null\`ish value received by \`${this.name}\``, 36 | ); 37 | } else { 38 | return super.fromApi(value); 39 | } 40 | } 41 | }, 42 | }; 43 | 44 | return obj[name]; 45 | } 46 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/with-eq.js: -------------------------------------------------------------------------------- 1 | import anyOf from './any-of'; 2 | 3 | /** 4 | * Enhances `prototype.eq` of the provided class to make it catch `null`ish values and 5 | * attempt to instantiate a new value of the supplied class in case if constructor is different. 6 | * @template C 7 | * @param {C} klass 8 | * @returns {C} 9 | */ 10 | export default function withEq(klass) { 11 | const name = `withEq(${klass.name})`; 12 | 13 | const obj = { 14 | [name]: class extends klass { 15 | eq(other) { 16 | if (other == null) { 17 | return false; 18 | } else if (Object.is(this, other)) { 19 | return true; 20 | } else { 21 | let compareWith = other; 22 | const { value, constructor } = this; 23 | const tryFrom = [ 24 | constructor, 25 | value?.constructor, 26 | value?.constructor?.Class, 27 | ].filter((fn) => typeof fn?.from === 'function'); 28 | try { 29 | compareWith = constructor.from(anyOf(...tryFrom).from(compareWith)); 30 | } catch (err) { 31 | return false; 32 | } 33 | 34 | return super.eq(compareWith); 35 | } 36 | } 37 | }, 38 | }; 39 | 40 | return obj[name]; 41 | } 42 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/with-from-json-bytes.js: -------------------------------------------------------------------------------- 1 | import { u8aToString } from '../../utils'; 2 | 3 | export default function withFromJSONBytes(klass) { 4 | const name = `withFromJSONBytes(${klass.name})`; 5 | 6 | const obj = { 7 | [name]: class extends klass { 8 | static from(value) { 9 | if (value instanceof Uint8Array) { 10 | return this.fromJSON(JSON.parse(u8aToString(value))); 11 | } else { 12 | return super.from(value); 13 | } 14 | } 15 | }, 16 | }; 17 | 18 | return obj[name]; 19 | } 20 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/with-from.js: -------------------------------------------------------------------------------- 1 | export default function withFrom(klass, from, fromJSON = from, fromApi = from) { 2 | const name = `withFrom(${klass.name})`; 3 | 4 | if (!from) { 5 | throw new Error(`No \`from\` function provided for \`${klass.name}\``); 6 | } 7 | 8 | const obj = { 9 | [name]: class extends klass { 10 | static from(value) { 11 | return from.call(this, value, (v) => super.from(v)); 12 | } 13 | 14 | static fromJSON(value) { 15 | return fromJSON.call(this, value, (v) => super.fromJSON(v)); 16 | } 17 | 18 | static fromApi(value) { 19 | return fromApi.call(this, value, (v) => super.fromApi(v)); 20 | } 21 | }, 22 | }; 23 | 24 | return obj[name]; 25 | } 26 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/generic/with-prop.js: -------------------------------------------------------------------------------- 1 | import withProps from './with-props'; 2 | 3 | /** 4 | * Extends supplied class which must be a successor of `TypedStruct`/`TypedEnum` by adding/overriding 5 | * its property class. 6 | * 7 | * @template C 8 | * @template K 9 | * @param {C} klass 10 | * @param {string} prop 11 | * @param {K} PropClass 12 | * @param {function(*, string, K): *} handleNested 13 | * @returns {C} 14 | */ 15 | export default function withProp( 16 | klass, 17 | prop, 18 | PropClass, 19 | handleNested = withProp, 20 | ) { 21 | return withProps(klass, { [prop]: PropClass }, (k, _) => handleNested(k, prop, PropClass)); 22 | } 23 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/index.js: -------------------------------------------------------------------------------- 1 | export * from './blob'; 2 | export * from './attest'; 3 | export * from './did'; 4 | export * from './offchain-signatures'; 5 | export * from './payload'; 6 | export * from './policy'; 7 | export * from './public-keys'; 8 | export * from './signatures'; 9 | export * from './status-list-credential'; 10 | export * from './anchor'; 11 | export * from './accumulator'; 12 | export * from './trust-registry'; 13 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/offchain-signatures/curve-type.js: -------------------------------------------------------------------------------- 1 | import { Null, TypedEnum } from '../generic'; 2 | 3 | export class CurveType extends TypedEnum {} 4 | 5 | export class CurveTypeBls12381 extends CurveType { 6 | static Class = Null; 7 | 8 | static Type = 'bls12381'; 9 | } 10 | 11 | CurveType.bindVariants(CurveTypeBls12381); 12 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/offchain-signatures/index.js: -------------------------------------------------------------------------------- 1 | import { TypedTuple } from '../generic'; 2 | import { 3 | OffchainSignatureParams, 4 | OffchainSignatureParamsValue, 5 | } from './params'; 6 | import { 7 | OffchainSignaturePublicKey, 8 | OffchainSignaturePublicKeyValue, 9 | } from './public-keys'; 10 | 11 | export * from './params'; 12 | export * from './public-keys'; 13 | export * from './curve-type'; 14 | 15 | export class OffchainSignaturePublicKeyWithParams extends TypedTuple { 16 | static Classes = [OffchainSignaturePublicKey, OffchainSignatureParams]; 17 | } 18 | 19 | export class OffchainSignaturePublicKeyValueWithParamsValue extends TypedTuple { 20 | static Classes = [ 21 | OffchainSignaturePublicKeyValue, 22 | OffchainSignatureParamsValue, 23 | ]; 24 | } 25 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/offchain-signatures/params/id.js: -------------------------------------------------------------------------------- 1 | import { TypedNumber, TypedUUID } from '../../generic'; 2 | import withFromDockId from '../../generic/with-from-dock-id'; 3 | 4 | export class DockParamsId extends TypedNumber {} 5 | 6 | export class CheqdParamsId extends withFromDockId( 7 | TypedUUID, 8 | DockParamsId, 9 | 'offchain-signature-params', 10 | ) {} 11 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/offchain-signatures/params/index.js: -------------------------------------------------------------------------------- 1 | import { TypedEnum } from '../../generic'; 2 | import { BBSParamsValue, BBSPlusParamsValue, PSParamsValue } from './value'; 3 | 4 | export class OffchainSignatureParams extends TypedEnum { 5 | get bytes() { 6 | return this.value.bytes; 7 | } 8 | 9 | get label() { 10 | return this.value.label; 11 | } 12 | 13 | get curveType() { 14 | return this.value.curveType; 15 | } 16 | } 17 | export class BBSParams extends OffchainSignatureParams { 18 | static Type = 'bbs'; 19 | 20 | static Class = BBSParamsValue; 21 | } 22 | export class BBSPlusParams extends OffchainSignatureParams { 23 | static Type = 'bbsPlus'; 24 | 25 | static Class = BBSPlusParamsValue; 26 | } 27 | export class PSParams extends OffchainSignatureParams { 28 | static Type = 'ps'; 29 | 30 | static Class = PSParamsValue; 31 | } 32 | export class BBDT16Params extends OffchainSignatureParams { 33 | static Type = 'bbdt16'; 34 | 35 | static Class = BBDT16Params; 36 | } 37 | 38 | OffchainSignatureParams.bindVariants(BBSParams, BBSPlusParams, PSParams); 39 | 40 | export * from './value'; 41 | export * from './id'; 42 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/offchain-signatures/params/value.js: -------------------------------------------------------------------------------- 1 | import { TypedBytes, TypedStruct, option } from '../../generic'; 2 | import { CurveType, CurveTypeBls12381 } from '../curve-type'; 3 | 4 | export class OffchainSignatureParamsValue extends TypedStruct { 5 | static Classes = { 6 | bytes: class Bytes extends TypedBytes {}, 7 | label: option(class Label extends TypedBytes {}), 8 | curveType: CurveType, 9 | }; 10 | 11 | constructor(bytes, label, curveType = new CurveTypeBls12381()) { 12 | super(bytes, label, curveType); 13 | } 14 | } 15 | export class BBSParamsValue extends OffchainSignatureParamsValue { 16 | static Type = 'bbs'; 17 | } 18 | export class BBSPlusParamsValue extends OffchainSignatureParamsValue { 19 | static Type = 'bbsPlus'; 20 | } 21 | export class PSParamsValue extends OffchainSignatureParamsValue { 22 | static Type = 'ps'; 23 | } 24 | export class BBDT16ParamsValue extends OffchainSignatureParamsValue { 25 | static Type = 'bbdt16'; 26 | } 27 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/offchain-signatures/public-keys/id.js: -------------------------------------------------------------------------------- 1 | import { TypedNumber, TypedUUID, anyOf } from '../../generic'; 2 | 3 | export class DockPublicKeyId extends TypedNumber {} 4 | 5 | export class CheqdPublicKeyId extends TypedUUID {} 6 | 7 | export class DockOrCheqdPublicKeyId extends anyOf( 8 | DockPublicKeyId, 9 | CheqdPublicKeyId, 10 | ) {} 11 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/payload/index.js: -------------------------------------------------------------------------------- 1 | export * from './cheqd'; 2 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/policy/index.js: -------------------------------------------------------------------------------- 1 | import { TypedEnum } from '../generic'; 2 | import OneOfPolicyValue from './one-of-policy-value'; 3 | 4 | export class Policy extends TypedEnum {} 5 | export class OneOfPolicy extends Policy { 6 | static Class = OneOfPolicyValue; 7 | 8 | /** 9 | * Add a owner to the policy 10 | * @param {*} ownerDID - Owner's DID 11 | */ 12 | addOwner(ownerDID) { 13 | return this.value.add(ownerDID); 14 | } 15 | } 16 | 17 | Policy.bindVariants(OneOfPolicy); 18 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/policy/one-of-policy-value.js: -------------------------------------------------------------------------------- 1 | import { TypedSet } from '../generic'; 2 | import { DockDidOrDidMethodKey } from '../did/onchain/typed-did'; 3 | 4 | /** 5 | * Constructs a OneOfPolicy with given controllers 6 | * @param {Iterable<*>} [controllers] - Controller set 7 | * @constructor 8 | */ 9 | export default class OneOfPolicyValue extends TypedSet { 10 | static Type = 'oneOf'; 11 | 12 | static Class = DockDidOrDidMethodKey; 13 | } 14 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/public-keys/index.js: -------------------------------------------------------------------------------- 1 | export * from './public-key'; 2 | 3 | export { default as PublicKeySr25519Value } from './public-key-sr25519-value'; 4 | export { default as PublicKeyEd25519Value } from './public-key-ed25519-value'; 5 | export { default as PublicKeySecp256k1Value } from './public-key-secp256k1-value'; 6 | export { default as PublicKeyX25519Value } from './public-key-x25519-value'; 7 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/public-keys/public-key-ed25519-value.js: -------------------------------------------------------------------------------- 1 | import { sized, TypedBytes } from '../generic'; 2 | import { Ed25519VerKeyName } from '../../vc/crypto/constants'; 3 | 4 | /** Class representing value of a Ed25519 PublicKey */ 5 | export default class PublicKeyEd25519Value extends sized(TypedBytes) { 6 | static Type = 'ed25519'; 7 | 8 | static Size = 32; 9 | 10 | static VerKeyType = Ed25519VerKeyName; 11 | } 12 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/public-keys/public-key-secp256k1-value.js: -------------------------------------------------------------------------------- 1 | import { sized, TypedBytes } from '../generic'; 2 | import { EcdsaSecp256k1VerKeyName } from '../../vc/crypto/constants'; 3 | 4 | /** Class representing value of a compressed Secp256k1 PublicKey */ 5 | export default class PublicKeySecp256k1Value extends sized(TypedBytes) { 6 | static Type = 'secp256k1'; 7 | 8 | static Size = 33; 9 | 10 | static VerKeyType = EcdsaSecp256k1VerKeyName; 11 | } 12 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/public-keys/public-key-sr25519-value.js: -------------------------------------------------------------------------------- 1 | import { sized, TypedBytes } from '../generic'; 2 | import { Sr25519VerKeyName } from '../../vc/crypto/constants'; 3 | 4 | /** Class representing value of a Sr25519 PublicKey */ 5 | export default class PublicKeySr25519Value extends sized(TypedBytes) { 6 | static Type = 'sr25519'; 7 | 8 | static Size = 32; 9 | 10 | static VerKeyType = Sr25519VerKeyName; 11 | } 12 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/public-keys/public-key-x25519-value.js: -------------------------------------------------------------------------------- 1 | import { sized, TypedBytes } from '../generic'; 2 | 3 | /** Class representing value of a X25519 PublicKey */ 4 | export default class PublicKeyX25519Value extends sized(TypedBytes) { 5 | static Type = 'x25519'; 6 | 7 | static Size = 32; 8 | 9 | static VerKeyType = 'X25519KeyAgreementKey2019'; 10 | } 11 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/public-keys/public-key.js: -------------------------------------------------------------------------------- 1 | import { TypedEnum } from '../generic'; 2 | import PublicKeyX25519Value from './public-key-x25519-value'; 3 | import PublicKeyEd25519Value from './public-key-ed25519-value'; 4 | import PublicKeySecp256k1Value from './public-key-secp256k1-value'; 5 | import PublicKeySr25519Value from './public-key-sr25519-value'; 6 | 7 | /** 8 | * Class representing either Ed25519 or Secp256k1 or Sr25519 or X25519 PublicKey 9 | * @class 10 | * @extends {TypedEnum} 11 | */ 12 | export class PublicKey extends TypedEnum { 13 | static get VerKeyType() { 14 | return this.Class.VerKeyType; 15 | } 16 | } 17 | /** 18 | * Class representing Ed25519 PublicKey 19 | * @class 20 | * @extends {PublicKey} 21 | */ 22 | export class PublicKeyEd25519 extends PublicKey { 23 | static Class = PublicKeyEd25519Value; 24 | } 25 | /** 26 | * Class representing Secp256k1 PublicKey 27 | * @class 28 | * @extends {PublicKey} 29 | */ 30 | export class PublicKeySecp256k1 extends PublicKey { 31 | static Class = PublicKeySecp256k1Value; 32 | } 33 | /** 34 | * Class representing Sr25519 PublicKey 35 | * @class 36 | * @extends {PublicKey} 37 | */ 38 | export class PublicKeySr25519 extends PublicKey { 39 | static Class = PublicKeySr25519Value; 40 | } 41 | /** 42 | * Class representing X25519 PublicKey 43 | * @class 44 | * @extends {PublicKey} 45 | */ 46 | export class PublicKeyX25519 extends PublicKey { 47 | static Class = PublicKeyX25519Value; 48 | } 49 | 50 | PublicKey.bindVariants( 51 | PublicKeyEd25519, 52 | PublicKeySecp256k1, 53 | PublicKeySr25519, 54 | PublicKeyX25519, 55 | ); 56 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/signatures/index.js: -------------------------------------------------------------------------------- 1 | import SignatureSr25519Value from './signature-sr25519-value'; 2 | import SignatureEd25519Value from './signature-ed25519-value'; 3 | import SignatureSecp256k1Value from './signature-secp256k1-value'; 4 | 5 | export { 6 | SignatureSr25519Value, 7 | SignatureEd25519Value, 8 | SignatureSecp256k1Value, 9 | }; 10 | export * from './signature'; 11 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/signatures/signature-ed25519-value.js: -------------------------------------------------------------------------------- 1 | import { PublicKeyEd25519 } from '../public-keys'; 2 | import SignatureValue from './signature-value'; 3 | 4 | /** Class representing a Ed25519 Signature */ 5 | export default class SignatureEd25519Value extends SignatureValue { 6 | static PublicKey = PublicKeyEd25519; 7 | 8 | static Size = 64; 9 | } 10 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/signatures/signature-secp256k1-value.js: -------------------------------------------------------------------------------- 1 | import SignatureValue from './signature-value'; 2 | import { PublicKeySecp256k1 } from '../public-keys'; 3 | 4 | /** Class representing a Secp256k1 Signature */ 5 | export default class SignatureSecp256k1Value extends SignatureValue { 6 | static PublicKey = PublicKeySecp256k1; 7 | 8 | static Size = 65; 9 | } 10 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/signatures/signature-sr25519-value.js: -------------------------------------------------------------------------------- 1 | import { PublicKeySr25519 } from '../public-keys'; 2 | import SignatureValue from './signature-value'; 3 | 4 | /** Class representing a Sr25519 Signature */ 5 | export default class SignatureSr25519Value extends SignatureValue { 6 | static PublicKey = PublicKeySr25519; 7 | 8 | static Size = 64; 9 | } 10 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/signatures/signature-value.js: -------------------------------------------------------------------------------- 1 | import { withExtendedStaticProperties } from '../../utils/inheritance'; 2 | import { sized, TypedBytes } from '../generic'; 3 | 4 | /** Class representing a Signature. This export class should always be extended (abstract export class in some languages) */ 5 | export default withExtendedStaticProperties( 6 | ['PublicKey'], 7 | class SignatureValue extends sized(TypedBytes) { 8 | /** 9 | * Public key associated with the signature. 10 | * @type {typeof PublicKey} 11 | */ 12 | static PublicKey; 13 | 14 | static get Type() { 15 | return this.PublicKey.Type; 16 | } 17 | 18 | /** 19 | * Returns the size of the underlying signature. 20 | */ 21 | get size() { 22 | return this.constructor.Size; 23 | } 24 | }, 25 | ); 26 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/signatures/signature.js: -------------------------------------------------------------------------------- 1 | import { TypedEnum } from '../generic'; 2 | import SignatureEd25519Value from './signature-ed25519-value'; 3 | import SignatureSecp256k1Value from './signature-secp256k1-value'; 4 | import SignatureSr25519Value from './signature-sr25519-value'; 5 | 6 | /** 7 | * Class representing either Ed25519 or Secp256k1 or Sr25519 Signature 8 | * @class 9 | * @extends {TypedEnum} 10 | */ 11 | export class Signature extends TypedEnum { 12 | static get PublicKey() { 13 | return this.Class.PublicKey; 14 | } 15 | 16 | get bytes() { 17 | return this.value.bytes; 18 | } 19 | } 20 | /** 21 | * Class representing Ed25519 Signature 22 | * @class 23 | * @extends {Signature} 24 | */ 25 | export class SignatureEd25519 extends Signature { 26 | static Class = SignatureEd25519Value; 27 | } 28 | /** 29 | * Class representing Secp256k1 Signature 30 | * @class 31 | * @extends {Signature} 32 | */ 33 | export class SignatureSecp256k1 extends Signature { 34 | static Class = SignatureSecp256k1Value; 35 | } 36 | /** 37 | * Class representing Sr25519 Signature 38 | * @class 39 | * @extends {SignatureEd25519OrSignatureSecp256k1OrSignatureSr25519} 40 | */ 41 | export class SignatureSr25519 extends Signature { 42 | static Class = SignatureSr25519Value; 43 | } 44 | 45 | Signature.bindVariants(SignatureEd25519, SignatureSecp256k1, SignatureSr25519); 46 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/trust-registry/id.js: -------------------------------------------------------------------------------- 1 | import { TypedBytes, sized } from '../generic'; 2 | 3 | export class TrustRegistryId extends TypedBytes {} 4 | 5 | export class DockTrustRegistryId extends sized(TrustRegistryId) { 6 | static Size = 32; 7 | } 8 | 9 | export class TrustRegistrySchemaId extends TypedBytes {} 10 | 11 | export class DockTrustRegistrySchemaId extends sized(TypedBytes) { 12 | static Size = 32; 13 | } 14 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/trust-registry/index.js: -------------------------------------------------------------------------------- 1 | import { TypedMap, TypedString, TypedStruct } from '../generic'; 2 | import { DockDidOrDidMethodKey } from '../did'; 3 | import { TrustRegistrySchemas } from './schema'; 4 | import { TrustRegistryId } from './id'; 5 | 6 | export class TrustRegistryInfo extends TypedStruct { 7 | static Classes = { 8 | name: class Name extends TypedString {}, 9 | govFramework: class GovFramework extends TypedString {}, 10 | convener: class Convener extends DockDidOrDidMethodKey {}, 11 | }; 12 | } 13 | 14 | export class TrustRegistryParticipantInformation extends TypedStruct { 15 | static Classes = { 16 | orgName: class OrgName extends TypedString {}, 17 | logo: class Logo extends TypedString {}, 18 | description: class Description extends TypedString {}, 19 | }; 20 | } 21 | 22 | export class TrustRegistry extends TypedStruct { 23 | static Classes = { 24 | info: TrustRegistryInfo, 25 | schemas: TrustRegistrySchemas, 26 | }; 27 | } 28 | 29 | export class TrustRegistries extends TypedMap { 30 | static KeyClass = TrustRegistryId; 31 | 32 | static ValueClass = TrustRegistry; 33 | } 34 | 35 | export * from './id'; 36 | export * from './issuer'; 37 | export * from './schema'; 38 | export * from './verifier'; 39 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/trust-registry/issuer.js: -------------------------------------------------------------------------------- 1 | import { DockDidOrDidMethodKey } from '../did'; 2 | import { 3 | TypedMap, TypedNumber, TypedSet, TypedString, 4 | } from '../generic'; 5 | 6 | export class VerificationPrices extends TypedMap { 7 | static KeyClass = TypedString; 8 | 9 | static ValueClass = TypedNumber; 10 | } 11 | 12 | export class Issuer extends DockDidOrDidMethodKey {} 13 | 14 | export class IssuersSet extends TypedSet { 15 | static Class = Issuer; 16 | } 17 | 18 | export class Issuers extends TypedMap { 19 | static KeyClass = Issuer; 20 | 21 | static ValueClass = VerificationPrices; 22 | } 23 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/trust-registry/schema.js: -------------------------------------------------------------------------------- 1 | import { TrustRegistryId } from './id'; 2 | import { TypedMap, TypedStruct } from '../generic'; 3 | import { Issuers } from './issuer'; 4 | import { Verifiers } from './verifier'; 5 | 6 | export class TrustRegistrySchema extends TypedStruct { 7 | static Classes = { 8 | verifiers: Verifiers, 9 | issuers: Issuers, 10 | }; 11 | } 12 | 13 | export class TrustRegistrySchemas extends TypedMap { 14 | static KeyClass = TrustRegistryId; 15 | 16 | static ValueClass = TrustRegistrySchema; 17 | } 18 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/types/trust-registry/verifier.js: -------------------------------------------------------------------------------- 1 | import { DockDidOrDidMethodKey } from '../did'; 2 | import { TypedSet } from '../generic'; 3 | 4 | export class Verifier extends DockDidOrDidMethodKey {} 5 | 6 | export class Verifiers extends TypedSet { 7 | static Class = Verifier; 8 | } 9 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/assert.js: -------------------------------------------------------------------------------- 1 | import { panic } from './error'; 2 | 3 | /** 4 | * Asserts that a condition is true; otherwise, throws an error using the panic function. 5 | * @param {boolean} cond - The condition to check. 6 | * @param {function | string | Error} error - The error message, function returning an error, or an Error object to throw. 7 | */ 8 | export const assert = (cond, error) => { 9 | if (!cond) { 10 | panic(error); 11 | } 12 | }; 13 | 14 | /** 15 | * Error thrown when the provided function was executed more than once or wasn't executed at all. 16 | */ 17 | export class MustBeCalledOnce extends Error { 18 | constructor(fn) { 19 | super(`Function must be executed exactly once: \`${fn}\``); 20 | } 21 | 22 | static ensure(fn, call) { 23 | let executed = false; 24 | 25 | const name = `mustBeExecutedOnce(${fn.name})`; 26 | const obj = { 27 | [name](...args) { 28 | let res; 29 | let err; 30 | 31 | assert(!executed, () => new this(fn)); 32 | try { 33 | res = fn.apply(this, args); 34 | } catch (e) { 35 | err = e; 36 | } finally { 37 | executed = true; 38 | } 39 | 40 | if (err != null) { 41 | throw err; 42 | } 43 | return res; 44 | }, 45 | }; 46 | 47 | const res = call(obj[name]); 48 | assert(executed, () => new this(fn)); 49 | 50 | return res; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/async/index.js: -------------------------------------------------------------------------------- 1 | export * from './merge'; 2 | export { default as MemoizedPromise } from './memoized-promise'; 3 | export { default as MemoizedPromiseMap } from './memoized-promise-map'; 4 | export { default as retry } from './retry'; 5 | export * from './timeout'; 6 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/async/memoized-promise.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A promise that can be reused. 3 | */ 4 | export default class MemoizedPromise { 5 | /** 6 | * 7 | * @param {object} configuration 8 | * @param {boolean} [configuration.save=false] - if set to `true`, stores the result of the first successful promise forever. 9 | */ 10 | constructor({ save = false } = {}) { 11 | this.promise = null; 12 | this.save = save; 13 | } 14 | 15 | /** 16 | * Checks if a promise exists, if so, `await`s it, otherwise sets a new `Promise` produced by 17 | * calling `createPromise` function. 18 | * 19 | * @template T 20 | * @param {function(): Promise} createPromise 21 | * @returns {Promise} 22 | */ 23 | async call(createPromise) { 24 | if (this.promise != null) { 25 | return await this.promise; 26 | } 27 | const promise = createPromise(); 28 | this.promise = promise; 29 | 30 | let res; 31 | let err; 32 | try { 33 | res = await this.promise; 34 | } catch (e) { 35 | err = e; 36 | } finally { 37 | if ((!this.save || err != null) && this.promise === promise) { 38 | this.clear(); 39 | } 40 | } 41 | 42 | if (err != null) { 43 | throw err; 44 | } 45 | return res; 46 | } 47 | 48 | clear() { 49 | this.promise = null; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/async/merge.js: -------------------------------------------------------------------------------- 1 | import { toIterable } from '../types'; 2 | 3 | /** 4 | * Merges objects obtained from an iterable of promises sequentially. Each promise is expected to resolve to an object. 5 | * The properties are merged into an accumulated object, with later ones overwriting earlier duplicates if keys conflict. 6 | * 7 | * @template T 8 | * @param {Iterable>>} objectPromises - An iterable of promises where each promise resolves to an object. 9 | * @returns {Promise>} The accumulated merged object containing properties from all resolved objects. If duplicate keys exist, 10 | * later values overwrite earlier ones. 11 | * @throws {Error} If any promise does not resolve to an object or rejects, this function will throw an error. 12 | */ 13 | export const mergeAwait = async (objectPromises) => { 14 | const res = {}; 15 | 16 | for await (const obj of toIterable(objectPromises)) { 17 | Object.assign(res, obj); 18 | } 19 | 20 | return res; 21 | }; 22 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/async/timeout.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Creates a promise that will call the optional supplied function `f` and return its result after `time` passes. 3 | * If no function is provided, the promise will be resolved to `undefined`. 4 | * 5 | * @template T 6 | * @param {number} time 7 | * @param {function(): Promise} f 8 | * @returns {Promise} 9 | */ 10 | export const timeout = async (time, f = async () => {}) => await new Promise((resolve, reject) => setTimeout(async () => { 11 | try { 12 | resolve(await f()); 13 | } catch (error) { 14 | reject(error); 15 | } 16 | }, time)); 17 | 18 | /** 19 | * Combines supplied `promise` with a `timeout` that will call supplied `f` after `time` passes. 20 | * Resolves to the earliest produced value. 21 | * 22 | * @template T 23 | * @param {Promise} promise 24 | * @param {number} time 25 | * @param {function(): Promise} [f=()=>{throw new Error("Timeout exceeded")}] 26 | * @returns {Promise} 27 | */ 28 | export const withTimeout = async ( 29 | promise, 30 | time, 31 | f = () => { 32 | throw new Error('Timeout exceeded'); 33 | }, 34 | ) => await Promise.race([promise, timeout(time, f)]); 35 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/encoding/base-58-btc.js: -------------------------------------------------------------------------------- 1 | import { base58btc } from 'multiformats/bases/base58'; 2 | import varint from 'varint'; 3 | import { ensureString } from '../types/string'; 4 | import { normalizeToU8a } from '../types/bytes'; 5 | import { catchFnErrorWith } from '../error'; 6 | 7 | /** 8 | * Encodes supplied bytes as base58btc string using given prefix. 9 | * @param {Uint8Array} value 10 | * @param {Uint8Array} prefix 11 | * @returns {string} 12 | */ 13 | export const encodeAsBase58btc = (prefix, value) => { 14 | const prefixBytes = normalizeToU8a(prefix); 15 | const bytes = normalizeToU8a(value); 16 | 17 | // Use the supplied prefix 18 | const multibase = new Uint8Array(prefixBytes.length + bytes.length); 19 | 20 | // Add multibase prefix and concatenate with bytes 21 | multibase.set(prefixBytes); 22 | multibase.set(bytes, prefixBytes.length); 23 | 24 | // Return the encoded base58btc multibase string 25 | return base58btc.encode(multibase); 26 | }; 27 | 28 | /** 29 | * Decodes bytes of the supplied base58btc string. 30 | * @param {string} string 31 | * @returns {Uint8Array} 32 | */ 33 | export const decodeFromBase58btc = catchFnErrorWith( 34 | 'Invalid base58btc string', 35 | (string) => { 36 | // Decode base58btc multibase string 37 | const decoded = base58btc.decode(ensureString(string)); 38 | varint.decode(decoded); // Decode to get byte length 39 | return decoded.slice(varint.decode.bytes); 40 | }, 41 | ); 42 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/encoding/base-58.js: -------------------------------------------------------------------------------- 1 | import bs58 from 'bs58'; 2 | import { ensureString } from '../types/string'; 3 | import { normalizeToU8a } from '../types/bytes'; 4 | import { catchFnErrorWith } from '../error'; 5 | 6 | /** 7 | * Encodes supplied bytes as base58 string. 8 | * @param {Uint8Array} bytes 9 | * @returns {string} 10 | */ 11 | export const encodeAsBase58 = (bytes) => bs58.encode(normalizeToU8a(bytes)); 12 | /** 13 | * Decodes bytes of the supplied base58 string. 14 | * @param {string} string 15 | * @returns {Uint8Array} 16 | */ 17 | export const decodeFromBase58 = catchFnErrorWith( 18 | 'Invalid base58btc string', 19 | (string) => bs58.decode(ensureString(string)), 20 | ); 21 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/encoding/base-64.js: -------------------------------------------------------------------------------- 1 | import { ensureString } from '../types/string'; 2 | import { normalizeToU8a, u8aToU8a } from '../types/bytes'; 3 | import { catchFnErrorWith } from '../error'; 4 | 5 | /** 6 | * Encodes supplied bytes as base64 string. 7 | * @param {Uint8Array} bytes 8 | * @returns {string} 9 | */ 10 | export const encodeAsBase64 = (bytes) => Buffer.from(normalizeToU8a(bytes)).toString('base64'); 11 | /** 12 | * Decodes bytes of the supplied base64 string. 13 | * @param {string} string 14 | * @returns {Uint8Array} 15 | */ 16 | export const decodeFromBase64 = catchFnErrorWith( 17 | 'Invalid base64 string', 18 | (string) => u8aToU8a(Buffer.from(ensureString(string), 'base64')), 19 | ); 20 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/encoding/index.js: -------------------------------------------------------------------------------- 1 | export * from './base-58'; 2 | export * from './base-58-btc'; 3 | export * from './base-64'; 4 | export * from './ss-58'; 5 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/ident/index.js: -------------------------------------------------------------------------------- 1 | export * from './ensure-ident'; 2 | export * from './matchers'; 3 | export * from './parsers'; 4 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/ident/parsers.js: -------------------------------------------------------------------------------- 1 | import { DID_MATCHER } from './matchers'; 2 | import { ensureString } from '../types/string'; 3 | 4 | /** 5 | * Parses supplied DID URL. 6 | * @param {string} didUrl 7 | * @returns {object} 8 | */ 9 | export function parseDIDUrl(didUrl) { 10 | const sections = ensureString(didUrl).match(DID_MATCHER); 11 | 12 | if (sections == null) { 13 | throw new Error(`Invalid DID: \`${didUrl}\``); 14 | } 15 | 16 | const parts = { 17 | did: `did:${sections[1]}:${sections[2]}`, 18 | method: sections[1], 19 | id: sections[2], 20 | didUrl, 21 | }; 22 | if (sections[4]) { 23 | const params = sections[4].slice(1).split(';'); 24 | parts.params = {}; 25 | for (const p of params) { 26 | const kv = p.split('='); 27 | 28 | // eslint-disable-next-line prefer-destructuring 29 | parts.params[kv[0]] = kv[1]; 30 | } 31 | } 32 | // eslint-disable-next-line prefer-destructuring 33 | if (sections[6]) parts.path = sections[6]; 34 | if (sections[7]) parts.query = sections[7].slice(1); 35 | if (sections[8]) parts.fragment = sections[8].slice(1); 36 | return parts; 37 | } 38 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/index.js: -------------------------------------------------------------------------------- 1 | export * from './types'; 2 | export * from './interfaces'; 3 | export * from './async'; 4 | export * from './json-fetch'; 5 | export * from './inheritance'; 6 | export * from './encoding'; 7 | export * from './pattern-matcher'; 8 | export * from './ident'; 9 | export * from './error'; 10 | export * from './assert'; 11 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/json-fetch.js: -------------------------------------------------------------------------------- 1 | export class JSONFetchError extends Error { 2 | constructor(message, statusCode) { 3 | super(message); 4 | 5 | this.statusCode = statusCode; 6 | } 7 | } 8 | 9 | export default async function jsonFetch(url, options) { 10 | if (url.startsWith('blob:')) { 11 | throw new Error('Unsupported protocol blob:'); 12 | } 13 | 14 | let response; 15 | try { 16 | response = await fetch(url, options); 17 | } catch (e) { 18 | throw new Error(`Fetch failed for URL: ${url}`); 19 | } 20 | if (response.ok) { 21 | let doc; 22 | try { 23 | doc = await response.json(); 24 | } catch (e) { 25 | throw new Error(`URL: ${url} is not JSON`); 26 | } 27 | return doc; 28 | } else { 29 | // Handle the case when the fetch request fails (e.g., non-2xx response status) 30 | throw new JSONFetchError('Failed to fetch data', response.status); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/types/index.js: -------------------------------------------------------------------------------- 1 | export * from './array'; 2 | export * from './number'; 3 | export * from './promise'; 4 | export * from './iterable'; 5 | export * from './map'; 6 | export * from './object'; 7 | export * from './string'; 8 | export * from './set'; 9 | export * from './bigint'; 10 | export * from './bytes'; 11 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/types/number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Return true if the given value is a number. 3 | * @param value 4 | * @returns {boolean} 5 | */ 6 | export function isNumber(value) { 7 | return ( 8 | (typeof value === 'number' && !Number.isNaN(value)) 9 | || value instanceof Number 10 | ); 11 | } 12 | 13 | /** 14 | * Ensures that the given value is a number. Throws an error with an optional context message if not. 15 | * @param {any} value - The value to check. 16 | * @param {string} [message] - Optional message for the error. 17 | * @returns {number} - The value converted to a number. 18 | */ 19 | export function ensureNumber(value) { 20 | if (isNumber(value)) { 21 | return Number(value); 22 | } 23 | 24 | throw new TypeError(`\`${value}\` needs to be a number.`); 25 | } 26 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/types/promise.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Return true if the given value is a an instance of `Promise`. 3 | * @param value 4 | * @returns {boolean} 5 | */ 6 | export function isPromise(value) { 7 | return value instanceof Promise; 8 | } 9 | 10 | /** 11 | * Ensures that the given value is a Promise. Throws an error with an optional context message if not. 12 | * @param {any} value - The value to check. 13 | * @param {string} [message] - Optional message for the error. 14 | * @returns {Promise} - The original promise value. 15 | */ 16 | export function ensurePromise(value) { 17 | if (isPromise(value)) { 18 | return value; 19 | } 20 | 21 | throw new TypeError(`\`${value}\` needs to be a Promise.`); 22 | } 23 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/types/set.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Return true if the given value is a Set. 3 | * @param value 4 | * @returns {boolean} 5 | */ 6 | export function isSet(value) { 7 | return value instanceof Set; 8 | } 9 | 10 | /** 11 | * Ensures that the given value is a Set. Throws an error with an optional context message if not. 12 | * @param {any} value - The value to check. 13 | * @param {string} [message] - Optional message for the error. 14 | * @returns {Set} - The value if it's a Set. 15 | */ 16 | export function ensureSet(value) { 17 | if (isSet(value)) { 18 | return value; 19 | } 20 | 21 | throw new TypeError(`\`${value}\` needs to be a Set.`); 22 | } 23 | 24 | /** 25 | * Ensures that there is no intersection between two sets 26 | * @param {Set} set1 - The first set to compare 27 | * @param {Set} set2 - The second set to compare 28 | * @throws {Error} - If there is an intersection between set1 and set2 29 | */ 30 | export const ensureNoIntersection = (set1, set2) => { 31 | const [min, max] = [set1, set2] 32 | .map(ensureSet) 33 | .sort((a, b) => a.size - b.size); 34 | 35 | for (const item of min) { 36 | if (max.has(item)) { 37 | throw new Error(`Item \`${item}\` exists in both sets`); 38 | } 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/utils/types/string.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Return true if the given value is a string. 3 | * @param value 4 | * @returns {boolean} 5 | */ 6 | export function isString(value) { 7 | return typeof value === 'string' || value instanceof String; 8 | } 9 | 10 | /** 11 | * Ensures that the given value is a string. If not, throws an error with an optional context message. 12 | * 13 | * @param {*} value - The value to check. 14 | * @returns {string} - The value converted to a string. 15 | */ 16 | export function ensureString(value) { 17 | if (isString(value)) { 18 | return String(value); 19 | } 20 | 21 | throw new TypeError(`${value} needs to be a string`); 22 | } 23 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/constants.js: -------------------------------------------------------------------------------- 1 | // XXX: Does it make sense to have a revocation registry type for Dock like below and eliminate the need for `rev_reg:dock:`? 2 | // export const RevRegType = 'DockRevocationRegistry2020'; 3 | export const RevRegType = 'CredentialStatusList2017'; 4 | export const StatusList2021EntryType = 'StatusList2021Entry'; 5 | export const PrivateStatusList2021EntryType = 'PrivateStatusList2021Entry'; 6 | export const DockRevRegQualifier = 'rev-reg:dock:'; 7 | export const DockStatusList2021Qualifier = 'status-list2021:dock:'; 8 | export const CheqdStatusList2021Qualifier = 'status-list2021:cheqd:'; 9 | export const PrivateStatusList2021Qualifier = 'private-status-list2021:'; 10 | export const DEFAULT_TYPE = 'VerifiableCredential'; 11 | export const DEFAULT_CONTEXT_URL = 'https://www.w3.org/2018/credentials'; 12 | export const DEFAULT_CONTEXT = `${DEFAULT_CONTEXT_URL}/v1`; 13 | export const DEFAULT_CONTEXT_V1_URL = 'https://www.w3.org/2018/credentials/v1'; 14 | export const expandedStatusProperty = `${DEFAULT_CONTEXT_URL}#credentialStatus`; 15 | export const expandedCredentialProperty = `${DEFAULT_CONTEXT_URL}#verifiableCredential`; 16 | export const expandedSubjectProperty = `${DEFAULT_CONTEXT_URL}#credentialSubject`; 17 | export const expandedSchemaProperty = `${DEFAULT_CONTEXT_URL}#credentialSchema`; 18 | export const credentialIDField = '@id'; 19 | export const credentialContextField = '@context'; 20 | export const credentialTypeField = '@type'; 21 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/contexts/prettyvc.json: -------------------------------------------------------------------------------- 1 | { 2 | "@context": { 3 | "@version": 1.1, 4 | "id": "@id", 5 | "type": "@type", 6 | "PrettyVerifiableCredential": { 7 | "@id": "https://ld.truvera.io/credentials#PrettyVerifiableCredential", 8 | "@context": { 9 | "@version": 1.1, 10 | "@protected": true, 11 | "id": "@id", 12 | "type": "@type", 13 | "cred": "https://www.w3.org/2018/credentials#", 14 | "prettyVC": { 15 | "@id": "cred:prettyVC", 16 | "@type": "@id", 17 | "@context": { 18 | "@version": 1.1, 19 | "@protected": true, 20 | "id": "@id", 21 | "type": "@type", 22 | "prettyCred": "https://ld.truvera.io/credentials/prettyvc#", 23 | "liquid": "prettyCred:liquid", 24 | "orientation": "prettyCred:orientation", 25 | "size": "prettyCred:size", 26 | "proof": "prettyCred:proof" 27 | } 28 | } 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/contexts/private-status-list-21.js: -------------------------------------------------------------------------------- 1 | export default { 2 | '@context': { 3 | PrivateStatusList2021Credential: { 4 | '@id': 'https://ld.truvera.io/security#PrivateStatusList2021Credential', 5 | '@context': { 6 | id: '@id', 7 | type: '@type', 8 | description: 'https://schema.org/description', 9 | name: 'https://schema.org/name', 10 | }, 11 | }, 12 | 13 | StatusList2021: { 14 | '@id': 'https://w3id.org/vc/status-list#StatusList2021', 15 | '@context': { 16 | '@protected': true, 17 | id: '@id', 18 | type: '@type', 19 | statusPurpose: 'https://w3id.org/vc/status-list#statusPurpose', 20 | encodedList: 'https://w3id.org/vc/status-list#encodedList', 21 | }, 22 | }, 23 | 24 | PrivateStatusList2021Entry: { 25 | '@id': 'https://w3id.org/vc/status-list#StatusList2021Entry', 26 | '@context': { 27 | id: '@id', 28 | type: '@type', 29 | statusPurpose: 'https://w3id.org/vc/status-list#statusPurpose', 30 | statusListIndex: 'https://w3id.org/vc/status-list#statusListIndex', 31 | statusListCredential: { 32 | '@id': 'https://ld.truvera.io/security#PrivateStatusListCredential', 33 | '@type': '@id', 34 | }, 35 | }, 36 | }, 37 | }, 38 | }; 39 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/contexts/sphereon-wallet-identity-v1.json: -------------------------------------------------------------------------------- 1 | { 2 | "@context": { 3 | "@version": 1.1, 4 | "@protected": true, 5 | "swi": "https://sphereon-opensource.github.io/ssi-mobile-wallet/context/sphereon-wallet-identity-v1#", 6 | "schema": "https://schema.org/", 7 | "SphereonWalletIdentityCredential": "swi:SphereonWalletIdentityCredential", 8 | "id": "@id", 9 | "type": "@type", 10 | "firstName": "swi:firstName", 11 | "lastName": "swi:lastName", 12 | "emailAddress": { 13 | "@id": "swi:emailAddress", 14 | "@type": "schema:email" 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/contexts/status-list-21.js: -------------------------------------------------------------------------------- 1 | // Taken from https://w3c.github.io/vc-bitstring-status-list/contexts/v1.jsonld 2 | export default { 3 | '@context': { 4 | '@protected': true, 5 | 6 | StatusList2021Credential: { 7 | '@id': 'https://w3id.org/vc/status-list#StatusList2021Credential', 8 | '@context': { 9 | '@protected': true, 10 | 11 | id: '@id', 12 | type: '@type', 13 | 14 | description: 'https://schema.org/description', 15 | name: 'https://schema.org/name', 16 | }, 17 | }, 18 | 19 | StatusList2021: { 20 | '@id': 'https://w3id.org/vc/status-list#StatusList2021', 21 | '@context': { 22 | '@protected': true, 23 | 24 | id: '@id', 25 | type: '@type', 26 | 27 | statusPurpose: 'https://w3id.org/vc/status-list#statusPurpose', 28 | encodedList: 'https://w3id.org/vc/status-list#encodedList', 29 | }, 30 | }, 31 | 32 | StatusList2021Entry: { 33 | '@id': 'https://w3id.org/vc/status-list#StatusList2021Entry', 34 | '@context': { 35 | '@protected': true, 36 | 37 | id: '@id', 38 | type: '@type', 39 | 40 | statusPurpose: 'https://w3id.org/vc/status-list#statusPurpose', 41 | statusListIndex: 'https://w3id.org/vc/status-list#statusListIndex', 42 | statusListCredential: { 43 | '@id': 'https://w3id.org/vc/status-list#statusListCredential', 44 | '@type': '@id', 45 | }, 46 | }, 47 | }, 48 | }, 49 | }; 50 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/contexts/vc-examples-v1.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright (c) 2019 Digital Bazaar, Inc. All rights reserved. 3 | */ 4 | export default { 5 | '@context': [ 6 | { 7 | '@version': 1.1, 8 | }, 9 | 'https://www.w3.org/ns/odrl.jsonld', 10 | { 11 | ex: 'https://example.org/examples#', 12 | schema: 'http://schema.org/', 13 | rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 14 | '3rdPartyCorrelation': 'ex:3rdPartyCorrelation', 15 | AllVerifiers: 'ex:AllVerifiers', 16 | Archival: 'ex:Archival', 17 | BachelorDegree: 'ex:BachelorDegree', 18 | Child: 'ex:Child', 19 | CLCredentialDefinition2019: 'ex:CLCredentialDefinition2019', 20 | CLSignature2019: 'ex:CLSignature2019', 21 | IssuerPolicy: 'ex:IssuerPolicy', 22 | HolderPolicy: 'ex:HolderPolicy', 23 | Mother: 'ex:Mother', 24 | RelationshipCredential: 'ex:RelationshipCredential', 25 | UniversityDegreeCredential: 'ex:UniversityDegreeCredential', 26 | ZkpExampleSchema2018: 'ex:ZkpExampleSchema2018', 27 | alumniOf: { '@id': 'schema:alumniOf', '@type': 'rdf:HTML' }, 28 | child: { '@id': 'ex:child', '@type': '@id' }, 29 | degree: 'ex:degree', 30 | name: { '@id': 'schema:name', '@type': 'rdf:HTML' }, 31 | parent: { '@id': 'ex:parent', '@type': '@id' }, 32 | referenceId: 'ex:referenceId', 33 | documentPresence: 'ex:documentPresence', 34 | evidenceDocument: 'ex:evidenceDocument', 35 | subjectPresence: 'ex:subjectPresence', 36 | verifier: { '@id': 'ex:verifier', '@type': '@id' }, 37 | }, 38 | ], 39 | }; 40 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381BBDT16KeyPairDock2024.js: -------------------------------------------------------------------------------- 1 | import { 2 | BBDT16_MAC_PARAMS_LABEL_BYTES, 3 | BBDT16KeypairG1, 4 | BBDT16MacPublicKeyG1, 5 | BBDT16Mac, 6 | BBDT16MacParams, 7 | BBDT16MacSecretKey, 8 | } from '@docknetwork/crypto-wasm-ts'; 9 | 10 | import { Bls12381BBDT16DockVerKeyName } from './constants'; 11 | import DockCryptoKeyPair from './common/DockCryptoKeyPair'; 12 | 13 | export default class Bls12381BBDT16KeyPairDock2024 extends DockCryptoKeyPair { 14 | constructor(options) { 15 | super(options, Bls12381BBDT16DockVerKeyName); 16 | } 17 | 18 | static get paramGenerator() { 19 | return this.SignatureParams.getMacParamsOfRequiredSize; 20 | } 21 | } 22 | 23 | Bls12381BBDT16KeyPairDock2024.SecretKey = BBDT16MacSecretKey; 24 | Bls12381BBDT16KeyPairDock2024.PublicKey = BBDT16MacPublicKeyG1; 25 | Bls12381BBDT16KeyPairDock2024.SignatureParams = BBDT16MacParams; 26 | Bls12381BBDT16KeyPairDock2024.Signature = BBDT16Mac; 27 | Bls12381BBDT16KeyPairDock2024.KeyPair = BBDT16KeypairG1; 28 | Bls12381BBDT16KeyPairDock2024.defaultLabelBytes = BBDT16_MAC_PARAMS_LABEL_BYTES; 29 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381BBDT16MACDock2024.js: -------------------------------------------------------------------------------- 1 | import { BBDT16Credential, BBDT16CredentialBuilder } from '../../crypto'; 2 | 3 | import { Bls12381BBDT16MacDockName } from './constants'; 4 | 5 | import DockCryptoSignature from './common/DockCryptoSignature'; 6 | import Bls12381BBDT16KeyPairDock2024 from './Bls12381BBDT16KeyPairDock2024'; 7 | 8 | /** 9 | * A BBDT16 signature suite for use with BLS12-381 Dock key pairs 10 | */ 11 | export default class Bls12381BBDT16MACDock2024 extends DockCryptoSignature { 12 | /** 13 | * Default constructor 14 | * @param options {SignatureSuiteOptions} options for constructing the signature suite 15 | */ 16 | constructor(options = {}) { 17 | super( 18 | { 19 | ...options, 20 | signer: 21 | options.signer 22 | || Bls12381BBDT16MACDock2024.signerFactory( 23 | options.keypair, 24 | options.verificationMethod, 25 | ), 26 | }, 27 | Bls12381BBDT16MacDockName, 28 | Bls12381BBDT16KeyPairDock2024, 29 | 'https://ld.truvera.io/security/bbdt16/v1', 30 | ); 31 | } 32 | 33 | static get paramGenerator() { 34 | return this.KeyPair.SignatureParams.getMacParamsOfRequiredSize; 35 | } 36 | } 37 | 38 | Bls12381BBDT16MACDock2024.KeyPair = Bls12381BBDT16KeyPairDock2024; 39 | Bls12381BBDT16MACDock2024.CredentialBuilder = BBDT16CredentialBuilder; 40 | Bls12381BBDT16MACDock2024.Credential = BBDT16Credential; 41 | Bls12381BBDT16MACDock2024.proofType = [ 42 | Bls12381BBDT16MacDockName, 43 | `sec:${Bls12381BBDT16MacDockName}`, 44 | `https://w3id.org/security#${Bls12381BBDT16MacDockName}`, 45 | ]; 46 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381BBDT16MACProofDock2024.js: -------------------------------------------------------------------------------- 1 | import { 2 | Bls12381BBDT16MacProofDockName, 3 | Bls12381BBDT16MacDockName, 4 | } from './constants'; 5 | 6 | import DockCryptoSignatureProof from './common/DockCryptoSignatureProof'; 7 | import Bls12381BBDT16KeyPairDock2024 from './Bls12381BBDT16KeyPairDock2024'; 8 | import Bls12381BBDT16MACDock2024 from './Bls12381BBDT16MACDock2024'; 9 | 10 | /** 11 | * A BBDT16 signature suite for use with derived BBDT16 credentials aka BBDT16 presentations 12 | */ 13 | export default class Bls12381BBDT16MACProofDock2024 extends DockCryptoSignatureProof { 14 | /** 15 | * Default constructor 16 | * @param options {SignatureSuiteOptions} options for constructing the signature suite 17 | */ 18 | constructor(options = {}) { 19 | super( 20 | options, 21 | Bls12381BBDT16MacProofDockName, 22 | Bls12381BBDT16KeyPairDock2024, 23 | 'https://ld.truvera.io/security/bbdt16/v1', 24 | ); 25 | } 26 | 27 | /** 28 | * 29 | * @param _ 30 | * @returns {Promise} - Public key isn't used for verifying KVACs 31 | */ 32 | // eslint-disable-next-line no-empty-function 33 | async getVerificationMethod(_) {} 34 | } 35 | 36 | Bls12381BBDT16MACProofDock2024.Signature = Bls12381BBDT16MACDock2024; 37 | Bls12381BBDT16MACProofDock2024.sigName = Bls12381BBDT16MacDockName; 38 | Bls12381BBDT16MACProofDock2024.proofType = [ 39 | Bls12381BBDT16MacProofDockName, 40 | `sec:${Bls12381BBDT16MacProofDockName}`, 41 | `https://w3id.org/security#${Bls12381BBDT16MacProofDockName}`, 42 | ]; 43 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381BBSKeyPairDock2023.js: -------------------------------------------------------------------------------- 1 | import { 2 | BBSKeypair, 3 | BBSSignature, 4 | BBSPublicKey, 5 | BBSSecretKey, 6 | BBSSignatureParams, 7 | BBS_SIGNATURE_PARAMS_LABEL_BYTES, 8 | } from '@docknetwork/crypto-wasm-ts'; 9 | 10 | import { Bls12381BBS23DockVerKeyName } from './constants'; 11 | import DockCryptoKeyPair from './common/DockCryptoKeyPair'; 12 | 13 | export default class Bls12381BBSKeyPairDock2023 extends DockCryptoKeyPair { 14 | constructor(options) { 15 | super(options, Bls12381BBS23DockVerKeyName); 16 | } 17 | } 18 | 19 | Bls12381BBSKeyPairDock2023.SecretKey = BBSSecretKey; 20 | Bls12381BBSKeyPairDock2023.PublicKey = BBSPublicKey; 21 | Bls12381BBSKeyPairDock2023.SignatureParams = BBSSignatureParams; 22 | Bls12381BBSKeyPairDock2023.Signature = BBSSignature; 23 | Bls12381BBSKeyPairDock2023.KeyPair = BBSKeypair; 24 | Bls12381BBSKeyPairDock2023.defaultLabelBytes = BBS_SIGNATURE_PARAMS_LABEL_BYTES; 25 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381BBSSignatureDock2022.js: -------------------------------------------------------------------------------- 1 | import { 2 | BBSPlusCredential, 3 | BBSPlusCredentialBuilder, 4 | } from '@docknetwork/crypto-wasm-ts'; 5 | 6 | import { Bls12381BBSSigDockSigName } from './constants'; 7 | 8 | import Bls12381G2KeyPairDock2022 from './Bls12381G2KeyPairDock2022'; 9 | import DockCryptoSignature from './common/DockCryptoSignature'; 10 | 11 | /** 12 | * A BBS+ signature suite for use with BLS12-381 Dock key pairs 13 | */ 14 | export default class Bls12381BBSSignatureDock2022 extends DockCryptoSignature { 15 | /** 16 | * Default constructor 17 | * @param options {SignatureSuiteOptions} options for constructing the signature suite 18 | */ 19 | constructor(options = {}) { 20 | super( 21 | { 22 | ...options, 23 | signer: 24 | options.signer 25 | || Bls12381BBSSignatureDock2022.signerFactory( 26 | options.keypair, 27 | options.verificationMethod, 28 | ), 29 | }, 30 | Bls12381BBSSigDockSigName, 31 | Bls12381G2KeyPairDock2022, 32 | 'https://ld.truvera.io/security/bbs/v1', 33 | ); 34 | } 35 | } 36 | 37 | Bls12381BBSSignatureDock2022.KeyPair = Bls12381G2KeyPairDock2022; 38 | Bls12381BBSSignatureDock2022.CredentialBuilder = BBSPlusCredentialBuilder; 39 | Bls12381BBSSignatureDock2022.Credential = BBSPlusCredential; 40 | Bls12381BBSSignatureDock2022.proofType = [ 41 | Bls12381BBSSigDockSigName, 42 | `sec:${Bls12381BBSSigDockSigName}`, 43 | `https://w3id.org/security#${Bls12381BBSSigDockSigName}`, 44 | ]; 45 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381BBSSignatureDock2023.js: -------------------------------------------------------------------------------- 1 | import { 2 | BBSCredential, 3 | BBSCredentialBuilder, 4 | } from '@docknetwork/crypto-wasm-ts'; 5 | 6 | import { Bls12381BBS23SigDockSigName } from './constants'; 7 | 8 | import Bls12381BBSKeyPairDock2023 from './Bls12381BBSKeyPairDock2023'; 9 | import DockCryptoSignature from './common/DockCryptoSignature'; 10 | 11 | /** 12 | * A BBS signature suite for use with BLS12-381 Dock key pairs 13 | */ 14 | export default class Bls12381BBSSignatureDock2023 extends DockCryptoSignature { 15 | /** 16 | * Default constructor 17 | * @param options {SignatureSuiteOptions} options for constructing the signature suite 18 | */ 19 | constructor(options = {}) { 20 | super( 21 | { 22 | ...options, 23 | signer: 24 | options.signer 25 | || Bls12381BBSSignatureDock2023.signerFactory( 26 | options.keypair, 27 | options.verificationMethod, 28 | ), 29 | }, 30 | Bls12381BBS23SigDockSigName, 31 | Bls12381BBSKeyPairDock2023, 32 | 'https://ld.truvera.io/security/bbs23/v1', 33 | ); 34 | } 35 | } 36 | 37 | Bls12381BBSSignatureDock2023.KeyPair = Bls12381BBSKeyPairDock2023; 38 | Bls12381BBSSignatureDock2023.CredentialBuilder = BBSCredentialBuilder; 39 | Bls12381BBSSignatureDock2023.Credential = BBSCredential; 40 | Bls12381BBSSignatureDock2023.proofType = [ 41 | Bls12381BBS23SigDockSigName, 42 | `sec:${Bls12381BBS23SigDockSigName}`, 43 | `https://w3id.org/security#${Bls12381BBS23SigDockSigName}`, 44 | ]; 45 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381BBSSignatureProofDock2022.js: -------------------------------------------------------------------------------- 1 | import { 2 | Bls12381BBSSigProofDockSigName, 3 | Bls12381BBSSigDockSigName, 4 | } from './constants'; 5 | 6 | import Bls12381G2KeyPairDock2022 from './Bls12381G2KeyPairDock2022'; 7 | import DockCryptoSignatureProof from './common/DockCryptoSignatureProof'; 8 | import Bls12381BBSSignatureDock2022 from './Bls12381BBSSignatureDock2022'; 9 | 10 | /** 11 | * A BBS+ signature suite for use with derived BBS+ credentials aka BBS+ presentations 12 | */ 13 | export default class Bls12381BBSSignatureProofDock2022 extends DockCryptoSignatureProof { 14 | /** 15 | * Default constructor 16 | * @param options {SignatureSuiteOptions} options for constructing the signature suite 17 | */ 18 | constructor(options = {}) { 19 | super( 20 | options, 21 | Bls12381BBSSigProofDockSigName, 22 | Bls12381G2KeyPairDock2022, 23 | 'https://ld.truvera.io/security/bbs/v1', 24 | ); 25 | } 26 | } 27 | 28 | Bls12381BBSSignatureProofDock2022.Signature = Bls12381BBSSignatureDock2022; 29 | Bls12381BBSSignatureProofDock2022.sigName = Bls12381BBSSigDockSigName; 30 | Bls12381BBSSignatureProofDock2022.proofType = [ 31 | Bls12381BBSSigProofDockSigName, 32 | `sec:${Bls12381BBSSigProofDockSigName}`, 33 | `https://w3id.org/security#${Bls12381BBSSigProofDockSigName}`, 34 | ]; 35 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381BBSSignatureProofDock2023.js: -------------------------------------------------------------------------------- 1 | import { 2 | Bls12381BBS23SigProofDockSigName, 3 | Bls12381BBS23SigDockSigName, 4 | } from './constants'; 5 | 6 | import Bls12381BBSKeyPairDock2023 from './Bls12381BBSKeyPairDock2023'; 7 | import DockCryptoSignatureProof from './common/DockCryptoSignatureProof'; 8 | import Bls12381BBSSignatureDock2023 from './Bls12381BBSSignatureDock2023'; 9 | 10 | /** 11 | * A BBS signature suite for use with derived BBS credentials aka BBS presentations 12 | */ 13 | export default class Bls12381BBSSignatureProofDock2023 extends DockCryptoSignatureProof { 14 | /** 15 | * Default constructor 16 | * @param options {SignatureSuiteOptions} options for constructing the signature suite 17 | */ 18 | constructor(options = {}) { 19 | super( 20 | options, 21 | Bls12381BBS23SigProofDockSigName, 22 | Bls12381BBSKeyPairDock2023, 23 | 'https://ld.truvera.io/security/bbs23/v1', 24 | ); 25 | } 26 | } 27 | 28 | Bls12381BBSSignatureProofDock2023.Signature = Bls12381BBSSignatureDock2023; 29 | Bls12381BBSSignatureProofDock2023.sigName = Bls12381BBS23SigDockSigName; 30 | Bls12381BBSSignatureProofDock2023.proofType = [ 31 | Bls12381BBS23SigProofDockSigName, 32 | `sec:${Bls12381BBS23SigProofDockSigName}`, 33 | `https://w3id.org/security#${Bls12381BBS23SigProofDockSigName}`, 34 | ]; 35 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381BDDT16KeyPairDock2024.js: -------------------------------------------------------------------------------- 1 | import { 2 | BBDT16_MAC_PARAMS_LABEL_BYTES, 3 | BBDT16KeypairG1, 4 | BBDT16MacPublicKeyG1, 5 | BBDT16Mac, 6 | BBDT16MacParams, 7 | BBDT16MacSecretKey, 8 | } from '@docknetwork/crypto-wasm-ts'; 9 | 10 | import { Bls12381BBDT16DockVerKeyName } from './constants'; 11 | import DockCryptoKeyPair from './common/DockCryptoKeyPair'; 12 | 13 | export default class Bls12381BBDT16KeyPairDock2024 extends DockCryptoKeyPair { 14 | constructor(options) { 15 | super(options, Bls12381BBDT16DockVerKeyName); 16 | } 17 | 18 | static get paramGenerator() { 19 | return this.SignatureParams.getMacParamsOfRequiredSize; 20 | } 21 | } 22 | 23 | Bls12381BBDT16KeyPairDock2024.SecretKey = BBDT16MacSecretKey; 24 | Bls12381BBDT16KeyPairDock2024.PublicKey = BBDT16MacPublicKeyG1; 25 | Bls12381BBDT16KeyPairDock2024.SignatureParams = BBDT16MacParams; 26 | Bls12381BBDT16KeyPairDock2024.Signature = BBDT16Mac; 27 | Bls12381BBDT16KeyPairDock2024.KeyPair = BBDT16KeypairG1; 28 | Bls12381BBDT16KeyPairDock2024.defaultLabelBytes = BBDT16_MAC_PARAMS_LABEL_BYTES; 29 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381BDDT16MACProofDock2024.js: -------------------------------------------------------------------------------- 1 | import { 2 | Bls12381BBDT16MacProofDockName, 3 | Bls12381BBDT16MacDockName, 4 | } from './constants'; 5 | 6 | import DockCryptoSignatureProof from './common/DockCryptoSignatureProof'; 7 | import Bls12381BBDT16KeyPairDock2024 from './Bls12381BBDT16KeyPairDock2024'; 8 | import Bls12381BBDT16MACDock2024 from './Bls12381BBDT16MACDock2024'; 9 | 10 | /** 11 | * A BBDT16 signature suite for use with derived BBDT16 credentials aka BBDT16 presentations 12 | */ 13 | export default class Bls12381BBDT16MACProofDock2024 extends DockCryptoSignatureProof { 14 | /** 15 | * Default constructor 16 | * @param options {SignatureSuiteOptions} options for constructing the signature suite 17 | */ 18 | constructor(options = {}) { 19 | super( 20 | options, 21 | Bls12381BBDT16MacProofDockName, 22 | Bls12381BBDT16KeyPairDock2024, 23 | 'https://ld.truvera.io/security/bbdt16/v1', 24 | ); 25 | } 26 | 27 | /** 28 | * 29 | * @param _ 30 | * @returns {Promise} - Public key isn't used for verifying KVACs 31 | */ 32 | // eslint-disable-next-line no-empty-function 33 | async getVerificationMethod(_) {} 34 | } 35 | 36 | Bls12381BBDT16MACProofDock2024.Signature = Bls12381BBDT16MACDock2024; 37 | Bls12381BBDT16MACProofDock2024.sigName = Bls12381BBDT16MacDockName; 38 | Bls12381BBDT16MACProofDock2024.proofType = [ 39 | Bls12381BBDT16MacProofDockName, 40 | `sec:${Bls12381BBDT16MacProofDockName}`, 41 | `https://w3id.org/security#${Bls12381BBDT16MacProofDockName}`, 42 | ]; 43 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381G2KeyPairDock2022.js: -------------------------------------------------------------------------------- 1 | import { 2 | BBSPlusKeypairG2, 3 | BBSPlusSignatureG1, 4 | BBSPlusSecretKey, 5 | BBSPlusSignatureParamsG1, 6 | BBSPlusPublicKeyG2, 7 | BBS_PLUS_SIGNATURE_PARAMS_LABEL_BYTES, 8 | } from '@docknetwork/crypto-wasm-ts'; 9 | 10 | import { Bls12381BBSDockVerKeyName } from './constants'; 11 | import DockCryptoKeyPair from './common/DockCryptoKeyPair'; 12 | 13 | export default class Bls12381G2KeyPairDock2022 extends DockCryptoKeyPair { 14 | constructor(options) { 15 | super(options, Bls12381BBSDockVerKeyName); 16 | } 17 | } 18 | 19 | Bls12381G2KeyPairDock2022.SecretKey = BBSPlusSecretKey; 20 | Bls12381G2KeyPairDock2022.PublicKey = BBSPlusPublicKeyG2; 21 | Bls12381G2KeyPairDock2022.SignatureParams = BBSPlusSignatureParamsG1; 22 | Bls12381G2KeyPairDock2022.Signature = BBSPlusSignatureG1; 23 | Bls12381G2KeyPairDock2022.KeyPair = BBSPlusKeypairG2; 24 | Bls12381G2KeyPairDock2022.defaultLabelBytes = BBS_PLUS_SIGNATURE_PARAMS_LABEL_BYTES; 25 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381PSSignatureDock2023.js: -------------------------------------------------------------------------------- 1 | import { PSCredential, PSCredentialBuilder } from '@docknetwork/crypto-wasm-ts'; 2 | 3 | import { Bls12381PSSigDockSigName } from './constants'; 4 | 5 | import Bls12381PSKeyPairDock2023 from './Bls12381PSKeyPairDock2023'; 6 | import DockCryptoSignature from './common/DockCryptoSignature'; 7 | 8 | /** 9 | * A PS signature suite for use with BLS12-381 Dock key pairs 10 | */ 11 | export default class Bls12381PSSignatureDock2023 extends DockCryptoSignature { 12 | /** 13 | * Default constructor 14 | * @param options {SignatureSuiteOptions} options for constructing the signature suite 15 | */ 16 | constructor(options = {}) { 17 | super( 18 | { 19 | ...options, 20 | signer: 21 | options.signer 22 | || Bls12381PSSignatureDock2023.signerFactory( 23 | options.keypair, 24 | options.verificationMethod, 25 | ), 26 | }, 27 | Bls12381PSSigDockSigName, 28 | Bls12381PSKeyPairDock2023, 29 | 'https://ld.truvera.io/security/ps/v1', 30 | ); 31 | } 32 | } 33 | 34 | Bls12381PSSignatureDock2023.KeyPair = Bls12381PSKeyPairDock2023; 35 | Bls12381PSSignatureDock2023.CredentialBuilder = PSCredentialBuilder; 36 | Bls12381PSSignatureDock2023.Credential = PSCredential; 37 | Bls12381PSSignatureDock2023.proofType = [ 38 | Bls12381PSSigDockSigName, 39 | `sec:${Bls12381PSSigDockSigName}`, 40 | `https://w3id.org/security#${Bls12381PSSigDockSigName}`, 41 | ]; 42 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Bls12381PSSignatureProofDock2023.js: -------------------------------------------------------------------------------- 1 | import { 2 | Bls12381PSSigDockSigName, 3 | Bls12381PSSigProofDockSigName, 4 | } from './constants'; 5 | 6 | import Bls12381PSKeyPairDock2023 from './Bls12381PSKeyPairDock2023'; 7 | import DockCryptoSignatureProof from './common/DockCryptoSignatureProof'; 8 | import Bls12381PSSignatureDock2023 from './Bls12381PSSignatureDock2023'; 9 | 10 | /** 11 | * A PS signature suite for use with derived PS credentials aka PS presentations 12 | */ 13 | export default class Bls12381PSSignatureProofDock2022 extends DockCryptoSignatureProof { 14 | /** 15 | * Default constructor 16 | * @param options {SignatureSuiteOptions} options for constructing the signature suite 17 | */ 18 | constructor(options = {}) { 19 | super( 20 | options, 21 | Bls12381PSSigProofDockSigName, 22 | Bls12381PSKeyPairDock2023, 23 | 'https://ld.truvera.io/security/ps/v1', 24 | ); 25 | } 26 | } 27 | 28 | Bls12381PSSignatureProofDock2022.Signature = Bls12381PSSignatureDock2023; 29 | Bls12381PSSignatureProofDock2022.sigName = Bls12381PSSigDockSigName; 30 | Bls12381PSSignatureProofDock2022.proofType = [ 31 | Bls12381PSSigProofDockSigName, 32 | `sec:${Bls12381PSSigProofDockSigName}`, 33 | `https://w3id.org/security#${Bls12381PSSigProofDockSigName}`, 34 | ]; 35 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Ed25519Signature2018.js: -------------------------------------------------------------------------------- 1 | import { Ed25519SigName, Ed25519VerKeyName } from './constants'; 2 | import Ed25519VerificationKey2018 from './Ed25519VerificationKey2018'; 3 | import CustomLinkedDataSignature from './common/CustomLinkedDataSignature'; 4 | import { valueBytes } from '../../utils/types/bytes'; 5 | 6 | const SUITE_CONTEXT_URL = 'https://www.w3.org/2018/credentials/v1'; 7 | 8 | export default class Ed25519Signature2018 extends CustomLinkedDataSignature { 9 | /** 10 | * Creates a new Ed25519Signature2018 instance 11 | * @constructor 12 | * @param {object} config - Configuration options 13 | */ 14 | constructor({ 15 | keypair, verificationMethod, verifier, signer, 16 | } = {}) { 17 | super({ 18 | type: Ed25519SigName, 19 | LDKeyClass: Ed25519VerificationKey2018, 20 | contextUrl: SUITE_CONTEXT_URL, 21 | alg: 'EdDSA', 22 | signer: 23 | signer 24 | || Ed25519Signature2018.signerFactory(keypair, verificationMethod), 25 | verifier, 26 | }); 27 | this.requiredKeyType = Ed25519VerKeyName; 28 | } 29 | 30 | /** 31 | * Generate object with `sign` method 32 | * @param keypair 33 | * @param verificationMethod 34 | * @returns {object} 35 | */ 36 | static signerFactory(keypair, verificationMethod) { 37 | return { 38 | id: verificationMethod, 39 | async sign({ data }) { 40 | return valueBytes(keypair.sign(data)); 41 | }, 42 | }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Ed25519Signature2020.js: -------------------------------------------------------------------------------- 1 | import { Ed255192020SigName, Ed255192020VerKeyName } from './constants'; 2 | import Ed25519VerificationKey2020 from './Ed25519VerificationKey2020'; 3 | import CustomLinkedDataSignature from './common/CustomLinkedDataSignature'; 4 | import { valueBytes } from '../../utils/types/bytes'; 5 | 6 | const SUITE_CONTEXT_URL = 'https://w3id.org/security/suites/ed25519-2020/v1'; 7 | 8 | export default class Ed25519Signature2020 extends CustomLinkedDataSignature { 9 | /** 10 | * Creates a new Ed25519Signature2020 instance 11 | * @constructor 12 | * @param {object} config - Configuration options 13 | */ 14 | constructor({ 15 | keypair, verificationMethod, verifier, signer, 16 | } = {}) { 17 | super({ 18 | type: Ed255192020SigName, 19 | LDKeyClass: Ed25519VerificationKey2020, 20 | contextUrl: SUITE_CONTEXT_URL, 21 | alg: 'EdDSA', 22 | signer: 23 | signer 24 | || Ed25519Signature2020.signerFactory(keypair, verificationMethod), 25 | verifier, 26 | }); 27 | this.requiredKeyType = Ed255192020VerKeyName; 28 | } 29 | 30 | /** 31 | * Generate object with `sign` method 32 | * @param keypair 33 | * @param verificationMethod 34 | * @returns {object} 35 | */ 36 | static signerFactory(keypair, verificationMethod) { 37 | return { 38 | id: verificationMethod, 39 | async sign({ data }) { 40 | return valueBytes(keypair.sign(data)); 41 | }, 42 | }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/Ed25519VerificationKey2020.js: -------------------------------------------------------------------------------- 1 | import b58 from 'bs58'; 2 | import * as base64 from '@juanelas/base64'; 3 | import { Ed25519VerKeyName, Ed255192020VerKeyName } from './constants'; 4 | import Ed25519VerificationKey2018 from './Ed25519VerificationKey2018'; 5 | 6 | export default class Ed25519VerificationKey2020 extends Ed25519VerificationKey2018 { 7 | /** 8 | * Construct the public key object from the verification method 9 | * @param verificationMethod 10 | * @returns {Ed25519VerificationKey2020} 11 | */ 12 | static from(verificationMethod) { 13 | const isEd25519Type = verificationMethod.type.indexOf(Ed255192020VerKeyName) !== -1 14 | || verificationMethod.type.indexOf(Ed25519VerKeyName) !== -1; 15 | if (!verificationMethod.type || !isEd25519Type) { 16 | throw new Error( 17 | `verification method should have type ${Ed255192020VerKeyName} - got: ${verificationMethod.type}`, 18 | ); 19 | } 20 | 21 | if (verificationMethod.publicKeyBase58) { 22 | return new this(b58.decode(verificationMethod.publicKeyBase58)); 23 | } 24 | 25 | if (verificationMethod.publicKeyBase64) { 26 | return new this(base64.decode(verificationMethod.publicKeyBase64)); 27 | } 28 | 29 | throw new Error( 30 | `Unsupported signature encoding for ${Ed255192020VerKeyName}`, 31 | ); 32 | } 33 | 34 | // NOTE: Ed255192020 has the same cryptography as Ed255192018, so we inherit the verifier methods 35 | } 36 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/crypto/constants.js: -------------------------------------------------------------------------------- 1 | export const EcdsaSecp256k1VerKeyName = 'EcdsaSecp256k1VerificationKey2019'; 2 | export const EcdsaSecp256k1SigName = 'EcdsaSecp256k1Signature2019'; 3 | export const Ed25519VerKeyName = 'Ed25519VerificationKey2018'; 4 | export const Ed255192020VerKeyName = 'Ed25519VerificationKey2020'; 5 | export const Ed25519SigName = 'Ed25519Signature2018'; 6 | export const Ed255192020SigName = 'Ed25519Signature2020'; 7 | export const Sr25519VerKeyName = 'Sr25519VerificationKey2020'; 8 | export const Sr25519SigName = 'Sr25519Signature2020'; 9 | export const Bls12381BBSSigDockSigName = 'Bls12381BBS+SignatureDock2022'; 10 | export const Bls12381BBSSigProofDockSigName = 'Bls12381BBS+SignatureProofDock2022'; 11 | export const Bls12381BBSDockVerKeyName = 'Bls12381G2VerificationKeyDock2022'; 12 | export const Bls12381BBS23SigDockSigName = 'Bls12381BBSSignatureDock2023'; 13 | export const Bls12381BBDT16MacDockName = 'Bls12381BBDT16MACDock2024'; 14 | export const Bls12381BBDT16MacProofDockName = 'Bls12381BBDT16MACProofDock2024'; 15 | export const Bls12381BBS23SigProofDockSigName = 'Bls12381BBSSignatureProofDock2023'; 16 | export const Bls12381BBS23DockVerKeyName = 'Bls12381BBSVerificationKeyDock2023'; 17 | export const Bls12381BBDT16DockVerKeyName = 'Bls12381BBDT16VerificationKeyDock2024'; 18 | export const Bls12381PSSigDockSigName = 'Bls12381PSSignatureDock2023'; 19 | export const Bls12381PSSigProofDockSigName = 'Bls12381PSSignatureProofDock2023'; 20 | export const Bls12381PSDockVerKeyName = 'Bls12381PSVerificationKeyDock2023'; 21 | -------------------------------------------------------------------------------- /packages/credential-sdk/src/vc/private-status-list2021-credential.js: -------------------------------------------------------------------------------- 1 | import StatusList2021Credential from './status-list2021-credential'; 2 | import { PrivateStatusList2021Qualifier } from './constants'; 3 | import { ensurePrivateStatusListId } from '../utils'; 4 | 5 | /** 6 | * Private Status list 2021 verifiable credential. Similar to Status list 2021 credential but isn't stored on chain. 7 | * Issuer either keeps it with itself or shares it only with specific parties in charge of checking revocation 8 | */ 9 | export default class PrivateStatusList2021Credential extends StatusList2021Credential { 10 | toSubstrate() { 11 | throw new Error('This is not meant to be stored on chain'); 12 | } 13 | 14 | static verifyID(id) { 15 | ensurePrivateStatusListId(id); 16 | } 17 | } 18 | 19 | PrivateStatusList2021Credential.qualifier = PrivateStatusList2021Qualifier; 20 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/__snapshots__/did.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`\`DockDidOrDidMethodKey.from\` \`DidMethodKey.from\` work for a raw did:key 1`] = `"Unsupported qualified string: \`zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme\`, expected with either prefix: [did:dock:, did:key:]"`; 4 | 5 | exports[`\`DockDidOrDidMethodKey.from\` \`DockDid.from\` work for a raw did 1`] = `"Unsupported qualified string: \`5DEHasvC9G3eVF3qCsN2VQvEbHYdQtsv74ozZ1ngQQj39Luk\`, expected with either prefix: [did:dock:, did:key:]"`; 6 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/__snapshots__/utils.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Testing isHexWithGivenByteSize \`MemoizedPromise\` capacity 1`] = `"\`MemoizedPromiseMap\`'s queue reached its capacity"`; 4 | 5 | exports[`Testing isHexWithGivenByteSize \`retry\` works properly 1`] = `"From \`onError\` callback"`; 6 | 7 | exports[`Testing isHexWithGivenByteSize \`retry\` works properly 2`] = ` 8 | "Promise created by \`async () => { 9 | if (!ctr--) { 10 | return 0; 11 | } else { 12 | return placeholder; 13 | } 14 | }\` didn't resolve within the specified timeout of 1 ms 100 times" 15 | `; 16 | 17 | exports[`Testing isHexWithGivenByteSize \`retry\` works properly 3`] = ` 18 | "Promise created by \`async () => { 19 | if (!ctr--) { 20 | return 0; 21 | } else { 22 | return placeholder; 23 | } 24 | }\` didn't resolve within the specified timeout of 300 ms 4 times" 25 | `; 26 | 27 | exports[`Testing isHexWithGivenByteSize \`timeout\` works properly 1`] = `"Rejected timeout"`; 28 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/base-x.test.js: -------------------------------------------------------------------------------- 1 | import { 2 | encodeAsBase64, 3 | decodeFromBase64, 4 | encodeAsBase58, 5 | decodeFromBase58, 6 | encodeAsBase58btc, 7 | decodeFromBase58btc, 8 | stringFromU8a, 9 | u8aToHex, 10 | hexToU8a 11 | } from '../src/utils'; 12 | 13 | const HEX_STR = '0xdeadbeefcafebabe'; 14 | const BYTES = hexToU8a(HEX_STR); 15 | 16 | describe('base-x functions', () => { 17 | test('base58', () => { 18 | expect(encodeAsBase58(BYTES)).toBe('eFGDJTv8RoB'); 19 | expect(u8aToHex(decodeFromBase58('eFGDJTv8RoB'))).toBe(HEX_STR); 20 | }); 21 | 22 | test('base64', () => { 23 | expect(encodeAsBase64(BYTES)).toBe('3q2+78r+ur4='); 24 | expect(u8aToHex(decodeFromBase64('3q2+78r+ur4='))).toBe(HEX_STR); 25 | }); 26 | 27 | test('multibase', () => { 28 | expect(encodeAsBase58btc(hexToU8a('0xed01'), BYTES)).toBe('zEKJLyQ1fpXdB5F'); 29 | expect(u8aToHex(decodeFromBase58btc('zEKJLyQ1fpXdB5F'))).toBe(HEX_STR); 30 | }); 31 | 32 | test('base58 and multibase', () => { 33 | const prefix = hexToU8a('0xed01'); 34 | expect(`z${encodeAsBase58([...prefix, ...BYTES])}`).toBe(encodeAsBase58btc(prefix, BYTES)); 35 | }) 36 | }) 37 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/canonicalize.test.js: -------------------------------------------------------------------------------- 1 | import deepEqual from "deep-equal"; 2 | import { canon } from "../src/rdf-and-cd/canonicalize"; 3 | 4 | describe("Canonicalization.", () => { 5 | test("canon: ∀ A, B ∈ Node: canon(A) = canon(B) <-> A = B", async () => { 6 | const samples = [ 7 | { Iri: "did:example:ebfeb1f712ebc6f1c276e12ec21" }, 8 | { Iri: "http://schema.org/alumniOf" }, 9 | { 10 | Literal: { 11 | value: "Example University", 12 | datatype: "http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML", 13 | }, 14 | }, 15 | { 16 | Literal: { 17 | // the keys in this are swapped but the canonical representation shouldn't change 18 | datatype: "http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML", 19 | value: "Example University", 20 | }, 21 | }, 22 | { Iri: "https://example.com/credentials/1872" }, 23 | { Iri: "https://w3id.org/security#proof" }, 24 | { Blank: "_:b1" }, 25 | ]; 26 | for (const A of samples) { 27 | for (const B of samples) { 28 | expect(deepEqual(A, B)).toEqual(canon(A) === canon(B)); 29 | } 30 | } 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/data/static-bbs-cred-610.json: -------------------------------------------------------------------------------- 1 | { 2 | "@context": [ 3 | "https://www.w3.org/2018/credentials/v1", 4 | { 5 | "dk": "https://ld.dock.io/credentials#", 6 | "BasicCredential": "dk:BasicCredential", 7 | "name": "dk:name" 8 | } 9 | ], 10 | "id": "https://creds-staging.dock.io/be2b56a51e0ec8aa2ee5e92a0267a82bff6cc11a5f2275cfc8b014f3b9422a21", 11 | "type": ["VerifiableCredential", "BasicCredential"], 12 | "credentialSubject": { 13 | "id": "mysnjid", 14 | "name": "sbj name" 15 | }, 16 | "issuanceDate": "2023-09-25T18:27:27.053Z", 17 | "issuer": { 18 | "name": "newdid", 19 | "id": "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd" 20 | }, 21 | "name": "static bbs plus test", 22 | "proof": { 23 | "@context": [ 24 | { 25 | "sec": "https://w3id.org/security#", 26 | "proof": { 27 | "@id": "sec:proof", 28 | "@type": "@id", 29 | "@container": "@graph" 30 | } 31 | }, 32 | "https://ld.dock.io/security/bbs/v1" 33 | ], 34 | "type": "Bls12381BBS+SignatureDock2022", 35 | "created": "2023-09-25T18:28:13Z", 36 | "verificationMethod": "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd#keys-2", 37 | "proofPurpose": "assertionMethod", 38 | "proofValue": "zToVRuY4HPCWvXjKCcNFvc3FsxYGMzjSvsfBNS41XHWuAbq9G583kqNhLueELxYCdcL5KSNSr9ABA7JopkyNhoxuB9VaLjXhsn5V7ZxEmAu4W1XpKEXMSoae9MLtRRNDdDpPusihQe7uhM9FhuAEkuBnnp" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/data/static-bbs-cred-630.json: -------------------------------------------------------------------------------- 1 | { 2 | "@context": [ 3 | "https://www.w3.org/2018/credentials/v1", 4 | { 5 | "dk": "https://ld.dock.io/credentials#", 6 | "BasicCredential": "dk:BasicCredential", 7 | "name": "dk:name" 8 | } 9 | ], 10 | "id": "https://creds-staging.dock.io/0985a64f2910e74c48e4066fa683e4cdd9c54d021f6b83a9fd8cb56db9c460e3", 11 | "type": ["VerifiableCredential", "BasicCredential"], 12 | "credentialSubject": { 13 | "name": "basic bbs static" 14 | }, 15 | "issuanceDate": "2023-09-22T20:59:25.847Z", 16 | "issuer": { 17 | "name": "newdid", 18 | "id": "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd" 19 | }, 20 | "name": "basic bbs static", 21 | "proof": { 22 | "@context": [ 23 | { 24 | "sec": "https://w3id.org/security#", 25 | "proof": { 26 | "@id": "sec:proof", 27 | "@type": "@id", 28 | "@container": "@graph" 29 | } 30 | }, 31 | "https://ld.dock.io/security/bbs/v1" 32 | ], 33 | "type": "Bls12381BBS+SignatureDock2022", 34 | "created": "2023-09-22T20:59:55Z", 35 | "verificationMethod": "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd#keys-2", 36 | "proofPurpose": "assertionMethod", 37 | "proofValue": "zaEUvk9cmVeVrHueiKMKPwxtV3zab2fRiVkGmah74rFnyXbQtYBtyrGs4zmVTs2jrrWQzeHsgNjf4H1MYMqVjvQmKCfnw4PPjMXS2p8gYQiwm8XaJJwSjT94p1af1ygHrbkpjQmMafPf3gfVqRbyvULW2G" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/data/static-did-dock.json: -------------------------------------------------------------------------------- 1 | { 2 | "@context": ["https://www.w3.org/ns/did/v1"], 3 | "id": "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd", 4 | "controller": ["did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd"], 5 | "publicKey": [ 6 | { 7 | "id": "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd#keys-1", 8 | "type": "Ed25519VerificationKey2018", 9 | "controller": "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd", 10 | "publicKeyBase58": "D74srRGhLCCWK9GEE7m1EXKtUVsAXu4DC6kZ7qPEt7JE" 11 | }, 12 | { 13 | "id": "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd#keys-2", 14 | "type": "Bls12381G2VerificationKeyDock2022", 15 | "controller": "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd", 16 | "publicKeyBase58": "zqgSKjTri2v5dvKsMi2FY1p2FFVcUd4kRGi4QxQgHyr1g9V7JH42bsvLkfZNqWvS5MhisgwToWseGvifV7TvtMZJzWAopTVrWejpviWejBA1JY8xxpqvVPAwvArrj3Dr1Ng" 17 | } 18 | ], 19 | "authentication": [ 20 | "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd#keys-1" 21 | ], 22 | "assertionMethod": [ 23 | "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd#keys-1", 24 | "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd#keys-2" 25 | ], 26 | "capabilityInvocation": [ 27 | "did:dock:5GZn9zQTggPWijzgnoV8sZ5a74rFqC8qrz2ncp7GggeGCtKd#keys-1" 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/data/test-keys.js: -------------------------------------------------------------------------------- 1 | import { Secp256k1Keypair } from "../../src/keypairs"; 2 | 3 | const keypairEcdsaSecp256k1 = new Secp256k1Keypair( 4 | "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" 5 | ); 6 | 7 | // TODO: add more testing keys (ed25519 etc) 8 | export default [ 9 | { 10 | sigType: "JsonWebSignature2020", 11 | keyDocument: { 12 | "@context": "https://w3id.org/security/suites/jws-2020/v1", 13 | id: "urn:JsonWebKey2020#keys-1", 14 | controller: "urn:JsonWebKey2020", 15 | type: "JsonWebKey2020", 16 | publicKeyJwk: { 17 | kty: "EC", 18 | crv: "P-384", 19 | x: "dMtj6RjwQK4G5HP3iwOD94RwbzPhS4wTZHO1luk_0Wz89chqV6uJyb51KaZzK0tk", 20 | y: "viPKF7Zbc4FxKegoupyVRcBr8TZHFxUrKQq4huOAyMuhTYJbFpAwMhIrWppql02E", 21 | }, 22 | privateKeyJwk: { 23 | kty: "EC", 24 | crv: "P-384", 25 | x: "dMtj6RjwQK4G5HP3iwOD94RwbzPhS4wTZHO1luk_0Wz89chqV6uJyb51KaZzK0tk", 26 | y: "viPKF7Zbc4FxKegoupyVRcBr8TZHFxUrKQq4huOAyMuhTYJbFpAwMhIrWppql02E", 27 | d: "Wq5_KgqjvYh_EGvBDYtSs_0ufJJP0y0tkAXl6GqxHMkY0QP8vmD76mniXD-BWhd_", 28 | }, 29 | }, 30 | }, 31 | { 32 | sigType: "EcdsaSecp256k1Signature2019", 33 | keyDocument: { 34 | id: "urn:EcdsaSecp256k1VerificationKey2019#keys-1", 35 | controller: "urn:EcdsaSecp256k1VerificationKey2019", 36 | type: "EcdsaSecp256k1VerificationKey2019", 37 | keypair: keypairEcdsaSecp256k1, 38 | publicKey: keypairEcdsaSecp256k1.publicKey(), 39 | }, 40 | }, 41 | ]; 42 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/ipfs/ipfs.test.disabled.js: -------------------------------------------------------------------------------- 1 | const ipfsDefaultConfig = "http://localhost:5001"; 2 | 3 | const rdfInput = ` 4 | @prefix : . 5 | :a :b ( "apple" "banana" ) . 6 | `; 7 | 8 | const rdfCID = "bafkreia2fxwzy4hs6pkl7aygxl4t7ws2euxs7jbkp7qacmljqful2anwei"; 9 | 10 | describe("IPFS", () => { 11 | let ipfsClient; 12 | beforeAll(async () => { 13 | const { createHelia } = await import("helia"); 14 | const { strings } = await import("@helia/strings"); 15 | ipfsClient = strings(await createHelia(ipfsDefaultConfig)); 16 | }); 17 | 18 | test("Can dereference document from IPFs", async () => { 19 | // Write document to node 20 | const cid = await ipfsClient.add(rdfInput); 21 | expect(cid.toString()).toEqual(rdfCID); 22 | 23 | // Pull document as string 24 | const document = await ipfsClient.get(cid); 25 | expect(document).toEqual(rdfInput); 26 | }, 10000); 27 | 28 | test("Dereference from IPNS fails", async () => { 29 | await expect( 30 | ipfsClient.get("/ipns/QmSrPmbaUKA3ZodhzPWZnpFgcPMFWF4QsxXbkWfEptTBJd") 31 | ).rejects.toThrow(); 32 | }, 10000); 33 | }); 34 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/mocks/fetch.js: -------------------------------------------------------------------------------- 1 | import networkCache from "../utils/network-cache"; 2 | 3 | // Mock the global fetch function 4 | global.fetch = jest.fn(); 5 | 6 | // Function to set up a mock response for fetch 7 | const mockFetchResponse = (status, data) => { 8 | const response = new Response(JSON.stringify(data), { 9 | status, 10 | headers: { 11 | "Content-type": "application/json", 12 | }, 13 | }); 14 | return Promise.resolve(response); 15 | }; 16 | 17 | export default function mockFetch() { 18 | // Set up a mock response for all GET requests 19 | fetch.mockImplementation((url) => { 20 | if (networkCache[url]) { 21 | return mockFetchResponse(200, networkCache[url]); 22 | } 23 | 24 | console.error(`Test should cache this URL: ${url}`); 25 | throw new Error(`Test should cache this URL: ${url}`); 26 | }); 27 | } 28 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/presigned-validation.test.js: -------------------------------------------------------------------------------- 1 | // Mock fetch 2 | import mockFetch from "./mocks/fetch"; 3 | 4 | import { verifyCredential } from "../src/vc"; 5 | 6 | mockFetch(); 7 | 8 | const controllerUrl = 9 | "https://gist.githubusercontent.com/lovesh/312d407e3a16be0e7d5e43169e824958/raw"; 10 | const keyUrl = 11 | "https://gist.githubusercontent.com/lovesh/67bdfd354cfaf4fb853df4d6713f4610/raw"; 12 | 13 | function getSamplePresignedCredential() { 14 | return { 15 | "@context": [ 16 | "https://www.w3.org/2018/credentials/v1", 17 | "https://www.w3.org/2018/credentials/examples/v1", 18 | ], 19 | id: "https://example.com/credentials/1872", 20 | type: ["VerifiableCredential", "AlumniCredential"], 21 | issuanceDate: "2020-04-15T09:05:35Z", 22 | credentialSubject: { 23 | id: "did:example:ebfeb1f712ebc6f1c276e12ec21", 24 | alumniOf: "Example University", 25 | }, 26 | issuer: controllerUrl, 27 | proof: { 28 | type: "EcdsaSecp256k1Signature2019", 29 | created: "2021-11-24T21:47:28Z", 30 | proofValue: 31 | "zAN1rKvtBajWcQS61LU4wX8hB4tUNFze44pHKwkVYoZaGMRxXquAaKcnUiwarZyWmMQzB4ttFLCEFXQq6F9dnq5pWJSC1WZgga", 32 | proofPurpose: "assertionMethod", 33 | verificationMethod: keyUrl, 34 | }, 35 | }; 36 | } 37 | 38 | describe("Static pre-signed credential validation", () => { 39 | test("Presigned credential should verify", async () => { 40 | const results = await verifyCredential(getSamplePresignedCredential()); 41 | expect(results.verified).toBe(true); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/setup-test-env.js: -------------------------------------------------------------------------------- 1 | import "core-js/stable"; 2 | import "regenerator-runtime/runtime"; 3 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/static-bbs.test.js: -------------------------------------------------------------------------------- 1 | import { verifyCredential } from "../src/vc"; 2 | import defaultDocumentLoader from "../src/vc/document-loader"; 3 | import didDocument from "./data/static-did-dock.json"; 4 | import staticCred610 from "./data/static-bbs-cred-610.json"; 5 | // import staticCred630 from '../data/static-bbs-cred-630.json'; // TODO: add a credential from 6.3.0 6 | 7 | const loadDocumentDefault = defaultDocumentLoader(null); 8 | 9 | async function documentLoader(doc) { 10 | if (doc.startsWith(staticCred610.issuer.id)) { 11 | return { 12 | contextUrl: null, 13 | documentUrl: doc, 14 | document: didDocument, 15 | }; 16 | } 17 | 18 | return loadDocumentDefault(doc); 19 | } 20 | 21 | describe("Static BBS+ Credential Verification (backwards compatibility)", () => { 22 | test("verifies BBS+ credential from SDK 6.1.0", async () => { 23 | const result = await verifyCredential(staticCred610, { 24 | documentLoader, 25 | }); 26 | 27 | if (!result.verified) { 28 | console.error(JSON.stringify(result, null, 2)); 29 | } 30 | expect(result.verified).toBe(true); 31 | }); 32 | 33 | // test('verifies BBS+ credential from SDK 6.3.0', async () => { 34 | // const result = await verifyCredential(staticCred630, { 35 | // documentLoader, 36 | // }); 37 | // console.error(JSON.stringify(result, null, 2)); 38 | // expect(result.verified).toBe(true); 39 | // }); 40 | }); 41 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/test-environment.js: -------------------------------------------------------------------------------- 1 | import { TestEnvironment as NodeEnvironment } from "jest-environment-node"; 2 | 3 | class MyEnvironment extends NodeEnvironment { 4 | constructor(config, context) { 5 | super( 6 | { 7 | ...config, 8 | globals: { 9 | ...config.globals, 10 | Uint32Array, 11 | Uint8Array, 12 | ArrayBuffer, 13 | TextDecoder, 14 | TextEncoder, 15 | Buffer, 16 | }, 17 | }, 18 | context 19 | ); 20 | } 21 | 22 | async setup() {} 23 | 24 | async teardown() {} 25 | } 26 | 27 | export default MyEnvironment; 28 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/utils/create-presentation.js: -------------------------------------------------------------------------------- 1 | import VerifiablePresentation from "../../src/vc/verifiable-presentation"; 2 | 3 | /** 4 | * Create an unsigned Verifiable Presentation 5 | * @param {object|Array} verifiableCredential - verifiable credential (or an array of them) to be bundled as a presentation. 6 | * @param {string} id - optional verifiable presentation id to use 7 | * @param {string} [holder] - optional presentation holder url 8 | * @return {object} verifiable presentation. 9 | */ 10 | export function createPresentation( 11 | verifiableCredential, 12 | id = "http://example.edu/presentation/2803", 13 | holder = null 14 | ) { 15 | const presentation = new VerifiablePresentation(id); 16 | if (Array.isArray(verifiableCredential)) { 17 | presentation.addCredentials(verifiableCredential); 18 | } else { 19 | presentation.addCredential(verifiableCredential); 20 | } 21 | if (holder) { 22 | presentation.setHolder(String(holder)); 23 | } 24 | return presentation.toJSON(); 25 | } 26 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/utils/example-credential.js: -------------------------------------------------------------------------------- 1 | export default { 2 | "@context": [ 3 | "https://www.w3.org/2018/credentials/v1", 4 | "https://www.w3.org/2018/credentials/examples/v1", 5 | { 6 | emailAddress: "https://schema.org/email", 7 | alumniOf: "https://schema.org/alumniOf", 8 | }, 9 | ], 10 | id: "uuid:0x9b561796d3450eb2673fed26dd9c07192390177ad93e0835bc7a5fbb705d52bc", 11 | type: ["VerifiableCredential", "AlumniCredential"], 12 | issuanceDate: "2020-03-18T19:23:24Z", 13 | credentialSchema: { 14 | // this is the schema 15 | id: "blob:dock:5C78GCA", 16 | type: "JsonSchemaValidator2018", 17 | }, 18 | credentialSubject: { 19 | id: "did:dock:5GL3xbkr3vfs4qJ94YUHwpVVsPSSAyvJcafHz1wNb5zrSPGi", 20 | emailAddress: "johnsmith@example.com", 21 | alumniOf: "Example University", 22 | }, 23 | credentialStatus: { 24 | id: "rev-reg:dock:0x0194...", 25 | type: "CredentialStatusList2017", 26 | }, 27 | issuer: "did:dock:5GUBvwnV6UyRWZ7wjsBptSquiSHGr9dXAy8dZYUR9WdjmLUr", 28 | proof: { 29 | type: "Ed25519Signature2018", 30 | created: "2020-04-22T07:50:13Z", 31 | jws: "eyJhbGciOiJFZERTQSIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19..GBqyaiTMhVt4R5P2bMGcLNJPWEUq7WmGHG7Wc6mKBo9k3vSo7v7sRKwqS8-m0og_ANKcb5m-_YdXC2KMnZwLBg", 32 | proofPurpose: "assertionMethod", 33 | verificationMethod: 34 | "did:dock:5GUBvwnV6UyRWZ7wjsBptSquiSHGr9dXAy8dZYUR9WdjmLUr#keys-1", 35 | }, 36 | }; 37 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/utils/example-schema.js: -------------------------------------------------------------------------------- 1 | export default { 2 | $schema: "http://json-schema.org/draft-07/schema#", 3 | description: "Alumni", 4 | type: "object", 5 | properties: { 6 | id: { 7 | type: "string", 8 | }, 9 | emailAddress: { 10 | type: "string", 11 | format: "email", 12 | }, 13 | alumniOf: { 14 | type: "string", 15 | }, 16 | }, 17 | required: ["emailAddress", "alumniOf"], 18 | additionalProperties: false, 19 | }; 20 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/utils/test-keys.js: -------------------------------------------------------------------------------- 1 | import { Secp256k1Keypair } from "../../src/keypairs"; 2 | 3 | const keypairEcdsaSecp256k1 = new Secp256k1Keypair( 4 | "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" 5 | ); 6 | 7 | // TODO: add more testing keys (ed25519 etc) 8 | export default [ 9 | { 10 | sigType: "JsonWebSignature2020", 11 | keyDocument: { 12 | "@context": "https://w3id.org/security/suites/jws-2020/v1", 13 | id: "urn:JsonWebKey2020#keys-1", 14 | controller: "urn:JsonWebKey2020", 15 | type: "JsonWebKey2020", 16 | publicKeyJwk: { 17 | kty: "EC", 18 | crv: "P-384", 19 | x: "dMtj6RjwQK4G5HP3iwOD94RwbzPhS4wTZHO1luk_0Wz89chqV6uJyb51KaZzK0tk", 20 | y: "viPKF7Zbc4FxKegoupyVRcBr8TZHFxUrKQq4huOAyMuhTYJbFpAwMhIrWppql02E", 21 | }, 22 | privateKeyJwk: { 23 | kty: "EC", 24 | crv: "P-384", 25 | x: "dMtj6RjwQK4G5HP3iwOD94RwbzPhS4wTZHO1luk_0Wz89chqV6uJyb51KaZzK0tk", 26 | y: "viPKF7Zbc4FxKegoupyVRcBr8TZHFxUrKQq4huOAyMuhTYJbFpAwMhIrWppql02E", 27 | d: "Wq5_KgqjvYh_EGvBDYtSs_0ufJJP0y0tkAXl6GqxHMkY0QP8vmD76mniXD-BWhd_", 28 | }, 29 | }, 30 | }, 31 | { 32 | sigType: "EcdsaSecp256k1Signature2019", 33 | keyDocument: { 34 | id: "urn:EcdsaSecp256k1VerificationKey2019#keys-1", 35 | controller: "urn:EcdsaSecp256k1VerificationKey2019", 36 | type: "EcdsaSecp256k1VerificationKey2019", 37 | keypair: keypairEcdsaSecp256k1, 38 | publicKey: keypairEcdsaSecp256k1.publicKey(), 39 | }, 40 | }, 41 | ]; 42 | -------------------------------------------------------------------------------- /packages/credential-sdk/tests/utils/type-helpers.test.js: -------------------------------------------------------------------------------- 1 | import { ensureValidDatetime } from "../../src/utils"; 2 | 3 | describe("ensureValidDatetime.", () => { 4 | test("happy path", () => { 5 | for (const value of [ 6 | "2023-10-09T20:05:44.039Z", 7 | "2020-01-01T20:12:08.613Z", 8 | "1970-01-01T20:12:08.613Z", 9 | ]) { 10 | expect(ensureValidDatetime(value)).toBe(value); 11 | } 12 | }); 13 | 14 | test("unhappy path", () => { 15 | expect(() => ensureValidDatetime("2023-13-09T15:12:08.613Z")).toThrow(); 16 | expect(() => ensureValidDatetime("2020-01-01")).toThrow(); 17 | expect(() => ensureValidDatetime("not a date")).toThrow(); 18 | }); 19 | }); 20 | -------------------------------------------------------------------------------- /scripts/bench/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # @docknetwork/benchmarks 2 | 3 | ## 0.2.0 4 | 5 | ### Minor Changes 6 | 7 | - Package cleanup 8 | 9 | ### Patch Changes 10 | 11 | - Updated dependencies 12 | - @docknetwork/cheqd-blockchain-modules@1.0.0 13 | - @docknetwork/cheqd-blockchain-api@1.0.0 14 | - @docknetwork/credential-sdk@0.51.0 15 | 16 | ## 0.1.5 17 | 18 | ### Patch Changes 19 | 20 | - Updated dependencies 21 | - @docknetwork/cheqd-blockchain-api@0.37.0 22 | 23 | ## 0.1.4 24 | 25 | ### Patch Changes 26 | 27 | - Updated dependencies 28 | - @docknetwork/cheqd-blockchain-api@0.36.1 29 | 30 | ## 0.1.3 31 | 32 | ### Patch Changes 33 | 34 | - Updated dependencies 35 | - @docknetwork/cheqd-blockchain-modules@0.33.0 36 | - @docknetwork/credential-sdk@0.50.0 37 | - @docknetwork/cheqd-blockchain-api@0.36.0 38 | - @docknetwork/dock-blockchain-modules@0.30.0 39 | 40 | ## 0.1.2 41 | 42 | ### Patch Changes 43 | 44 | - Updated dependencies 45 | - @docknetwork/cheqd-blockchain-api@0.35.0 46 | - @docknetwork/credential-sdk@0.49.0 47 | - @docknetwork/cheqd-blockchain-modules@0.32.1 48 | - @docknetwork/dock-blockchain-modules@0.29.0 49 | 50 | ## 0.1.1 51 | 52 | ### Patch Changes 53 | 54 | - Updated dependencies 55 | - @docknetwork/cheqd-blockchain-api@0.34.0 56 | -------------------------------------------------------------------------------- /scripts/bench/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@docknetwork/benchmarks", 3 | "private": true, 4 | "type": "module", 5 | "version": "0.2.0", 6 | "scripts": { 7 | "bench": "babel-node src/main.js" 8 | }, 9 | "dependencies": { 10 | "@docknetwork/cheqd-blockchain-api": "1.0.0", 11 | "@docknetwork/cheqd-blockchain-modules": "1.0.0", 12 | "@docknetwork/credential-sdk": "0.51.0", 13 | "@docknetwork/crypto-wasm-ts": "^0.63.0" 14 | }, 15 | "devDependencies": { 16 | "babel-eslint": "^10.1.0", 17 | "eslint": "^8.0.0", 18 | "eslint-config-airbnb-base": "^14.1.0", 19 | "eslint-plugin-import": "^2.20.2", 20 | "eslint-plugin-jest": "^26.0.0", 21 | "eslint-plugin-sonarjs": "0.5.0", 22 | "eslint-plugin-unused-imports": "^3.0.0" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /scripts/config: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CONFIG_DOCK_NODE_MASTER_IMAGE=${CONFIG_DOCK_NODE_MASTER_IMAGE:-docknetwork/dock-substrate:fastblock_master} 4 | CONFIG_DOCK_NODE_MAINNET_IMAGE=${CONFIG_DOCK_NODE_MAINNET_IMAGE:-docknetwork/dock-substrate:fastblock_mainnet} 5 | CONFIG_DOCK_NODE_TESTNET_IMAGE=${CONFIG_DOCK_NODE_TESTNET_IMAGE:-docknetwork/dock-substrate:fastblock_testnet} 6 | 7 | if [ -z ${CONFIG_DOCK_NODE_IMAGE_TAG+x} ]; then 8 | CONFIG_DOCK_NODE_IMAGE=${CONFIG_DOCK_NODE_IMAGE:-$CONFIG_DOCK_NODE_MAINNET_IMAGE} 9 | else 10 | case $CONFIG_DOCK_NODE_IMAGE_TAG in 11 | master) 12 | CONFIG_DOCK_NODE_IMAGE=$CONFIG_DOCK_NODE_MASTER_IMAGE 13 | ;; 14 | mainnet) 15 | CONFIG_DOCK_NODE_IMAGE=$CONFIG_DOCK_NODE_MAINNET_IMAGE 16 | ;; 17 | testnet) 18 | CONFIG_DOCK_NODE_IMAGE=$CONFIG_DOCK_NODE_TESTNET_IMAGE 19 | ;; 20 | *) 21 | echo "Invalid CONFIG_DOCK_NODE_IMAGE_TAG env" 22 | exit 1 23 | ;; 24 | esac; 25 | fi 26 | -------------------------------------------------------------------------------- /scripts/run_cheqd_node_in_docker: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Starts a cheqd test node in docker for testing. Automatically deletes the container on exit. 4 | # Arguments passed to this script are forwarded to the node binary. 5 | # 6 | # Example use: 7 | # 8 | # ```bash 9 | # # Start a local test node 10 | # ./run_cheqd_node_in_docker --dev 11 | # 12 | # # Start a testnet node 13 | # ./run_cheqd_node_in_docker --chain=remdev --rpc-external --ws-external --rpc-cors=all 14 | # ``` 15 | 16 | set -uexo pipefail 17 | entrypoint="$(realpath $(dirname $0)/cheqd_entrypoint)" 18 | config="$(realpath $(dirname $0)/cheqd_config.toml)" 19 | 20 | # pre-pull 21 | docker pull --platform linux/amd64 ghcr.io/cheqd/cheqd-node:$CHEQD_IMAGE_TAG 22 | 23 | # run the node with the random name output by the build command 24 | docker run --platform linux/amd64 -e CHEQD_MNEMONIC="$CHEQD_MNEMONIC" -e CHEQD_NETWORK="$CHEQD_NETWORK" -p 26656:26656 -p 26657:26657 -p 1317:1317 -p 9090:9090 -v $entrypoint:/usr/local/bin/entrypoint.sh -v $config:/tmp/cheqd_config.toml --rm --entrypoint /usr/local/bin/entrypoint.sh ghcr.io/cheqd/cheqd-node:$CHEQD_IMAGE_TAG start 25 | -------------------------------------------------------------------------------- /scripts/run_dock_node_in_docker: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Starts a dock test node in docker for testing. Automatically deletes the container on exit. 4 | # Arguments passed to this script are forwarded to the node binary. 5 | # 6 | # Example use: 7 | # 8 | # ```bash 9 | # # Start a local test node 10 | # ./run_dock_node_in_docker --dev 11 | # 12 | # # Start a testnet node 13 | # ./run_dock_node_in_docker --chain=remdev --rpc-external --ws-external --rpc-cors=all 14 | # ``` 15 | 16 | set -uexo pipefail 17 | 18 | source $(dirname $0)/config 19 | 20 | # pre-pull 21 | docker pull $CONFIG_DOCK_NODE_IMAGE 22 | 23 | # run the node with the random name output by the build command 24 | docker run -p 9944:9944 -p 9933:9933 -p 30333:30333 --rm $CONFIG_DOCK_NODE_IMAGE $@ 25 | -------------------------------------------------------------------------------- /scripts/wait_for_node_rpc_http: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # block until node responds to rpc or until a timeout occurs 4 | 5 | set -ueo pipefail 6 | 7 | ALICE_NODE_HTTP=${ALICE_NODE_HTTP:-http://localhost:9933} 8 | 9 | callrpc() { 10 | curl $ALICE_NODE_HTTP -H "Content-Type:application/json;charset=utf-8" -d "$1" 11 | } 12 | 13 | wait_for_success() { 14 | if [ $# -eq 0 ]; then 15 | echo No command specified >&2 16 | return 1 17 | fi 18 | while ! ($@); do :; done 19 | } 20 | 21 | with_timeout() { 22 | local timeout="$1" 23 | shift 24 | 25 | sleep $timeout & 26 | local sproc=$! 27 | disown $sproc # keep the death of this command from being reported 28 | 29 | ($@) & 30 | local fproc=$! 31 | 32 | # wait for one of the processes to end 33 | while kill -0 $sproc 2>/dev/null && kill -0 $fproc 2>/dev/null; do :; done 34 | 35 | # end the sleep process if it is still running 36 | kill $sproc 2>/dev/null || true 37 | wait $sproc || true 38 | 39 | if kill $fproc 2>/dev/null; then 40 | echo Command "'"$@"'" timed out. >&2 41 | exit 124 42 | fi 43 | 44 | # success case, the command ran to completion, return it's status (could be nonzero) 45 | wait $fproc 46 | } 47 | 48 | quietly() { 49 | $@ >/dev/null 2>/dev/null 50 | } 51 | 52 | # Check that nodes' RPC server is ready 53 | with_timeout 15 wait_for_success quietly callrpc '[]' 54 | -------------------------------------------------------------------------------- /scripts/with_all_dock_docker_test_nodes: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ueo pipefail 4 | 5 | source $(dirname $0)/config 6 | 7 | root_dir="$(dirname $0)/.." 8 | 9 | declare -a images=("$CONFIG_DOCK_NODE_MASTER_IMAGE" "$CONFIG_DOCK_NODE_MAINNET_IMAGE" "$CONFIG_DOCK_NODE_TESTNET_IMAGE") 10 | 11 | for image in "${images[@]}" 12 | do 13 | CONFIG_DOCK_NODE_IMAGE=$image bash "$root_dir/scripts/with_dock_docker_test_node" $@ 14 | done 15 | 16 | exit 0 17 | -------------------------------------------------------------------------------- /scripts/with_cheqd_docker_test_node: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ueo pipefail 4 | 5 | entrypoint="$(realpath $(dirname $0)/cheqd_entrypoint)" 6 | config="$(realpath $(dirname $0)/cheqd_config.toml)" 7 | 8 | # pre-pull 9 | docker pull --platform linux/amd64 ghcr.io/cheqd/cheqd-node:$CHEQD_IMAGE_TAG 10 | 11 | # start a pos alice node 12 | alice_container_id=$(docker run --platform linux/amd64 -d --rm --name cheqd-dev -p 26656:26656 -p 26657:26657 -p 1317:1317 -p 9090:9090 -e CHEQD_MNEMONIC="$CHEQD_MNEMONIC" -e CHEQD_NETWORK="$CHEQD_NETWORK" -v $entrypoint:/usr/local/bin/entrypoint.sh -v $config:/tmp/cheqd_config.toml --entrypoint /usr/local/bin/entrypoint.sh ghcr.io/cheqd/cheqd-node:$CHEQD_IMAGE_TAG start) 13 | 14 | # locate the node's home directory 15 | alice_home=$(docker exec $alice_container_id sh -c 'echo $HOME') 16 | 17 | # tail logs, if necessary 18 | # docker logs -f $alice_container_id 19 | 20 | cleanup() { 21 | docker kill $alice_container_id 2> /dev/null 22 | } 23 | 24 | try_with_node() { 25 | sleep 10; 26 | # Execute the commands, potentially against the nodes 27 | $@ 28 | } 29 | 30 | trap cleanup EXIT SIGINT SIGTERM 31 | 32 | if try_with_node $@; then 33 | exit_code=$? 34 | else 35 | exit_code=$? 36 | fi 37 | 38 | exit $exit_code 39 | -------------------------------------------------------------------------------- /scripts/with_dock_docker_test_node: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ueo pipefail 4 | 5 | source $(dirname $0)/config 6 | 7 | root_dir="$(dirname $0)/.." 8 | 9 | # pre-pull 10 | docker pull $CONFIG_DOCK_NODE_IMAGE 11 | 12 | # start a pos alice node 13 | alice_container_id=$( 14 | docker run --rm -d --name dock-dev \ 15 | -p 9944:9944 -p 9933:9933 -p 30333:30333 \ 16 | $CONFIG_DOCK_NODE_IMAGE \ 17 | --alice --rpc-external --ws-external 18 | ) 19 | 20 | cleanup() { 21 | docker kill $alice_container_id 2> /dev/null 22 | } 23 | 24 | try_with_node() { 25 | # Wait for nodes to start listening for RPC 26 | "$root_dir"/scripts/wait_for_node_rpc_http 27 | 28 | sleep 5 29 | 30 | # Execute the commands, potentially against the nodes 31 | $@ 32 | } 33 | 34 | trap cleanup EXIT SIGINT SIGTERM 35 | 36 | if try_with_node $@; then 37 | exit_code=$? 38 | else 39 | exit_code=$? 40 | fi 41 | 42 | exit $exit_code 43 | -------------------------------------------------------------------------------- /turbo.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://turbo.build/schema.json", 3 | "tasks": { 4 | "build": { 5 | "cache": true, 6 | "dependsOn": ["^build"], 7 | "outputs": ["packages/**/dist/**"] 8 | }, 9 | "docs": { 10 | "cache": true, 11 | "outputs": ["out/**"] 12 | }, 13 | "lint": { 14 | "cache": false, 15 | "outputs": [] 16 | }, 17 | "publish": { 18 | "outputs": [] 19 | }, 20 | "test": { 21 | "cache": false, 22 | "dependsOn": ["^build"], 23 | "outputs": [] 24 | }, 25 | "examples": { 26 | "dependsOn": ["^build"], 27 | "outputs": [] 28 | }, 29 | "test-with-node": { 30 | "cache": false, 31 | "dependsOn": ["^build"], 32 | "outputs": [], 33 | "env": ["CHEQD_MNEMONIC", "CHEQD_IMAGE_TAG", "CHEQD_NETWORK"] 34 | }, 35 | "examples-with-node": { 36 | "cache": false, 37 | "dependsOn": ["^build"], 38 | "outputs": [], 39 | "env": ["CHEQD_MNEMONIC", "CHEQD_IMAGE_TAG", "CHEQD_NETWORK"] 40 | }, 41 | "publish-packages": { 42 | "dependsOn": ["^build"], 43 | "outputs": [] 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tutorials/.gitignore: -------------------------------------------------------------------------------- 1 | book 2 | -------------------------------------------------------------------------------- /tutorials/README.md: -------------------------------------------------------------------------------- 1 | This is an [mdBook](https://github.com/rust-lang/mdBook). See it [rendered here](https://docknetwork.github.io/sdk/tutorials). 2 | 3 | While editing, you can view changes live with auto-reload. Use the `mdbook` command. 4 | 5 | ```bash 6 | cd sdk/tutorials 7 | mdbook serve -o 8 | ``` 9 | -------------------------------------------------------------------------------- /tutorials/book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | authors = [ 3 | "Andrew Dirksen", 4 | "Fausto Woelflin", 5 | "Sam Hellawell", 6 | "Lovesh Harchandani", 7 | "Oleg Nosov", 8 | ] 9 | language = "en" 10 | multilingual = false 11 | src = "src" 12 | title = "Dock SDK Tutorial" 13 | -------------------------------------------------------------------------------- /tutorials/src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | - [Introduction](introduction.md) 4 | - [Concepts](concepts.md) 5 | - [DID](concepts_did.md) 6 | - [Verifiable credentials and presentations](concepts_vcdm.md) 7 | - [Schema](concepts_blobs_schemas.md) 8 | - [Claim Deduction](concepts_claim_deduction.md) 9 | - [PoE Anchors](concepts_poe_anchors.md) 10 | - [Private Delegation](concepts_private_delegation.md) 11 | - [Public Attestation](concepts_public_attestation.md) 12 | - [Public Delegation](concepts_public_delegation.md) 13 | - [Tutorials](tutorials.md) 14 | - [DID](tutorial_did.md) 15 | - [DID Resolver](tutorial_resolver.md) 16 | - [Credentials - Issuance, Presentation, Verification](tutorial_ipv.md) 17 | - [Revocation](tutorial_revocation.md) 18 | - [Schema](tutorial_blobs_schemas.md) 19 | - [Claim Deduction](tutorial_claim_deduction.md) 20 | - [PoE Anchors](tutorial_poe_anchors.md) 21 | - [Private Delegation](tutorial_private_delegation.md) 22 | - [Public Delegation](tutorial_public_delegation.md) 23 | - [Anonymous credentials using BBS+ signatures and accumulators](tutorial_anoncreds.md) 24 | -------------------------------------------------------------------------------- /tutorials/src/concepts.md: -------------------------------------------------------------------------------- 1 | # Concepts 2 | 3 | 1. [DID](./concepts_did.md) 4 | 2. [Verifiable credentials](./concepts_vcdm.md) 5 | 3. [Blobs and Schemas](./concepts_blobs_schemas.md) 6 | 4. [Claim Deduction](./concepts_claim_deduction.md) 7 | 5. [PoE Anchors](./concepts_poe_anchors.md) 8 | 6. [Private Delegation](./concepts_private_delegation.md) 9 | 7. [Public Attestation](./concepts_public_attestation.md) 10 | 8. [Public Delegation](./concepts_public_delegation.md) 11 | -------------------------------------------------------------------------------- /tutorials/src/concepts_poe_anchors.md: -------------------------------------------------------------------------------- 1 | The Dock Blockchain includes a module explicitly intended for proof of existence. Aside from being explicitly supported by the on-chain runtime, it works the same way you would expect. You post the hash of a document on-chain at a specific block. Later you can use that hash to prove the document existed at or before that block. 2 | 3 | The PoE module accepts arbitrary bytes as an anchor but in order to keep anchor size constant the chain stores only the blake2b256 hash of those bytes. 4 | 5 | Developers are free to use the anchoring module however they want, taloring their software to their own use case. An anchoring example can be found in the sdk examples directory. Dock Labs provides a [fully functioning reference client](https://fe.dock.io/#/anchor/batch) for anchoring. The client even implements batching anchors into a merkle tree so you can anchor multiple documents in a single transaction. 6 | -------------------------------------------------------------------------------- /tutorials/src/tutorials.md: -------------------------------------------------------------------------------- 1 | # Tutorials 2 | 3 | 1. [DID](./tutorial_did.md) 4 | 2. [DID Resolver](./did_resolver.md) 5 | 3. [Verifiable Credentials](./tutorial_ipv.md) 6 | 4. [Revocation](./tutorials_revocation.md) 7 | 5. [Blobs and Schemas](./tutorial_blobs_schemas.md) 8 | 6. [Claim Deduction](./tutorial_claim_deducation.md) 9 | 7. [PoE Anchors](./tutorial_poe_anchors.md) 10 | 8. [Private Delegation](./tutorial_private_delegation.md) 11 | 9. [Public Delegation](./tutorial_public_delegation.md) 12 | 10. [Anonymous Credentials](./tutorial_anoncreds.md) 13 | --------------------------------------------------------------------------------