bsv-bap 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1,14 @@
1
- {"version":3,"file":"index.modern.js","sources":["../src/utils.ts","../src/constants.ts","../src/api.ts","../src/id.ts","../src/index.ts"],"sourcesContent":["import randomBytes from \"randombytes\";\nimport type {PathPrefix} from \"./interface\";\n\nexport const Utils = {\n /**\n * Helper function for encoding strings to hex\n *\n * @param string\n * @returns {string}\n */\n hexEncode(string: string) {\n return `0x${Buffer.from(string).toString('hex')}`;\n },\n\n /**\n * Helper function for encoding strings to hex\n *\n * @param hexString string\n * @param encoding BufferEncoding\n * @returns {string}\n */\n hexDecode(hexString: string, encoding: BufferEncoding = 'utf8') {\n return Buffer.from(hexString.replace('0x', ''), 'hex').toString(encoding);\n },\n\n /**\n * Helper function to generate a random nonce\n *\n * @returns {string}\n */\n getRandomString(length = 32) {\n return randomBytes(length).toString('hex');\n },\n\n /**\n * Test whether the given string is hex\n *\n * @param value any\n * @returns {boolean}\n */\n isHex(value: string): boolean {\n if (typeof value !== 'string') {\n return false;\n }\n return /^[0-9a-fA-F]+$/.test(value);\n },\n\n /**\n * Get a signing path from a hex number\n *\n * @param hexString {string}\n * @param hardened {boolean} Whether to return a hardened path\n * @returns {string}\n */\n getSigningPathFromHex(hexString: string, hardened = true) {\n // \"m/0/0/1\"\n let signingPath = 'm';\n const signingHex = hexString.match(/.{1,8}/g);\n if (!signingHex) {\n throw new Error('Invalid hex string');\n }\n const maxNumber = 2147483648 - 1; // 0x80000000\n for (const hexNumber of signingHex) {\n let number = Number(`0x${hexNumber}`);\n if (number > maxNumber) number -= maxNumber;\n signingPath += `/${number}${(hardened ? \"'\" : '')}`;\n }\n\n return signingPath;\n },\n\n /**\n * Increment that second to last part from the given part, set the last part to 0\n *\n * @param path string\n * @returns {*}\n */\n getNextIdentityPath(path: string): PathPrefix {\n const pathValues = path.split('/');\n const secondToLastPart = pathValues[pathValues.length - 2];\n\n let hardened = false;\n if (secondToLastPart.match('\\'')) {\n hardened = true;\n }\n\n const nextPath = (Number(secondToLastPart.replace(/[^0-9]/g, '')) + 1).toString();\n pathValues[pathValues.length - 2] = nextPath + (hardened ? '\\'' : '');\n pathValues[pathValues.length - 1] = `0${hardened ? '\\'' : ''}`;\n\n return pathValues.join('/') as PathPrefix;\n },\n\n /**\n * Increment that last part of the given path\n *\n * @param path string\n * @returns {*}\n */\n getNextPath(path: string) {\n const pathValues = path.split('/');\n const lastPart = pathValues[pathValues.length - 1];\n let hardened = false;\n if (lastPart.match('\\'')) {\n hardened = true;\n }\n const nextPath = (Number(lastPart.replace(/[^0-9]/g, '')) + 1).toString();\n pathValues[pathValues.length - 1] = nextPath + (hardened ? '\\'' : '');\n return pathValues.join('/');\n },\n};\n","export const BAP_BITCOM_ADDRESS = '1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT';\nexport const BAP_BITCOM_ADDRESS_HEX = `0x${Buffer.from(BAP_BITCOM_ADDRESS).toString('hex')}`;\nexport const AIP_BITCOM_ADDRESS = '15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva';\nexport const AIP_BITCOM_ADDRESS_HEX = `0x${Buffer.from(AIP_BITCOM_ADDRESS).toString('hex')}`;\nexport const BAP_SERVER = 'https://api.sigmaidentity.com/v1';\nexport const MAX_INT = 2147483648 - 1; // 0x80000000\n\n// This is just a choice for this library and could be anything else if so needed/wanted\n// but it is advisable to use the same derivation between libraries for compatibility\nexport const SIGNING_PATH_PREFIX = 'm/424150\\'/0\\'/0\\''; // BAP in hex\nexport const ENCRYPTION_PATH = `m/424150'/${MAX_INT}'/${MAX_INT}'`;\n","\n/**\n\t * Helper function to get attestation from a BAP API server\n\t *\n\t * @param apiUrl\n\t * @param apiData\n\t * @returns {Promise<any>}\n\t */\nexport const getApiData = async <T>(apiUrl: string, apiData: unknown, server: string, token: string): Promise<T> => {\n const url = `${server}${apiUrl}`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-type\": \"application/json; charset=utf-8\",\n token,\n format: \"json\",\n },\n body: JSON.stringify(apiData),\n });\n\n return response.json();\n}\n\nexport type APIFetcher = <T>(url: string, data: unknown) => Promise<T>;\n\nexport const apiFetcher = (host: string, token: string): APIFetcher => async <T>(url: string, data: unknown): Promise<T> => {\n return getApiData<T>(url, data, host, token);\n}","import { BSM, Hash, type HD, ECIES, PublicKey, BigNumber, type Signature } from \"@bsv/sdk\";\nimport {\n\tMAX_INT,\n\tSIGNING_PATH_PREFIX,\n\tBAP_SERVER,\n\tBAP_BITCOM_ADDRESS,\n\tAIP_BITCOM_ADDRESS,\n\tENCRYPTION_PATH,\n} from \"./constants\";\nimport { type APIFetcher, apiFetcher } from \"./api\";\nimport { Utils } from \"./utils\";\nimport type {\n\tIdentity,\n\tIdentityAttribute,\n\tIdentityAttributes,\n} from \"./interface\";\nimport { Utils as BSVUtils } from \"@bsv/sdk\";\nimport type { GetAttestationResponse } from \"./apiTypes\";\nconst { toArray, toHex, toBase58, toUTF8, toBase64 } = BSVUtils;\nconst { electrumDecrypt, electrumEncrypt } = ECIES;\nconst { magicHash } = BSM;\n/**\n * BAP_ID class\n *\n * This class should be used in conjunction with the BAP class\n *\n * @type {BAP_ID}\n */\nclass BAP_ID {\n\t#HDPrivateKey: HD;\n\t#BAP_SERVER: string = BAP_SERVER;\n\t#BAP_TOKEN = \"\";\n\t#rootPath: string;\n\t#previousPath: string;\n\t#currentPath: string;\n\t#idSeed: string;\n\n\tidName: string;\n\tdescription: string;\n\n\trootAddress: string;\n\tidentityKey: string;\n\tidentityAttributes: IdentityAttributes;\n\n getApiData: APIFetcher\n \n\tconstructor(\n HDPrivateKey: HD,\n\t\tidentityAttributes: IdentityAttributes = {},\n\t\tidSeed = \"\",\n\t) {\n this.#idSeed = idSeed;\n\t\tif (idSeed) {\n\t\t\t// create a new HDPrivateKey based on the seed\n\t\t\tconst seedHex = toHex(Hash.sha256(idSeed, \"utf8\"));\n\t\t\tconst seedPath = Utils.getSigningPathFromHex(seedHex);\n\t\t\tthis.#HDPrivateKey = HDPrivateKey.derive(seedPath);\n\t\t} else {\n\t\t\tthis.#HDPrivateKey = HDPrivateKey;\n\t\t}\n\n\t\tthis.idName = \"ID 1\";\n\t\tthis.description = \"\";\n\n\t\tthis.#rootPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n\t\tthis.#previousPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n\t\tthis.#currentPath = `${SIGNING_PATH_PREFIX}/0/0/1`;\n\n\t\tconst rootChild = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tthis.rootAddress = rootChild.privKey.toPublicKey().toAddress();\n\t\tthis.identityKey = this.deriveIdentityKey(this.rootAddress);\n\n\t\t// unlink the object\n\t\tconst attributes = { ...identityAttributes };\n\t\tthis.identityAttributes = this.parseAttributes(attributes);\n\n this.getApiData = apiFetcher(this.#BAP_SERVER, this.#BAP_TOKEN);\n\t}\n\n\tset BAP_SERVER(bapServer) {\n\t\tthis.#BAP_SERVER = bapServer;\n\t}\n\n\tget BAP_SERVER(): string {\n\t\treturn this.#BAP_SERVER;\n\t}\n\n\tset BAP_TOKEN(token) {\n\t\tthis.#BAP_TOKEN = token;\n\t}\n\n\tget BAP_TOKEN(): string {\n\t\treturn this.#BAP_TOKEN;\n\t}\n\n\tderiveIdentityKey(address: string): string {\n\t\t// base58( ripemd160 ( sha256 ( rootAddress ) ) )\n\t\tconst rootAddressHash = toHex(Hash.sha256(address, \"utf8\"));\n\t\treturn toBase58(Hash.ripemd160(rootAddressHash, \"hex\"));\n\t}\n\n\t/**\n\t * Helper function to parse identity attributes\n\t *\n\t * @param identityAttributes\n\t * @returns {{}}\n\t */\n\tparseAttributes(\n\t\tidentityAttributes: IdentityAttributes | string,\n\t): IdentityAttributes {\n\t\tif (typeof identityAttributes === \"string\") {\n\t\t\treturn this.parseStringUrns(identityAttributes);\n\t\t}\n\n\t\tfor (const key in identityAttributes) {\n\t\t\tif (!identityAttributes[key].value || !identityAttributes[key].nonce) {\n\t\t\t\tthrow new Error(\"Invalid identity attribute\");\n\t\t\t}\n\t\t}\n\n\t\treturn identityAttributes || {};\n\t}\n\n\t/**\n\t * Parse a text of urn string into identity attributes\n\t *\n\t * urn:bap:id:name:John Doe:e2c6fb4063cc04af58935737eaffc938011dff546d47b7fbb18ed346f8c4d4fa\n\t * urn:bap:id:birthday:1990-05-22:e61f23cbbb2284842d77965e2b0e32f0ca890b1894ca4ce652831347ee3596d9\n\t * urn:bap:id:over18:1:480ca17ccaacd671b28dc811332525f2f2cd594d8e8e7825de515ce5d52d30e8\n\t *\n\t * @param urnIdentityAttributes\n\t */\n\tparseStringUrns(urnIdentityAttributes: string): IdentityAttributes {\n\t\tconst identityAttributes: IdentityAttributes = {};\n\t\t// avoid forEach\n\n\t\tconst attributesRaw = urnIdentityAttributes\n\t\t\t.replace(/^\\s+/g, \"\")\n\t\t\t.replace(/\\r/gm, \"\")\n\t\t\t.split(\"\\n\");\n\n\t\tfor (const line of attributesRaw) {\n\t\t\t// remove any whitespace from the string (trim)\n\t\t\tconst attribute = line.replace(/^\\s+/g, \"\").replace(/\\s+$/g, \"\");\n\t\t\tconst urn = attribute.split(\":\");\n\t\t\tif (\n\t\t\t\turn[0] === \"urn\" &&\n\t\t\t\turn[1] === \"bap\" &&\n\t\t\t\turn[2] === \"id\" &&\n\t\t\t\turn[3] &&\n\t\t\t\turn[4] &&\n\t\t\t\turn[5]\n\t\t\t) {\n\t\t\t\tidentityAttributes[urn[3]] = {\n\t\t\t\t\tvalue: urn[4],\n\t\t\t\t\tnonce: urn[5],\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn identityAttributes;\n\t}\n\n\t/**\n\t * Returns the identity key\n\t *\n\t * @returns {*|string}\n\t */\n\tgetIdentityKey(): string {\n\t\treturn this.identityKey;\n\t}\n\n\t/**\n\t * Returns all the attributes in the identity\n\t *\n\t * @returns {*}\n\t */\n\tgetAttributes(): IdentityAttributes {\n\t\treturn this.identityAttributes;\n\t}\n\n\t/**\n\t * Get the value of the given attribute\n\t *\n\t * @param attributeName\n\t * @returns {{}|null}\n\t */\n\tgetAttribute(attributeName: string): IdentityAttribute | null {\n\t\tif (this.identityAttributes[attributeName]) {\n\t\t\treturn this.identityAttributes[attributeName];\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Set the value of the given attribute\n\t *\n\t * If an empty value ('' || null || false) is given, the attribute is removed from the ID\n\t *\n\t * @param attributeName string\n\t * @param attributeValue any\n\t * @returns {{}|null}\n\t */\n\tsetAttribute(attributeName: string, attributeValue: string | Record<string,string>): void {\n\t\tif (attributeValue) {\n\t\t\tif (this.identityAttributes[attributeName]) {\n\t\t\t\tthis.identityAttributes[attributeName].value = attributeValue;\n\t\t\t} else {\n\t\t\t\tthis.addAttribute(attributeName, attributeValue);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Unset the given attribute from the ID\n\t *\n\t * @param attributeName\n\t * @returns {{}|null}\n\t */\n\tunsetAttribute(attributeName: string): void {\n\t\tdelete this.identityAttributes[attributeName];\n\t}\n\n\t/**\n\t * Get all attribute urn's for this id\n\t *\n\t * @returns {string}\n\t */\n\tgetAttributeUrns(): string {\n\t\tlet urns = \"\";\n\t\tfor (const key in this.identityAttributes) {\n\t\t\tconst urn = this.getAttributeUrn(key);\n\t\t\tif (urn) {\n\t\t\t\turns += `${urn}\\n`;\n\t\t\t}\n\t\t}\n\n\t\treturn urns;\n\t}\n\n\t/**\n\t * Create an return the attribute urn for the given attribute\n\t *\n\t * @param attributeName\n\t * @returns {string|null}\n\t */\n\tgetAttributeUrn(attributeName: string): string | null {\n\t\tconst attribute = this.identityAttributes[attributeName];\n\t\tif (attribute) {\n\t\t\treturn `urn:bap:id:${attributeName}:${attribute.value}:${attribute.nonce}`;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Add an attribute to this identity\n\t *\n\t * @param attributeName\n\t * @param value\n\t * @param nonce\n\t */\n\taddAttribute(attributeName: string, value: any, nonce = \"\"): void {\n\t\tlet nonceToUse = nonce;\n\t\tif (!nonce) {\n\t\t\tnonceToUse = Utils.getRandomString();\n\t\t}\n\n\t\tthis.identityAttributes[attributeName] = {\n\t\t\tvalue,\n\t\t\tnonce: nonceToUse,\n\t\t};\n\t}\n\n\t/**\n\t * This should be called with the last part of the signing path (/.../.../...)\n\t * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file\n\t *\n\t * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9}\n\t */\n\tset rootPath(path: string) {\n\t\tif (this.#HDPrivateKey) {\n\t\t\tlet pathToUse = path;\n\t\t\tif (path.split(\"/\").length < 5) {\n\t\t\t\tpathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n\t\t\t}\n\n\t\t\tif (!this.validatePath(pathToUse)) {\n\t\t\t\tthrow new Error(`invalid signing path given ${pathToUse}`);\n\t\t\t}\n\n\t\t\tthis.#rootPath = pathToUse;\n\n\t\t\tconst derivedChild = this.#HDPrivateKey.derive(pathToUse);\n\t\t\tthis.rootAddress = derivedChild.pubKey.toAddress();\n\t\t\t// Identity keys should be derivatives of the root address - this allows checking\n\t\t\t// of the creation transaction\n\t\t\tthis.identityKey = this.deriveIdentityKey(this.rootAddress);\n\n\t\t\t// we also set this previousPath / currentPath to the root as we seem to be (re)setting this ID\n\t\t\tthis.#previousPath = pathToUse;\n\t\t\tthis.#currentPath = pathToUse;\n\t\t}\n\t}\n\n\tget rootPath(): string {\n\t\treturn this.#rootPath;\n\t}\n\n\tgetRootPath(): string {\n\t\treturn this.#rootPath;\n\t}\n\n\t/**\n\t * This should be called with the last part of the signing path (/.../.../...)\n\t * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file\n\t *\n\t * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9}\n\t */\n\tset currentPath(path) {\n\t\tlet pathToUse = path;\n\t\tif (path.split(\"/\").length < 5) {\n\t\t\tpathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n\t\t}\n\n\t\tif (!this.validatePath(pathToUse)) {\n\t\t\tthrow new Error(\"invalid signing path given\");\n\t\t}\n\n\t\tthis.#previousPath = this.#currentPath;\n\t\tthis.#currentPath = pathToUse;\n\t}\n\n\tget currentPath(): string {\n\t\treturn this.#currentPath;\n\t}\n\n\tget previousPath(): string {\n\t\treturn this.#previousPath;\n\t}\n\n\t/**\n\t * This can be used to break the deterministic way child keys are created to make it harder for\n\t * an attacker to steal the identites when the root key is compromised. This does however require\n\t * the seeds to be stored at all times. If the seed is lost, the identity will not be recoverable.\n\t */\n\tget idSeed(): string {\n\t\treturn this.#idSeed;\n\t}\n\n\t/**\n\t * Increment current path to a new path\n\t *\n\t * @returns {*}\n\t */\n\tincrementPath(): void {\n\t\tthis.currentPath = Utils.getNextPath(this.currentPath);\n\t}\n\n\t/**\n\t * Check whether the given path is a valid path for use with this class\n\t * The signing paths used here always have a length of 3\n\t *\n\t * @param path The last part of the signing path (example \"/0/0/1\")\n\t * @returns {boolean}\n\t */\n\tvalidatePath(path: string) {\n\t\t/* eslint-disable max-len */\n\t\tif (\n\t\t\tpath.match(\n\t\t\t\t/\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?/,\n\t\t\t)\n\t\t) {\n\t\t\tconst pathValues = path.split(\"/\");\n\t\t\tif (\n\t\t\t\tpathValues.length === 7 &&\n\t\t\t\tNumber(pathValues[1].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[2].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[3].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[4].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[5].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[6].replace(\"'\", \"\")) <= MAX_INT\n\t\t\t) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Get the OP_RETURN for the initial ID transaction (signed with root address)\n\t *\n\t * @returns {[]}\n\t */\n\tgetInitialIdTransaction() {\n\t\treturn this.getIdTransaction(this.#rootPath);\n\t}\n\n\t/**\n\t * Get the OP_RETURN for the ID transaction of the current address / path\n\t *\n\t * @returns {[]}\n\t */\n\tgetIdTransaction(previousPath = \"\") {\n\t\tif (this.#currentPath === this.#rootPath) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Current path equals rootPath. ID was probably not initialized properly\",\n\t\t\t);\n\t\t}\n\n\t\tconst opReturn = [\n\t\t\tBuffer.from(BAP_BITCOM_ADDRESS).toString(\"hex\"),\n\t\t\tBuffer.from(\"ID\").toString(\"hex\"),\n\t\t\tBuffer.from(this.identityKey).toString(\"hex\"),\n\t\t\tBuffer.from(this.getCurrentAddress()).toString(\"hex\"),\n\t\t];\n\n\t\treturn this.signOpReturnWithAIP(\n\t\t\topReturn,\n\t\t\tpreviousPath || this.#previousPath,\n\t\t);\n\t}\n\n\t/**\n\t * Get address for given path\n\t *\n\t * @param path\n\t * @returns {*}\n\t */\n\tgetAddress(path: string): string {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(path);\n\t\treturn derivedChild.privKey.toPublicKey().toAddress();\n\t}\n\n\t/**\n\t * Get current signing address\n\t *\n\t * @returns {*}\n\t */\n\tgetCurrentAddress(): string {\n\t\treturn this.getAddress(this.#currentPath);\n\t}\n\n\t/**\n\t * Get the public key for encrypting data for this identity\n\t */\n\tgetEncryptionPublicKey(): string {\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst encryptionKey = HDPrivateKey.derive(ENCRYPTION_PATH).privKey;\n\t\t// @ts-ignore\n\t\treturn encryptionKey.toPublicKey().toString();\n\t}\n\n\t/**\n\t * Get the public key for encrypting data for this identity, using a seed for the encryption\n\t */\n\tgetEncryptionPublicKeyWithSeed(seed: string): string {\n\t\tconst encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n\t\t// @ts-ignore\n\t\treturn encryptionKey.toPublicKey().toString(\"hex\");\n\t}\n\n\t/**\n\t * Encrypt the given string data with the identity encryption key\n\t * @param stringData\n\t * @param counterPartyPublicKey Optional public key of the counterparty\n\t * @return string Base64\n\t */\n\tencrypt(stringData: string, counterPartyPublicKey?: string): string {\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst encryptionKey = HDPrivateKey.derive(ENCRYPTION_PATH).privKey;\n\t\tconst publicKey = encryptionKey.toPublicKey();\n\t\tconst pubKey = counterPartyPublicKey\n\t\t\t? PublicKey.fromString(counterPartyPublicKey)\n\t\t\t: publicKey;\n // @ts-ignore - remove this when SDK is updated\n\t\treturn toBase64(electrumEncrypt(toArray(stringData), pubKey, null));\n\t}\n\n\t/**\n\t * Decrypt the given ciphertext with the identity encryption key\n\t * @param ciphertext\n\t */\n\tdecrypt(ciphertext: string, counterPartyPublicKey?: string): string {\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst encryptionKey = HDPrivateKey.derive(ENCRYPTION_PATH).privKey;\n let pubKey = undefined\n if (counterPartyPublicKey) {\n pubKey = PublicKey.fromString(counterPartyPublicKey);\n }\n\t\treturn toUTF8(electrumDecrypt(toArray(ciphertext, \"base64\"), encryptionKey, pubKey));\n\t}\n\n\t/**\n\t * Encrypt the given string data with the identity encryption key\n\t * @param stringData\n\t * @param seed String seed\n\t * @param counterPartyPublicKey Optional public key of the counterparty\n\t * @return string Base64\n\t */\n\tencryptWithSeed(\n\t\tstringData: string,\n\t\tseed: string,\n\t\tcounterPartyPublicKey?: string,\n\t): string {\n\t\tconst encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n\t\tconst publicKey = encryptionKey.toPublicKey();\n\t\tconst pubKey = counterPartyPublicKey\n\t\t\t? PublicKey.fromString(counterPartyPublicKey)\n\t\t\t: publicKey;\n\t\treturn toBase64(electrumEncrypt(toArray(stringData), pubKey, encryptionKey));\n\t}\n\n\t/**\n\t * Decrypt the given ciphertext with the identity encryption key\n\t * @param ciphertext\n\t * @param seed String seed\n\t// * @param counterPartyPublicKey Public key of the counterparty\n\t */\n\tdecryptWithSeed(ciphertext: string, seed: string, counterPartyPublicKey?: string): string {\n\t\tconst encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n let pubKey = undefined\n if (counterPartyPublicKey) {\n pubKey = PublicKey.fromString(counterPartyPublicKey);\n }\n\t\treturn toUTF8(electrumDecrypt(toArray(ciphertext, \"base64\"), encryptionKey, pubKey));\n\t}\n\n\tprivate getEncryptionPrivateKeyWithSeed(seed: string) {\n\t\tconst pathHex = toHex(Hash.sha256(seed, \"utf8\"));\n\t\tconst path = Utils.getSigningPathFromHex(pathHex);\n\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\treturn HDPrivateKey.derive(path).privKey;\n\t}\n\n\t/**\n\t * Get an attestation string for the given urn for this identity\n\t *\n\t * @param urn\n\t * @returns {string}\n\t */\n\tgetAttestation(urn: string) {\n\t\tconst urnHash = Hash.sha256(urn, \"utf8\");\n\t\treturn `bap:attest:${toHex(urnHash)}:${this.getIdentityKey()}`;\n\t}\n\n\t/**\n\t * Generate and return the attestation hash for the given attribute of this identity\n\t *\n\t * @param attribute Attribute name (name, email etc.)\n\t * @returns {string}\n\t */\n\tgetAttestationHash(attribute: string) {\n\t\tconst urn = this.getAttributeUrn(attribute);\n\t\tif (!urn) return null;\n\n\t\tconst attestation = this.getAttestation(urn);\n\t\tconst attestationHash = Hash.sha256(attestation, \"utf8\");\n\n\t\treturn toHex(attestationHash);\n\t}\n\n\t/**\n\t * Sign a message with the current signing address of this identity\n\t *\n\t * @param message\n\t * @param signingPath\n\t * @returns {{address: string, signature: string}}\n\t */\n\tsignMessage(message: string | Buffer, signingPath = \"\"): { address: string, signature: string } {\n\t\tlet msg: Buffer;\n\t\tif (!(message instanceof Buffer)) {\n\t\t\tmsg = Buffer.from(message);\n\t\t} else {\n\t\t\tmsg = message;\n\t\t}\n\n\t\tconst pathToUse = signingPath || this.#currentPath;\n\t\tconst childPk = this.#HDPrivateKey.derive(pathToUse).privKey;\n\t\tconst address = childPk.toAddress();\n\n // Needed to calculate the recovery factor\n const dummySig = BSM.sign(toArray(message), childPk, 'raw') as Signature;\n\t\tconst h = new BigNumber(magicHash(toArray(message, \"utf8\")));\n\t\tconst r = dummySig.CalculateRecoveryFactor(\n\t\t\tchildPk.toPublicKey(),\n\t\t\th,\n\t\t);\n\t\tconst signature = (BSM.sign(toArray(msg), childPk, 'raw') as Signature).toCompact(\n\t\t\tr,\n\t\t\ttrue,\n\t\t\t\"base64\",\n\t\t) as string;\n\n\t\treturn { address, signature };\n\t}\n\n\t/**\n\t * Sign a message using a key based on the given string seed\n\t *\n\t * This works by creating a private key from the root key of this identity. It will always\n\t * work with the rootPath / rootKey, to be deterministic. It will not change even if the keys\n\t * are rotated for this ID.\n\t *\n\t * This is used in for instance deterministic login systems, that do not support BAP.\n\t *\n\t * @param message\n\t * @param seed {string} String seed that will be used to generate a path\n\t */\n\tsignMessageWithSeed(\n\t\tmessage: string,\n\t\tseed: string,\n\t): { address: string; signature: string } {\n\t\tconst pathHex = toHex(Hash.sha256(seed, \"utf8\"));\n\t\tconst path = Utils.getSigningPathFromHex(pathHex);\n\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst derivedChild = HDPrivateKey.derive(path);\n\t\tconst address = derivedChild.privKey.toPublicKey().toAddress();\n\n\t\tconst dummySig = BSM.sign(toArray(message), derivedChild.privKey, 'raw') as Signature;\n\n\t\tconst h = new BigNumber(magicHash(toArray(message, \"utf8\")));\n\t\tconst r = dummySig.CalculateRecoveryFactor(\n\t\t\tderivedChild.privKey.toPublicKey(),\n\t\t\th,\n\t\t);\n\n\t\tconst signature = (BSM.sign(\n\t\t\ttoArray(Buffer.from(message)),\n\t\t\tderivedChild.privKey,\n 'raw',\n\t\t) as Signature).toCompact(r, true, \"base64\") as string;\n\n\t\treturn { address, signature };\n\t}\n\n\t/**\n\t * Sign an op_return hex array with AIP\n\t * @param opReturn {array}\n\t * @param signingPath {string}\n\t * @param outputType {string}\n\t * @return {[]}\n\t */\n\tsignOpReturnWithAIP(\n\t\topReturn: string[],\n\t\tsigningPath = \"\",\n\t\toutputType: BufferEncoding = \"hex\",\n\t): string[] {\n\t\tconst aipMessageBuffer = this.getAIPMessageBuffer(opReturn);\n\t\tconst { address, signature } = this.signMessage(\n\t\t\taipMessageBuffer,\n\t\t\tsigningPath,\n\t\t);\n\n\t\treturn opReturn.concat([\n\t\t\tBuffer.from(\"|\").toString(outputType),\n\t\t\tBuffer.from(AIP_BITCOM_ADDRESS).toString(outputType),\n\t\t\tBuffer.from(\"BITCOIN_ECDSA\").toString(outputType),\n\t\t\tBuffer.from(address).toString(outputType),\n\t\t\tBuffer.from(signature, \"base64\").toString(outputType),\n\t\t]);\n\t}\n\n\t/**\n\t * Construct an AIP buffer from the op return data\n\t * @param opReturn\n\t * @returns {Buffer}\n\t */\n\tgetAIPMessageBuffer(opReturn: string[]): Buffer {\n\t\tconst buffers = [];\n\t\tif (opReturn[0].replace(\"0x\", \"\") !== \"6a\") {\n\t\t\t// include OP_RETURN in constructing the signature buffer\n\t\t\tbuffers.push(Buffer.from(\"6a\", \"hex\"));\n\t\t}\n\t\tfor (const op of opReturn) {\n\t\t\tbuffers.push(Buffer.from(op.replace(\"0x\", \"\"), \"hex\"));\n\t\t}\n\t\t// add a trailing \"|\" - this is the AIP way\n\t\tbuffers.push(Buffer.from(\"|\"));\n\n\t\treturn Buffer.concat([...buffers] as unknown as Uint8Array[]);\n\t}\n\n\t/**\n\t * Get all signing keys for this identity\n\t */\n\tasync getIdSigningKeys(): Promise<any> {\n\t\tconst signingKeys = await this.getApiData(\"/signing-keys\", {\n\t\t\tidKey: this.identityKey,\n\t\t});\n\t\tconsole.log(\"getIdSigningKeys\", signingKeys);\n\n\t\treturn signingKeys;\n\t}\n\n\t/**\n\t * Get all attestations for the given attribute\n\t *\n\t * @param attribute\n\t */\n\tasync getAttributeAttestations(attribute: string): Promise<GetAttestationResponse> {\n\t\t// This function needs to make a call to a BAP server to get all the attestations for this\n\t\t// identity for the given attribute\n\t\tconst attestationHash = this.getAttestationHash(attribute);\n\n\t\t// get all BAP ATTEST records for the given attestationHash\n\t\tconst attestations = await this.getApiData<GetAttestationResponse>(\"/attestation/get\", {\n\t\t\thash: attestationHash,\n\t\t});\n\t\tconsole.log(\"getAttestations\", attribute, attestationHash, attestations);\n\n\t\treturn attestations;\n\t}\n\n\t// /**\n\t// * Helper function to get attestation from a BAP API server\n\t// *\n\t// * @param apiUrl\n\t// * @param apiData\n\t// * @returns {Promise<any>}\n\t// */\n\t// async getApiData(apiUrl: string, apiData: any): Promise<any> {\n\t// \tconst url = `${this.#BAP_SERVER}${apiUrl}`;\n\t// \tconst response = await fetch(url, {\n\t// \t\tmethod: \"post\",\n\t// \t\theaders: {\n\t// \t\t\t\"Content-type\": \"application/json; charset=utf-8\",\n\t// \t\t\ttoken: this.#BAP_TOKEN,\n\t// \t\t\tformat: \"json\",\n\t// \t\t},\n\t// \t\tbody: JSON.stringify(apiData),\n\t// \t});\n\t// \treturn response.json();\n\t// }\n\n\t/**\n\t * Import an identity from a JSON object\n\t *\n\t * @param identity{{}}\n\t */\n\timport(identity: Identity): void {\n\t\tthis.idName = identity.name;\n\t\tthis.description = identity.description || \"\";\n\t\tthis.identityKey = identity.identityKey;\n\t\tthis.#rootPath = identity.rootPath;\n\t\tthis.rootAddress = identity.rootAddress;\n\t\tthis.#previousPath = identity.previousPath;\n\t\tthis.#currentPath = identity.currentPath;\n\t\tthis.#idSeed = identity.idSeed || \"\";\n\t\tthis.identityAttributes = this.parseAttributes(identity.identityAttributes);\n\t}\n\n\t/**\n\t * Export this identity to a JSON object\n\t * @returns {{}}\n\t */\n\texport(): Identity {\n\t\treturn {\n\t\t\tname: this.idName,\n\t\t\tdescription: this.description,\n\t\t\tidentityKey: this.identityKey,\n\t\t\trootPath: this.#rootPath,\n\t\t\trootAddress: this.rootAddress,\n\t\t\tpreviousPath: this.#previousPath,\n\t\t\tcurrentPath: this.#currentPath,\n\t\t\tidSeed: this.#idSeed,\n\t\t\tidentityAttributes: this.getAttributes(),\n\t\t\tlastIdPath: \"\",\n\t\t};\n\t}\n}\n\nexport { BAP_ID };\n","import { BigNumber, BSM, HD, type PublicKey, Signature, ECIES } from \"@bsv/sdk\";\n\nimport { Utils } from \"./utils\";\nimport { BAP_ID } from \"./id\";\nimport {\n\tENCRYPTION_PATH,\n\tBAP_SERVER,\n\tBAP_BITCOM_ADDRESS,\n\tBAP_BITCOM_ADDRESS_HEX,\n\tAIP_BITCOM_ADDRESS,\n} from \"./constants\";\nimport { type APIFetcher, apiFetcher } from \"./api\";\nimport type { Attestation, Identity, IdentityAttributes, PathPrefix } from \"./interface\";\nimport { Utils as BSVUtils } from \"@bsv/sdk\";\nimport type { AttestationValidResponse, GetAttestationResponse, GetIdentityByAddressResponse } from \"./apiTypes\";\nconst { toArray, toUTF8, toBase64 } = BSVUtils;\nconst { electrumEncrypt, electrumDecrypt } = ECIES;\n\ntype Identities = { lastIdPath: string; ids: Identity[] };\n\n\n/**\n * BAP class\n *\n * Creates an instance of the BAP class and uses the given HDPrivateKey for all BAP operations.\n *\n * @param HDPrivateKey\n */\nexport class BAP {\n\t#HDPrivateKey;\n\t#ids: { [key: string]: BAP_ID } = {};\n\t#BAP_SERVER = BAP_SERVER;\n\t#BAP_TOKEN = \"\";\n\t#lastIdPath = \"\";\n getApiData: APIFetcher;\n\n\n \n\tconstructor(HDPrivateKey: string, token = \"\", server = \"\") {\n\t\tif (!HDPrivateKey) {\n\t\t\tthrow new Error(\"No HDPrivateKey given\");\n\t\t}\n\t\tthis.#HDPrivateKey = HD.fromString(HDPrivateKey);\n\n\t\tif (token) {\n\t\t\tthis.#BAP_TOKEN = token;\n\t\t}\n\n if (server) {\n this.#BAP_SERVER = server;\n }\n\n this.getApiData = apiFetcher(this.#BAP_SERVER, this.#BAP_TOKEN);\n\t}\n\n\tget lastIdPath(): string {\n\t\treturn this.#lastIdPath;\n\t}\n\n\t/**\n\t * Get the public key of the given childPath, or of the current HDPrivateKey of childPath is empty\n\t *\n\t * @param childPath Full derivation path for this child\n\t * @returns {*}\n\t */\n\tgetPublicKey(childPath = \"\"): string {\n\t\tif (childPath) {\n\t\t\treturn this.#HDPrivateKey.derive(childPath).pubKey.toString();\n\t\t}\n\n\t\treturn this.#HDPrivateKey.pubKey.toString();\n\t}\n\n\t/**\n\t * Get the public key of the given childPath, or of the current HDPrivateKey of childPath is empty\n\t *\n\t * @param childPath Full derivation path for this child\n\t * @returns {*}\n\t */\n\tgetHdPublicKey(childPath = \"\"): string {\n\t\tif (childPath) {\n\t\t\treturn this.#HDPrivateKey.derive(childPath).toPublic().toString();\n\t\t}\n\n\t\treturn this.#HDPrivateKey.toPublic().toString();\n\t}\n\n\tset BAP_SERVER(bapServer) {\n\t\tthis.#BAP_SERVER = bapServer;\n\t\tfor (const key in this.#ids) {\n\t\t\tthis.#ids[key].BAP_SERVER = bapServer;\n\t\t}\n\t}\n\n\tget BAP_SERVER(): string {\n\t\treturn this.#BAP_SERVER;\n\t}\n\n\tset BAP_TOKEN(token) {\n\t\tthis.#BAP_TOKEN = token;\n\t\tfor (const key in this.#ids) {\n\t\t\t// @ts-ignore - does not recognize private fields that can be set\n\t\t\tthis.#ids[key].BAP_TOKEN = token;\n\t\t}\n\t}\n\n\tget BAP_TOKEN(): string {\n\t\treturn this.#BAP_TOKEN;\n\t}\n\n\t/**\n\t * This function verifies that the given bapId matches the given root address\n\t * This is used as a data integrity check\n\t *\n\t * @param bapId BAP_ID instance\n\t */\n\tcheckIdBelongs(bapId: BAP_ID): boolean {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(bapId.rootPath);\n\t\tconst checkRootAddress = derivedChild.pubKey.toAddress();\n\t\tif (checkRootAddress !== bapId.rootAddress) {\n\t\t\tthrow new Error(\"ID does not belong to this private key\");\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns a list of all the identity keys that are stored in this instance\n\t *\n\t * @returns {string[]}\n\t */\n\tlistIds(): string[] {\n\t\treturn Object.keys(this.#ids);\n\t}\n\n\t/**\n\t * Create a new Id and link it to this BAP instance\n\t *\n\t * This function uses the length of the #ids of this class to determine the next valid path.\n\t * If not all ids related to this HDPrivateKey have been loaded, determine the path externally\n\t * and pass it to newId when creating a new ID.\n\t *\n\t * @param path\n\t * @param identityAttributes\n\t * @param idSeed\n\t * @returns {*}\n\t */\n\tnewId(path?: string, identityAttributes: IdentityAttributes = {}, idSeed = \"\"): BAP_ID {\n let pathToUse: string;\n\t\tif (!path) {\n\t\t\t// get next usable path for this key\n\t\t\tpathToUse = this.getNextValidPath();\n\t\t} else {\n pathToUse = path;\n }\n\n\t\tconst newIdentity = new BAP_ID(\n\t\t\tthis.#HDPrivateKey,\n\t\t\tidentityAttributes,\n\t\t\tidSeed,\n\t\t);\n\t\tnewIdentity.BAP_SERVER = this.#BAP_SERVER;\n\t\tnewIdentity.BAP_TOKEN = this.#BAP_TOKEN;\n\n\t\tnewIdentity.rootPath = pathToUse;\n\t\tnewIdentity.currentPath = Utils.getNextPath(pathToUse);\n\n\t\tconst idKey = newIdentity.getIdentityKey();\n\t\tthis.#ids[idKey] = newIdentity;\n\t\tthis.#lastIdPath = pathToUse;\n\n\t\treturn this.#ids[idKey];\n\t}\n\n\t/**\n\t * Remove identity\n\t *\n\t * @param idKey\n\t * @returns {*}\n\t */\n\tremoveId(idKey: string): void {\n\t\tdelete this.#ids[idKey];\n\t}\n\n\t/**\n\t * Get the next valid path for the used HDPrivateKey and loaded #ids\n\t *\n\t * @returns {string}\n\t */\n\tgetNextValidPath(): PathPrefix {\n\t\t// prefer hardened paths\n\t\tif (this.#lastIdPath) {\n\t\t\treturn Utils.getNextIdentityPath(this.#lastIdPath);\n\t\t}\n\n\t\treturn `/0'/${Object.keys(this.#ids).length}'/0'`;\n\t}\n\n\t/**\n\t * Get a certain Id\n\t *\n\t * @param identityKey\n\t * @returns {null}\n\t */\n\tgetId(identityKey: string): BAP_ID | null {\n\t\treturn this.#ids[identityKey] || null;\n\t}\n\n\t/**\n\t * This function is used when manipulating ID's, adding or removing attributes etc\n\t * First create an id through this class and then use getId to get it. Then you can add/edit or\n\t * increment the signing path and then re-set it with this function.\n\t *\n\t * Note: when you getId() from this class, you will be working on the same object as this class\n\t * has and any changes made will be propagated to the id in this class. When you call exportIds\n\t * your new changes will also be included, without having to setId().\n\t *\n\t * @param bapId\n\t */\n\tsetId(bapId: BAP_ID): void {\n\t\tthis.checkIdBelongs(bapId);\n\t\tthis.#ids[bapId.getIdentityKey()] = bapId;\n\t}\n\n\t/**\n\t * This function is used to import IDs and attributes from some external storage\n\t *\n\t * The ID information should NOT be stored together with the HD private key !\n\t *\n\t * @param idData Array of ids that have been exported\n\t * @param encrypted Whether the data should be treated as being encrypted (default true)\n\t */\n\timportIds(idData: Identities | string, encrypted = true): void {\n\t\tif (encrypted && typeof idData === \"string\") {\n\t\t\tthis.importEncryptedIds(idData);\n\t\t\treturn;\n\t\t}\n const identity = idData as Identities\n if (!identity.lastIdPath) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n\n if (!identity.ids) {\n throw new Error(`ID data is not in the correct format: ${idData}`);\n }\n \n\t\tlet lastIdPath = (idData as Identities).lastIdPath;\n\t\tfor (const id of identity.ids) {\n\t\t\tif (!id.identityKey || !id.identityAttributes || !id.rootAddress) {\n\t\t\t\tthrow new Error(\"ID cannot be imported as it is not complete\");\n\t\t\t}\n\t\t\tconst importId = new BAP_ID(this.#HDPrivateKey, {}, id.idSeed);\n\t\t\timportId.BAP_SERVER = this.#BAP_SERVER;\n\t\t\timportId.BAP_TOKEN = this.#BAP_TOKEN;\n\t\t\timportId.import(id);\n if (lastIdPath === \"\") {\n lastIdPath = importId.currentPath;\n }\n\n\t\t\tthis.checkIdBelongs(importId);\n\t\t\tthis.#ids[importId.getIdentityKey()] = importId;\n\t\t}\n\n\t\tthis.#lastIdPath = lastIdPath;\n\t}\n \n\timportEncryptedIds(idData: string): void {\n\t\t// decrypt the ids array using ECIES\n const decrypted = this.decrypt(idData);\n\t\tconst ids = JSON.parse(decrypted) as Identities;\n \n const isOldFormat = Array.isArray(ids)\n if (isOldFormat) {\n console.log(\"Importing old format:\\n\", ids)\n this.importOldIds(ids)\n return\n }\n if (typeof ids !== \"object\") {\n throw new Error(\"decrypted, but found unrecognized identities format\")\n }\n\t\tthis.importIds(ids, false);\n\t}\n\n\timportOldIds(idData: Identity[]): void {\n\t\tfor (const id of idData) {\n\t\t\tconst importId = new BAP_ID(this.#HDPrivateKey, {}, id.idSeed);\n\t\t\timportId.BAP_SERVER = this.#BAP_SERVER;\n\t\t\timportId.BAP_TOKEN = this.#BAP_TOKEN;\n\t\t\timportId.import(id);\n\n\t\t\tthis.checkIdBelongs(importId);\n\n\t\t\tthis.#ids[importId.getIdentityKey()] = importId;\n\n\t\t\t// overwrite with the last value on this array\n\t\t\tthis.#lastIdPath = importId.currentPath;\n\t\t}\n\t}\n\n\n\t/**\n\t * Export all the IDs of this instance for external storage\n\t *\n\t * By default this function will encrypt the data, using a derivative child of the main HD key\n\t *\n\t * @param encrypted Whether the data should be encrypted (default true)\n\t * @returns {[]|*}\n\t */\n // Overload signatures\n exportIds(encrypted?: true): string;\n exportIds(encrypted: false): Identities;\n\texportIds(encrypted = true): Identities | string {\n\t\tconst idData: Identities = {\n\t\t\tlastIdPath: this.#lastIdPath,\n\t\t\tids: [] as Identity[],\n\t\t};\n\n\t\tfor (const key in this.#ids) {\n\t\t\tidData.ids.push(this.#ids[key].export());\n\t\t}\n\n\t\tif (encrypted) {\n\t\t\treturn this.encrypt(JSON.stringify(idData));\n\t\t}\n\n\t\treturn idData \n\t}\n\n\t/**\n\t * Encrypt a string of data\n\t *\n\t * @param string\n\t * @returns {string}\n\t */\n\tencrypt(string: string): string {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n\t\treturn toBase64(\n // @ts-ignore - you can remove the null when this is merged https://github.com/bitcoin-sv/ts-sdk/pull/123\n\t\t\telectrumEncrypt(toArray(string), derivedChild.pubKey, null),\n\t\t);\n\t}\n\n\t/**\n\t * Decrypt a string of data\n\t *\n\t * @param string\n\t * @returns {string}\n\t */\n\tdecrypt(string: string): string {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n\t\treturn toUTF8(\n\t\t\telectrumDecrypt(toArray(string, \"base64\"), derivedChild.privKey),\n\t\t);\n\t}\n\n\t/**\n\t * Sign an attestation for a user\n\t *\n\t * @param attestationHash The computed attestation hash for the user - this should be calculated with the BAP_ID class for an identity for the user\n\t * @param identityKey The identity key we are using for the signing\n\t * @param counter\n\t * @param dataString Optional data string that will be appended to the BAP attestation\n\t * @returns {string[]}\n\t */\n\tsignAttestationWithAIP(\n\t\tattestationHash: string,\n\t\tidentityKey: string,\n\t\tcounter = 0,\n\t\tdataString = \"\",\n\t) {\n\t\tconst id = this.getId(identityKey);\n\t\tif (!id) {\n\t\t\tthrow new Error(\"Could not find identity to attest with\");\n\t\t}\n\n\t\tconst attestationBuffer = this.getAttestationBuffer(\n\t\t\tattestationHash,\n\t\t\tcounter,\n\t\t\tdataString,\n\t\t);\n\t\tconst { address, signature } = id.signMessage(attestationBuffer);\n\n\t\treturn this.createAttestationTransaction(\n\t\t\tattestationHash,\n\t\t\tcounter,\n\t\t\taddress,\n\t\t\tsignature,\n\t\t\tdataString,\n\t\t);\n\t}\n\n\t/**\n\t * Verify an AIP signed attestation for a user\n\t *\n\t * [\n\t * '0x6a',\n\t * '0x31424150537561506e66476e53424d33474c56397968785564596534764762644d54',\n\t * '0x415454455354',\n\t * '0x33656166366361396334313936356538353831366439336439643034333136393032376633396661623034386333633031333663343364663635376462383761',\n\t * '0x30',\n\t * '0x7c',\n\t * '0x313550636948473232534e4c514a584d6f5355615756693757537163376843667661',\n\t * '0x424954434f494e5f4543445341',\n\t * '0x31477531796d52567a595557634638776f6f506a7a4a4c764d383550795a64655876',\n\t * '0x20ef60c5555001ddb1039bb0f215e46571fcb39ee46f48b089d1c08b0304dbcb3366d8fdf8bafd82be24b5ac42dcd6a5e96c90705dd42e3ad918b1b47ac3ce6ac2'\n\t * ]\n\t *\n\t * @param tx Array of hex values for the OP_RETURN values\n\t * @returns {{}}\n\t */\n\tverifyAttestationWithAIP(tx: string[]): Attestation {\n\t\tif (\n\t\t\t!Array.isArray(tx) ||\n\t\t\ttx[0] !== \"0x6a\" ||\n\t\t\ttx[1] !== BAP_BITCOM_ADDRESS_HEX\n\t\t) {\n\t\t\tthrow new Error(\"Not a valid BAP transaction\");\n\t\t}\n\n\t\tconst dataOffset = tx[7] === \"0x44415441\" ? 5 : 0; // DATA\n\t\tconst attestation: Attestation = {\n\t\t\ttype: Utils.hexDecode(tx[2]),\n\t\t\thash: Utils.hexDecode(tx[3]),\n\t\t\tsequence: Utils.hexDecode(tx[4]),\n\t\t\tsigningProtocol: Utils.hexDecode(tx[7 + dataOffset]),\n\t\t\tsigningAddress: Utils.hexDecode(tx[8 + dataOffset]),\n\t\t\tsignature: Utils.hexDecode(tx[9 + dataOffset], \"base64\"),\n\t\t};\n\n\t\tif (dataOffset && tx[3] === tx[8]) {\n\t\t\t// valid data addition\n\t\t\tattestation.data = Utils.hexDecode(tx[9]);\n\t\t}\n\n\t\ttry {\n\t\t\tconst signatureBufferStatements: Buffer[] = [];\n\t\t\tfor (let i = 0; i < 6 + dataOffset; i++) {\n\t\t\t\tsignatureBufferStatements.push(\n\t\t\t\t\tBuffer.from(tx[i].replace(\"0x\", \"\"), \"hex\"),\n\t\t\t\t);\n\t\t\t}\n const attestationBuffer = Buffer.concat(signatureBufferStatements as unknown as Uint8Array[]);\n attestation.verified = this.verifySignature(\n\t\t\t\tattestationBuffer,\n\t\t\t\tattestation.signingAddress,\n\t\t\t\tattestation.signature,\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tattestation.verified = false;\n\t\t}\n\n\t\treturn attestation;\n\t}\n\n\t/**\n\t * For BAP attestations we use all fields for the attestation\n\t *\n\t * @param attestationHash\n\t * @param counter\n\t * @param address\n\t * @param signature\n\t * @param dataString Optional data string that will be appended to the BAP attestation\n\t * @returns {[string]}\n\t */\n\tcreateAttestationTransaction(\n\t\tattestationHash: string,\n\t\tcounter: number,\n\t\taddress: string,\n\t\tsignature: string,\n\t\tdataString = \"\",\n\t): string[] {\n\t\tconst transaction = [\"0x6a\", Utils.hexEncode(BAP_BITCOM_ADDRESS)];\n\t\ttransaction.push(Utils.hexEncode(\"ATTEST\"));\n\t\ttransaction.push(Utils.hexEncode(attestationHash));\n\t\ttransaction.push(Utils.hexEncode(`${counter}`));\n\t\ttransaction.push(\"0x7c\"); // |\n\t\tif (dataString) {\n\t\t\t// data should be a string, either encrypted or stringified JSON if applicable\n\t\t\ttransaction.push(Utils.hexEncode(BAP_BITCOM_ADDRESS));\n\t\t\ttransaction.push(Utils.hexEncode(\"DATA\"));\n\t\t\ttransaction.push(Utils.hexEncode(attestationHash));\n\t\t\ttransaction.push(Utils.hexEncode(dataString));\n\t\t\ttransaction.push(\"0x7c\"); // |\n\t\t}\n\t\ttransaction.push(Utils.hexEncode(AIP_BITCOM_ADDRESS));\n\t\ttransaction.push(Utils.hexEncode(\"BITCOIN_ECDSA\"));\n\t\ttransaction.push(Utils.hexEncode(address));\n\t\ttransaction.push(`0x${Buffer.from(signature, \"base64\").toString(\"hex\")}`);\n\n\t\treturn transaction;\n\t}\n\n\t/**\n\t * This is a re-creation of how the bitcoinfiles-sdk creates a hash to sign for AIP\n\t *\n\t * @param attestationHash\n\t * @param counter\n\t * @param dataString Optional data string\n\t * @returns {Buffer}\n\t */\n\tgetAttestationBuffer(\n\t\tattestationHash: string,\n\t\tcounter = 0,\n\t\tdataString = \"\",\n\t): Buffer {\n\t\t// re-create how AIP creates the buffer to sign\n\t\tlet dataStringBuffer = Buffer.from(\"\");\n\t\tif (dataString) {\n\t\t\tdataStringBuffer = Buffer.concat([\n\t\t\t\tBuffer.from(BAP_BITCOM_ADDRESS) as unknown as Uint8Array,\n\t\t\t\tBuffer.from(\"DATA\") as unknown as Uint8Array,\n\t\t\t\tBuffer.from(attestationHash) as unknown as Uint8Array,\n\t\t\t\tBuffer.from(dataString) as unknown as Uint8Array,\n\t\t\t\tBuffer.from(\"7c\", \"hex\") as unknown as Uint8Array,\n\t\t\t]);\n\t\t}\n\t\treturn Buffer.concat([\n\t\t\tBuffer.from(\"6a\", \"hex\") as unknown as Uint8Array, // OP_RETURN\n\t\t\tBuffer.from(BAP_BITCOM_ADDRESS) as unknown as Uint8Array,\n\t\t\tBuffer.from(\"ATTEST\") as unknown as Uint8Array,\n\t\t\tBuffer.from(attestationHash) as unknown as Uint8Array,\n\t\t\tBuffer.from(`${counter}`) as unknown as Uint8Array,\n\t\t\tBuffer.from(\"7c\", \"hex\") as unknown as Uint8Array,\n\t\t\tdataStringBuffer as unknown as Uint8Array,\n\t\t]);\n\t}\n\n\t/**\n\t * Verify that the identity challenge is signed by the address\n\t *\n\t * @param message Buffer or utf-8 string\n\t * @param address Bitcoin address of signee\n\t * @param signature Signature base64 string\n\t *\n\t * @return boolean\n\t */\n\tverifySignature(\n\t\tmessage: string | Buffer,\n\t\taddress: string,\n\t\tsignature: string,\n\t): boolean {\n\t\t// check the signature against the challenge\n\t\tconst messageBuffer = Buffer.isBuffer(message)\n\t\t\t? message\n\t\t\t: Buffer.from(message);\n\t\tconst sig = Signature.fromCompact(signature, \"base64\");\n\t\tlet publicKey: PublicKey | undefined;\n\t\tconst msg = toArray(messageBuffer.toString(\"hex\"), \"hex\");\n\t\tfor (let recovery = 0; recovery < 4; recovery++) {\n\t\t\ttry {\n\t\t\t\tpublicKey = sig.RecoverPublicKey(\n\t\t\t\t\trecovery,\n\t\t\t\t\tnew BigNumber(BSM.magicHash(msg)),\n\t\t\t\t);\n\t\t\t\tconst sigFitsPubkey = BSM.verify(msg, sig, publicKey);\n\t\t\t\tif (sigFitsPubkey && publicKey.toAddress() === address) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\t// try next recovery\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Check whether the given transaction (BAP OP_RETURN) is valid, is signed and that the\n\t * identity signing is also valid at the time of signing\n\t *\n\t * @param idKey\n\t * @param address\n\t * @param challenge\n\t * @param signature\n\t *\n\t * @returns {Promise<boolean|*>}\n\t */\n\tasync verifyChallengeSignature(\n\t\tidKey: string,\n\t\taddress: string,\n\t\tchallenge: string,\n\t\tsignature: string,\n\t): Promise<boolean> {\n\t\t// first we test locally before sending to server\n\t\tif (this.verifySignature(challenge, address, signature)) {\n\t\t\tconst result = await this.getApiData<AttestationValidResponse>(\"/attestation/valid\", {\n\t\t\t\tidKey,\n\t\t\t\tchallenge,\n\t\t\t\tsignature,\n\t\t\t});\n\t\t\treturn result ? result.valid : false;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Check whether the given transaction (BAP OP_RETURN) is valid, is signed and that the\n\t * identity signing is also valid at the time of signing\n\t *\n\t * @param tx\n\t * @returns {Promise<boolean|*>}\n\t */\n\tasync isValidAttestationTransaction(tx: string[]): Promise<any> {\n\t\t// first we test locally before sending to server\n\t\tif (this.verifyAttestationWithAIP(tx)) {\n\t\t\treturn this.getApiData(\"/attestation/valid\", {\n\t\t\t\ttx,\n\t\t\t});\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Get all signing keys for the given idKey\n\t *\n\t * @param address\n\t * @returns {Promise<*>}\n\t */\n\tasync getIdentityFromAddress(address: string): Promise<GetIdentityByAddressResponse> {\n\t\treturn this.getApiData(\"/identity/from-address\", {\n\t\t\taddress,\n\t\t});\n\t}\n\n\t/**\n\t * Get all signing keys for the given idKey\n\t *\n\t * @param idKey\n\t * @returns {Promise<*>}\n\t */\n\tasync getIdentity(idKey: string): Promise<any> {\n\t\treturn this.getApiData(\"/identity/get\", {\n\t\t\tidKey,\n\t\t});\n\t}\n\n\t/**\n\t * Get all attestations for the given attestation hash\n\t *\n\t * @param attestationHash\n\t */\n\tasync getAttestationsForHash(attestationHash: string): Promise<GetAttestationResponse> {\n\t\t// get all BAP ATTEST records for the given attestationHash\n\t\treturn this.getApiData(\"/attestations\", {\n\t\t\thash: attestationHash,\n\t\t});\n\t}\n\n \n};\n\nexport { BAP_ID }"],"names":["Utils","hexEncode","string","Buffer","from","toString","hexDecode","hexString","encoding","replace","getRandomString","length","randomBytes","isHex","value","test","getSigningPathFromHex","hardened","signingPath","signingHex","match","Error","maxNumber","hexNumber","number","Number","getNextIdentityPath","path","pathValues","split","secondToLastPart","nextPath","join","getNextPath","lastPart","BAP_BITCOM_ADDRESS","BAP_BITCOM_ADDRESS_HEX","AIP_BITCOM_ADDRESS","BAP_SERVER","MAX_INT","SIGNING_PATH_PREFIX","ENCRYPTION_PATH","apiFetcher","host","token","async","url","data","apiUrl","apiData","server","fetch","method","headers","format","body","JSON","stringify","json","getApiData","toArray","toHex","toBase58","toUTF8","toBase64","BSVUtils","electrumDecrypt","electrumEncrypt","ECIES","magicHash","BSM","_HDPrivateKey","_classPrivateFieldLooseKey","_BAP_SERVER","_BAP_TOKEN","_rootPath","_previousPath","_currentPath","_idSeed","BAP_ID","constructor","HDPrivateKey","identityAttributes","idSeed","Object","defineProperty","writable","this","idName","description","rootAddress","identityKey","_classPrivateFieldLooseBase","seedHex","Hash","sha256","seedPath","derive","rootChild","privKey","toPublicKey","toAddress","deriveIdentityKey","attributes","_extends","parseAttributes","bapServer","BAP_TOKEN","address","rootAddressHash","ripemd160","parseStringUrns","key","nonce","urnIdentityAttributes","attributesRaw","line","urn","getIdentityKey","getAttributes","getAttribute","attributeName","setAttribute","attributeValue","addAttribute","unsetAttribute","getAttributeUrns","urns","getAttributeUrn","attribute","nonceToUse","rootPath","pathToUse","validatePath","derivedChild","pubKey","getRootPath","currentPath","previousPath","incrementPath","getInitialIdTransaction","getIdTransaction","opReturn","getCurrentAddress","signOpReturnWithAIP","getAddress","getEncryptionPublicKey","getEncryptionPublicKeyWithSeed","seed","getEncryptionPrivateKeyWithSeed","encrypt","stringData","counterPartyPublicKey","publicKey","PublicKey","fromString","decrypt","ciphertext","encryptionKey","encryptWithSeed","decryptWithSeed","pathHex","getAttestation","urnHash","getAttestationHash","attestation","attestationHash","signMessage","message","msg","childPk","dummySig","sign","h","BigNumber","r","CalculateRecoveryFactor","signature","toCompact","signMessageWithSeed","outputType","aipMessageBuffer","getAIPMessageBuffer","concat","buffers","push","op","getIdSigningKeys","signingKeys","idKey","console","log","getAttributeAttestations","attestations","hash","import","identity","name","export","lastIdPath","_ids","_lastIdPath","BAP","HD","getPublicKey","childPath","getHdPublicKey","toPublic","checkIdBelongs","bapId","listIds","keys","newId","getNextValidPath","newIdentity","removeId","getId","setId","importIds","idData","encrypted","importEncryptedIds","ids","id","importId","decrypted","parse","Array","isArray","importOldIds","exportIds","signAttestationWithAIP","counter","dataString","attestationBuffer","getAttestationBuffer","createAttestationTransaction","verifyAttestationWithAIP","tx","dataOffset","type","sequence","signingProtocol","signingAddress","signatureBufferStatements","i","verified","verifySignature","e","transaction","dataStringBuffer","messageBuffer","isBuffer","sig","Signature","fromCompact","recovery","RecoverPublicKey","verify","verifyChallengeSignature","challenge","result","valid","isValidAttestationTransaction","getIdentityFromAddress","getIdentity","getAttestationsForHash"],"mappings":"yhBAGO,MAAMA,EAAQ,CAOnBC,UAAUC,GACD,KAAKC,OAAOC,KAAKF,GAAQG,SAAS,SAU3CC,UAASA,CAACC,EAAmBC,EAA2B,SAC/CL,OAAOC,KAAKG,EAAUE,QAAQ,KAAM,IAAK,OAAOJ,SAASG,GAQlEE,gBAAeA,CAACC,EAAS,KAChBC,EAAYD,GAAQN,SAAS,OAStCQ,MAAMC,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5E,GACjB,OAAWtG,KAAC5B,WAAW,gBAAiB,CACvCkI,SAEF,CAOA,4BAAM6E,CAAuBpG,GAE5B,OAAO/E,KAAK5B,WAAW,gBAAiB,CACvCuI,KAAM5B,GAER"}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/api.ts", "../src/constants.ts", "../src/id.ts", "../src/utils.ts"],
4
+ "sourcesContent": [
5
+ "import { BSM, Utils as BSVUtils, BigNumber, ECIES, HD, PrivateKey, type PublicKey, Signature } from \"@bsv/sdk\";\nimport { type APIFetcher, apiFetcher } from \"./api\";\nimport type { AttestationValidResponse, GetAttestationResponse, GetIdentityByAddressResponse, GetIdentityResponse } from \"./apiTypes\";\nimport {\n AIP_BITCOM_ADDRESS,\n BAP_BITCOM_ADDRESS,\n BAP_BITCOM_ADDRESS_HEX,\n BAP_SERVER,\n ENCRYPTION_PATH,\n} from \"./constants\";\nimport { BAP_ID } from \"./id\";\nimport type { Attestation, HDIdentity, Identity, IdentityAttributes, OldIdentity, PathPrefix, SingleKeyIdentity } from \"./interface\";\nimport { Utils } from \"./utils\";\nconst { toArray, toUTF8, toBase64 } = BSVUtils;\nconst { electrumEncrypt, electrumDecrypt } = ECIES;\n\ntype Identities = {\n lastIdPath: string;\n ids: Identity[];\n};\n\nexport type { HDIdentity, SingleKeyIdentity, Attestation, Identity, IdentityAttributes, PathPrefix };\nexport { BAP_ID };\n\n/**\n * BAP class\n *\n * Creates an instance of the BAP class and uses the given HDPrivateKey for all BAP operations.\n *\n * @param HDPrivateKey\n */\nexport class BAP {\n #HDPrivateKey: HD | PrivateKey;\n #lastIdPath = \"\";\n public get lastIdPath(): string {\n return this.#lastIdPath;\n }\n #ids: { [key: string]: BAP_ID } = {};\n #BAP_SERVER: string = BAP_SERVER;\n #BAP_TOKEN = \"\";\n getApiData: APIFetcher;\n\n constructor(key: string | HD | PrivateKey, token?: string) {\n if (!key) {\n throw new Error(\"Key is required for BAP initialization\");\n }\n\n if (typeof key === 'string') {\n try {\n this.#HDPrivateKey = HD.fromString(key);\n } catch (e) {\n try {\n this.#HDPrivateKey = PrivateKey.fromWif(key);\n } catch (e2) {\n throw new Error('Invalid private key format');\n }\n }\n } else {\n this.#HDPrivateKey = key;\n }\n\n if (token !== undefined) this.#BAP_TOKEN = token;\n\n this.getApiData = apiFetcher(this.#BAP_SERVER, this.#BAP_TOKEN);\n }\n\n private isHD(key: HD | PrivateKey): key is HD {\n return 'depth' in key && 'parentFingerPrint' in key;\n }\n\n /**\n * Get the public key of the given childPath, or of the current HDPrivateKey if childPath is empty\n *\n * @param childPath Full derivation path for this child\n * @returns {string}\n */\n getPublicKey(childPath = \"\"): string {\n if (this.isHD(this.#HDPrivateKey)) {\n if (childPath !== \"\") {\n return this.#HDPrivateKey.derive(childPath).pubKey.toString();\n }\n return this.#HDPrivateKey.pubKey.toString();\n }\n // For single key mode, derivation is not supported, ignore childPath\n return this.#HDPrivateKey.toPublicKey().toString();\n }\n\n /**\n * Get the HD public key (xpub) of the given childPath, or of the current HDPrivateKey if childPath is empty\n *\n * @param childPath Full derivation path for this child\n * @returns {string}\n */\n getHdPublicKey(childPath = \"\"): string {\n if (!this.isHD(this.#HDPrivateKey)) {\n throw new Error(\"Not an HD key\");\n }\n\n if (childPath) {\n return this.#HDPrivateKey.derive(childPath).toPublic().toString();\n }\n return this.#HDPrivateKey.toPublic().toString();\n }\n\n set BAP_SERVER(bapServer) {\n this.#BAP_SERVER = bapServer;\n for (const key in this.#ids) {\n this.#ids[key].BAP_SERVER = bapServer;\n }\n }\n\n get BAP_SERVER(): string {\n return this.#BAP_SERVER;\n }\n\n set BAP_TOKEN(token) {\n this.#BAP_TOKEN = token;\n for (const key in this.#ids) {\n // @ts-ignore - does not recognize private fields that can be set\n this.#ids[key].BAP_TOKEN = token;\n }\n }\n\n get BAP_TOKEN(): string {\n return this.#BAP_TOKEN;\n }\n\n /**\n * This function verifies that the given bapId matches the given root address\n * This is used as a data integrity check\n *\n * @param bapId BAP_ID instance\n */\n checkIdBelongs(bapId: BAP_ID): boolean {\n if (!this.isHD(this.#HDPrivateKey)) {\n throw new Error(\"checkIdBelongs can only be used in HD mode\");\n }\n\n const derivedChild = this.#HDPrivateKey.derive(bapId.rootPath);\n const checkRootAddress = derivedChild.pubKey.toAddress();\n\n if (checkRootAddress !== bapId.rootAddress) {\n throw new Error(\"ID does not belong to this private key\");\n }\n\n return true;\n }\n\n /**\n * Returns a list of all the identity keys that are stored in this instance\n *\n * @returns {string[]}\n */\n listIds(): string[] {\n return Object.keys(this.#ids);\n }\n\n /**\n * Create a new Id and link it to this BAP instance\n *\n * This function uses the length of the #ids of this class to determine the next valid path.\n * If not all ids related to this HDPrivateKey have been loaded, determine the path externally\n * and pass it to newId when creating a new ID.\n *\n * @param path\n * @param identityAttributes\n * @param idSeed\n * @returns {*}\n */\n newId(path?: string, identityAttributes: IdentityAttributes = {}, idSeed = \"\"): BAP_ID {\n let pathToUse: string;\n if (!path) {\n // get next usable path for this key\n pathToUse = this.getNextValidPath();\n } else {\n pathToUse = path;\n }\n\n const newIdentity = new BAP_ID(\n this.#HDPrivateKey,\n identityAttributes,\n idSeed,\n );\n newIdentity.BAP_SERVER = this.#BAP_SERVER;\n newIdentity.BAP_TOKEN = this.#BAP_TOKEN;\n\n newIdentity.rootPath = pathToUse;\n newIdentity.currentPath = Utils.getNextPath(pathToUse);\n\n const idKey = newIdentity.getIdentityKey();\n this.#ids[idKey] = newIdentity;\n this.#lastIdPath = pathToUse;\n\n return this.#ids[idKey];\n }\n\n /**\n * Remove identity\n *\n * @param idKey\n * @returns {*}\n */\n removeId(idKey: string): void {\n delete this.#ids[idKey];\n }\n\n /**\n * Get the next valid path for the used HDPrivateKey and loaded #ids\n *\n * @returns {string}\n */\n getNextValidPath(): PathPrefix {\n // prefer hardened paths\n if (this.#lastIdPath) {\n return Utils.getNextIdentityPath(this.#lastIdPath);\n }\n\n return `/0'/${Object.keys(this.#ids).length}'/0'`;\n }\n\n /**\n * Get a certain Id\n *\n * @param identityKey\n * @returns {null}\n */\n getId(identityKey: string): BAP_ID | null {\n return this.#ids[identityKey] || null;\n }\n\n /**\n * This function is used when manipulating ID's, adding or removing attributes etc\n * First create an id through this class and then use getId to get it. Then you can add/edit or\n * increment the signing path and then re-set it with this function.\n *\n * Note: when you getId() from this class, you will be working on the same object as this class\n * has and any changes made will be propagated to the id in this class. When you call exportIds\n * your new changes will also be included, without having to setId().\n *\n * @param bapId\n */\n setId(bapId: BAP_ID): void {\n this.checkIdBelongs(bapId);\n this.#ids[bapId.getIdentityKey()] = bapId;\n }\n\n /**\n * This function is used to import IDs and attributes from some external storage\n *\n * The ID information should NOT be stored together with the HD private key !\n *\n * @param idData Array of ids that have been exported\n * @param encrypted Whether the data should be treated as being encrypted (default true)\n */\n importIds(idData: Identities | string, encrypted = true): void {\n if (encrypted && typeof idData === \"string\") {\n this.importEncryptedIds(idData);\n return;\n }\n\n const identity = idData as Identities;\n if (!identity.lastIdPath || !Array.isArray(identity.ids)) {\n throw new Error(\"ID data is not in the correct format\");\n }\n\n const isSingleKeyMode = !(this.#HDPrivateKey instanceof HD);\n if (isSingleKeyMode && identity.ids.length > 1) {\n throw new Error(\"Cannot import multiple IDs in single key mode\");\n }\n\n let lastIdPath = identity.lastIdPath;\n\n for (const id of identity.ids) {\n if (!id.identityKey || !id.identityAttributes || !id.rootAddress) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n\n let importId: BAP_ID;\n\n if (isSingleKeyIdentity(id)) {\n if (!isSingleKeyMode) {\n throw new Error(\"Cannot import single key identity in HD mode\");\n }\n const privKey = PrivateKey.fromString(id.derivedPrivateKey, \"hex\");\n importId = new BAP_ID(\n privKey,\n id.identityAttributes,\n id.idSeed\n );\n } else if (isHDIdentity(id)) {\n if (isSingleKeyMode) {\n throw new Error(\"Cannot import HD identity in single key mode\");\n }\n const hdKey = this.#HDPrivateKey as HD;\n importId = new BAP_ID(\n hdKey,\n id.identityAttributes,\n id.idSeed\n );\n importId.rootPath = id.rootPath;\n importId.currentPath = id.currentPath;\n } else {\n throw new Error(\"Invalid identity format\");\n }\n\n importId.BAP_SERVER = this.#BAP_SERVER;\n importId.BAP_TOKEN = this.#BAP_TOKEN;\n importId.import(id);\n\n if (!isSingleKeyMode && isHDIdentity(id)) {\n if (lastIdPath === \"\") {\n lastIdPath = id.currentPath;\n }\n this.checkIdBelongs(importId);\n }\n\n this.#ids[importId.getIdentityKey()] = importId;\n }\n\n if (!isSingleKeyMode) {\n this.#lastIdPath = lastIdPath;\n }\n }\n\n importEncryptedIds(idData: string): void {\n const decrypted = this.decrypt(idData);\n const ids = JSON.parse(decrypted) as Identities | OldIdentity[];\n\n const isOldFormat = Array.isArray(ids);\n if (isOldFormat) {\n console.log(\"Importing old format:\\n\", ids);\n this.importOldIds(ids);\n return;\n }\n\n if (typeof ids !== \"object\") {\n throw new Error(\"decrypted, but found unrecognized identities format\");\n }\n\n this.importIds(ids, false);\n }\n\n importOldIds(idData: OldIdentity[]): void {\n for (const id of idData) {\n const importId = new BAP_ID(\n this.#HDPrivateKey,\n {},\n id.idSeed ?? \"\"\n );\n importId.BAP_SERVER = this.#BAP_SERVER;\n importId.BAP_TOKEN = this.#BAP_TOKEN;\n importId.import(id);\n\n this.checkIdBelongs(importId);\n this.#ids[importId.getIdentityKey()] = importId;\n\n // Ensure currentPath is always a string\n if ('currentPath' in id && typeof id.currentPath === 'string') {\n this.#lastIdPath = id.currentPath;\n } else {\n this.#lastIdPath = \"\";\n }\n }\n }\n\n\n /**\n * Export identities. If no idKeys are provided, exports all identities.\n * @param encrypted Whether to encrypt the export. Defaults to true\n * @param idKeys Optional array of identity keys to export\n * @returns A string if encrypted is true, otherwise an Identities object\n */\n exportIds(encrypted?: true, idKeys?: string[]): string;\n exportIds(encrypted: false, idKeys?: string[]): Identities;\n exportIds(encrypted = true, idKeys?: string[]): Identities | string {\n const idData: Identities = {\n lastIdPath: this.#lastIdPath,\n ids: [],\n };\n\n const keysToExport = idKeys || Object.keys(this.#ids);\n\n for (const key of keysToExport) {\n if (!this.#ids[key]) {\n throw new Error(`Identity ${key} not found`);\n }\n idData.ids.push(this.#ids[key].export());\n }\n\n if (encrypted) {\n return this.encrypt(JSON.stringify(idData));\n }\n return idData;\n }\n\n\n /**\n * Encrypt a string of data\n *\n * @param string\n * @returns {string}\n */\n encrypt(string: string): string {\n if (!this.isHD(this.#HDPrivateKey)) {\n throw new Error(\"Encryption not supported in single key mode\");\n }\n const derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n return toBase64(\n electrumEncrypt(toArray(string), derivedChild.pubKey),\n );\n }\n\n /**\n * Decrypt a string of data\n *\n * @param string\n * @returns {string}\n */\n decrypt(string: string): string {\n if (!this.isHD(this.#HDPrivateKey)) {\n throw new Error(\"Decryption not supported in single key mode\");\n }\n const derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n return toUTF8(\n electrumDecrypt(toArray(string, \"base64\"), derivedChild.privKey),\n );\n }\n\n /**\n * Sign an attestation for a user\n *\n * @param attestationHash The computed attestation hash for the user - this should be calculated with the BAP_ID class for an identity for the user\n * @param identityKey The identity key we are using for the signing\n * @param counter\n * @param dataString Optional data string that will be appended to the BAP attestation\n * @returns {string[]}\n */\n signAttestationWithAIP(\n attestationHash: string,\n identityKey: string,\n counter = 0,\n dataString = \"\",\n ) {\n const id = this.getId(identityKey);\n if (!id) {\n throw new Error(\"Could not find identity to attest with\");\n }\n\n const attestationBuffer = this.getAttestationBuffer(\n attestationHash,\n counter,\n dataString,\n );\n const { address, signature } = id.signMessage(attestationBuffer);\n\n return this.createAttestationTransaction(\n attestationHash,\n counter,\n address,\n signature,\n dataString,\n );\n }\n\n /**\n * Verify an AIP signed attestation for a user\n *\n * [\n * '0x6a',\n * '0x31424150537561506e66476e53424d33474c56397968785564596534764762644d54',\n * '0x415454455354',\n * '0x33656166366361396334313936356538353831366439336439643034333136393032376633396661623034386333633031333663343364663635376462383761',\n * '0x30',\n * '0x7c',\n * '0x313550636948473232534e4c514a584d6f5355615756693757537163376843667661',\n * '0x424954434f494e5f4543445341',\n * '0x31477531796d52567a595557634638776f6f506a7a4a4c764d383550795a64655876',\n * '0x20ef60c5555001ddb1039bb0f215e46571fcb39ee46f48b089d1c08b0304dbcb3366d8fdf8bafd82be24b5ac42dcd6a5e96c90705dd42e3ad918b1b47ac3ce6ac2'\n * ]\n *\n * @param tx Array of hex values for the OP_RETURN values\n * @returns {{}}\n */\n verifyAttestationWithAIP(tx: string[]): Attestation {\n if (\n !Array.isArray(tx) ||\n tx[0] !== \"0x6a\" ||\n tx[1] !== BAP_BITCOM_ADDRESS_HEX\n ) {\n throw new Error(\"Not a valid BAP transaction\");\n }\n\n const dataOffset = tx[7] === \"0x44415441\" ? 5 : 0; // DATA\n const attestation: Attestation = {\n type: Utils.hexDecode(tx[2]),\n hash: Utils.hexDecode(tx[3]),\n sequence: Utils.hexDecode(tx[4]),\n signingProtocol: Utils.hexDecode(tx[7 + dataOffset]),\n signingAddress: Utils.hexDecode(tx[8 + dataOffset]),\n signature: Utils.hexDecode(tx[9 + dataOffset], \"base64\"),\n };\n\n if (dataOffset && tx[3] === tx[8]) {\n // valid data addition\n attestation.data = Utils.hexDecode(tx[9]);\n }\n\n try {\n const signatureBufferStatements: Buffer[] = [];\n for (let i = 0; i < 6 + dataOffset; i++) {\n signatureBufferStatements.push(\n Buffer.from(tx[i].replace(\"0x\", \"\"), \"hex\"),\n );\n }\n const attestationBuffer = Buffer.concat(signatureBufferStatements as unknown as Uint8Array[]);\n attestation.verified = this.verifySignature(\n attestationBuffer,\n attestation.signingAddress,\n attestation.signature,\n );\n } catch (e) {\n attestation.verified = false;\n }\n\n return attestation;\n }\n\n /**\n * For BAP attestations we use all fields for the attestation\n *\n * @param attestationHash\n * @param counter\n * @param address\n * @param signature\n * @param dataString Optional data string that will be appended to the BAP attestation\n * @returns {[string]}\n */\n createAttestationTransaction(\n attestationHash: string,\n counter: number,\n address: string,\n signature: string,\n dataString = \"\",\n ): string[] {\n const transaction = [\"0x6a\", Utils.hexEncode(BAP_BITCOM_ADDRESS)];\n transaction.push(Utils.hexEncode(\"ATTEST\"));\n transaction.push(Utils.hexEncode(attestationHash));\n transaction.push(Utils.hexEncode(`${counter}`));\n transaction.push(\"0x7c\"); // |\n if (dataString) {\n // data should be a string, either encrypted or stringified JSON if applicable\n transaction.push(Utils.hexEncode(BAP_BITCOM_ADDRESS));\n transaction.push(Utils.hexEncode(\"DATA\"));\n transaction.push(Utils.hexEncode(attestationHash));\n transaction.push(Utils.hexEncode(dataString));\n transaction.push(\"0x7c\"); // |\n }\n transaction.push(Utils.hexEncode(AIP_BITCOM_ADDRESS));\n transaction.push(Utils.hexEncode(\"BITCOIN_ECDSA\"));\n transaction.push(Utils.hexEncode(address));\n transaction.push(`0x${Buffer.from(signature, \"base64\").toString(\"hex\")}`);\n\n return transaction;\n }\n\n /**\n * This is a re-creation of how the bitcoinfiles-sdk creates a hash to sign for AIP\n *\n * @param attestationHash\n * @param counter\n * @param dataString Optional data string\n * @returns {Buffer}\n */\n getAttestationBuffer(\n attestationHash: string,\n counter = 0,\n dataString = \"\",\n ): Buffer {\n // re-create how AIP creates the buffer to sign\n let dataStringBuffer = Buffer.from(\"\");\n if (dataString) {\n dataStringBuffer = Buffer.concat([\n Buffer.from(BAP_BITCOM_ADDRESS) as unknown as Uint8Array,\n Buffer.from(\"DATA\") as unknown as Uint8Array,\n Buffer.from(attestationHash) as unknown as Uint8Array,\n Buffer.from(dataString) as unknown as Uint8Array,\n Buffer.from(\"7c\", \"hex\") as unknown as Uint8Array,\n ]);\n }\n return Buffer.concat([\n Buffer.from(\"6a\", \"hex\") as unknown as Uint8Array, // OP_RETURN\n Buffer.from(BAP_BITCOM_ADDRESS) as unknown as Uint8Array,\n Buffer.from(\"ATTEST\") as unknown as Uint8Array,\n Buffer.from(attestationHash) as unknown as Uint8Array,\n Buffer.from(`${counter}`) as unknown as Uint8Array,\n Buffer.from(\"7c\", \"hex\") as unknown as Uint8Array,\n dataStringBuffer as unknown as Uint8Array,\n ]);\n }\n\n /**\n * Verify that the identity challenge is signed by the address\n *\n * @param message Buffer or utf-8 string\n * @param address Bitcoin address of signee\n * @param signature Signature base64 string\n *\n * @return boolean\n */\n verifySignature(\n message: string | Buffer,\n address: string,\n signature: string,\n ): boolean {\n // check the signature against the challenge\n const messageBuffer = Buffer.isBuffer(message)\n ? message\n : Buffer.from(message);\n const sig = Signature.fromCompact(signature, \"base64\");\n let publicKey: PublicKey | undefined;\n const msg = toArray(messageBuffer.toString(\"hex\"), \"hex\");\n for (let recovery = 0; recovery < 4; recovery++) {\n try {\n publicKey = sig.RecoverPublicKey(\n recovery,\n new BigNumber(BSM.magicHash(msg)),\n );\n const sigFitsPubkey = BSM.verify(msg, sig, publicKey);\n if (sigFitsPubkey && publicKey.toAddress() === address) {\n return true;\n }\n } catch (e) {\n // try next recovery\n }\n }\n return false;\n }\n\n /**\n * Check whether the given transaction (BAP OP_RETURN) is valid, is signed and that the\n * identity signing is also valid at the time of signing\n *\n * @param idKey\n * @param address\n * @param challenge\n * @param signature\n *\n * @returns {Promise<boolean|*>}\n */\n async verifyChallengeSignature(\n idKey: string,\n address: string,\n challenge: string,\n signature: string,\n ): Promise<boolean> {\n // first we test locally before sending to server\n const localVerification = this.verifySignature(challenge, address, signature);\n\n if (!localVerification) {\n return false;\n }\n\n try {\n const response = await this.getApiData<AttestationValidResponse>(\"/attestation/valid\", {\n idKey,\n address,\n challenge,\n signature,\n });\n\n // Ensure we have a valid response with the expected structure\n if (response?.status === 'success' && response?.result?.valid === true) {\n return true;\n }\n\n return false;\n } catch (error) {\n console.error('API call failed:', error);\n return false;\n }\n }\n\n /**\n * Check whether the given transaction (BAP OP_RETURN) is valid, is signed and that the\n * identity signing is also valid at the time of signing\n *\n * @param tx\n * @returns {Promise<boolean|*>}\n */\n async isValidAttestationTransaction(tx: string[]): Promise<AttestationValidResponse | false> {\n if (this.verifyAttestationWithAIP(tx)) {\n return this.getApiData<AttestationValidResponse>(\"/attestation/valid\", {\n tx,\n });\n }\n return false;\n }\n\n /**\n * Get all signing keys for the given idKey\n *\n * @param address\n * @returns {Promise<*>}\n */\n async getIdentityFromAddress(address: string): Promise<GetIdentityByAddressResponse> {\n return this.getApiData<GetIdentityByAddressResponse>(\"/identity/from-address\", {\n address,\n });\n }\n\n /**\n * Get all signing keys for the given idKey\n *\n * @param idKey\n * @returns {Promise<*>}\n */\n async getIdentity(idKey: string): Promise<GetIdentityResponse> {\n return this.getApiData<GetIdentityResponse>(\"/identity/get\", {\n idKey,\n });\n }\n\n /**\n * Get all attestations for the given attestation hash\n *\n * @param attestationHash\n */\n async getAttestationsForHash(attestationHash: string): Promise<GetAttestationResponse> {\n // get all BAP ATTEST records for the given attestationHash\n return this.getApiData<GetAttestationResponse>(\"/attestations\", {\n hash: attestationHash,\n });\n }\n\n};\n\nexport function isSingleKeyIdentity(id: Identity): id is SingleKeyIdentity {\n return 'derivedPrivateKey' in id;\n}\n\nexport function isHDIdentity(id: Identity): id is HDIdentity {\n return 'rootPath' in id && 'currentPath' in id && 'previousPath' in id;\n}\n\n",
6
+ "\n/**\n\t * Helper function to get attestation from a BAP API server\n\t *\n\t * @param apiUrl\n\t * @param apiData\n\t * @returns {Promise<any>}\n\t */\nexport const getApiData = async <T>(apiUrl: string, apiData: unknown, server: string, token: string): Promise<T> => {\n const url = `${server}${apiUrl}`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-type\": \"application/json; charset=utf-8\",\n token,\n format: \"json\",\n },\n body: JSON.stringify(apiData),\n });\n\n return response.json();\n}\n\nexport type APIFetcher = <T>(url: string, data: unknown) => Promise<T>;\n\nexport const apiFetcher = (host: string, token: string): APIFetcher => async <T>(url: string, data: unknown): Promise<T> => {\n return getApiData<T>(url, data, host, token);\n}",
7
+ "export const BAP_BITCOM_ADDRESS = '1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT';\nexport const BAP_BITCOM_ADDRESS_HEX = `0x${Buffer.from(BAP_BITCOM_ADDRESS).toString('hex')}`;\nexport const AIP_BITCOM_ADDRESS = '15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva';\nexport const AIP_BITCOM_ADDRESS_HEX = `0x${Buffer.from(AIP_BITCOM_ADDRESS).toString('hex')}`;\nexport const BAP_SERVER = 'https://api.sigmaidentity.com/v1';\nexport const MAX_INT = 2147483648 - 1; // 0x80000000\n\n// This is just a choice for this library and could be anything else if so needed/wanted\n// but it is advisable to use the same derivation between libraries for compatibility\nexport const SIGNING_PATH_PREFIX = 'm/424150\\'/0\\'/0\\''; // BAP in hex\nexport const ENCRYPTION_PATH = `m/424150'/${MAX_INT}'/${MAX_INT}'`;\n",
8
+ "import { BSM, Utils as BSVUtils, BigNumber, ECIES, HD, Hash, type PrivateKey, PublicKey, type Signature } from \"@bsv/sdk\";\nimport { type APIFetcher, apiFetcher } from \"./api\";\nimport type { GetAttestationResponse, GetSigningKeysResponse } from \"./apiTypes\";\nimport {\n AIP_BITCOM_ADDRESS,\n BAP_BITCOM_ADDRESS,\n BAP_SERVER,\n ENCRYPTION_PATH,\n MAX_INT,\n SIGNING_PATH_PREFIX\n} from \"./constants\";\nimport type {\n Identity,\n IdentityAttribute,\n IdentityAttributes,\n OldIdentity\n} from \"./interface\";\nimport { Utils } from \"./utils\";\nconst { toArray, toHex, toBase58, toUTF8, toBase64 } = BSVUtils;\nconst { electrumDecrypt, electrumEncrypt } = ECIES;\nconst { magicHash } = BSM;\n/**\n * BAP_ID class\n *\n * This class should be used in conjunction with the BAP class\n *\n * @type {BAP_ID}\n */\nexport class BAP_ID {\n #HDPrivateKey?: HD;\n #singlePrivateKey?: PrivateKey;\n #rootPath?: string;\n #currentPath?: string;\n #previousPath?: string;\n lastIdPath = \"\";\n #idSeed: string;\n name: string;\n description: string;\n identityKey: string;\n rootAddress: string;\n identityAttributes: IdentityAttributes;\n private BAP_SERVER_: string;\n private BAP_TOKEN_: string;\n getApiData: APIFetcher;\n\n constructor(\n key: HD | PrivateKey,\n identityAttributes: IdentityAttributes = {},\n idSeed = \"\",\n ) {\n this.#idSeed = idSeed;\n this.BAP_SERVER_ = BAP_SERVER;\n this.BAP_TOKEN_ = \"\";\n this.getApiData = apiFetcher(this.BAP_SERVER_, this.BAP_TOKEN_);\n this.name = \"ID 1\";\n this.description = \"\";\n\n if (key instanceof HD) {\n this.#HDPrivateKey = key;\n if (idSeed) {\n const seedHex = toHex(Hash.sha256(idSeed, \"utf8\"));\n const seedPath = Utils.getSigningPathFromHex(seedHex);\n this.#HDPrivateKey = key.derive(seedPath);\n }\n\n this.rootPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n this.#previousPath = this.rootPath;\n this.#currentPath = `${SIGNING_PATH_PREFIX}/0/0/1`;\n\n const rootChild = this.#HDPrivateKey.derive(this.rootPath);\n this.rootAddress = rootChild.privKey.toPublicKey().toAddress();\n } else {\n this.#singlePrivateKey = key;\n this.rootAddress = key.toPublicKey().toAddress();\n }\n\n this.identityKey = this.deriveIdentityKey(this.rootAddress);\n\n // Deep clone the attributes to unlink the object\n const attributes = JSON.parse(JSON.stringify(identityAttributes));\n this.identityAttributes = this.parseAttributes(attributes);\n }\n\n get BAP_SERVER(): string {\n return this.BAP_SERVER_;\n }\n\n set BAP_SERVER(value: string) {\n this.BAP_SERVER_ = value;\n this.getApiData = apiFetcher(this.BAP_SERVER_, this.BAP_TOKEN_);\n }\n\n get BAP_TOKEN(): string {\n return this.BAP_TOKEN_;\n }\n\n set BAP_TOKEN(value: string) {\n this.BAP_TOKEN_ = value;\n this.getApiData = apiFetcher(this.BAP_SERVER_, this.BAP_TOKEN_);\n }\n\n deriveIdentityKey(address: string): string {\n // base58( ripemd160 ( sha256 ( rootAddress ) ) )\n const rootAddressHash = toHex(Hash.sha256(address, \"utf8\"));\n return toBase58(Hash.ripemd160(rootAddressHash, \"hex\"));\n }\n\n /**\n * Helper function to parse identity attributes\n *\n * @param identityAttributes\n * @returns {{}}\n */\n parseAttributes(\n identityAttributes: IdentityAttributes | string,\n ): IdentityAttributes {\n if (typeof identityAttributes === \"string\") {\n return this.parseStringUrns(identityAttributes);\n }\n\n for (const key in identityAttributes) {\n if (!identityAttributes[key].value || !identityAttributes[key].nonce) {\n throw new Error(\"Invalid identity attribute\");\n }\n }\n\n return identityAttributes || {};\n }\n\n /**\n * Parse a text of urn string into identity attributes\n *\n * urn:bap:id:name:John Doe:e2c6fb4063cc04af58935737eaffc938011dff546d47b7fbb18ed346f8c4d4fa\n * urn:bap:id:birthday:1990-05-22:e61f23cbbb2284842d77965e2b0e32f0ca890b1894ca4ce652831347ee3596d9\n * urn:bap:id:over18:1:480ca17ccaacd671b28dc811332525f2f2cd594d8e8e7825de515ce5d52d30e8\n *\n * @param urnIdentityAttributes\n */\n parseStringUrns(urnIdentityAttributes: string): IdentityAttributes {\n const identityAttributes: IdentityAttributes = {};\n // avoid forEach\n\n const attributesRaw = urnIdentityAttributes\n .replace(/^\\s+/g, \"\")\n .replace(/\\r/gm, \"\")\n .split(\"\\n\");\n\n for (const line of attributesRaw) {\n // remove any whitespace from the string (trim)\n const attribute = line.replace(/^\\s+/g, \"\").replace(/\\s+$/g, \"\");\n const urn = attribute.split(\":\");\n if (\n urn[0] === \"urn\" &&\n urn[1] === \"bap\" &&\n urn[2] === \"id\" &&\n urn[3] &&\n urn[4] &&\n urn[5]\n ) {\n identityAttributes[urn[3]] = {\n value: urn[4],\n nonce: urn[5],\n };\n }\n }\n\n return identityAttributes;\n }\n\n /**\n * Returns the identity key\n *\n * @returns {*|string}\n */\n getIdentityKey(): string {\n return this.identityKey;\n }\n\n /**\n * Returns all the attributes in the identity\n *\n * @returns {*}\n */\n getAttributes(): IdentityAttributes {\n return this.identityAttributes;\n }\n\n /**\n * Get the value of the given attribute\n *\n * @param attributeName\n * @returns {{}|null}\n */\n getAttribute(attributeName: string): IdentityAttribute | null {\n if (this.identityAttributes[attributeName]) {\n return this.identityAttributes[attributeName];\n }\n\n return null;\n }\n\n /**\n * Set the value of the given attribute\n *\n * If an empty value ('' || null || false) is given, the attribute is removed from the ID\n *\n * @param attributeName string\n * @param attributeValue any\n * @returns {{}|null}\n */\n setAttribute(attributeName: string, attributeValue: string | Record<string, string>): void {\n if (!attributeValue) {\n return;\n }\n\n if (this.identityAttributes[attributeName]) {\n this.updateExistingAttribute(attributeName, attributeValue);\n } else {\n this.createNewAttribute(attributeName, attributeValue);\n }\n }\n\n private updateExistingAttribute(\n attributeName: string,\n attributeValue: string | Record<string, string>\n ): void {\n if (typeof attributeValue === 'string') {\n this.identityAttributes[attributeName].value = attributeValue;\n return;\n }\n\n this.identityAttributes[attributeName].value = attributeValue.value || '';\n if (attributeValue.nonce) {\n this.identityAttributes[attributeName].nonce = attributeValue.nonce;\n }\n }\n\n private createNewAttribute(\n attributeName: string,\n attributeValue: string | Record<string, string>\n ): void {\n if (typeof attributeValue === 'string') {\n this.addAttribute(attributeName, attributeValue);\n return;\n }\n\n this.addAttribute(\n attributeName,\n attributeValue.value || '',\n attributeValue.nonce\n );\n }\n\n /**\n * Unset the given attribute from the ID\n *\n * @param attributeName\n * @returns {{}|null}\n */\n unsetAttribute(attributeName: string): void {\n delete this.identityAttributes[attributeName];\n }\n\n /**\n * Get all attribute urn's for this id\n *\n * @returns {string}\n */\n getAttributeUrns(): string {\n let urns = \"\";\n for (const key in this.identityAttributes) {\n const urn = this.getAttributeUrn(key);\n if (urn) {\n urns += `${urn}\\n`;\n }\n }\n\n return urns;\n }\n\n /**\n * Create an return the attribute urn for the given attribute\n *\n * @param attributeName\n * @returns {string|null}\n */\n getAttributeUrn(attributeName: string): string | null {\n const attribute = this.identityAttributes[attributeName];\n if (attribute) {\n return `urn:bap:id:${attributeName}:${attribute.value}:${attribute.nonce}`;\n }\n\n return null;\n }\n\n /**\n * Add an attribute to this identity\n *\n * @param attributeName\n * @param value\n * @param nonce\n */\n addAttribute(attributeName: string, value: string, nonce = \"\"): void {\n let nonceToUse = nonce;\n if (!nonce) {\n nonceToUse = Utils.getRandomString();\n }\n\n this.identityAttributes[attributeName] = {\n value,\n nonce: nonceToUse,\n };\n }\n\n /**\n * This should be called with the last part of the signing path (/.../.../...)\n * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file\n *\n * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9}\n */\n set rootPath(path: string) {\n if (this.#HDPrivateKey) {\n let pathToUse = path;\n if (path.split(\"/\").length < 5) {\n pathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n }\n\n if (!this.validatePath(pathToUse)) {\n throw new Error(`invalid signing path given ${pathToUse}`);\n }\n\n this.#rootPath = pathToUse;\n\n const derivedChild = this.#HDPrivateKey.derive(pathToUse);\n this.rootAddress = derivedChild.pubKey.toAddress();\n // Identity keys should be derivatives of the root address - this allows checking\n // of the creation transaction\n this.identityKey = this.deriveIdentityKey(this.rootAddress);\n\n // we also set this previousPath / currentPath to the root as we seem to be (re)setting this ID\n this.#previousPath = pathToUse;\n this.#currentPath = pathToUse;\n }\n }\n\n get rootPath(): string {\n if (!this.#rootPath) {\n throw new Error(\"rootPath not set\");\n }\n\n return this.#rootPath;\n }\n\n getRootPath(): string {\n if (!this.#rootPath) {\n throw new Error(\"rootPath not set\");\n }\n\n return this.#rootPath;\n }\n\n /**\n * This should be called with the last part of the signing path (/.../.../...)\n * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file\n *\n * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9}\n */\n set currentPath(path) {\n let pathToUse = path;\n if (path.split(\"/\").length < 5) {\n pathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n }\n\n if (!this.validatePath(pathToUse)) {\n throw new Error(\"invalid signing path given\");\n }\n\n this.#previousPath = this.#currentPath;\n this.#currentPath = pathToUse;\n }\n\n get currentPath(): string {\n if (!this.#currentPath) {\n throw new Error(\"currentPath not set\");\n }\n\n return this.#currentPath;\n }\n\n get previousPath(): string {\n if (!this.#previousPath) {\n throw new Error(\"previousPath not set\");\n }\n\n return this.#previousPath;\n }\n\n /**\n * This can be used to break the deterministic way child keys are created to make it harder for\n * an attacker to steal the identites when the root key is compromised. This does however require\n * the seeds to be stored at all times. If the seed is lost, the identity will not be recoverable.\n */\n get idSeed(): string {\n return this.#idSeed;\n }\n\n /**\n * Increment current path to a new path\n *\n * @returns {*}\n */\n incrementPath(): void {\n this.currentPath = Utils.getNextPath(this.currentPath);\n }\n\n /**\n * Check whether the given path is a valid path for use with this class\n * The signing paths used here always have a length of 3\n *\n * @param path The last part of the signing path (example \"/0/0/1\")\n * @returns {boolean}\n */\n validatePath(path: string) {\n /* eslint-disable max-len */\n if (\n path.match(\n /\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?/,\n )\n ) {\n const pathValues = path.split(\"/\");\n if (\n pathValues.length === 7 &&\n Number(pathValues[1].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[2].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[3].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[4].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[5].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[6].replace(\"'\", \"\")) <= MAX_INT\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Get the OP_RETURN for the initial ID transaction (signed with root address)\n *\n * @returns {[]}\n */\n getInitialIdTransaction() {\n return this.getIdTransaction(this.#rootPath);\n }\n\n /**\n * Get the OP_RETURN for the ID transaction of the current address / path\n *\n * @returns {[]}\n */\n getIdTransaction(previousPath = \"\") {\n if (this.#currentPath === this.#rootPath) {\n throw new Error(\n \"Current path equals rootPath. ID was probably not initialized properly\",\n );\n }\n\n const opReturn = [\n Buffer.from(BAP_BITCOM_ADDRESS).toString(\"hex\"),\n Buffer.from(\"ID\").toString(\"hex\"),\n Buffer.from(this.identityKey).toString(\"hex\"),\n Buffer.from(this.getCurrentAddress()).toString(\"hex\"),\n ];\n\n return this.signOpReturnWithAIP(\n opReturn,\n previousPath || this.#previousPath,\n );\n }\n\n /**\n * Get address for given path. Only works if HDPrivateKey is set\n *\n * @param path\n * @returns {*}\n */\n getAddress(path: string): string {\n if (!this.#HDPrivateKey) {\n throw new Error(\"HDPrivateKey not set\");\n }\n\n const derivedChild = this.#HDPrivateKey.derive(path);\n return derivedChild.privKey.toPublicKey().toAddress();\n }\n\n /**\n * Get current signing address\n *\n * @returns {*}\n */\n getCurrentAddress(): string {\n if (!this.#currentPath) {\n // get the address from the single key\n if (!this.#singlePrivateKey) {\n throw new Error(\"currentPath not set\");\n }\n return this.#singlePrivateKey.toPublicKey().toAddress();\n }\n\n return this.getAddress(this.#currentPath);\n }\n\n /**\n * Get the encryption public key for this identity\n * This key is derived from the identity's root path + ENCRYPTION_PATH\n */\n getEncryptionPublicKey(): string {\n if (this.#HDPrivateKey) {\n const rootChild = this.#HDPrivateKey.derive(this.rootPath);\n const encryptionChild = rootChild.derive(ENCRYPTION_PATH);\n return encryptionChild.pubKey.toString();\n }\n if (!this.#singlePrivateKey) {\n throw new Error(\"No private key available for encryption\");\n }\n return this.#singlePrivateKey.toPublicKey().toString();\n }\n\n /**\n * Get the encryption public key for this identity with a seed\n * This key is derived from the identity's root path + ENCRYPTION_PATH + seed path\n */\n getEncryptionPublicKeyWithSeed(seed: string): string {\n const encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n return encryptionKey.toPublicKey().toString();\n }\n\n /**\n * Encrypt data using this identity's encryption key\n */\n encrypt(stringData: string, counterPartyPublicKey?: string): string {\n if (!this.#HDPrivateKey) {\n throw new Error(\"HDPrivateKey not set\");\n }\n const rootChild = this.#HDPrivateKey.derive(this.rootPath);\n const encryptionKey = rootChild.derive(ENCRYPTION_PATH).privKey;\n const publicKey = encryptionKey.toPublicKey();\n const pubKey = counterPartyPublicKey\n ? PublicKey.fromString(counterPartyPublicKey)\n : publicKey;\n return toBase64(electrumEncrypt(toArray(stringData), pubKey, encryptionKey));\n }\n\n /**\n * Decrypt data using this identity's encryption key\n */\n decrypt(ciphertext: string, counterPartyPublicKey?: string): string {\n if (!this.#HDPrivateKey) {\n throw new Error(\"HDPrivateKey not set\");\n }\n const rootChild = this.#HDPrivateKey.derive(this.rootPath);\n const encryptionKey = rootChild.derive(ENCRYPTION_PATH).privKey;\n let pubKey: PublicKey | undefined;\n if (counterPartyPublicKey) {\n pubKey = PublicKey.fromString(counterPartyPublicKey);\n }\n return toUTF8(electrumDecrypt(toArray(ciphertext, \"base64\"), encryptionKey, pubKey));\n }\n\n /**\n * Encrypt data using this identity's encryption key with a seed\n */\n encryptWithSeed(\n stringData: string,\n seed: string,\n counterPartyPublicKey?: string,\n ): string {\n const encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n const publicKey = encryptionKey.toPublicKey();\n const pubKey = counterPartyPublicKey\n ? PublicKey.fromString(counterPartyPublicKey)\n : publicKey;\n return toBase64(electrumEncrypt(toArray(stringData), pubKey, encryptionKey));\n }\n\n /**\n * Decrypt data using this identity's encryption key with a seed\n */\n decryptWithSeed(ciphertext: string, seed: string, counterPartyPublicKey?: string): string {\n const encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n const publicKey = encryptionKey.toPublicKey();\n let pubKey = publicKey;\n if (counterPartyPublicKey) {\n pubKey = PublicKey.fromString(counterPartyPublicKey);\n }\n return toUTF8(electrumDecrypt(toArray(ciphertext, \"base64\"), encryptionKey, pubKey));\n }\n\n private getEncryptionPrivateKeyWithSeed(seed: string) {\n if (!this.#HDPrivateKey) {\n throw new Error(\"HDPrivateKey not set\");\n }\n if (!this.#rootPath) {\n throw new Error(\"rootPath not set\");\n }\n const seedHex = toHex(Hash.sha256(seed, \"utf8\"));\n const seedPath = Utils.getSigningPathFromHex(seedHex);\n const rootChild = this.#HDPrivateKey.derive(this.rootPath);\n return rootChild.derive(seedPath).privKey;\n }\n\n /**\n * Get an attestation string for the given urn for this identity\n *\n * @param urn\n * @returns {string}\n */\n getAttestation(urn: string) {\n const urnHash = Hash.sha256(urn, \"utf8\");\n return `bap:attest:${toHex(urnHash)}:${this.getIdentityKey()}`;\n }\n\n /**\n * Generate and return the attestation hash for the given attribute of this identity\n *\n * @param attribute Attribute name (name, email etc.)\n * @returns {string}\n */\n getAttestationHash(attribute: string) {\n const urn = this.getAttributeUrn(attribute);\n if (!urn) return null;\n\n const attestation = this.getAttestation(urn);\n const attestationHash = Hash.sha256(attestation, \"utf8\");\n\n return toHex(attestationHash);\n }\n\n /**\n * Sign a message with the current signing address of this identity\n *\n * @param message\n * @param signingPath\n * @returns {{address: string, signature: string}}\n */\n signMessage(\n msg: string | Buffer,\n signingPath = \"\",\n ): { address: string; signature: string } {\n if (!this.#HDPrivateKey && !this.#singlePrivateKey) {\n throw new Error(\"No private key available\");\n }\n\n if (this.#HDPrivateKey) {\n if (!this.#currentPath) {\n throw new Error(\"currentPath not set\");\n }\n\n const path = signingPath || this.#currentPath;\n const childPk = this.#HDPrivateKey.derive(path).privKey;\n const address = childPk.toPublicKey().toAddress();\n\n const dummySig = BSM.sign(toArray(msg), childPk, 'raw') as Signature;\n const h = new BigNumber(magicHash(toArray(msg, \"utf8\")));\n const r = dummySig.CalculateRecoveryFactor(\n childPk.toPublicKey(),\n h,\n );\n const signature = (BSM.sign(toArray(msg), childPk, 'raw') as Signature).toCompact(\n r,\n true,\n \"base64\",\n ) as string;\n\n return { address, signature };\n }\n\n // At this point, we know this.#singlePrivateKey is defined because of the first check\n const privateKey = this.#singlePrivateKey as PrivateKey;\n const address = privateKey.toPublicKey().toAddress();\n const dummySig = BSM.sign(toArray(msg), privateKey, 'raw') as Signature;\n const h = new BigNumber(magicHash(toArray(msg, \"utf8\")));\n const r = dummySig.CalculateRecoveryFactor(\n privateKey.toPublicKey(),\n h,\n );\n const signature = (BSM.sign(toArray(msg), privateKey, 'raw') as Signature).toCompact(\n r,\n true,\n \"base64\",\n ) as string;\n\n return { address, signature };\n }\n\n /**\n * Sign a message using a key based on the given string seed\n *\n * This works by creating a private key from the root key of this identity. It will always\n * work with the rootPath / rootKey, to be deterministic. It will not change even if the keys\n * are rotated for this ID.\n *\n * This is used in for instance deterministic login systems, that do not support BAP.\n *\n * @param message\n * @param seed {string} String seed that will be used to generate a path\n */\n signMessageWithSeed(\n message: string,\n seed: string,\n ): { address: string; signature: string } {\n if (!this.#HDPrivateKey) {\n throw new Error(\"HDPrivateKey not set\");\n }\n if (!this.#rootPath) {\n throw new Error(\"rootPath not set\");\n }\n const pathHex = toHex(Hash.sha256(seed, \"utf8\"));\n const path = Utils.getSigningPathFromHex(pathHex);\n\n const HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n const derivedChild = HDPrivateKey.derive(path);\n const address = derivedChild.privKey.toPublicKey().toAddress();\n\n const dummySig = BSM.sign(toArray(message), derivedChild.privKey, 'raw') as Signature;\n\n const h = new BigNumber(magicHash(toArray(message, \"utf8\")));\n const r = dummySig.CalculateRecoveryFactor(\n derivedChild.privKey.toPublicKey(),\n h,\n );\n\n const signature = (BSM.sign(\n toArray(Buffer.from(message)),\n derivedChild.privKey,\n 'raw',\n ) as Signature).toCompact(r, true, \"base64\") as string;\n\n return { address, signature };\n }\n\n /**\n * Sign an op_return hex array with AIP\n * @param opReturn {array}\n * @param signingPath {string}\n * @param outputType {string}\n * @return {[]}\n */\n signOpReturnWithAIP(\n opReturn: string[],\n signingPath = \"\",\n outputType: BufferEncoding = \"hex\",\n ): string[] {\n const aipMessageBuffer = this.getAIPMessageBuffer(opReturn);\n const { address, signature } = this.signMessage(\n aipMessageBuffer,\n signingPath,\n );\n\n return opReturn.concat([\n Buffer.from(\"|\").toString(outputType),\n Buffer.from(AIP_BITCOM_ADDRESS).toString(outputType),\n Buffer.from(\"BITCOIN_ECDSA\").toString(outputType),\n Buffer.from(address).toString(outputType),\n Buffer.from(signature, \"base64\").toString(outputType),\n ]);\n }\n\n /**\n * Construct an AIP buffer from the op return data\n * @param opReturn\n * @returns {Buffer}\n */\n getAIPMessageBuffer(opReturn: string[]): Buffer {\n const buffers = [];\n if (opReturn[0].replace(\"0x\", \"\") !== \"6a\") {\n // include OP_RETURN in constructing the signature buffer\n buffers.push(Buffer.from(\"6a\", \"hex\"));\n }\n for (const op of opReturn) {\n buffers.push(Buffer.from(op.replace(\"0x\", \"\"), \"hex\"));\n }\n // add a trailing \"|\" - this is the AIP way\n buffers.push(Buffer.from(\"|\"));\n\n return Buffer.concat([...buffers] as unknown as Uint8Array[]);\n }\n\n /**\n * Get all signing keys for this identity\n */\n async getIdSigningKeys(): Promise<GetSigningKeysResponse> {\n const signingKeys = await this.getApiData<GetSigningKeysResponse>(\"/signing-keys\", {\n idKey: this.identityKey,\n });\n console.log(\"getIdSigningKeys\", signingKeys);\n\n return signingKeys;\n }\n\n /**\n * Get all attestations for the given attribute\n *\n * @param attribute\n */\n async getAttributeAttestations(attribute: string): Promise<GetAttestationResponse> {\n // This function needs to make a call to a BAP server to get all the attestations for this\n // identity for the given attribute\n const attestationHash = this.getAttestationHash(attribute);\n\n // get all BAP ATTEST records for the given attestationHash\n const attestations = await this.getApiData<GetAttestationResponse>(\"/attestation/get\", {\n hash: attestationHash,\n });\n console.log(\"getAttestations\", attribute, attestationHash, attestations);\n\n return attestations;\n }\n\n /**\n * Import an identity from a JSON object\n *\n * @param identity{{}}\n */\n import(id: Identity | OldIdentity): void {\n this.name = ('name' in id && typeof id.name === 'string' ? id.name : \"ID 1\");\n this.description = id.description || \"\";\n this.identityKey = id.identityKey;\n this.rootAddress = id.rootAddress;\n if ('rootPath' in id && 'currentPath' in id && 'previousPath' in id) {\n this.#rootPath = id.rootPath;\n this.#currentPath = id.currentPath;\n this.#previousPath = id.previousPath;\n }\n this.#idSeed = id.idSeed || \"\";\n this.identityAttributes = this.parseAttributes(id.identityAttributes);\n }\n\n /**\n * Export this identity to a JSON object\n * @returns {{}}\n */\n export(): Identity {\n if (this.#HDPrivateKey) {\n if (!this.#rootPath || !this.#currentPath || !this.#previousPath) {\n throw new Error(\"Required paths are not set\");\n }\n return {\n rootPath: this.#rootPath,\n currentPath: this.#currentPath,\n previousPath: this.#previousPath,\n lastIdPath: this.lastIdPath,\n idSeed: this.#idSeed,\n name: this.name,\n description: this.description,\n identityKey: this.identityKey,\n rootAddress: this.rootAddress,\n identityAttributes: this.identityAttributes\n };\n }\n if (!this.#singlePrivateKey) {\n throw new Error(\"Neither HDPrivateKey nor singlePrivateKey is set\");\n }\n return {\n derivedPrivateKey: this.#singlePrivateKey.toString(),\n idSeed: this.#idSeed,\n name: this.name,\n description: this.description,\n identityKey: this.identityKey,\n rootAddress: this.rootAddress,\n identityAttributes: this.identityAttributes\n };\n }\n}\n\n// export { BAP_ID };\n",
9
+ "import { randomBytes } from 'node:crypto';\nimport type { PathPrefix } from \"./interface.js\";\n\nexport const Utils = {\n /**\n * Helper function for encoding strings to hex\n *\n * @param string\n * @returns {string}\n */\n hexEncode(string: string) {\n return `0x${Buffer.from(string).toString('hex')}`;\n },\n\n /**\n * Helper function for encoding strings to hex\n *\n * @param hexString string\n * @param encoding BufferEncoding\n * @returns {string}\n */\n hexDecode(hexString: string, encoding: BufferEncoding = 'utf8') {\n return Buffer.from(hexString.replace('0x', ''), 'hex').toString(encoding);\n },\n\n /**\n * Helper function to generate a random nonce\n *\n * @returns {string}\n */\n getRandomString(length = 32) {\n return randomBytes(length).toString('hex');\n },\n\n /**\n * Test whether the given string is hex\n *\n * @param value any\n * @returns {boolean}\n */\n isHex(value: string): boolean {\n if (typeof value !== 'string') {\n return false;\n }\n return /^[0-9a-fA-F]+$/.test(value);\n },\n\n /**\n * Get a signing path from a hex number\n *\n * @param hexString {string}\n * @param hardened {boolean} Whether to return a hardened path\n * @returns {string}\n */\n getSigningPathFromHex(hexString: string, hardened = true) {\n // \"m/0/0/1\"\n let signingPath = 'm';\n const signingHex = hexString.match(/.{1,8}/g);\n if (!signingHex) {\n throw new Error('Invalid hex string');\n }\n const maxNumber = 2147483648 - 1; // 0x80000000\n for (const hexNumber of signingHex) {\n let number = Number(`0x${hexNumber}`);\n if (number > maxNumber) number -= maxNumber;\n signingPath += `/${number}${(hardened ? \"'\" : '')}`;\n }\n\n return signingPath;\n },\n\n /**\n * Increment that second to last part from the given part, set the last part to 0\n *\n * @param path string\n * @returns {*}\n */\n getNextIdentityPath(path: string): PathPrefix {\n const pathValues = path.split('/');\n const secondToLastPart = pathValues[pathValues.length - 2];\n\n let hardened = false;\n if (secondToLastPart.match('\\'')) {\n hardened = true;\n }\n\n const nextPath = (Number(secondToLastPart.replace(/[^0-9]/g, '')) + 1).toString();\n pathValues[pathValues.length - 2] = nextPath + (hardened ? '\\'' : '');\n pathValues[pathValues.length - 1] = `0${hardened ? '\\'' : ''}`;\n\n return pathValues.join('/') as PathPrefix;\n },\n\n /**\n * Increment that last part of the given path\n *\n * @param path string\n * @returns {*}\n */\n getNextPath(path: string) {\n const pathValues = path.split('/');\n const lastPart = pathValues[pathValues.length - 1];\n let hardened = false;\n if (lastPart.match('\\'')) {\n hardened = true;\n }\n const nextPath = (Number(lastPart.replace(/[^0-9]/g, '')) + 1).toString();\n pathValues[pathValues.length - 1] = nextPath + (hardened ? '\\'' : '');\n return pathValues.join('/');\n },\n};\n"
10
+ ],
11
+ "mappings": ";AAAA,cAAS,WAAK,eAAmB,WAAW,QAAO,gBAAI,eAA4B,iBCQ5E,IAAM,EAAa,MAAU,EAAgB,EAAkB,EAAgB,IAA8B,CAClH,IAAM,EAAM,GAAG,IAAS,IAWxB,OAViB,MAAM,MAAM,EAAK,CAChC,OAAQ,OACR,QAAS,CACP,eAAgB,kCAChB,QACA,OAAQ,MACV,EACA,KAAM,KAAK,UAAU,CAAO,CAC9B,CAAC,GAEe,KAAK,GAKV,EAAa,CAAC,EAAc,IAA8B,MAAU,EAAa,IAA8B,CAC1H,OAAO,EAAc,EAAK,EAAM,EAAM,CAAK,GC1BtC,IAAM,EAAqB,qCACrB,EAAyB,KAAK,OAAO,KADhB,oCACuC,EAAE,SAAS,KAA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AC7C,MAAO,SAEF,EAAP,EAIJ,MAAO,QAcH,yBAAwB,CAC5B,EACA,EACA,EACA,EACkB,CAIlB,IAF0B,KAAK,gBAAgB,EAAW,EAAS,CAAS,EAG1E,MAAO,GAGT,GAAI,CACF,IAAM,EAAW,MAAM,KAAK,WAAqC,qBAAsB,CACrF,QACA,UACA,YACA,WACF,CAAC,EAGD,GAAI,GAAU,SAAW,WAAa,GAAU,QAAQ,QAAU,GAChE,MAAO,GAGT,MAAO,SACA,EAAP,CAEA,OADA,QAAQ,MAAM,mBAAoB,CAAK,EAChC,SAWL,8BAA6B,CAAC,EAAyD,CAC3F,GAAI,KAAK,yBAAyB,CAAE,EAClC,OAAO,KAAK,WAAqC,qBAAsB,CACrE,IACF,CAAC,EAEH,MAAO,QASH,uBAAsB,CAAC,EAAwD,CACnF,OAAO,KAAK,WAAyC,yBAA0B,CAC7E,SACF,CAAC,OASG,YAAW,CAAC,EAA6C,CAC7D,OAAO,KAAK,WAAgC,gBAAiB,CAC3D,OACF,CAAC,OAQG,uBAAsB,CAAC,EAA0D,CAErF,OAAO,KAAK,WAAmC,gBAAiB,CAC9D,KAAM,CACR,CAAC,EAGL,CAEO,SAAS,EAAmB,CAAC,EAAuC,CACzE,MAAO,sBAAuB,EAGzB,SAAS,CAAY,CAAC,EAAgC,CAC3D,MAAO,aAAc,GAAM,gBAAiB,GAAM,iBAAkB",
12
+ "debugId": "4036FD6C9BC6FFC664756E2164756E21",
13
+ "names": []
14
+ }
@@ -1,2 +1,7 @@
1
- import{Hash as t,PublicKey as e,BSM as r,BigNumber as i,Utils as n,ECIES as o,Signature as s,HD as a}from"@bsv/sdk";import u from"randombytes";function h(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,i=Array(e);r<e;r++)i[r]=t[r];return i}function f(t,e){if(!{}.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}var d=0;function c(t){return"__private_"+d+++"_"+t}function v(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,p(i.key),i)}}function y(t,e,r){return e&&v(t.prototype,e),r&&v(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function l(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(t){if("string"==typeof t)return h(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?h(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function g(){return g=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)({}).hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t},g.apply(null,arguments)}function p(t){var e=function(t){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var r=e.call(t,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==typeof e?e:e+""}var m=function(t){return"0x"+Buffer.from(t).toString("hex")},b=function(t,e){return void 0===e&&(e="utf8"),Buffer.from(t.replace("0x",""),"hex").toString(e)},A=function(t,e){void 0===e&&(e=!0);var r="m",i=t.match(/.{1,8}/g);if(!i)throw new Error("Invalid hex string");for(var n,o=2147483647,s=l(i);!(n=s()).done;){var a=Number("0x"+n.value);a>o&&(a-=o),r+="/"+a+(e?"'":"")}return r},P=function(t){var e=t.split("/"),r=e[e.length-1],i=!1;r.match("'")&&(i=!0);var n=(Number(r.replace(/[^0-9]/g,""))+1).toString();return e[e.length-1]=n+(i?"'":""),e.join("/")},S="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",B="0x"+Buffer.from(S).toString("hex"),K="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva";Buffer.from(K).toString("hex");var I="https://api.sigmaidentity.com/v1",w=2147483647,E="m/424150'/0'/0'",x="m/424150'/"+w+"'/"+w+"'",O=function(t,e){return function(r,i){return function(t,e,r,i){try{return Promise.resolve(fetch(""+r+t,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:i,format:"json"},body:JSON.stringify(e)})).then(function(t){return t.json()})}catch(t){return Promise.reject(t)}}(r,i,t,e)}},j=n.toArray,N=n.toHex,T=n.toBase58,D=n.toUTF8,R=n.toBase64,_=o.electrumDecrypt,k=o.electrumEncrypt,C=r.magicHash,W=/*#__PURE__*/c("HDPrivateKey"),V=/*#__PURE__*/c("BAP_SERVER"),U=/*#__PURE__*/c("BAP_TOKEN"),H=/*#__PURE__*/c("rootPath"),M=/*#__PURE__*/c("previousPath"),F=/*#__PURE__*/c("currentPath"),G=/*#__PURE__*/c("idSeed"),J=/*#__PURE__*/function(){function n(e,r,i){if(void 0===r&&(r={}),void 0===i&&(i=""),Object.defineProperty(this,W,{writable:!0,value:void 0}),Object.defineProperty(this,V,{writable:!0,value:I}),Object.defineProperty(this,U,{writable:!0,value:""}),Object.defineProperty(this,H,{writable:!0,value:void 0}),Object.defineProperty(this,M,{writable:!0,value:void 0}),Object.defineProperty(this,F,{writable:!0,value:void 0}),Object.defineProperty(this,G,{writable:!0,value:void 0}),this.idName=void 0,this.description=void 0,this.rootAddress=void 0,this.identityKey=void 0,this.identityAttributes=void 0,this.getApiData=void 0,f(this,G)[G]=i,i){var n=N(t.sha256(i,"utf8")),o=A(n);f(this,W)[W]=e.derive(o)}else f(this,W)[W]=e;this.idName="ID 1",this.description="",f(this,H)[H]=E+"/0/0/0",f(this,M)[M]=E+"/0/0/0",f(this,F)[F]=E+"/0/0/1";var s=f(this,W)[W].derive(f(this,H)[H]);this.rootAddress=s.privKey.toPublicKey().toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress);var a=g({},r);this.identityAttributes=this.parseAttributes(a),this.getApiData=O(f(this,V)[V],f(this,U)[U])}var o=n.prototype;return o.deriveIdentityKey=function(e){var r=N(t.sha256(e,"utf8"));return T(t.ripemd160(r,"hex"))},o.parseAttributes=function(t){if("string"==typeof t)return this.parseStringUrns(t);for(var e in t)if(!t[e].value||!t[e].nonce)throw new Error("Invalid identity attribute");return t||{}},o.parseStringUrns=function(t){for(var e,r={},i=l(t.replace(/^\s+/g,"").replace(/\r/gm,"").split("\n"));!(e=i()).done;){var n=e.value.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");"urn"===n[0]&&"bap"===n[1]&&"id"===n[2]&&n[3]&&n[4]&&n[5]&&(r[n[3]]={value:n[4],nonce:n[5]})}return r},o.getIdentityKey=function(){return this.identityKey},o.getAttributes=function(){return this.identityAttributes},o.getAttribute=function(t){return this.identityAttributes[t]?this.identityAttributes[t]:null},o.setAttribute=function(t,e){e&&(this.identityAttributes[t]?this.identityAttributes[t].value=e:this.addAttribute(t,e))},o.unsetAttribute=function(t){delete this.identityAttributes[t]},o.getAttributeUrns=function(){var t="";for(var e in this.identityAttributes){var r=this.getAttributeUrn(e);r&&(t+=r+"\n")}return t},o.getAttributeUrn=function(t){var e=this.identityAttributes[t];return e?"urn:bap:id:"+t+":"+e.value+":"+e.nonce:null},o.addAttribute=function(t,e,r){void 0===r&&(r="");var i,n=r;r||(void 0===i&&(i=32),n=u(i).toString("hex")),this.identityAttributes[t]={value:e,nonce:n}},o.getRootPath=function(){return f(this,H)[H]},o.incrementPath=function(){this.currentPath=P(this.currentPath)},o.validatePath=function(t){if(t.match(/\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?/)){var e=t.split("/");if(7===e.length&&Number(e[1].replace("'",""))<=w&&Number(e[2].replace("'",""))<=w&&Number(e[3].replace("'",""))<=w&&Number(e[4].replace("'",""))<=w&&Number(e[5].replace("'",""))<=w&&Number(e[6].replace("'",""))<=w)return!0}return!1},o.getInitialIdTransaction=function(){return this.getIdTransaction(f(this,H)[H])},o.getIdTransaction=function(t){if(void 0===t&&(t=""),f(this,F)[F]===f(this,H)[H])throw new Error("Current path equals rootPath. ID was probably not initialized properly");var e=[Buffer.from(S).toString("hex"),Buffer.from("ID").toString("hex"),Buffer.from(this.identityKey).toString("hex"),Buffer.from(this.getCurrentAddress()).toString("hex")];return this.signOpReturnWithAIP(e,t||f(this,M)[M])},o.getAddress=function(t){return f(this,W)[W].derive(t).privKey.toPublicKey().toAddress()},o.getCurrentAddress=function(){return this.getAddress(f(this,F)[F])},o.getEncryptionPublicKey=function(){return f(this,W)[W].derive(f(this,H)[H]).derive(x).privKey.toPublicKey().toString()},o.getEncryptionPublicKeyWithSeed=function(t){return this.getEncryptionPrivateKeyWithSeed(t).toPublicKey().toString("hex")},o.encrypt=function(t,r){var i=f(this,W)[W].derive(f(this,H)[H]).derive(x).privKey.toPublicKey(),n=r?e.fromString(r):i;return R(k(j(t),n,null))},o.decrypt=function(t,r){var i=f(this,W)[W].derive(f(this,H)[H]).derive(x).privKey,n=void 0;return r&&(n=e.fromString(r)),D(_(j(t,"base64"),i,n))},o.encryptWithSeed=function(t,r,i){var n=this.getEncryptionPrivateKeyWithSeed(r),o=n.toPublicKey(),s=i?e.fromString(i):o;return R(k(j(t),s,n))},o.decryptWithSeed=function(t,r,i){var n=this.getEncryptionPrivateKeyWithSeed(r),o=void 0;return i&&(o=e.fromString(i)),D(_(j(t,"base64"),n,o))},o.getEncryptionPrivateKeyWithSeed=function(e){var r=N(t.sha256(e,"utf8")),i=A(r);return f(this,W)[W].derive(f(this,H)[H]).derive(i).privKey},o.getAttestation=function(e){var r=t.sha256(e,"utf8");return"bap:attest:"+N(r)+":"+this.getIdentityKey()},o.getAttestationHash=function(e){var r=this.getAttributeUrn(e);if(!r)return null;var i=this.getAttestation(r),n=t.sha256(i,"utf8");return N(n)},o.signMessage=function(t,e){var n;void 0===e&&(e=""),n=t instanceof Buffer?t:Buffer.from(t);var o=e||f(this,F)[F],s=f(this,W)[W].derive(o).privKey,a=s.toAddress(),u=r.sign(j(t),s,"raw"),h=new i(C(j(t,"utf8"))),d=u.CalculateRecoveryFactor(s.toPublicKey(),h);return{address:a,signature:r.sign(j(n),s,"raw").toCompact(d,!0,"base64")}},o.signMessageWithSeed=function(e,n){var o=N(t.sha256(n,"utf8")),s=A(o),a=f(this,W)[W].derive(f(this,H)[H]).derive(s),u=a.privKey.toPublicKey().toAddress(),h=r.sign(j(e),a.privKey,"raw"),d=new i(C(j(e,"utf8"))),c=h.CalculateRecoveryFactor(a.privKey.toPublicKey(),d);return{address:u,signature:r.sign(j(Buffer.from(e)),a.privKey,"raw").toCompact(c,!0,"base64")}},o.signOpReturnWithAIP=function(t,e,r){void 0===e&&(e=""),void 0===r&&(r="hex");var i=this.getAIPMessageBuffer(t),n=this.signMessage(i,e),o=n.address,s=n.signature;return t.concat([Buffer.from("|").toString(r),Buffer.from(K).toString(r),Buffer.from("BITCOIN_ECDSA").toString(r),Buffer.from(o).toString(r),Buffer.from(s,"base64").toString(r)])},o.getAIPMessageBuffer=function(t){var e=[];"6a"!==t[0].replace("0x","")&&e.push(Buffer.from("6a","hex"));for(var r,i=l(t);!(r=i()).done;)e.push(Buffer.from(r.value.replace("0x",""),"hex"));return e.push(Buffer.from("|")),Buffer.concat([].concat(e))},o.getIdSigningKeys=function(){try{return Promise.resolve(this.getApiData("/signing-keys",{idKey:this.identityKey})).then(function(t){return console.log("getIdSigningKeys",t),t})}catch(t){return Promise.reject(t)}},o.getAttributeAttestations=function(t){try{var e=this.getAttestationHash(t);return Promise.resolve(this.getApiData("/attestation/get",{hash:e})).then(function(r){return console.log("getAttestations",t,e,r),r})}catch(t){return Promise.reject(t)}},o.import=function(t){this.idName=t.name,this.description=t.description||"",this.identityKey=t.identityKey,f(this,H)[H]=t.rootPath,this.rootAddress=t.rootAddress,f(this,M)[M]=t.previousPath,f(this,F)[F]=t.currentPath,f(this,G)[G]=t.idSeed||"",this.identityAttributes=this.parseAttributes(t.identityAttributes)},o.export=function(){return{name:this.idName,description:this.description,identityKey:this.identityKey,rootPath:f(this,H)[H],rootAddress:this.rootAddress,previousPath:f(this,M)[M],currentPath:f(this,F)[F],idSeed:f(this,G)[G],identityAttributes:this.getAttributes(),lastIdPath:""}},y(n,[{key:"BAP_SERVER",get:function(){return f(this,V)[V]},set:function(t){f(this,V)[V]=t}},{key:"BAP_TOKEN",get:function(){return f(this,U)[U]},set:function(t){f(this,U)[U]=t}},{key:"rootPath",get:function(){return f(this,H)[H]},set:function(t){if(f(this,W)[W]){var e=t;if(t.split("/").length<5&&(e=""+E+t),!this.validatePath(e))throw new Error("invalid signing path given "+e);f(this,H)[H]=e;var r=f(this,W)[W].derive(e);this.rootAddress=r.pubKey.toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress),f(this,M)[M]=e,f(this,F)[F]=e}}},{key:"currentPath",get:function(){return f(this,F)[F]},set:function(t){var e=t;if(t.split("/").length<5&&(e=""+E+t),!this.validatePath(e))throw new Error("invalid signing path given");f(this,M)[M]=f(this,F)[F],f(this,F)[F]=e}},{key:"previousPath",get:function(){return f(this,M)[M]}},{key:"idSeed",get:function(){return f(this,G)[G]}}])}(),q=n.toArray,z=n.toUTF8,L=n.toBase64,$=o.electrumEncrypt,Q=o.electrumDecrypt,X=/*#__PURE__*/c("HDPrivateKey"),Y=/*#__PURE__*/c("ids"),Z=/*#__PURE__*/c("BAP_SERVER"),tt=/*#__PURE__*/c("BAP_TOKEN"),et=/*#__PURE__*/c("lastIdPath"),rt=/*#__PURE__*/function(){function t(t,e,r){if(void 0===e&&(e=""),void 0===r&&(r=""),Object.defineProperty(this,X,{writable:!0,value:void 0}),Object.defineProperty(this,Y,{writable:!0,value:{}}),Object.defineProperty(this,Z,{writable:!0,value:I}),Object.defineProperty(this,tt,{writable:!0,value:""}),Object.defineProperty(this,et,{writable:!0,value:""}),this.getApiData=void 0,!t)throw new Error("No HDPrivateKey given");f(this,X)[X]=a.fromString(t),e&&(f(this,tt)[tt]=e),r&&(f(this,Z)[Z]=r),this.getApiData=O(f(this,Z)[Z],f(this,tt)[tt])}var e=t.prototype;return e.getPublicKey=function(t){return void 0===t&&(t=""),t?f(this,X)[X].derive(t).pubKey.toString():f(this,X)[X].pubKey.toString()},e.getHdPublicKey=function(t){return void 0===t&&(t=""),t?f(this,X)[X].derive(t).toPublic().toString():f(this,X)[X].toPublic().toString()},e.checkIdBelongs=function(t){if(f(this,X)[X].derive(t.rootPath).pubKey.toAddress()!==t.rootAddress)throw new Error("ID does not belong to this private key");return!0},e.listIds=function(){return Object.keys(f(this,Y)[Y])},e.newId=function(t,e,r){var i;void 0===e&&(e={}),void 0===r&&(r=""),i=t||this.getNextValidPath();var n=new J(f(this,X)[X],e,r);n.BAP_SERVER=f(this,Z)[Z],n.BAP_TOKEN=f(this,tt)[tt],n.rootPath=i,n.currentPath=P(i);var o=n.getIdentityKey();return f(this,Y)[Y][o]=n,f(this,et)[et]=i,f(this,Y)[Y][o]},e.removeId=function(t){delete f(this,Y)[Y][t]},e.getNextValidPath=function(){return f(this,et)[et]?function(t){var e=t.split("/"),r=e[e.length-2],i=!1;r.match("'")&&(i=!0);var n=(Number(r.replace(/[^0-9]/g,""))+1).toString();return e[e.length-2]=n+(i?"'":""),e[e.length-1]="0"+(i?"'":""),e.join("/")}(f(this,et)[et]):"/0'/"+Object.keys(f(this,Y)[Y]).length+"'/0'"},e.getId=function(t){return f(this,Y)[Y][t]||null},e.setId=function(t){this.checkIdBelongs(t),f(this,Y)[Y][t.getIdentityKey()]=t},e.importIds=function(t,e){if(void 0===e&&(e=!0),e&&"string"==typeof t)this.importEncryptedIds(t);else{var r=t;if(!r.lastIdPath)throw new Error("ID cannot be imported as it is not complete");if(!r.ids)throw new Error("ID data is not in the correct format: "+t);for(var i,n=t.lastIdPath,o=l(r.ids);!(i=o()).done;){var s=i.value;if(!s.identityKey||!s.identityAttributes||!s.rootAddress)throw new Error("ID cannot be imported as it is not complete");var a=new J(f(this,X)[X],{},s.idSeed);a.BAP_SERVER=f(this,Z)[Z],a.BAP_TOKEN=f(this,tt)[tt],a.import(s),""===n&&(n=a.currentPath),this.checkIdBelongs(a),f(this,Y)[Y][a.getIdentityKey()]=a}f(this,et)[et]=n}},e.importEncryptedIds=function(t){var e=this.decrypt(t),r=JSON.parse(e);if(Array.isArray(r))return console.log("Importing old format:\n",r),void this.importOldIds(r);if("object"!=typeof r)throw new Error("decrypted, but found unrecognized identities format");this.importIds(r,!1)},e.importOldIds=function(t){for(var e,r=l(t);!(e=r()).done;){var i=e.value,n=new J(f(this,X)[X],{},i.idSeed);n.BAP_SERVER=f(this,Z)[Z],n.BAP_TOKEN=f(this,tt)[tt],n.import(i),this.checkIdBelongs(n),f(this,Y)[Y][n.getIdentityKey()]=n,f(this,et)[et]=n.currentPath}},e.exportIds=function(t){void 0===t&&(t=!0);var e={lastIdPath:f(this,et)[et],ids:[]};for(var r in f(this,Y)[Y])e.ids.push(f(this,Y)[Y][r].export());return t?this.encrypt(JSON.stringify(e)):e},e.encrypt=function(t){var e=f(this,X)[X].derive(x);return L($(q(t),e.pubKey,null))},e.decrypt=function(t){var e=f(this,X)[X].derive(x);return z(Q(q(t,"base64"),e.privKey))},e.signAttestationWithAIP=function(t,e,r,i){void 0===r&&(r=0),void 0===i&&(i="");var n=this.getId(e);if(!n)throw new Error("Could not find identity to attest with");var o=this.getAttestationBuffer(t,r,i),s=n.signMessage(o);return this.createAttestationTransaction(t,r,s.address,s.signature,i)},e.verifyAttestationWithAIP=function(t){if(!Array.isArray(t)||"0x6a"!==t[0]||t[1]!==B)throw new Error("Not a valid BAP transaction");var e="0x44415441"===t[7]?5:0,r={type:b(t[2]),hash:b(t[3]),sequence:b(t[4]),signingProtocol:b(t[7+e]),signingAddress:b(t[8+e]),signature:b(t[9+e],"base64")};e&&t[3]===t[8]&&(r.data=b(t[9]));try{for(var i=[],n=0;n<6+e;n++)i.push(Buffer.from(t[n].replace("0x",""),"hex"));var o=Buffer.concat(i);r.verified=this.verifySignature(o,r.signingAddress,r.signature)}catch(t){r.verified=!1}return r},e.createAttestationTransaction=function(t,e,r,i,n){void 0===n&&(n="");var o=["0x6a",m(S)];return o.push(m("ATTEST")),o.push(m(t)),o.push(m(""+e)),o.push("0x7c"),n&&(o.push(m(S)),o.push(m("DATA")),o.push(m(t)),o.push(m(n)),o.push("0x7c")),o.push(m(K)),o.push(m("BITCOIN_ECDSA")),o.push(m(r)),o.push("0x"+Buffer.from(i,"base64").toString("hex")),o},e.getAttestationBuffer=function(t,e,r){void 0===e&&(e=0),void 0===r&&(r="");var i=Buffer.from("");return r&&(i=Buffer.concat([Buffer.from(S),Buffer.from("DATA"),Buffer.from(t),Buffer.from(r),Buffer.from("7c","hex")])),Buffer.concat([Buffer.from("6a","hex"),Buffer.from(S),Buffer.from("ATTEST"),Buffer.from(t),Buffer.from(""+e),Buffer.from("7c","hex"),i])},e.verifySignature=function(t,e,n){for(var o,a=Buffer.isBuffer(t)?t:Buffer.from(t),u=s.fromCompact(n,"base64"),h=q(a.toString("hex"),"hex"),f=0;f<4;f++)try{if(o=u.RecoverPublicKey(f,new i(r.magicHash(h))),r.verify(h,u,o)&&o.toAddress()===e)return!0}catch(t){}return!1},e.verifyChallengeSignature=function(t,e,r,i){try{var n,o=this,s=function(){if(o.verifySignature(r,e,i))return Promise.resolve(o.getApiData("/attestation/valid",{idKey:t,challenge:r,signature:i})).then(function(t){return n=1,!!t&&t.valid})}();return Promise.resolve(s&&s.then?s.then(function(t){return!!n&&t}):!!n&&s)}catch(t){return Promise.reject(t)}},e.isValidAttestationTransaction=function(t){try{return this.verifyAttestationWithAIP(t)?Promise.resolve(this.getApiData("/attestation/valid",{tx:t})):Promise.resolve(!1)}catch(t){return Promise.reject(t)}},e.getIdentityFromAddress=function(t){try{return Promise.resolve(this.getApiData("/identity/from-address",{address:t}))}catch(t){return Promise.reject(t)}},e.getIdentity=function(t){try{return Promise.resolve(this.getApiData("/identity/get",{idKey:t}))}catch(t){return Promise.reject(t)}},e.getAttestationsForHash=function(t){try{return Promise.resolve(this.getApiData("/attestations",{hash:t}))}catch(t){return Promise.reject(t)}},y(t,[{key:"lastIdPath",get:function(){return f(this,et)[et]}},{key:"BAP_SERVER",get:function(){return f(this,Z)[Z]},set:function(t){for(var e in f(this,Z)[Z]=t,f(this,Y)[Y])f(this,Y)[Y][e].BAP_SERVER=t}},{key:"BAP_TOKEN",get:function(){return f(this,tt)[tt]},set:function(t){for(var e in f(this,tt)[tt]=t,f(this,Y)[Y])f(this,Y)[Y][e].BAP_TOKEN=t}}])}();export{rt as BAP,J as BAP_ID};
2
- //# sourceMappingURL=index.module.js.map
1
+ // @bun
2
+ import{BSM as N,Utils as d,BigNumber as s,ECIES as r,HD as v,PrivateKey as g,Signature as i}from"@bsv/sdk";var P=async(j,$,q,J)=>{let Q=`${q}${j}`;return(await fetch(Q,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:J,format:"json"},body:JSON.stringify($)})).json()},M=(j,$)=>async(q,J)=>{return P(q,J,j,$)};var Y="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",A=`0x${Buffer.from("1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT").toString("hex")}`,E="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva",Jj=`0x${Buffer.from("15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva").toString("hex")}`,V="https://api.sigmaidentity.com/v1",F=2147483647,U="m/424150'/0'/0'",G="m/424150'/2147483647'/2147483647'";import{BSM as C,Utils as o,BigNumber as B,ECIES as y,HD as n,Hash as X,PublicKey as x}from"@bsv/sdk";import{randomBytes as h}from"crypto";var W={hexEncode(j){return`0x${Buffer.from(j).toString("hex")}`},hexDecode(j,$="utf8"){return Buffer.from(j.replace("0x",""),"hex").toString($)},getRandomString(j=32){return h(j).toString("hex")},isHex(j){if(typeof j!=="string")return!1;return/^[0-9a-fA-F]+$/.test(j)},getSigningPathFromHex(j,$=!0){let q="m",J=j.match(/.{1,8}/g);if(!J)throw new Error("Invalid hex string");let Q=2147483647;for(let z of J){let Z=Number(`0x${z}`);if(Z>Q)Z-=Q;q+=`/${Z}${$?"'":""}`}return q},getNextIdentityPath(j){let $=j.split("/"),q=$[$.length-2],J=!1;if(q.match("'"))J=!0;let Q=(Number(q.replace(/[^0-9]/g,""))+1).toString();return $[$.length-2]=Q+(J?"'":""),$[$.length-1]=`0${J?"'":""}`,$.join("/")},getNextPath(j){let $=j.split("/"),q=$[$.length-1],J=!1;if(q.match("'"))J=!0;let Q=(Number(q.replace(/[^0-9]/g,""))+1).toString();return $[$.length-1]=Q+(J?"'":""),$.join("/")}};var{toArray:w,toHex:f,toBase58:u,toUTF8:I,toBase64:S}=o,{electrumDecrypt:m,electrumEncrypt:H}=y,{magicHash:T}=C;class R{#j;#z;#$;#q;#J;lastIdPath="";#Q;name;description;identityKey;rootAddress;identityAttributes;BAP_SERVER_;BAP_TOKEN_;getApiData;constructor(j,$={},q=""){if(this.#Q=q,this.BAP_SERVER_=V,this.BAP_TOKEN_="",this.getApiData=M(this.BAP_SERVER_,this.BAP_TOKEN_),this.name="ID 1",this.description="",j instanceof n){if(this.#j=j,q){let z=f(X.sha256(q,"utf8")),Z=W.getSigningPathFromHex(z);this.#j=j.derive(Z)}this.rootPath=`${U}/0/0/0`,this.#J=this.rootPath,this.#q=`${U}/0/0/1`;let Q=this.#j.derive(this.rootPath);this.rootAddress=Q.privKey.toPublicKey().toAddress()}else this.#z=j,this.rootAddress=j.toPublicKey().toAddress();this.identityKey=this.deriveIdentityKey(this.rootAddress);let J=JSON.parse(JSON.stringify($));this.identityAttributes=this.parseAttributes(J)}get BAP_SERVER(){return this.BAP_SERVER_}set BAP_SERVER(j){this.BAP_SERVER_=j,this.getApiData=M(this.BAP_SERVER_,this.BAP_TOKEN_)}get BAP_TOKEN(){return this.BAP_TOKEN_}set BAP_TOKEN(j){this.BAP_TOKEN_=j,this.getApiData=M(this.BAP_SERVER_,this.BAP_TOKEN_)}deriveIdentityKey(j){let $=f(X.sha256(j,"utf8"));return u(X.ripemd160($,"hex"))}parseAttributes(j){if(typeof j==="string")return this.parseStringUrns(j);for(let $ in j)if(!j[$].value||!j[$].nonce)throw new Error("Invalid identity attribute");return j||{}}parseStringUrns(j){let $={},q=j.replace(/^\s+/g,"").replace(/\r/gm,"").split(`
3
+ `);for(let J of q){let z=J.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(z[0]==="urn"&&z[1]==="bap"&&z[2]==="id"&&z[3]&&z[4]&&z[5])$[z[3]]={value:z[4],nonce:z[5]}}return $}getIdentityKey(){return this.identityKey}getAttributes(){return this.identityAttributes}getAttribute(j){if(this.identityAttributes[j])return this.identityAttributes[j];return null}setAttribute(j,$){if(!$)return;if(this.identityAttributes[j])this.updateExistingAttribute(j,$);else this.createNewAttribute(j,$)}updateExistingAttribute(j,$){if(typeof $==="string"){this.identityAttributes[j].value=$;return}if(this.identityAttributes[j].value=$.value||"",$.nonce)this.identityAttributes[j].nonce=$.nonce}createNewAttribute(j,$){if(typeof $==="string"){this.addAttribute(j,$);return}this.addAttribute(j,$.value||"",$.nonce)}unsetAttribute(j){delete this.identityAttributes[j]}getAttributeUrns(){let j="";for(let $ in this.identityAttributes){let q=this.getAttributeUrn($);if(q)j+=`${q}
4
+ `}return j}getAttributeUrn(j){let $=this.identityAttributes[j];if($)return`urn:bap:id:${j}:${$.value}:${$.nonce}`;return null}addAttribute(j,$,q=""){let J=q;if(!q)J=W.getRandomString();this.identityAttributes[j]={value:$,nonce:J}}set rootPath(j){if(this.#j){let $=j;if(j.split("/").length<5)$=`${U}${j}`;if(!this.validatePath($))throw new Error(`invalid signing path given ${$}`);this.#$=$;let q=this.#j.derive($);this.rootAddress=q.pubKey.toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress),this.#J=$,this.#q=$}}get rootPath(){if(!this.#$)throw new Error("rootPath not set");return this.#$}getRootPath(){if(!this.#$)throw new Error("rootPath not set");return this.#$}set currentPath(j){let $=j;if(j.split("/").length<5)$=`${U}${j}`;if(!this.validatePath($))throw new Error("invalid signing path given");this.#J=this.#q,this.#q=$}get currentPath(){if(!this.#q)throw new Error("currentPath not set");return this.#q}get previousPath(){if(!this.#J)throw new Error("previousPath not set");return this.#J}get idSeed(){return this.#Q}incrementPath(){this.currentPath=W.getNextPath(this.currentPath)}validatePath(j){if(j.match(/\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?/)){let $=j.split("/");if($.length===7&&Number($[1].replace("'",""))<=F&&Number($[2].replace("'",""))<=F&&Number($[3].replace("'",""))<=F&&Number($[4].replace("'",""))<=F&&Number($[5].replace("'",""))<=F&&Number($[6].replace("'",""))<=F)return!0}return!1}getInitialIdTransaction(){return this.getIdTransaction(this.#$)}getIdTransaction(j=""){if(this.#q===this.#$)throw new Error("Current path equals rootPath. ID was probably not initialized properly");let $=[Buffer.from(Y).toString("hex"),Buffer.from("ID").toString("hex"),Buffer.from(this.identityKey).toString("hex"),Buffer.from(this.getCurrentAddress()).toString("hex")];return this.signOpReturnWithAIP($,j||this.#J)}getAddress(j){if(!this.#j)throw new Error("HDPrivateKey not set");return this.#j.derive(j).privKey.toPublicKey().toAddress()}getCurrentAddress(){if(!this.#q){if(!this.#z)throw new Error("currentPath not set");return this.#z.toPublicKey().toAddress()}return this.getAddress(this.#q)}getEncryptionPublicKey(){if(this.#j)return this.#j.derive(this.rootPath).derive(G).pubKey.toString();if(!this.#z)throw new Error("No private key available for encryption");return this.#z.toPublicKey().toString()}getEncryptionPublicKeyWithSeed(j){return this.getEncryptionPrivateKeyWithSeed(j).toPublicKey().toString()}encrypt(j,$){if(!this.#j)throw new Error("HDPrivateKey not set");let J=this.#j.derive(this.rootPath).derive(G).privKey,Q=J.toPublicKey(),z=$?x.fromString($):Q;return S(H(w(j),z,J))}decrypt(j,$){if(!this.#j)throw new Error("HDPrivateKey not set");let J=this.#j.derive(this.rootPath).derive(G).privKey,Q;if($)Q=x.fromString($);return I(m(w(j,"base64"),J,Q))}encryptWithSeed(j,$,q){let J=this.getEncryptionPrivateKeyWithSeed($),Q=J.toPublicKey(),z=q?x.fromString(q):Q;return S(H(w(j),z,J))}decryptWithSeed(j,$,q){let J=this.getEncryptionPrivateKeyWithSeed($),z=J.toPublicKey();if(q)z=x.fromString(q);return I(m(w(j,"base64"),J,z))}getEncryptionPrivateKeyWithSeed(j){if(!this.#j)throw new Error("HDPrivateKey not set");if(!this.#$)throw new Error("rootPath not set");let $=f(X.sha256(j,"utf8")),q=W.getSigningPathFromHex($);return this.#j.derive(this.rootPath).derive(q).privKey}getAttestation(j){let $=X.sha256(j,"utf8");return`bap:attest:${f($)}:${this.getIdentityKey()}`}getAttestationHash(j){let $=this.getAttributeUrn(j);if(!$)return null;let q=this.getAttestation($),J=X.sha256(q,"utf8");return f(J)}signMessage(j,$=""){if(!this.#j&&!this.#z)throw new Error("No private key available");if(this.#j){if(!this.#q)throw new Error("currentPath not set");let k=$||this.#q,O=this.#j.derive(k).privKey,_=O.toPublicKey().toAddress(),c=C.sign(w(j),O,"raw"),b=new B(T(w(j,"utf8"))),l=c.CalculateRecoveryFactor(O.toPublicKey(),b),p=C.sign(w(j),O,"raw").toCompact(l,!0,"base64");return{address:_,signature:p}}let q=this.#z,J=q.toPublicKey().toAddress(),Q=C.sign(w(j),q,"raw"),z=new B(T(w(j,"utf8"))),Z=Q.CalculateRecoveryFactor(q.toPublicKey(),z),L=C.sign(w(j),q,"raw").toCompact(Z,!0,"base64");return{address:J,signature:L}}signMessageWithSeed(j,$){if(!this.#j)throw new Error("HDPrivateKey not set");if(!this.#$)throw new Error("rootPath not set");let q=f(X.sha256($,"utf8")),J=W.getSigningPathFromHex(q),z=this.#j.derive(this.#$).derive(J),Z=z.privKey.toPublicKey().toAddress(),L=C.sign(w(j),z.privKey,"raw"),k=new B(T(w(j,"utf8"))),O=L.CalculateRecoveryFactor(z.privKey.toPublicKey(),k),_=C.sign(w(Buffer.from(j)),z.privKey,"raw").toCompact(O,!0,"base64");return{address:Z,signature:_}}signOpReturnWithAIP(j,$="",q="hex"){let J=this.getAIPMessageBuffer(j),{address:Q,signature:z}=this.signMessage(J,$);return j.concat([Buffer.from("|").toString(q),Buffer.from(E).toString(q),Buffer.from("BITCOIN_ECDSA").toString(q),Buffer.from(Q).toString(q),Buffer.from(z,"base64").toString(q)])}getAIPMessageBuffer(j){let $=[];if(j[0].replace("0x","")!=="6a")$.push(Buffer.from("6a","hex"));for(let q of j)$.push(Buffer.from(q.replace("0x",""),"hex"));return $.push(Buffer.from("|")),Buffer.concat([...$])}async getIdSigningKeys(){let j=await this.getApiData("/signing-keys",{idKey:this.identityKey});return console.log("getIdSigningKeys",j),j}async getAttributeAttestations(j){let $=this.getAttestationHash(j),q=await this.getApiData("/attestation/get",{hash:$});return console.log("getAttestations",j,$,q),q}import(j){if(this.name="name"in j&&typeof j.name==="string"?j.name:"ID 1",this.description=j.description||"",this.identityKey=j.identityKey,this.rootAddress=j.rootAddress,"rootPath"in j&&"currentPath"in j&&"previousPath"in j)this.#$=j.rootPath,this.#q=j.currentPath,this.#J=j.previousPath;this.#Q=j.idSeed||"",this.identityAttributes=this.parseAttributes(j.identityAttributes)}export(){if(this.#j){if(!this.#$||!this.#q||!this.#J)throw new Error("Required paths are not set");return{rootPath:this.#$,currentPath:this.#q,previousPath:this.#J,lastIdPath:this.lastIdPath,idSeed:this.#Q,name:this.name,description:this.description,identityKey:this.identityKey,rootAddress:this.rootAddress,identityAttributes:this.identityAttributes}}if(!this.#z)throw new Error("Neither HDPrivateKey nor singlePrivateKey is set");return{derivedPrivateKey:this.#z.toString(),idSeed:this.#Q,name:this.name,description:this.description,identityKey:this.identityKey,rootAddress:this.rootAddress,identityAttributes:this.identityAttributes}}}var{toArray:D,toUTF8:a,toBase64:e}=d,{electrumEncrypt:t,electrumDecrypt:jj}=r;class $j{#j;#z="";get lastIdPath(){return this.#z}#$={};#q=V;#J="";getApiData;constructor(j,$){if(!j)throw new Error("Key is required for BAP initialization");if(typeof j==="string")try{this.#j=v.fromString(j)}catch(q){try{this.#j=g.fromWif(j)}catch(J){throw new Error("Invalid private key format")}}else this.#j=j;if($!==void 0)this.#J=$;this.getApiData=M(this.#q,this.#J)}isHD(j){return"depth"in j&&"parentFingerPrint"in j}getPublicKey(j=""){if(this.isHD(this.#j)){if(j!=="")return this.#j.derive(j).pubKey.toString();return this.#j.pubKey.toString()}return this.#j.toPublicKey().toString()}getHdPublicKey(j=""){if(!this.isHD(this.#j))throw new Error("Not an HD key");if(j)return this.#j.derive(j).toPublic().toString();return this.#j.toPublic().toString()}set BAP_SERVER(j){this.#q=j;for(let $ in this.#$)this.#$[$].BAP_SERVER=j}get BAP_SERVER(){return this.#q}set BAP_TOKEN(j){this.#J=j;for(let $ in this.#$)this.#$[$].BAP_TOKEN=j}get BAP_TOKEN(){return this.#J}checkIdBelongs(j){if(!this.isHD(this.#j))throw new Error("checkIdBelongs can only be used in HD mode");if(this.#j.derive(j.rootPath).pubKey.toAddress()!==j.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#$)}newId(j,$={},q=""){let J;if(!j)J=this.getNextValidPath();else J=j;let Q=new R(this.#j,$,q);Q.BAP_SERVER=this.#q,Q.BAP_TOKEN=this.#J,Q.rootPath=J,Q.currentPath=W.getNextPath(J);let z=Q.getIdentityKey();return this.#$[z]=Q,this.#z=J,this.#$[z]}removeId(j){delete this.#$[j]}getNextValidPath(){if(this.#z)return W.getNextIdentityPath(this.#z);return`/0'/${Object.keys(this.#$).length}'/0'`}getId(j){return this.#$[j]||null}setId(j){this.checkIdBelongs(j),this.#$[j.getIdentityKey()]=j}importIds(j,$=!0){if($&&typeof j==="string"){this.importEncryptedIds(j);return}let q=j;if(!q.lastIdPath||!Array.isArray(q.ids))throw new Error("ID data is not in the correct format");let J=!(this.#j instanceof v);if(J&&q.ids.length>1)throw new Error("Cannot import multiple IDs in single key mode");let Q=q.lastIdPath;for(let z of q.ids){if(!z.identityKey||!z.identityAttributes||!z.rootAddress)throw new Error("ID cannot be imported as it is not complete");let Z;if(qj(z)){if(!J)throw new Error("Cannot import single key identity in HD mode");let L=g.fromString(z.derivedPrivateKey,"hex");Z=new R(L,z.identityAttributes,z.idSeed)}else if(K(z)){if(J)throw new Error("Cannot import HD identity in single key mode");let L=this.#j;Z=new R(L,z.identityAttributes,z.idSeed),Z.rootPath=z.rootPath,Z.currentPath=z.currentPath}else throw new Error("Invalid identity format");if(Z.BAP_SERVER=this.#q,Z.BAP_TOKEN=this.#J,Z.import(z),!J&&K(z)){if(Q==="")Q=z.currentPath;this.checkIdBelongs(Z)}this.#$[Z.getIdentityKey()]=Z}if(!J)this.#z=Q}importEncryptedIds(j){let $=this.decrypt(j),q=JSON.parse($);if(Array.isArray(q)){console.log(`Importing old format:
5
+ `,q),this.importOldIds(q);return}if(typeof q!=="object")throw new Error("decrypted, but found unrecognized identities format");this.importIds(q,!1)}importOldIds(j){for(let $ of j){let q=new R(this.#j,{},$.idSeed??"");if(q.BAP_SERVER=this.#q,q.BAP_TOKEN=this.#J,q.import($),this.checkIdBelongs(q),this.#$[q.getIdentityKey()]=q,"currentPath"in $&&typeof $.currentPath==="string")this.#z=$.currentPath;else this.#z=""}}exportIds(j=!0,$){let q={lastIdPath:this.#z,ids:[]},J=$||Object.keys(this.#$);for(let Q of J){if(!this.#$[Q])throw new Error(`Identity ${Q} not found`);q.ids.push(this.#$[Q].export())}if(j)return this.encrypt(JSON.stringify(q));return q}encrypt(j){if(!this.isHD(this.#j))throw new Error("Encryption not supported in single key mode");let $=this.#j.derive(G);return e(t(D(j),$.pubKey))}decrypt(j){if(!this.isHD(this.#j))throw new Error("Decryption not supported in single key mode");let $=this.#j.derive(G);return a(jj(D(j,"base64"),$.privKey))}signAttestationWithAIP(j,$,q=0,J=""){let Q=this.getId($);if(!Q)throw new Error("Could not find identity to attest with");let z=this.getAttestationBuffer(j,q,J),{address:Z,signature:L}=Q.signMessage(z);return this.createAttestationTransaction(j,q,Z,L,J)}verifyAttestationWithAIP(j){if(!Array.isArray(j)||j[0]!=="0x6a"||j[1]!==A)throw new Error("Not a valid BAP transaction");let $=j[7]==="0x44415441"?5:0,q={type:W.hexDecode(j[2]),hash:W.hexDecode(j[3]),sequence:W.hexDecode(j[4]),signingProtocol:W.hexDecode(j[7+$]),signingAddress:W.hexDecode(j[8+$]),signature:W.hexDecode(j[9+$],"base64")};if($&&j[3]===j[8])q.data=W.hexDecode(j[9]);try{let J=[];for(let z=0;z<6+$;z++)J.push(Buffer.from(j[z].replace("0x",""),"hex"));let Q=Buffer.concat(J);q.verified=this.verifySignature(Q,q.signingAddress,q.signature)}catch(J){q.verified=!1}return q}createAttestationTransaction(j,$,q,J,Q=""){let z=["0x6a",W.hexEncode(Y)];if(z.push(W.hexEncode("ATTEST")),z.push(W.hexEncode(j)),z.push(W.hexEncode(`${$}`)),z.push("0x7c"),Q)z.push(W.hexEncode(Y)),z.push(W.hexEncode("DATA")),z.push(W.hexEncode(j)),z.push(W.hexEncode(Q)),z.push("0x7c");return z.push(W.hexEncode(E)),z.push(W.hexEncode("BITCOIN_ECDSA")),z.push(W.hexEncode(q)),z.push(`0x${Buffer.from(J,"base64").toString("hex")}`),z}getAttestationBuffer(j,$=0,q=""){let J=Buffer.from("");if(q)J=Buffer.concat([Buffer.from(Y),Buffer.from("DATA"),Buffer.from(j),Buffer.from(q),Buffer.from("7c","hex")]);return Buffer.concat([Buffer.from("6a","hex"),Buffer.from(Y),Buffer.from("ATTEST"),Buffer.from(j),Buffer.from(`${$}`),Buffer.from("7c","hex"),J])}verifySignature(j,$,q){let J=Buffer.isBuffer(j)?j:Buffer.from(j),Q=i.fromCompact(q,"base64"),z,Z=D(J.toString("hex"),"hex");for(let L=0;L<4;L++)try{if(z=Q.RecoverPublicKey(L,new s(N.magicHash(Z))),N.verify(Z,Q,z)&&z.toAddress()===$)return!0}catch(k){}return!1}async verifyChallengeSignature(j,$,q,J){if(!this.verifySignature(q,$,J))return!1;try{let z=await this.getApiData("/attestation/valid",{idKey:j,address:$,challenge:q,signature:J});if(z?.status==="success"&&z?.result?.valid===!0)return!0;return!1}catch(z){return console.error("API call failed:",z),!1}}async isValidAttestationTransaction(j){if(this.verifyAttestationWithAIP(j))return this.getApiData("/attestation/valid",{tx:j});return!1}async getIdentityFromAddress(j){return this.getApiData("/identity/from-address",{address:j})}async getIdentity(j){return this.getApiData("/identity/get",{idKey:j})}async getAttestationsForHash(j){return this.getApiData("/attestations",{hash:j})}}function qj(j){return"derivedPrivateKey"in j}function K(j){return"rootPath"in j&&"currentPath"in j&&"previousPath"in j}export{qj as isSingleKeyIdentity,K as isHDIdentity,R as BAP_ID,$j as BAP};
6
+
7
+ //# debugId=B3510871523B166964756E2164756E21