@0xpolygonid/js-sdk
Version:
SDK to work with Polygon ID
976 lines (956 loc) • 601 kB
JavaScript
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// src/kms/kms.ts
var KMS = class {
_registry = /* @__PURE__ */ new Map();
/**
* register key provider in the KMS
*
* @param {KmsKeyType} keyType - kms key type
* @param {IKeyProvider} keyProvider - key provider implementation
*/
registerKeyProvider(keyType, keyProvider) {
if (this._registry.get(keyType)) {
throw new Error("present keyType");
}
this._registry.set(keyType, keyProvider);
}
/**
* generates a new key and returns it kms key id
*
* @param {KmsKeyType} keyType
* @param {Uint8Array} bytes
* @returns kms key id
*/
async createKeyFromSeed(keyType, bytes) {
const keyProvider = this._registry.get(keyType);
if (!keyProvider) {
throw new Error(`keyProvider not found for: ${keyType}`);
}
return keyProvider.newPrivateKeyFromSeed(bytes);
}
async createKey(keyType) {
const keyProvider = this._registry.get(keyType);
if (!keyProvider) {
throw new Error(`keyProvider not found for: ${keyType}`);
}
return keyProvider.newPrivateKey();
}
/**
* gets public key for key id
*
* @param {KmsKeyId} keyId -- key id
* @returns public key
*/
async publicKey(keyId) {
const keyProvider = this._registry.get(keyId.type);
if (!keyProvider) {
throw new Error(`keyProvider not found for: ${keyId.type}`);
}
return keyProvider.publicKey(keyId);
}
/**
* sign Uint8Array with giv KmsKeyIden
*
* @param {KmsKeyId} keyId - key id
* @param {Uint8Array} data - prepared data bytes
* @returns `Promise<Uint8Array>` - return signature
*/
async sign(keyId, data, opts) {
const keyProvider = this._registry.get(keyId.type);
if (!keyProvider) {
throw new Error(`keyProvider not found for: ${keyId.type}`);
}
return keyProvider.sign(keyId, data, opts);
}
/**
* Verifies a signature against the provided data and key ID.
*
* @param data - The data to verify the signature against.
* @param signatureHex - The signature to verify, in hexadecimal format.
* @param keyId - The key ID to use for verification.
* @returns A promise that resolves to a boolean indicating whether the signature is valid.
*/
verify(data, signatureHex, keyId) {
const keyProvider = this._registry.get(keyId.type);
if (!keyProvider) {
throw new Error(`keyProvider not found for: ${keyId.type}`);
}
return keyProvider.verify(data, signatureHex, keyId);
}
/**
* get all keys by key type
*
* @param keyType - Key type
* @returns list of keys
*/
list(keyType) {
const keyProvider = this._registry.get(keyType);
if (!keyProvider) {
throw new Error(`keyProvider not found for: ${keyType}`);
}
return keyProvider.list();
}
/**
* get key provider by key type
*
* @param keyType - Key type
* @returns key provider
*/
getKeyProvider(keyType) {
return this._registry.get(keyType);
}
};
// src/kms/key-providers/bjj-provider.ts
import { Hex as Hex4, PrivateKey, PublicKey as PublicKey4, Signature as Signature2 } from "@iden3/js-crypto";
import { BytesHelper as BytesHelper2, checkBigIntInField } from "@iden3/js-iden3-core";
// src/kms/store/abstract-key-store.ts
var AbstractPrivateKeyStore = class {
};
// src/kms/store/memory-key-store.ts
var InMemoryPrivateKeyStore = class {
_data;
constructor() {
this._data = /* @__PURE__ */ new Map();
}
list() {
return Promise.resolve(Array.from(this._data).map(([alias, key]) => ({ alias, key })));
}
async get(args) {
const privateKey = this._data.get(args.alias);
if (!privateKey) {
throw new Error("no key under given alias");
}
return privateKey;
}
async importKey(args) {
this._data.set(args.alias, args.key);
}
};
// src/kms/store/types.ts
var KmsKeyType = /* @__PURE__ */ ((KmsKeyType2) => {
KmsKeyType2["BabyJubJub"] = "BJJ";
KmsKeyType2["Secp256k1"] = "Secp256k1";
KmsKeyType2["Ed25519"] = "Ed25519";
KmsKeyType2["RsaOaep256"] = "RSA-OAEP-256";
KmsKeyType2["P384"] = "P-384";
return KmsKeyType2;
})(KmsKeyType || {});
// src/kms/store/local-storage-key-store.ts
var LocalStoragePrivateKeyStore = class _LocalStoragePrivateKeyStore {
static storageKey = "keystore";
/**
* get all keys
*
* @abstract
* @returns `Promise<{ alias: string; key: string }[]>`
*/
list() {
const dataStr = localStorage.getItem(_LocalStoragePrivateKeyStore.storageKey);
if (!dataStr) {
throw new Error("no key under given alias");
}
const data = JSON.parse(dataStr);
return data.map((i) => ({ alias: i.id, key: i.value }));
}
/**
* Gets key from the local storage
*
* @param {{ alias: string }} args
* @returns hex string
*/
async get(args) {
const dataStr = localStorage.getItem(_LocalStoragePrivateKeyStore.storageKey);
if (!dataStr) {
throw new Error("no key under given alias");
}
const data = JSON.parse(dataStr);
const privateKey = data.find((d) => d.id === args.alias);
if (!privateKey) {
throw new Error("no key under given alias");
}
return privateKey.value;
}
/**
* Import key to the local storage
*
* @param {{ alias: string; key: string }} args - alias and private key in the hex
* @returns void
*/
async importKey(args) {
const dataStr = localStorage.getItem(_LocalStoragePrivateKeyStore.storageKey);
let data = [];
if (dataStr) {
data = JSON.parse(dataStr);
}
const index = data.findIndex((d) => d.id === args.alias);
if (index > -1) {
data[index].value = args.key;
} else {
data.push({ id: args.alias, value: args.key });
}
localStorage.setItem(_LocalStoragePrivateKeyStore.storageKey, JSON.stringify(data));
}
};
// src/kms/store/indexed-db-key-store.ts
import { createStore, get, set, entries } from "idb-keyval";
var IndexedDBPrivateKeyStore = class _IndexedDBPrivateKeyStore {
static storageKey = "keystore";
_store;
constructor() {
this._store = createStore(
`${_IndexedDBPrivateKeyStore.storageKey}-db`,
_IndexedDBPrivateKeyStore.storageKey
);
}
/**
* get all keys
*
* @abstract
* @returns `Promise<{ alias: string; key: string }[]>`
*/
async list() {
const allEntries = await entries(this._store);
return allEntries.map(([alias, key]) => ({ alias, key: key.value }));
}
/**
* Gets key from the indexed db storage
*
* @param {{ alias: string }} args
* @returns hex string
*/
async get(args) {
const key = await get(args.alias, this._store);
if (!key) {
throw new Error("no key under given alias");
}
return key.value;
}
/**
* Import key to the indexed db storage
*
* @param {{ alias: string; key: string }} args - alias and private key in the hex
* @returns void
*/
async importKey(args) {
await set(args.alias, { value: args.key }, this._store);
}
};
// src/kms/provider-helpers.ts
function keyPath(keyType, keyID) {
const basePath = "";
return basePath + String(keyType) + ":" + keyID;
}
// src/utils/encoding.ts
import { base58FromBytes, base58ToBytes as b58ToBytes, Hex } from "@iden3/js-crypto";
import { base64url, base64 } from "rfc4648";
var byteEncoder = new TextEncoder();
var byteDecoder = new TextDecoder();
function bytesToBase64url(b, opts = { pad: false }) {
return base64url.stringify(b, opts);
}
function base64ToBytes(s, opts = { loose: true }) {
return base64.parse(s, opts);
}
function bytesToBase64(b, opts = { pad: false }) {
return base64.stringify(b, opts);
}
function base64UrlToBytes(s, opts = { loose: true }) {
const inputBase64Url = s.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
return base64url.parse(inputBase64Url, opts);
}
function base58ToBytes(s) {
return b58ToBytes(s);
}
function bytesToBase58(b) {
return base58FromBytes(b);
}
function hexToBytes(s) {
const input = s.startsWith("0x") ? s.substring(2) : s;
return Hex.decodeString(input.toLowerCase());
}
function encodeBase64url(s, opts = { pad: false }) {
return base64url.stringify(byteEncoder.encode(s), opts);
}
function decodeBase64url(s, opts = { loose: true }) {
return byteDecoder.decode(base64url.parse(s, opts));
}
function bytesToHex(b) {
return Hex.encodeString(b);
}
// src/utils/object.ts
function mergeObjects(credSubject, otherCredSubject) {
let result = {};
const credSubjectKeys = Object.keys(credSubject);
for (const key of credSubjectKeys) {
if (typeof otherCredSubject[key] !== "undefined") {
if (typeof credSubject[key] !== "object" && typeof otherCredSubject[key] !== "object") {
throw new Error("Invalid query");
}
const subjectProperty = credSubject[key];
const otherSubjectProperty = otherCredSubject[key];
const propertyOperators = Object.keys(subjectProperty);
const subjectPropertyResult = {};
for (const operatorKey of propertyOperators) {
if (typeof otherSubjectProperty[operatorKey] !== "undefined") {
const operatorValue1 = subjectProperty[operatorKey];
const operatorValue2 = otherSubjectProperty[operatorKey];
subjectPropertyResult[operatorKey] = [
.../* @__PURE__ */ new Set([
...subjectPropertyResult[operatorKey] ?? [],
operatorValue1,
...Array.isArray(operatorValue2) ? operatorValue2 : [operatorValue2]
])
];
} else {
subjectPropertyResult[operatorKey] = subjectProperty[operatorKey];
}
}
result[key] = {
...otherCredSubject[key],
...subjectPropertyResult
};
}
}
result = { ...credSubject, ...otherCredSubject, ...result };
return result;
}
// src/utils/did-helper.ts
import { Hex as Hex2 } from "@iden3/js-crypto";
import { Id, buildDIDType, genesisFromEthAddress, DID } from "@iden3/js-iden3-core";
import { Hash } from "@iden3/js-merkletree";
import { keccak256 } from "ethers";
var DIDDocumentSignature = /* @__PURE__ */ ((DIDDocumentSignature2) => {
DIDDocumentSignature2["EthereumEip712Signature2021"] = "EthereumEip712Signature2021";
return DIDDocumentSignature2;
})(DIDDocumentSignature || {});
function isGenesisState(did, state) {
if (typeof state === "string") {
state = Hash.fromHex(state).bigInt();
}
const id = DID.idFromDID(did);
return getIsGenesisStateById(id, state);
}
function getIsGenesisStateById(id, state) {
const { method, blockchain, networkId } = DID.decodePartsFromId(id);
const type = buildDIDType(method, blockchain, networkId);
const idFromState = Id.idGenesisFromIdenState(type, state);
return id.bigInt().toString() === idFromState.bigInt().toString();
}
function isEthereumIdentity(did) {
const issuerId = DID.idFromDID(did);
try {
Id.ethAddressFromId(issuerId);
return true;
} catch {
return false;
}
}
var buildVerifierId = (address, info) => {
address = address.replace("0x", "");
const ethAddrBytes = Hex2.decodeString(address);
const ethAddr = ethAddrBytes.slice(0, 20);
const genesis = genesisFromEthAddress(ethAddr);
const tp = buildDIDType(info.method, info.blockchain, info.networkId);
return new Id(tp, genesis);
};
var validateDIDDocumentAuth = async (did, resolverURL, state) => {
const vm = await resolveDIDDocumentAuth(did, resolverURL, state);
if (!vm) {
throw new Error(`can't resolve DID document`);
}
if (!vm.published && !isGenesisState(did, state.bigInt())) {
throw new Error(`issuer state not published and not genesis`);
}
};
var resolveDIDDocumentAuth = async (did, resolveURL, state) => {
let url = `${resolveURL}/${encodeURIComponent(did.string())}`;
if (state) {
url += `?state=${state.hex()}`;
}
const resp = await fetch(url);
const didResolutionRes = await resp.json();
return didResolutionRes.didDocument?.verificationMethod?.find(
(i) => i.type === "Iden3StateInfo2023"
);
};
function emptyStateDID(did) {
const id = DID.idFromDID(did);
const didType = buildDIDType(
DID.methodFromId(id),
DID.blockchainFromId(id),
DID.networkIdFromId(id)
);
const identifier = Id.idGenesisFromIdenState(didType, 0n);
const emptyDID = DID.parseFromId(identifier);
return emptyDID;
}
var resolveDidDocument = async (did, resolverUrl, opts) => {
let didString = encodeURIComponent(did.string());
const isGistRequest = opts?.gist && !opts.state;
if (isGistRequest) {
didString = encodeURIComponent(emptyStateDID(did).string());
}
let url = `${resolverUrl}/1.0/identifiers/${didString}`;
if (opts?.signature) {
url += `?signature=${opts.signature}`;
}
if (opts?.state) {
url += `${url.includes("?") ? "&" : "?"}state=${opts.state.hex()}`;
}
if (opts?.gist) {
url += `${url.includes("?") ? "&" : "?"}gist=${opts.gist.hex()}`;
}
try {
const resp = await fetch(url);
const data = await resp.json();
return data;
} catch (e) {
throw new Error(`Failed to resolve DID document for ${did} ${e}`);
}
};
var _buildDIDFromEthAddress = (didType, ethAddress) => {
const genesis = genesisFromEthAddress(ethAddress);
const identifier = new Id(didType, genesis);
return DID.parseFromId(identifier);
};
var buildDIDFromEthPubKey = (didType, pubKeyEth) => {
const hashOfPublicKey = keccak256(hexToBytes(pubKeyEth));
const ethAddressBuffer = hexToBytes(hashOfPublicKey);
const ethAddr = ethAddressBuffer.slice(-20);
return _buildDIDFromEthAddress(didType, ethAddr);
};
var buildDIDFromEthAddress = (didType, ethAddress) => {
return _buildDIDFromEthAddress(didType, hexToBytes(ethAddress));
};
// src/utils/message-bus.ts
import PubSub from "pubsub-js";
var SDK_EVENTS = {
TX_RECEIPT_ACCEPTED: "TX_RECEIPT_ACCEPTED"
};
var MessageBus = class _MessageBus {
/**
* The singleton instance of the MessageBus class.
*/
static instance;
/**
* Private constructor for the MessageBus class.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-function
constructor() {
}
/**
* Returns the singleton instance of the MessageBus class.
* If the instance doesn't exist, it creates a new one.
* @returns The singleton instance of the MessageBus class.
*/
static getInstance() {
if (!_MessageBus.instance) {
_MessageBus.instance = new _MessageBus();
}
return _MessageBus.instance;
}
/**
* Publishes a message to the specified topic.
*
* @template T - The type of data being published.
* @param {SdkTopic} topic - The topic to publish the message to.
* @param {T} data - The data to be published.
* @returns {boolean} - Returns true if the message was successfully published, false otherwise.
*/
publish(topic, data) {
return PubSub.publish(topic.toString(), data);
}
/**
* Subscribes to a specific topic and registers a callback function to be executed when a message is published.
*
* @param topic - The topic to subscribe to.
* @param callback - The callback function to be executed when a message is published.
*/
subscribe(topic, callback) {
return PubSub.subscribe(topic.toString(), (_, data) => callback(data));
}
/**
* Subscribes to a specific topic and registers a callback function to be executed when a message is published.
* The callback function is executed only once.
*
* @param topic - The topic to subscribe to.
* @param callback - The callback function to be executed when a message is published.
*/
subscribeOnce(topic, callback) {
PubSub.subscribeOnce(topic.toString(), (_, data) => callback(data));
}
/**
* Unsubscribes from a specific topic in the message bus.
*
* @param topic - The topic to unsubscribe from.
* @returns A string or boolean indicating the success of the unsubscribe operation.
*/
unsubscribe(topic) {
return PubSub.unsubscribe(topic.toString());
}
};
// src/utils/compare-func.ts
var bigIntCompare = (a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
};
// src/utils/payments/solana.ts
import { serialize } from "borsh";
import { ed25519 } from "@noble/curves/ed25519";
// src/verifiable/proof.ts
import { Hash as Hash2, Proof } from "@iden3/js-merkletree";
// src/verifiable/constants.ts
var VerifiableConstants = Object.freeze({
ERRORS: {
FiELD_IS_EMPTY: "fieldPath is empty",
CONTEXT_TYPE_IS_EMPTY: "ctxType is empty",
// ErrStateNotFound issuer state is genesis state.
IDENTITY_DOES_NOT_EXIST: "Identity does not exist",
IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR: "IdentityDoesNotExist",
NO_AUTH_CRED_FOUND: "no auth credentials found",
STATE_DOES_NOT_EXIST: "State does not exist",
STATE_DOES_NOT_EXIST_CUSTOM_ERROR: "StateDoesNotExist",
ROOT_DOES_NOT_EXIST: "Root does not exist",
ROOT_DOES_NOT_EXIST_CUSTOM_ERROR: "RootDoesNotExist",
// identity wallet
ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY: "no credential satisfied query",
ID_WALLET_SIGNER_IS_REQUIRED: "Ethereum signer is required to create Ethereum identities in order to transit state",
ID_WALLET_PROVER_IS_REQUIRED: "prover is required to generate proofs for non ethereum identities",
ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF: "credential must have coreClaim representation in the signature proof",
ID_WALLET_CORE_CLAIM_REQUIRED_IN_ANY_PROOF: "credential must have coreClaim representation in proofs",
ID_WALLET_CORE_CLAIM_MISMATCH: "core claim representations is set in both proofs but they are not equal",
ID_WALLET_CORE_CLAIM_IS_NOT_SET: "core claim is not set in credential proofs",
ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND: "profile or identity not found",
ID_WALLET_PROFILE_ALREADY_EXISTS: "profile with given nonce or verifier already exists",
ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS: "profile with given verifier and tags already exists",
ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF: "issuer auth credential must have proof",
ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF: "mtp is required for auth bjj key to issue new credentials",
// proof service
PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE: "no credentials belong to did or its profiles",
PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY: "credential not found for query",
PROOF_SERVICE_PROFILE_GENESIS_DID_MISMATCH: "subject and auth profiles are not derived from the same did",
PROOF_SERVICE_NO_QUERIES_IN_ZKP_REQUEST: "no queries in zkp request",
// credential wallet
CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED: "all claims are revoked"
},
CREDENTIAL_TYPE: {
// VerifiableCredential is a W3C verifiable credential type
W3C_VERIFIABLE_CREDENTIAL: "VerifiableCredential",
W3C_VERIFIABLE_PRESENTATION: "VerifiablePresentation"
},
CREDENTIAL_SUBJECT_PATH: "https://www.w3.org/2018/credentials#credentialSubject",
JSONLD_SCHEMA: {
// JSONLDSchemaIden3Credential is a schema for context with Iden3Credential type
IDEN3_CREDENTIAL: "https://schema.iden3.io/core/jsonld/iden3proofs.jsonld",
// JSONLDSchemaIden3DisplayMethod is a schema for context with Iden3BasicDisplayMethodV1 type
IDEN3_DISPLAY_METHOD: "https://schema.iden3.io/core/jsonld/displayMethod.jsonld",
// JSONLDSchemaW3CCredential2018 is a schema for context with VerifiableCredential type
W3C_CREDENTIAL_2018: "https://www.w3.org/2018/credentials/v1",
W3C_VC_DOCUMENT_2018: `{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","VerifiableCredential":{"@id":"https://www.w3.org/2018/credentials#VerifiableCredential","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","credentialSchema":{"@id":"cred:credentialSchema","@type":"@id","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","JsonSchemaValidator2018":"cred:JsonSchemaValidator2018"}},"credentialStatus":{"@id":"cred:credentialStatus","@type":"@id"},"credentialSubject":{"@id":"cred:credentialSubject","@type":"@id"},"evidence":{"@id":"cred:evidence","@type":"@id"},"expirationDate":{"@id":"cred:expirationDate","@type":"xsd:dateTime"},"holder":{"@id":"cred:holder","@type":"@id"},"issued":{"@id":"cred:issued","@type":"xsd:dateTime"},"issuer":{"@id":"cred:issuer","@type":"@id"},"issuanceDate":{"@id":"cred:issuanceDate","@type":"xsd:dateTime"},"proof":{"@id":"sec:proof","@type":"@id","@container":"@graph"},"refreshService":{"@id":"cred:refreshService","@type":"@id","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","ManualRefreshService2018":"cred:ManualRefreshService2018"}},"termsOfUse":{"@id":"cred:termsOfUse","@type":"@id"},"validFrom":{"@id":"cred:validFrom","@type":"xsd:dateTime"},"validUntil":{"@id":"cred:validUntil","@type":"xsd:dateTime"}}},"VerifiablePresentation":{"@id":"https://www.w3.org/2018/credentials#VerifiablePresentation","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","sec":"https://w3id.org/security#","holder":{"@id":"cred:holder","@type":"@id"},"proof":{"@id":"sec:proof","@type":"@id","@container":"@graph"},"verifiableCredential":{"@id":"cred:verifiableCredential","@type":"@id","@container":"@graph"}}},"EcdsaSecp256k1Signature2019":{"@id":"https://w3id.org/security#EcdsaSecp256k1Signature2019","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"EcdsaSecp256r1Signature2019":{"@id":"https://w3id.org/security#EcdsaSecp256r1Signature2019","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"Ed25519Signature2018":{"@id":"https://w3id.org/security#Ed25519Signature2018","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"RsaSignature2018":{"@id":"https://w3id.org/security#RsaSignature2018","@context":{"@version":1.1,"@protected":true,"challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"proof":{"@id":"https://w3id.org/security#proof","@type":"@id","@container":"@graph"}}}`,
IDEN3_PROOFS_DEFINITION_DOCUMENT: `{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","Iden3SparseMerkleTreeProof":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3SparseMerkleTreeProof","@context":{"@version":1.1,"@protected":true,"@propagate":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","@vocab":"https://schema.iden3.io/core/vocab/Iden3SparseMerkleTreeProof.md#","xsd":"http://www.w3.org/2001/XMLSchema#","mtp":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#SparseMerkleTreeProof","@type":"SparseMerkleTreeProof"},"coreClaim":{"@id":"coreClaim","@type":"xsd:string"},"issuerData":{"@id":"issuerData","@context":{"@version":1.1,"state":{"@id":"state","@context":{"txId":{"@id":"txId","@type":"xsd:string"},"blockTimestamp":{"@id":"blockTimestamp","@type":"xsd:integer"},"blockNumber":{"@id":"blockNumber","@type":"xsd:integer"},"rootOfRoots":{"@id":"rootOfRoots","@type":"xsd:string"},"claimsTreeRoot":{"@id":"claimsTreeRoot","@type":"xsd:string"},"revocationTreeRoot":{"@id":"revocationTreeRoot","@type":"xsd:string"},"authCoreClaim":{"@id":"authCoreClaim","@type":"xsd:string"},"value":{"@id":"value","@type":"xsd:string"}}}}}}},"SparseMerkleTreeProof":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#SparseMerkleTreeProof","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","smt-proof-vocab":"https://schema.iden3.io/core/vocab/SparseMerkleTreeProof.md#","xsd":"http://www.w3.org/2001/XMLSchema#","existence":{"@id":"smt-proof-vocab:existence","@type":"xsd:boolean"},"revocationNonce":{"@id":"smt-proof-vocab:revocationNonce","@type":"xsd:number"},"siblings":{"@id":"smt-proof-vocab:siblings","@container":"@list"},"nodeAux":"@nest","hIndex":{"@id":"smt-proof-vocab:hIndex","@nest":"nodeAux","@type":"xsd:string"},"hValue":{"@id":"smt-proof-vocab:hValue","@nest":"nodeAux","@type":"xsd:string"}}},"BJJSignature2021":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#BJJSignature2021","@context":{"@version":1.1,"@protected":true,"id":"@id","@vocab":"https://schema.iden3.io/core/vocab/BJJSignature2021.md#","@propagate":true,"type":"@type","xsd":"http://www.w3.org/2001/XMLSchema#","coreClaim":{"@id":"coreClaim","@type":"xsd:string"},"issuerData":{"@id":"issuerData","@context":{"@version":1.1,"authCoreClaim":{"@id":"authCoreClaim","@type":"xsd:string"},"mtp":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#SparseMerkleTreeProof","@type":"SparseMerkleTreeProof"},"revocationStatus":{"@id":"revocationStatus","@type":"@id"},"state":{"@id":"state","@context":{"@version":1.1,"rootOfRoots":{"@id":"rootOfRoots","@type":"xsd:string"},"claimsTreeRoot":{"@id":"claimsTreeRoot","@type":"xsd:string"},"revocationTreeRoot":{"@id":"revocationTreeRoot","@type":"xsd:string"},"value":{"@id":"value","@type":"xsd:string"}}}}},"signature":{"@id":"signature","@type":"https://w3id.org/security#multibase"},"domain":"https://w3id.org/security#domain","creator":{"@id":"creator","@type":"http://www.w3.org/2001/XMLSchema#string"},"challenge":"https://w3id.org/security#challenge","created":{"@id":"created","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},"expires":{"@id":"https://w3id.org/security#expiration","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},"nonce":"https://w3id.org/security#nonce","proofPurpose":{"@id":"https://w3id.org/security#proofPurpose","@type":"@vocab","@context":{"@protected":true,"id":"@id","type":"@type","assertionMethod":{"@id":"https://w3id.org/security#assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"https://w3id.org/security#authenticationMethod","@type":"@id","@container":"@set"},"capabilityInvocation":{"@id":"https://w3id.org/security#capabilityInvocationMethod","@type":"@id","@container":"@set"},"capabilityDelegation":{"@id":"https://w3id.org/security#capabilityDelegationMethod","@type":"@id","@container":"@set"},"keyAgreement":{"@id":"https://w3id.org/security#keyAgreementMethod","@type":"@id","@container":"@set"}}},"proofValue":{"@id":"https://w3id.org/security#proofValue","@type":"https://w3id.org/security#multibase"},"verificationMethod":{"@id":"https://w3id.org/security#verificationMethod","@type":"@id"}}},"Iden3ReverseSparseMerkleTreeProof":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3ReverseSparseMerkleTreeProof","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3-reverse-sparse-merkle-tree-proof-vocab":"https://schema.iden3.io/core/vocab/Iden3ReverseSparseMerkleTreeProof.md#","xsd":"http://www.w3.org/2001/XMLSchema#","revocationNonce":{"@id":"iden3-reverse-sparse-merkle-tree-proof-vocab:revocationNonce","@type":"xsd:integer"},"statusIssuer":{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type"},"@id":"iden3-reverse-sparse-merkle-tree-proof-vocab:statusIssuer"}}},"Iden3commRevocationStatusV1.0":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3commRevocationStatusV1.0","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3-comm-revocation-statusV1.0-vocab":"https://schema.iden3.io/core/vocab/Iden3commRevocationStatusV1.0.md#","xsd":"http://www.w3.org/2001/XMLSchema#","revocationNonce":{"@id":"iden3-comm-revocation-statusV1.0-vocab:revocationNonce","@type":"xsd:integer"},"statusIssuer":{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type"},"@id":"iden3-comm-revocation-statusV1.0-vocab:statusIssuer"}}},"Iden3OnchainSparseMerkleTreeProof2023":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3OnchainSparseMerkleTreeProof2023","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3-onchain-sparse-merkle-tree-proof-2023-vocab":"https://schema.iden3.io/core/vocab/Iden3OnchainSparseMerkleTreeProof2023.md#","xsd":"http://www.w3.org/2001/XMLSchema#","revocationNonce":{"@id":"iden3-onchain-sparse-merkle-tree-proof-2023-vocab:revocationNonce","@type":"xsd:integer"},"statusIssuer":{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type"},"@id":"iden3-onchain-sparse-merkle-tree-proof-2023-vocab:statusIssuer"}}},"JsonSchema2023":"https://www.w3.org/ns/credentials#JsonSchema2023","Iden3RefreshService2023":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3RefreshService2023"}}`,
IDEN3_DISPLAY_METHOD_DEFINITION_DOCUMENT: `{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","displayMethod":{"@id":"https://schema.iden3.io/core/vocab/displayMethod.md#displayMethod","@type":"@id","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","Iden3BasicDisplayMethodV1":"https://schema.iden3.io/core/vocab/displayMethod.md#Iden3BasicDisplayMethodV1"}}}}`
},
// JsonSchema2023 JSON schema for verification of Iden3Credential
JSON_SCHEMA_VALIDATOR: "JsonSchema2023",
SERVICE_TYPE: {
// Iden3CommServiceType is service type for iden3comm protocol
IDEN3_COMM: "iden3-communication",
// PushNotificationServiceType is service type for delivering push notifications to identity
PUSH_NOTIFICATION: "push-notification"
},
AUTH: {
AUTH_BJJ_CREDENTIAL_HASH: "013fd3f623559d850fb5b02ff012d0e2",
AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL: "https://schema.iden3.io/core/json/auth.json",
AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL: "https://schema.iden3.io/core/jsonld/auth.jsonld",
AUTH_BJJ_CREDENTIAL_TYPE: "AuthBJJCredential",
AUTH_BJJ_CREDENTIAL_SCHEMA_JSON: `{"$schema":"http://json-schema.org/draft-07/schema#","$metadata":{"uris":{"jsonLdContext":"https://schema.iden3.io/core/jsonld/auth.jsonld","jsonSchema":"https://schema.iden3.io/core/json/auth.json"},"serialization":{"indexDataSlotA":"x","indexDataSlotB":"y"}},"type":"object","required":["@context","id","type","issuanceDate","credentialSubject","credentialSchema","credentialStatus","issuer"],"properties":{"@context":{"type":["string","array","object"]},"id":{"type":"string"},"type":{"type":["string","array"],"items":{"type":"string"}},"issuer":{"type":["string","object"],"format":"uri","required":["id"],"properties":{"id":{"type":"string","format":"uri"}}},"issuanceDate":{"type":"string","format":"date-time"},"expirationDate":{"type":"string","format":"date-time"},"credentialSchema":{"type":"object","required":["id","type"],"properties":{"id":{"type":"string","format":"uri"},"type":{"type":"string"}}},"credentialSubject":{"type":"object","required":["x","y"],"properties":{"id":{"title":"Credential Subject ID","type":"string","format":"uri"},"x":{"type":"string"},"y":{"type":"string"}}}}}`,
AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD: `{"@context":[{"@version":1.1,"@protected":true,"id":"@id","type":"@type","AuthBJJCredential":{"@id":"https://schema.iden3.io/core/jsonld/auth.jsonld#AuthBJJCredential","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3_serialization":"iden3:v1:slotIndexA=x&slotIndexB=y","xsd":"http://www.w3.org/2001/XMLSchema#","auth-vocab":"https://schema.iden3.io/core/vocab/auth.md#","x":{"@id":"auth-vocab:x","@type":"xsd:positiveInteger"},"y":{"@id":"auth-vocab:y","@type":"xsd:positiveInteger"}}},"Iden3StateInfo2023":{"@id":"https://schema.iden3.io/core/jsonld/auth.jsonld#Iden3StateInfo2023","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","xsd":"http://www.w3.org/2001/XMLSchema#","@vocab":"https://schema.iden3.io/core/vocab/state-info.md#","@propagate":true,"stateContractAddress":{"@id":"stateContractAddress","@type":"xsd:string"},"published":{"@id":"published","@type":"xsd:boolean"},"info":{"@id":"info","@type":"@id","@context":{"@protected":true,"id":{"@id":"id","@type":"xsd:string"},"state":{"@id":"state","@type":"xsd:string"},"replacedByState":{"@id":"replacedByState","@type":"xsd:string"},"createdAtTimestamp":{"@id":"createdAtTimestamp","@type":"xsd:string"},"replacedAtTimestamp":{"@id":"replacedAtTimestamp","@type":"xsd:string"},"createdAtBlock":{"@id":"createdAtBlock","@type":"xsd:string"},"replacedAtBlock":{"@id":"replacedAtBlock","@type":"xsd:string"}}},"global":{"@id":"global","@type":"@id","@context":{"@protected":true,"sec":"https://w3id.org/security#","root":{"@id":"root","@type":"xsd:string"},"replacedByRoot":{"@id":"replacedByRoot","@type":"xsd:string"},"createdAtTimestamp":{"@id":"createdAtTimestamp","@type":"xsd:string"},"replacedAtTimestamp":{"@id":"replacedAtTimestamp","@type":"xsd:string"},"createdAtBlock":{"@id":"createdAtBlock","@type":"xsd:string"},"replacedAtBlock":{"@id":"replacedAtBlock","@type":"xsd:string"},"proof":{"@id":"sec:proof","@type":"@id","@container":"@graph"}}}}}}]}`
}
});
var ProofType = /* @__PURE__ */ ((ProofType2) => {
ProofType2["BJJSignature"] = "BJJSignature2021";
ProofType2["Iden3SparseMerkleTreeProof"] = "Iden3SparseMerkleTreeProof";
return ProofType2;
})(ProofType || {});
var CredentialStatusType = /* @__PURE__ */ ((CredentialStatusType2) => {
CredentialStatusType2["SparseMerkleTreeProof"] = "SparseMerkleTreeProof";
CredentialStatusType2["Iden3ReverseSparseMerkleTreeProof"] = "Iden3ReverseSparseMerkleTreeProof";
CredentialStatusType2["Iden3commRevocationStatusV1"] = "Iden3commRevocationStatusV1.0";
CredentialStatusType2["Iden3OnchainSparseMerkleTreeProof2023"] = "Iden3OnchainSparseMerkleTreeProof2023";
return CredentialStatusType2;
})(CredentialStatusType || {});
var ProofPurpose = /* @__PURE__ */ ((ProofPurpose2) => {
ProofPurpose2["Authentication"] = "Authentication";
return ProofPurpose2;
})(ProofPurpose || {});
var MerklizedRootPosition = /* @__PURE__ */ ((MerklizedRootPosition4) => {
MerklizedRootPosition4["Index"] = "index";
MerklizedRootPosition4["Value"] = "value";
MerklizedRootPosition4["None"] = "";
return MerklizedRootPosition4;
})(MerklizedRootPosition || {});
var SubjectPosition = /* @__PURE__ */ ((SubjectPosition2) => {
SubjectPosition2["None"] = "";
SubjectPosition2["Index"] = "index";
SubjectPosition2["Value"] = "value";
return SubjectPosition2;
})(SubjectPosition || {});
var RefreshServiceType = /* @__PURE__ */ ((RefreshServiceType2) => {
RefreshServiceType2["Iden3RefreshService2023"] = "Iden3RefreshService2023";
return RefreshServiceType2;
})(RefreshServiceType || {});
var PaymentRequestDataType = /* @__PURE__ */ ((PaymentRequestDataType2) => {
PaymentRequestDataType2["Iden3PaymentRequestCryptoV1"] = "Iden3PaymentRequestCryptoV1";
PaymentRequestDataType2["Iden3PaymentRailsRequestV1"] = "Iden3PaymentRailsRequestV1";
PaymentRequestDataType2["Iden3PaymentRailsERC20RequestV1"] = "Iden3PaymentRailsERC20RequestV1";
PaymentRequestDataType2["Iden3PaymentRailsSolanaRequestV1"] = "Iden3PaymentRailsSolanaRequestV1";
PaymentRequestDataType2["Iden3PaymentRailsSolanaSPLRequestV1"] = "Iden3PaymentRailsSolanaSPLRequestV1";
return PaymentRequestDataType2;
})(PaymentRequestDataType || {});
var PaymentType = /* @__PURE__ */ ((PaymentType2) => {
PaymentType2["Iden3PaymentCryptoV1"] = "Iden3PaymentCryptoV1";
PaymentType2["Iden3PaymentRailsV1"] = "Iden3PaymentRailsV1";
PaymentType2["Iden3PaymentRailsERC20V1"] = "Iden3PaymentRailsERC20V1";
PaymentType2["Iden3PaymentRailsSolanaV1"] = "Iden3PaymentRailsSolanaV1";
PaymentType2["Iden3PaymentRailsSolanaSPLV1"] = "Iden3PaymentRailsSolanaSPLV1";
return PaymentType2;
})(PaymentType || {});
var SupportedPaymentProofType = /* @__PURE__ */ ((SupportedPaymentProofType2) => {
SupportedPaymentProofType2["EthereumEip712Signature2021"] = "EthereumEip712Signature2021";
SupportedPaymentProofType2["SolanaEd25519Signature2025"] = "SolanaEd25519Signature2025";
return SupportedPaymentProofType2;
})(SupportedPaymentProofType || {});
var SupportedCurrencies = /* @__PURE__ */ ((SupportedCurrencies2) => {
SupportedCurrencies2["ETH"] = "ETH";
SupportedCurrencies2["ETH_WEI"] = "ETHWEI";
SupportedCurrencies2["ETH_GWEI"] = "ETHGWEI";
SupportedCurrencies2["MATIC"] = "MATIC";
SupportedCurrencies2["POL"] = "POL";
return SupportedCurrencies2;
})(SupportedCurrencies || {});
var PaymentFeatures = /* @__PURE__ */ ((PaymentFeatures2) => {
PaymentFeatures2["EIP_2612"] = "EIP-2612";
return PaymentFeatures2;
})(PaymentFeatures || {});
var DisplayMethodType = /* @__PURE__ */ ((DisplayMethodType2) => {
DisplayMethodType2["Iden3BasicDisplayMethodV1"] = "Iden3BasicDisplayMethodV1";
return DisplayMethodType2;
})(DisplayMethodType || {});
var DEFAULT_CACHE_MAX_SIZE = 1e4;
var SOLANA_CHAIN_REF = Object.freeze({
DEVNET: "EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
TESTNET: "4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",
MAINNET: "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
});
// src/verifiable/proof.ts
import { Hex as Hex3, Signature } from "@iden3/js-crypto";
import { Claim, DID as DID2 } from "@iden3/js-iden3-core";
var Iden3SparseMerkleTreeProof = class _Iden3SparseMerkleTreeProof {
type;
issuerData;
mtp;
coreClaim;
/**
* Creates an instance of Iden3SparseMerkleTreeProof.
* @param {object} obj
*/
constructor(obj) {
this.coreClaim = obj.coreClaim;
this.issuerData = obj.issuerData;
this.type = "Iden3SparseMerkleTreeProof" /* Iden3SparseMerkleTreeProof */;
this.mtp = obj.mtp;
}
/**
*
*
* @returns `json object in serialized presentation`
*/
toJSON() {
const issuerId = this.issuerData.id;
return {
issuerData: {
id: issuerId.string(),
state: {
...this.issuerData.state,
rootOfRoots: this.issuerData.state.rootOfRoots.hex(),
claimsTreeRoot: this.issuerData.state.claimsTreeRoot.hex(),
revocationTreeRoot: this.issuerData.state.revocationTreeRoot.hex(),
value: this.issuerData.state.value.hex()
}
},
type: this.type,
coreClaim: this.coreClaim.hex(),
mtp: this.mtp.toJSON()
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static fromJSON(obj) {
let mtp;
if (obj?.mtp?.notEmpties && obj?.mtp?.depth && obj?.mtp?.siblings) {
const ne = obj?.mtp?.notEmpties;
const notEmpties = ne instanceof Uint8Array ? ne : new Uint8Array(Object.values(ne));
const siblingsHashes = obj?.mtp?.siblings.map(
(h) => Hash2.fromString(JSON.stringify(h))
);
const allSiblings = Proof.buildAllSiblings(obj?.mtp?.depth, notEmpties, siblingsHashes);
let nodeAux = obj.mtp.nodeAux || obj.mtp.node_aux;
if (nodeAux) {
nodeAux = {
key: Hash2.fromString(JSON.stringify(nodeAux.key)),
value: Hash2.fromString(JSON.stringify(nodeAux.value))
};
}
mtp = new Proof({ existence: obj?.mtp.existence, nodeAux, siblings: allSiblings });
} else {
mtp = Proof.fromJSON(obj.mtp);
}
return new _Iden3SparseMerkleTreeProof({
coreClaim: new Claim().fromHex(obj.coreClaim),
mtp,
issuerData: {
id: DID2.parse(obj.issuerData.id),
state: {
...obj.issuerData.state,
rootOfRoots: Hash2.fromHex(obj.issuerData.state.rootOfRoots),
claimsTreeRoot: Hash2.fromHex(obj.issuerData.state.claimsTreeRoot),
revocationTreeRoot: Hash2.fromHex(obj.issuerData.state.revocationTreeRoot),
value: Hash2.fromHex(obj.issuerData.state.value)
}
}
});
}
};
var BJJSignatureProof2021 = class _BJJSignatureProof2021 {
type;
issuerData;
signature;
coreClaim;
constructor(obj) {
this.type = "BJJSignature2021" /* BJJSignature */;
this.issuerData = obj.issuerData;
this.coreClaim = obj.coreClaim;
this.signature = obj.signature;
}
/**
* toJSON is a method to serialize BJJSignatureProof2021 to json
*
* @returns `json object in serialized presentation`
*/
toJSON() {
return {
issuerData: {
id: this.issuerData.id.string(),
state: {
...this.issuerData.state,
rootOfRoots: this.issuerData.state.rootOfRoots.hex(),
claimsTreeRoot: this.issuerData.state.claimsTreeRoot.hex(),
revocationTreeRoot: this.issuerData.state.revocationTreeRoot.hex(),
value: this.issuerData.state.value.hex()
},
mtp: this.issuerData.mtp.toJSON(),
authCoreClaim: this.issuerData.authCoreClaim.hex(),
credentialStatus: this.issuerData.credentialStatus
},
type: this.type,
coreClaim: this.coreClaim.hex(),
signature: Hex3.encodeString(this.signature.compress())
};
}
/**
* fromJSON is a method to deserialize BJJSignatureProof2021 from json
* @param obj
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static fromJSON(obj) {
return new _BJJSignatureProof2021({
issuerData: {
id: DID2.parse(obj.issuerData.id),
mtp: Proof.fromJSON(obj.issuerData.mtp),
state: {
...obj.issuerData.state,
rootOfRoots: Hash2.fromHex(obj.issuerData.state.rootOfRoots),
claimsTreeRoot: Hash2.fromHex(obj.issuerData.state.claimsTreeRoot),
revocationTreeRoot: Hash2.fromHex(obj.issuerData.state.revocationTreeRoot),
value: Hash2.fromHex(obj.issuerData.state.value)
},
credentialStatus: obj.issuerData.credentialStatus,
authCoreClaim: new Claim().fromHex(obj.issuerData.authCoreClaim)
},
coreClaim: new Claim().fromHex(obj.coreClaim),
signature: Signature.newFromCompressed(
Uint8Array.from(Hex3.decodeString(obj.signature)).slice(0, 64)
)
});
}
};
// src/verifiable/credential.ts
import {
Claim as Claim2,
DID as DID4,
MerklizedRootPosition as MerklizedRootPositionCore,
IdPosition,
ClaimOptions,
getChainId
} from "@iden3/js-iden3-core";
import { Hash as Hash3, rootFromProof, verifyProof } from "@iden3/js-merkletree";
import { Merklizer as Merklizer2 } from "@iden3/js-jsonld-merklization";
import { PublicKey as PublicKey2, poseidon } from "@iden3/js-crypto";
// src/credentials/utils.ts
import { DID as DID3 } from "@iden3/js-iden3-core";
import { PublicKey } from "@iden3/js-crypto";
var getUserDIDFromCredential = (issuerDID, credential) => {
if (!credential.credentialSubject.id) {
return issuerDID;
}
if (typeof credential.credentialSubject.id !== "string") {
throw new Error("credential subject `id` is not a string");
}
return DID3.parse(credential.credentialSubject.id);
};
var getKMSIdByAuthCredential = (credential) => {
if (!credential.type.includes("AuthBJJCredential")) {
throw new Error("can't sign with not AuthBJJCredential credential");
}
const x = credential.credentialSubject["x"];
const y = credential.credentialSubject["y"];
const pb = new PublicKey([BigInt(x), BigInt(y)]);
const kp = keyPath("BJJ" /* BabyJubJub */, pb.hex());
return { type: "BJJ" /* BabyJubJub */, id: kp };
};
// src/verifiable/core-utils.ts
import { BytesHelper, SchemaHash } from "@iden3/js-iden3-core";
import { Path } from "@iden3/js-jsonld-merklization";
import jsonld from "jsonld";
import { keccak256 as keccak2562 } from "ethers";
var credentialSubjectKey = "credentialSubject";
var contextFullKey = "@context";
var serializationFullKey = "iden3_serialization";
var fieldPrefix = "iden3:v1:";
var credentialSubjectFullKey = "https://www.w3.org/2018/credentials#credentialSubject";
var verifiableCredentialFullKey = "https://www.w3.org/2018/credentials#VerifiableCredential";
var typeFullKey = "@type";
var getFieldSlotIndex = async (field, typeName, schemaBytes) => {
let ctxDoc = JSON.parse(byteDecoder.decode(schemaBytes));
ctxDoc = ctxDoc[contextFullKey];
if (ctxDoc === void 0) {
throw new Error("document has no @context");
}
const ldCtx = await jsonld.processContext(
await jsonld.processContext(null, null, {}),
ctxDoc,
{}
);
const serAttr = await getSerializationAttrFromParsedContext(
ldCtx,
typeName
);
if (!serAttr) {
throw new Error("serialization attribute is not set");
}
const sPaths = parseSerializationAttr(serAttr);
switch (field) {
case sPaths.indexAPath:
return 2;
case sPaths.indexBPath:
return 3;
case sPaths.valueAPath:
return 6;
case sPaths.valueBPath:
return 7;
default:
throw new Error(`field ${field} not specified in serialization info`);
}
};
var fillCoreClaimSlot = async (slotData, mz, path) => {
if (!path) {
return;
}
path = credentialSubjectKey + "." + path;
try {
const p = await mz.resolveDocPath(path, mz.options);
const entry = await mz.entry(p);
const intVal = await entry.getValueMtEntry();
const bytesVal = BytesHelper.intToBytes(intVal);
slotData.set(bytesVal, 0);
} catch (err) {
if (err.toString().includes("entry not found")) {
throw new Error(`field not found in credential ${path}`);
}
throw err;
}
};
var getSerializationAttrFromContext = async (context, opts, tp) => {
const ldCtx = await jsonld.processContext(
await jsonld.processContext(null, null, {}),
context,
opts
);
return getSerializationAttrFromParsedContext(ldCtx, tp);
};
var getSerializationAttrFromParsedContext = async (ldCtx, tp) => {
const termDef = ldCtx.mappings;
if (!termDef) {
throw new Error("terms definitions is not of correct type");
}
const term = termDef.get(tp) ?? [...termDef.values()].find((value) => value["@id"] === tp);
if (!term) {
return "";
}
const termCtx = term[contextFullKey];
if (!termCtx) {
throw new Error("type @context is not of correct type");
}
const serStr = termCtx[serializationFullKey] ?? "";
return serStr;
};
var parseSerializationAttr = (serAttr) => {
if (!serAttr.startsWith(fieldPrefix)) {
throw new Error("serialization attribute does not have correct prefix");
}
const parts = serAttr.slice(fieldPrefix.length).split("&");
if (parts.length > 4) {
throw new Error("serialization attribute has too many parts");
}
const paths = {};
for (const part of parts) {
const kv = part.split("=");
if (kv.length !== 2) {
throw new Error("serialization attribute part does not have correct format");
}
switch (kv[0]) {
case "slotIndexA":
paths.indexAPath = kv[1];
break;
case "slotIndexB":
paths.indexBPath = kv[1];
break;
case "slotValueA":
paths.valueAPath = kv[1];
break;
case "slotValueB":
paths.valueBPath = kv[1];
break;
default:
throw new Error("unknown serialization attribute slot");
}
}
return paths;
};
var findCredentialType = (mz) => {
const opts = mz.options;
try {
const path1 = new Path([credentialSubjectFullKey, typeFullKey], opts.hasher);
const e = mz.rawValue(path1);
return e;
} catch (err) {
const path2 = new Path([typeFullKey], opts.hasher);
const topLevelTypes = mz.rawValue(path2);
if (!Array.isArray(topLevelTypes)) {
throw new Error("top level @type expected to be an array");
}
if (topLevelTypes.length