bsv-bap 0.1.11 → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/MemberID.d.ts +38 -1
- package/dist/apiTypes.d.ts +0 -9
- package/dist/index.cjs +5 -5
- package/dist/index.d.ts +1 -0
- package/dist/index.modern.js +5 -5
- package/dist/index.modern.js.map +6 -6
- package/dist/index.module.js +5 -5
- package/dist/index.module.js.map +6 -6
- package/package.json +5 -5
package/dist/MemberID.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { PublicKey, PrivateKey } from "@bsv/sdk";
|
|
2
2
|
import { BaseClass } from "./BaseClass";
|
|
3
3
|
import type { IdentityAttributes, MemberIdentity } from "./interface";
|
|
4
4
|
export declare class MemberID extends BaseClass {
|
|
@@ -33,6 +33,43 @@ export declare class MemberID extends BaseClass {
|
|
|
33
33
|
* Get the public key for encrypting data for this identity
|
|
34
34
|
*/
|
|
35
35
|
getEncryptionPublicKey(): string;
|
|
36
|
+
/**
|
|
37
|
+
* Get a derived encryption key using a seed string (Type42 derivation)
|
|
38
|
+
* This allows deriving unique encryption keys per friend/conversation
|
|
39
|
+
* @param seed - The seed string (e.g., friend's BAP ID)
|
|
40
|
+
* @returns The derived private key for this seed
|
|
41
|
+
*/
|
|
42
|
+
private getEncryptionPrivateKeyWithSeed;
|
|
43
|
+
/**
|
|
44
|
+
* Get the encryption key pair for a specific seed
|
|
45
|
+
* @param seed - The seed string (e.g., friend's BAP ID)
|
|
46
|
+
*/
|
|
47
|
+
getEncryptionKeyWithSeed(seed: string): {
|
|
48
|
+
privKey: PrivateKey;
|
|
49
|
+
pubKey: PublicKey;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Get the public key for encrypting data for a specific seed
|
|
53
|
+
* This is the public key to include in friend requests
|
|
54
|
+
* @param seed - The seed string (e.g., friend's BAP ID)
|
|
55
|
+
*/
|
|
56
|
+
getEncryptionPublicKeyWithSeed(seed: string): string;
|
|
57
|
+
/**
|
|
58
|
+
* Encrypt data using a seed-derived key
|
|
59
|
+
* @param stringData - The data to encrypt
|
|
60
|
+
* @param seed - The seed string for key derivation (e.g., friend's BAP ID)
|
|
61
|
+
* @param counterPartyPublicKey - Optional public key of the recipient
|
|
62
|
+
* @returns Base64 encoded encrypted data
|
|
63
|
+
*/
|
|
64
|
+
encryptWithSeed(stringData: string, seed: string, counterPartyPublicKey?: string): string;
|
|
65
|
+
/**
|
|
66
|
+
* Decrypt data using a seed-derived key
|
|
67
|
+
* @param ciphertext - Base64 encoded encrypted data
|
|
68
|
+
* @param seed - The seed string for key derivation (e.g., friend's BAP ID)
|
|
69
|
+
* @param counterPartyPublicKey - Optional public key of the sender
|
|
70
|
+
* @returns Decrypted string
|
|
71
|
+
*/
|
|
72
|
+
decryptWithSeed(ciphertext: string, seed: string, counterPartyPublicKey?: string): string;
|
|
36
73
|
/**
|
|
37
74
|
* Export member data in bitcoin-backup compatible format
|
|
38
75
|
* @param label Optional user-defined label
|
package/dist/apiTypes.d.ts
CHANGED
|
@@ -21,15 +21,6 @@ export interface Attestation {
|
|
|
21
21
|
urn?: string;
|
|
22
22
|
signers: Signer[];
|
|
23
23
|
}
|
|
24
|
-
export interface SigningKey {
|
|
25
|
-
idKey: string;
|
|
26
|
-
signingAddress: string;
|
|
27
|
-
sequence: number;
|
|
28
|
-
block: number;
|
|
29
|
-
txId: string;
|
|
30
|
-
timestamp: number;
|
|
31
|
-
revoked: boolean;
|
|
32
|
-
}
|
|
33
24
|
export type GetSigningKeysResponse = APIResponse<Signer[]>;
|
|
34
25
|
export interface APIIdentityAddress {
|
|
35
26
|
address: string;
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun @bun-cjs
|
|
2
|
-
(function(exports, require, module, __filename, __dirname) {var{defineProperty:g,getOwnPropertyNames:
|
|
2
|
+
(function(exports, require, module, __filename, __dirname) {var{defineProperty:g,getOwnPropertyNames:i,getOwnPropertyDescriptor:r}=Object,a=Object.prototype.hasOwnProperty;var K=new WeakMap,e=(j)=>{var $=K.get(j),J;if($)return $;if($=g({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function")i(j).map((q)=>!a.call($,q)&&g($,q,{get:()=>j[q],enumerable:!(J=r(j,q))||J.enumerable}));return K.set(j,$),$};var t=(j,$)=>{for(var J in $)g(j,J,{get:$[J],enumerable:!0,configurable:!0,set:(q)=>$[J]=()=>q})};var Xj={};t(Xj,{MemberID:()=>_,MasterID:()=>V,BAP:()=>s});module.exports=e(Xj);var G=require("@bsv/sdk"),y=require("@bsv/sdk");var jj=async(j,$,J,q)=>{let z=`${J}${j}`;return(await fetch(z,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:q,format:"json"},body:JSON.stringify($)})).json()},H=(j,$)=>async(J,q)=>{return jj(J,q,j,$)};var c=require("@bsv/sdk"),{toHex:m,toArray:b}=c.Utils,k="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",p=m(b(k)),B="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva",Mj=m(b(B)),D="https://api.sigmaidentity.com/v1",M=2147483647,x="m/424150'/0'/0'",F=`m/424150'/${M}'/${M}'`;var Z=require("@bsv/sdk");var C={getRandomBytes(j=32){if(typeof globalThis<"u"&&globalThis.crypto&&globalThis.crypto.getRandomValues){let $=new Uint8Array(j);return globalThis.crypto.getRandomValues($),$}throw Error("Secure random number generation not available. crypto.getRandomValues() is required for cryptographic operations. This environment may not be suitable for secure key generation.")},getRandomString(j=32){let $=this.getRandomBytes(j);return Array.from($,(J)=>J.toString(16).padStart(2,"0")).join("")},getSigningPathFromHex(j,$=!0){let J="m",q=j.match(/.{1,8}/g);if(!q)throw Error("Invalid hex string");let z=2147483647;for(let Q of q){let L=Number(`0x${Q}`);if(L>z)L-=z;J+=`/${L}${$?"'":""}`}return J},getNextIdentityPath(j){let $=j.split("/"),J=$[$.length-2],q=!1;if(J.match("'"))q=!0;let z=(Number(J.replace(/[^0-9]/g,""))+1).toString();return $[$.length-2]=z+(q?"'":""),$[$.length-1]=`0${q?"'":""}`,$.join("/")},getNextPath(j){let $=j.split("/"),J=$[$.length-1],q=!1;if(J.match("'"))q=!0;let z=(Number(J.replace(/[^0-9]/g,""))+1).toString();return $[$.length-1]=z+(q?"'":""),$.join("/")}};var Y=require("@bsv/sdk");var f=require("@bsv/sdk");var{toArray:O,toUTF8:$j,toBase64:Jj}=f.Utils,{electrumDecrypt:qj,electrumEncrypt:zj}=f.ECIES;class N{identityAttributes={};encrypt(j,$){let{privKey:J,pubKey:q}=this.getEncryptionKey(),z=$?f.PublicKey.fromString($):q;return Jj(zj(O(j),z,J))}decrypt(j,$){let{privKey:J}=this.getEncryptionKey(),q;if($)q=f.PublicKey.fromString($);return $j(qj(O(j,"base64"),J,q))}signOpReturnWithAIP(j,$){let J=this.getAIPMessageBuffer(j),{address:q,signature:z}=this.signMessage(J.flat(),$);return this.formatAIPOutput(J,q,z)}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,$)}unsetAttribute(j){delete this.identityAttributes[j]}addAttribute(j,$,J=""){let q=J;if(!J)q=C.getRandomString();this.identityAttributes[j]={value:$,nonce:q}}getAttributeUrns(){let j="";for(let $ in this.identityAttributes){let J=this.getAttributeUrn($);if(J)j+=`${J}
|
|
3
3
|
`}return j}getAttributeUrn(j){let $=this.identityAttributes[j];if($)return`urn:bap:id:${j}:${$.value}:${$.nonce}`;return null}parseStringUrns(j){let $={},J=j.replace(/^\s+/g,"").replace(/\r/gm,"").split(`
|
|
4
|
-
`);for(let q of J){let Q=q.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(Q[0]==="urn"&&Q[1]==="bap"&&Q[2]==="id"&&Q[3]&&Q[4]&&Q[5])$[Q[3]]={value:Q[4],nonce:Q[5]}}return $}parseAttributes(j){if(typeof j==="string")return this.parseStringUrns(j);for(let $ in j)if(!j[$].value||!j[$].nonce)throw
|
|
5
|
-
`);for(let q of J){let Q=q.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(Q[0]==="urn"&&Q[1]==="bap"&&Q[2]==="id"&&Q[3]&&Q[4]&&Q[5])$[Q[3]]={value:Q[4],nonce:Q[5]}}return $}getIdentityKey(){return this.identityKey}set rootPath(j){if(this.#J){if(this.#q=j,!this.#j)throw new Error("Master private key not initialized");let $=this.#j.deriveChild(this.#j.toPublicKey(),j);this.rootAddress=$.toPublicKey().toAddress(),this.#Z=j,this.#z=j}else{let $=j;if(j.split("/").length<5)$=`${x}${j}`;if(!this.validatePath($))throw new Error(`invalid signing path given ${$}`);if(this.#q=$,!this.#$)throw new Error("HD private key not initialized");let J=this.#$.derive($);this.rootAddress=J.pubKey.toAddress(),this.#Z=$,this.#z=$}this.identityKey=this.deriveIdentityKey(this.rootAddress)}get rootPath(){return this.#q}getRootPath(){return this.#q}set currentPath(j){if(this.#J)this.#Z=this.#z,this.#z=j;else{let $=j;if(j.split("/").length<5)$=`${x}${j}`;if(!this.validatePath($))throw new Error("invalid signing path given");this.#Z=this.#z,this.#z=$}}get currentPath(){return this.#z}get previousPath(){return this.#Z}get idSeed(){return this.#L}incrementPath(){this.currentPath=C.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("'",""))<=M&&Number($[2].replace("'",""))<=M&&Number($[3].replace("'",""))<=M&&Number($[4].replace("'",""))<=M&&Number($[5].replace("'",""))<=M&&Number($[6].replace("'",""))<=M)return!0}return!1}getInitialIdTransaction(){return this.getIdTransaction(this.#q)}getIdTransaction(j=""){if(this.#z===this.#q)throw new Error("Current path equals rootPath. ID was probably not initialized properly");let $=[f(k),f("ID"),f(this.identityKey),f(this.getCurrentAddress())];return this.signOpReturnWithAIP($,j||this.#Z)}getAddress(j){if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");return this.#j.deriveChild(this.#j.toPublicKey(),j).toPublicKey().toAddress()}if(!this.#$)throw new Error("HD private key not initialized");return this.#$.derive(j).privKey.toPublicKey().toAddress()}getCurrentAddress(){return this.getAddress(this.#z)}getEncryptionKey(){if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");let J=this.#j.deriveChild(this.#j.toPublicKey(),this.#q),q=J.deriveChild(J.toPublicKey(),X);return{privKey:q,pubKey:q.toPublicKey()}}if(!this.#$)throw new Error("HD private key not initialized");let $=this.#$.derive(this.#q).derive(X).privKey;return{privKey:$,pubKey:$.toPublicKey()}}getEncryptionKeyType42(){if(this.#J)return this.getEncryptionKey();if(!this.#$)throw new Error("HD private key not initialized");let j=this.#$.derive(this.#q),$=j.privKey.deriveChild(j.toPublic().pubKey,X);return{privKey:$,pubKey:$.toPublicKey()}}getEncryptionPublicKey(){let{pubKey:j}=this.getEncryptionKey();return j.toString()}getEncryptionPublicKeyWithSeed(j){return this.getEncryptionPrivateKeyWithSeed(j).toPublicKey().toString()}encrypt(j,$){let{privKey:J,pubKey:q}=this.getEncryptionKey(),z=$?Z.PublicKey.fromString($):q;return v(A(f(j),z,null))}decrypt(j,$){let{privKey:J}=this.getEncryptionKey(),q=void 0;if($)q=Z.PublicKey.fromString($);return h(P(f(j,"base64"),J,q))}encryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z=q.toPublicKey(),Q=J?Z.PublicKey.fromString(J):z;return v(A(f(j),Q,q))}decryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z=void 0;if(J)z=Z.PublicKey.fromString(J);return h(P(f(j,"base64"),q,z))}getEncryptionPrivateKeyWithSeed(j){let $=R(Z.Hash.sha256(j,"utf8"));if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");let z=this.#j.deriveChild(this.#j.toPublicKey(),this.#q);return z.deriveChild(z.toPublicKey(),$)}if(!this.#$)throw new Error("HD private key not initialized");let J=C.getSigningPathFromHex($);return this.#$.derive(this.#q).derive(J).privKey}getAttestation(j){let $=Z.Hash.sha256(j,"utf8");return`bap:attest:${R($)}:${this.getIdentityKey()}`}getAttestationHash(j){let $=this.getAttributeUrn(j);if(!$)return null;let J=this.getAttestation($),q=Z.Hash.sha256(J,"utf8");return R(q)}signMessage(j,$){let J=$||this.#z,q;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");q=this.#j.deriveChild(this.#j.toPublicKey(),J)}else{if(!this.#$)throw new Error("HD private key not initialized");q=this.#$.derive(J).privKey}let z=q.toAddress(),Q=Z.BSM.sign(j,q,"raw"),L=new Z.BigNumber(o(j)),w=Q.CalculateRecoveryFactor(q.toPublicKey(),L),G=Z.BSM.sign(j,q,"raw").toCompact(w,!0,"base64");return{address:z,signature:G}}signMessageWithSeed(j,$){let J=R(Z.Hash.sha256($,"utf8")),q;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");let H=this.#j.deriveChild(this.#j.toPublicKey(),this.#q);q=H.deriveChild(H.toPublicKey(),J)}else{if(!this.#$)throw new Error("HD private key not initialized");let H=C.getSigningPathFromHex(J);q=this.#$.derive(this.#q).derive(H).privKey}let z=q.toPublicKey().toAddress(),Q=f(j,"utf8"),L=Z.BSM.sign(Q,q,"raw"),w=new Z.BigNumber(o(Q)),G=L.CalculateRecoveryFactor(q.toPublicKey(),w),T=Z.BSM.sign(Q,q,"raw").toCompact(G,!0,"base64");return{address:z,signature:T}}signOpReturnWithAIP(j,$=""){let J=this.getAIPMessageBuffer(j),{address:q,signature:z}=this.signMessage(J.flat(),$);return this.formatAIPOutput(j,q,z)}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),J=await this.getApiData("/attestation/get",{hash:$});return console.log("getAttestations",j,$,J),J}import(j){this.idName=j.name,this.description=j.description||"",this.identityKey=j.identityKey,this.#q=j.rootPath,this.rootAddress=j.rootAddress,this.#Z=j.previousPath,this.#z=j.currentPath,this.#L=("idSeed"in j?j.idSeed:"")||"",this.identityAttributes=this.parseAttributes(j.identityAttributes)}export(){return{name:this.idName,description:this.description,identityKey:this.identityKey,rootPath:this.#q,rootAddress:this.rootAddress,previousPath:this.#Z,currentPath:this.#z,idSeed:this.#L,identityAttributes:this.getAttributes(),lastIdPath:""}}exportMemberBackup(){let j;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");j=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw new Error("HD private key not initialized");j=this.#$.derive(this.#z).privKey}return{name:this.idName,description:this.description,derivedPrivateKey:j.toWif(),address:j.toPublicKey().toAddress(),identityAttributes:this.getAttributes(),identityKey:this.identityKey}}newId(){this.incrementPath();let j;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");j=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw new Error("HD private key not initialized");j=this.#$.derive(this.#z).privKey}return new _(j)}exportMember(){let j=this.exportMemberBackup(),$;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");$=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw new Error("HD private key not initialized");$=this.#$.derive(this.#z).privKey}let J=v(A(f(JSON.stringify(j)),$.toPublicKey()));return{wif:j.derivedPrivateKey,encryptedData:J}}}var{toArray:W,toUTF8:E,toBase64:l,toHex:I}=d.Utils,{electrumEncrypt:n,electrumDecrypt:u}=Y.ECIES;class y{#$;#j;#J;#Q={};#W=D;#q="";#Z="";#z=0;getApiData;constructor(j,$="",J=""){if(!j)throw new Error("No key source given");if(typeof j==="string")this.#$=Y.HD.fromString(j),this.#J=!1;else this.#j=Y.PrivateKey.fromWif(j.rootPk),this.#J=!0;if($)this.#q=$;if(J)this.#W=J;this.getApiData=S(this.#W,this.#q)}get lastIdPath(){return this.#Z}getPublicKey(j=""){if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");if(j)return this.#j.deriveChild(this.#j.toPublicKey(),j).toPublicKey().toString();return this.#j.toPublicKey().toString()}if(!this.#$)throw new Error("HD private key not initialized");if(j)return this.#$.derive(j).pubKey.toString();return this.#$.pubKey.toString()}getHdPublicKey(j=""){if(this.#J)throw new Error("HD public keys are not available in Type 42 mode");if(!this.#$)throw new Error("HD private key not initialized");if(j)return this.#$.derive(j).toPublic().toString();return this.#$.toPublic().toString()}set BAP_SERVER(j){this.#W=j;for(let $ in this.#Q)this.#Q[$].BAP_SERVER=j}get BAP_SERVER(){return this.#W}set BAP_TOKEN(j){this.#q=j;for(let $ in this.#Q)this.#Q[$].BAP_TOKEN=j}get BAP_TOKEN(){return this.#q}checkIdBelongs(j){let $;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");$=this.#j.deriveChild(this.#j.toPublicKey(),j.rootPath).toPublicKey().toAddress()}else{if(!this.#$)throw new Error("HD private key not initialized");$=this.#$.derive(j.rootPath).pubKey.toAddress()}if($!==j.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#Q)}newId(j,$,J={},q=""){let z,Q,L;if(typeof j==="object"||j===void 0||typeof j==="string"&&j.startsWith("/"))Q=typeof j==="string"?j:void 0,L=typeof j==="object"?j:typeof $==="object"?$:{},z="Default Identity";else z=j,Q=typeof $==="string"?$:void 0,L=typeof $==="object"?$:J;let w;if(Q)w=Q;else if(this.#J)w=`bap:${this.#z}`,this.#z++;else w=this.getNextValidPath();let G;if(this.#J){if(!this.#j)throw new Error("Type 42 parameters not initialized");G=new V({rootPk:this.#j},L,q)}else{if(!this.#$)throw new Error("HD private key not initialized");G=new V(this.#$,L,q)}if(G.BAP_SERVER=this.#W,G.BAP_TOKEN=this.#q,G.idName=z,G.rootPath=w,this.#J)G.currentPath=w;else G.currentPath=C.getNextPath(w);let T=G.getIdentityKey();return this.#Q[T]=G,this.#Z=w,this.#Q[T]}removeId(j){delete this.#Q[j]}getNextValidPath(){if(this.#Z)return C.getNextIdentityPath(this.#Z);return`/0'/${Object.keys(this.#Q).length}'/0'`}newIdWithCounter(j,$=`Identity ${j}`){if(!this.#J)throw new Error("newIdWithCounter only works in Type 42 mode");let J=`bap:${j}`;return this.newId($,J)}getId(j){return this.#Q[j]||null}setId(j){this.checkIdBelongs(j),this.#Q[j.getIdentityKey()]=j}importIds(j,$=!0){if($&&typeof j==="string"){this.importEncryptedIds(j);return}let J=j;if(!J.lastIdPath)throw new Error("ID cannot be imported as it is not complete");if(!J.ids)throw new Error(`ID data is not in the correct format: ${j}`);let q=j.lastIdPath;for(let z of J.ids){if(!z.identityKey||!z.identityAttributes||!z.rootAddress)throw new Error("ID cannot be imported as it is not complete");let Q;if(this.#J){if(!this.#j)throw new Error("Type 42 parameters not initialized");Q=new V({rootPk:this.#j},{},z.idSeed)}else{if(!this.#$)throw new Error("HD private key not initialized");Q=new V(this.#$,{},z.idSeed)}if(Q.BAP_SERVER=this.#W,Q.BAP_TOKEN=this.#q,Q.import(z),q==="")q=Q.currentPath;if(this.checkIdBelongs(Q),this.#Q[Q.getIdentityKey()]=Q,this.#J&&Q.rootPath.startsWith("bap:")){let L=Q.rootPath.split(":");if(L.length>=2){let w=parseInt(L[1],10);if(!isNaN(w))this.#z=Math.max(this.#z,w+1)}}}this.#Z=q}importEncryptedIds(j){let $=this.decrypt(j),J=JSON.parse($);if(Array.isArray(J)){console.log(`Importing old format:
|
|
6
|
-
`,J),this.importOldIds(J);return}if(typeof J!=="object")throw
|
|
4
|
+
`);for(let q of J){let Q=q.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(Q[0]==="urn"&&Q[1]==="bap"&&Q[2]==="id"&&Q[3]&&Q[4]&&Q[5])$[Q[3]]={value:Q[4],nonce:Q[5]}}return $}parseAttributes(j){if(typeof j==="string")return this.parseStringUrns(j);for(let $ in j)if(!j[$].value||!j[$].nonce)throw Error("Invalid identity attribute");return 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)}getAIPMessageBuffer(j,$){let J=j.findIndex((z)=>z[0]===f.OP.OP_RETURN),q=[];if(J===-1)q.push([f.OP.OP_RETURN]),J=0;if($)for(let z of $)q.push(j[J+z]);else for(let z of j)q.push(z);return q}formatAIPOutput(j,$,J){let q=[O("|"),O(B),O("BITCOIN_ECDSA"),O($),O(J,"base64")];return[...j,...q]}}var{magicHash:Qj}=Y.BSM,{toArray:h,toUTF8:Zj,toBase64:Wj,toHex:Lj}=Y.Utils,{electrumDecrypt:wj,electrumEncrypt:Yj}=Y.ECIES;class _ extends N{key;idName;description;address;identityKey;constructor(j,$={}){super();this.key=j,this.address=j.toAddress(),this.idName="Member ID 1",this.description="",this.identityKey="",this.identityAttributes=this.parseAttributes($)}signMessage(j,$){let J=this.key,q=J.toAddress(),z=Y.BSM.sign(j,J,"raw"),Q=new Y.BigNumber(Qj(j)),L=z.CalculateRecoveryFactor(J.toPublicKey(),Q),w=Y.BSM.sign(j,J,"raw").toCompact(L,!0,"base64");return{address:q,signature:w}}signOpReturnWithAIP(j){let $=this.getAIPMessageBuffer(j),{address:J,signature:q}=this.signMessage($.flat());return this.formatAIPOutput($,J,q)}getPublicKey(){return this.key.toPublicKey().toString()}import(j){this.idName=j.name,this.description=j.description,this.key=Y.PrivateKey.fromWif(j.derivedPrivateKey),this.address=this.key.toAddress(),this.identityAttributes=j.identityAttributes||{},this.identityKey=j.identityKey}static fromMemberIdentity(j){let $=new _(Y.PrivateKey.fromWif(j.derivedPrivateKey));return $.import(j),$}static fromBackup(j){let $=new _(Y.PrivateKey.fromWif(j.wif)),J=JSON.parse($.decrypt(j.id));return $.import(J),$}export(){return{name:this.idName,description:this.description,derivedPrivateKey:this.key.toWif(),address:this.address,identityAttributes:this.getAttributes(),identityKey:this.identityKey}}getEncryptionKey(){return{privKey:this.key.deriveChild(this.key.toPublicKey(),F),pubKey:this.key.deriveChild(this.key.toPublicKey(),F).toPublicKey()}}getEncryptionPublicKey(){let{pubKey:j}=this.getEncryptionKey();return j.toString()}getEncryptionPrivateKeyWithSeed(j){let $=Lj(Y.Hash.sha256(j,"utf8"));return this.key.deriveChild(this.key.toPublicKey(),$)}getEncryptionKeyWithSeed(j){let $=this.getEncryptionPrivateKeyWithSeed(j);return{privKey:$,pubKey:$.toPublicKey()}}getEncryptionPublicKeyWithSeed(j){return this.getEncryptionPrivateKeyWithSeed(j).toPublicKey().toString()}encryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z=q.toPublicKey(),Q=this.key.toPublicKey().constructor,L=J?Q.fromString(J):z;return Wj(Yj(h(j),L,q))}decryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z;if(J)z=Y.PublicKey.fromString(J);return Zj(wj(h(j,"base64"),q,z))}exportForBackup(j){let $=this.export(),J=this.encrypt(JSON.stringify($));return{wif:this.key.toWif(),id:J,...j&&{label:j},createdAt:new Date().toISOString()}}}var{toArray:U,toHex:R,toBase58:Gj,toUTF8:o,toBase64:v}=Z.Utils,{electrumDecrypt:P,electrumEncrypt:A}=Z.ECIES,{magicHash:n}=Z.BSM;class V extends N{#$;#j;#J;#Q=D;#W="";#q;#Z;#z;#L;idName;description;rootAddress;identityKey;identityAttributes;getApiData;constructor(j,$={},J=""){super();if(j instanceof Z.HD)if(this.#J=!1,J){let z=R(Z.Hash.sha256(J,"utf8")),Q=C.getSigningPathFromHex(z);this.#$=j.derive(Q)}else this.#$=j;else if(this.#J=!0,this.#j=j.rootPk,J){let z=R(Z.Hash.sha256(J,"utf8"));this.#j=this.#j.deriveChild(this.#j.toPublicKey(),z)}if(this.#L=J,this.idName="ID 1",this.description="",this.#q=`${x}/0/0/0`,this.#Z=`${x}/0/0/0`,this.#z=`${x}/0/0/1`,this.#J){if(!this.#j)throw Error("Master private key not initialized");let z=this.#j.deriveChild(this.#j.toPublicKey(),this.#q);this.rootAddress=z.toPublicKey().toAddress()}else{if(!this.#$)throw Error("HD private key not initialized");let z=this.#$.derive(this.#q);this.rootAddress=z.privKey.toPublicKey().toAddress()}this.identityKey=this.deriveIdentityKey(this.rootAddress);let q={...$};this.identityAttributes=this.parseAttributes(q),this.getApiData=H(this.#Q,this.#W)}set BAP_SERVER(j){this.#Q=j}get BAP_SERVER(){return this.#Q}set BAP_TOKEN(j){this.#W=j}get BAP_TOKEN(){return this.#W}deriveIdentityKey(j){let $=R(Z.Hash.sha256(j,"utf8"));return Gj(Z.Hash.ripemd160($,"hex"))}parseAttributes(j){if(typeof j==="string")return this.parseStringUrns(j);for(let $ in j)if(!j[$].value||!j[$].nonce)throw Error("Invalid identity attribute");return j||{}}parseStringUrns(j){let $={},J=j.replace(/^\s+/g,"").replace(/\r/gm,"").split(`
|
|
5
|
+
`);for(let q of J){let Q=q.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(Q[0]==="urn"&&Q[1]==="bap"&&Q[2]==="id"&&Q[3]&&Q[4]&&Q[5])$[Q[3]]={value:Q[4],nonce:Q[5]}}return $}getIdentityKey(){return this.identityKey}set rootPath(j){if(this.#J){if(this.#q=j,!this.#j)throw Error("Master private key not initialized");let $=this.#j.deriveChild(this.#j.toPublicKey(),j);this.rootAddress=$.toPublicKey().toAddress(),this.#Z=j,this.#z=j}else{let $=j;if(j.split("/").length<5)$=`${x}${j}`;if(!this.validatePath($))throw Error(`invalid signing path given ${$}`);if(this.#q=$,!this.#$)throw Error("HD private key not initialized");let J=this.#$.derive($);this.rootAddress=J.pubKey.toAddress(),this.#Z=$,this.#z=$}this.identityKey=this.deriveIdentityKey(this.rootAddress)}get rootPath(){return this.#q}getRootPath(){return this.#q}set currentPath(j){if(this.#J)this.#Z=this.#z,this.#z=j;else{let $=j;if(j.split("/").length<5)$=`${x}${j}`;if(!this.validatePath($))throw Error("invalid signing path given");this.#Z=this.#z,this.#z=$}}get currentPath(){return this.#z}get previousPath(){return this.#Z}get idSeed(){return this.#L}incrementPath(){this.currentPath=C.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("'",""))<=M&&Number($[2].replace("'",""))<=M&&Number($[3].replace("'",""))<=M&&Number($[4].replace("'",""))<=M&&Number($[5].replace("'",""))<=M&&Number($[6].replace("'",""))<=M)return!0}return!1}getInitialIdTransaction(){return this.getIdTransaction(this.#q)}getIdTransaction(j=""){if(this.#z===this.#q)throw Error("Current path equals rootPath. ID was probably not initialized properly");let $=[U(k),U("ID"),U(this.identityKey),U(this.getCurrentAddress())];return this.signOpReturnWithAIP($,j||this.#Z)}getAddress(j){if(this.#J){if(!this.#j)throw Error("Master private key not initialized");return this.#j.deriveChild(this.#j.toPublicKey(),j).toPublicKey().toAddress()}if(!this.#$)throw Error("HD private key not initialized");return this.#$.derive(j).privKey.toPublicKey().toAddress()}getCurrentAddress(){return this.getAddress(this.#z)}getEncryptionKey(){if(this.#J){if(!this.#j)throw Error("Master private key not initialized");let J=this.#j.deriveChild(this.#j.toPublicKey(),this.#q),q=J.deriveChild(J.toPublicKey(),F);return{privKey:q,pubKey:q.toPublicKey()}}if(!this.#$)throw Error("HD private key not initialized");let $=this.#$.derive(this.#q).derive(F).privKey;return{privKey:$,pubKey:$.toPublicKey()}}getEncryptionKeyType42(){if(this.#J)return this.getEncryptionKey();if(!this.#$)throw Error("HD private key not initialized");let j=this.#$.derive(this.#q),$=j.privKey.deriveChild(j.toPublic().pubKey,F);return{privKey:$,pubKey:$.toPublicKey()}}getEncryptionPublicKey(){let{pubKey:j}=this.getEncryptionKey();return j.toString()}getEncryptionPublicKeyWithSeed(j){return this.getEncryptionPrivateKeyWithSeed(j).toPublicKey().toString()}encrypt(j,$){let{privKey:J,pubKey:q}=this.getEncryptionKey(),z=$?Z.PublicKey.fromString($):q;return v(A(U(j),z,J))}decrypt(j,$){let{privKey:J}=this.getEncryptionKey(),q;if($)q=Z.PublicKey.fromString($);return o(P(U(j,"base64"),J,q))}encryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z=q.toPublicKey(),Q=J?Z.PublicKey.fromString(J):z;return v(A(U(j),Q,q))}decryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z;if(J)z=Z.PublicKey.fromString(J);return o(P(U(j,"base64"),q,z))}getEncryptionPrivateKeyWithSeed(j){let $=R(Z.Hash.sha256(j,"utf8"));if(this.#J){if(!this.#j)throw Error("Master private key not initialized");let z=this.#j.deriveChild(this.#j.toPublicKey(),this.#q);return z.deriveChild(z.toPublicKey(),$)}if(!this.#$)throw Error("HD private key not initialized");let J=C.getSigningPathFromHex($);return this.#$.derive(this.#q).derive(J).privKey}getAttestation(j){let $=Z.Hash.sha256(j,"utf8");return`bap:attest:${R($)}:${this.getIdentityKey()}`}getAttestationHash(j){let $=this.getAttributeUrn(j);if(!$)return null;let J=this.getAttestation($),q=Z.Hash.sha256(J,"utf8");return R(q)}signMessage(j,$){let J=$||this.#z,q;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");q=this.#j.deriveChild(this.#j.toPublicKey(),J)}else{if(!this.#$)throw Error("HD private key not initialized");q=this.#$.derive(J).privKey}let z=q.toAddress(),Q=Z.BSM.sign(j,q,"raw"),L=new Z.BigNumber(n(j)),w=Q.CalculateRecoveryFactor(q.toPublicKey(),L),X=Z.BSM.sign(j,q,"raw").toCompact(w,!0,"base64");return{address:z,signature:X}}signMessageWithSeed(j,$){let J=R(Z.Hash.sha256($,"utf8")),q;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");let S=this.#j.deriveChild(this.#j.toPublicKey(),this.#q);q=S.deriveChild(S.toPublicKey(),J)}else{if(!this.#$)throw Error("HD private key not initialized");let S=C.getSigningPathFromHex(J);q=this.#$.derive(this.#q).derive(S).privKey}let z=q.toPublicKey().toAddress(),Q=U(j,"utf8"),L=Z.BSM.sign(Q,q,"raw"),w=new Z.BigNumber(n(Q)),X=L.CalculateRecoveryFactor(q.toPublicKey(),w),T=Z.BSM.sign(Q,q,"raw").toCompact(X,!0,"base64");return{address:z,signature:T}}signOpReturnWithAIP(j,$=""){let J=this.getAIPMessageBuffer(j),{address:q,signature:z}=this.signMessage(J.flat(),$);return this.formatAIPOutput(j,q,z)}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),J=await this.getApiData("/attestation/get",{hash:$});return console.log("getAttestations",j,$,J),J}import(j){this.idName=j.name,this.description=j.description||"",this.identityKey=j.identityKey,this.#q=j.rootPath,this.rootAddress=j.rootAddress,this.#Z=j.previousPath,this.#z=j.currentPath,this.#L=("idSeed"in j?j.idSeed:"")||"",this.identityAttributes=this.parseAttributes(j.identityAttributes)}export(){return{name:this.idName,description:this.description,identityKey:this.identityKey,rootPath:this.#q,rootAddress:this.rootAddress,previousPath:this.#Z,currentPath:this.#z,idSeed:this.#L,identityAttributes:this.getAttributes(),lastIdPath:""}}exportMemberBackup(){let j;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");j=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw Error("HD private key not initialized");j=this.#$.derive(this.#z).privKey}return{name:this.idName,description:this.description,derivedPrivateKey:j.toWif(),address:j.toPublicKey().toAddress(),identityAttributes:this.getAttributes(),identityKey:this.identityKey}}newId(){this.incrementPath();let j;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");j=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw Error("HD private key not initialized");j=this.#$.derive(this.#z).privKey}return new _(j)}exportMember(){let j=this.exportMemberBackup(),$;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");$=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw Error("HD private key not initialized");$=this.#$.derive(this.#z).privKey}let J=v(A(U(JSON.stringify(j)),$.toPublicKey()));return{wif:j.derivedPrivateKey,encryptedData:J}}}var{toArray:W,toUTF8:E,toBase64:l,toHex:I}=y.Utils,{electrumEncrypt:u,electrumDecrypt:d}=G.ECIES;class s{#$;#j;#J;#Q={};#W=D;#q="";#Z="";#z=0;getApiData;constructor(j,$="",J=""){if(!j)throw Error("No key source given");if(typeof j==="string")this.#$=G.HD.fromString(j),this.#J=!1;else this.#j=G.PrivateKey.fromWif(j.rootPk),this.#J=!0;if($)this.#q=$;if(J)this.#W=J;this.getApiData=H(this.#W,this.#q)}get lastIdPath(){return this.#Z}getPublicKey(j=""){if(this.#J){if(!this.#j)throw Error("Master private key not initialized");if(j)return this.#j.deriveChild(this.#j.toPublicKey(),j).toPublicKey().toString();return this.#j.toPublicKey().toString()}if(!this.#$)throw Error("HD private key not initialized");if(j)return this.#$.derive(j).pubKey.toString();return this.#$.pubKey.toString()}getHdPublicKey(j=""){if(this.#J)throw Error("HD public keys are not available in Type 42 mode");if(!this.#$)throw Error("HD private key not initialized");if(j)return this.#$.derive(j).toPublic().toString();return this.#$.toPublic().toString()}set BAP_SERVER(j){this.#W=j;for(let $ in this.#Q)this.#Q[$].BAP_SERVER=j}get BAP_SERVER(){return this.#W}set BAP_TOKEN(j){this.#q=j;for(let $ in this.#Q)this.#Q[$].BAP_TOKEN=j}get BAP_TOKEN(){return this.#q}checkIdBelongs(j){let $;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");$=this.#j.deriveChild(this.#j.toPublicKey(),j.rootPath).toPublicKey().toAddress()}else{if(!this.#$)throw Error("HD private key not initialized");$=this.#$.derive(j.rootPath).pubKey.toAddress()}if($!==j.rootAddress)throw Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#Q)}newId(j,$,J={},q=""){let z,Q,L;if(typeof j==="object"||j===void 0||typeof j==="string"&&j.startsWith("/"))Q=typeof j==="string"?j:void 0,L=typeof j==="object"?j:typeof $==="object"?$:{},z="Default Identity";else z=j,Q=typeof $==="string"?$:void 0,L=typeof $==="object"?$:J;let w;if(Q)w=Q;else if(this.#J)w=`bap:${this.#z}`,this.#z++;else w=this.getNextValidPath();let X;if(this.#J){if(!this.#j)throw Error("Type 42 parameters not initialized");X=new V({rootPk:this.#j},L,q)}else{if(!this.#$)throw Error("HD private key not initialized");X=new V(this.#$,L,q)}if(X.BAP_SERVER=this.#W,X.BAP_TOKEN=this.#q,X.idName=z,X.rootPath=w,this.#J)X.currentPath=w;else X.currentPath=C.getNextPath(w);let T=X.getIdentityKey();return this.#Q[T]=X,this.#Z=w,this.#Q[T]}removeId(j){delete this.#Q[j]}getNextValidPath(){if(this.#Z)return C.getNextIdentityPath(this.#Z);return`/0'/${Object.keys(this.#Q).length}'/0'`}newIdWithCounter(j,$=`Identity ${j}`){if(!this.#J)throw Error("newIdWithCounter only works in Type 42 mode");let J=`bap:${j}`;return this.newId($,J)}getId(j){return this.#Q[j]||null}setId(j){this.checkIdBelongs(j),this.#Q[j.getIdentityKey()]=j}importIds(j,$=!0){if($&&typeof j==="string"){this.importEncryptedIds(j);return}let J=j;if(!J.lastIdPath)throw Error("ID cannot be imported as it is not complete");if(!J.ids)throw Error(`ID data is not in the correct format: ${j}`);let q=j.lastIdPath;for(let z of J.ids){if(!z.identityKey||!z.identityAttributes||!z.rootAddress)throw Error("ID cannot be imported as it is not complete");let Q;if(this.#J){if(!this.#j)throw Error("Type 42 parameters not initialized");Q=new V({rootPk:this.#j},{},z.idSeed)}else{if(!this.#$)throw Error("HD private key not initialized");Q=new V(this.#$,{},z.idSeed)}if(Q.BAP_SERVER=this.#W,Q.BAP_TOKEN=this.#q,Q.import(z),q==="")q=Q.currentPath;if(this.checkIdBelongs(Q),this.#Q[Q.getIdentityKey()]=Q,this.#J&&Q.rootPath.startsWith("bap:")){let L=Q.rootPath.split(":");if(L.length>=2){let w=Number.parseInt(L[1],10);if(!Number.isNaN(w))this.#z=Math.max(this.#z,w+1)}}}this.#Z=q}importEncryptedIds(j){let $=this.decrypt(j),J=JSON.parse($);if(Array.isArray(J)){console.log(`Importing old format:
|
|
6
|
+
`,J),this.importOldIds(J);return}if(typeof J!=="object")throw Error("decrypted, but found unrecognized identities format");this.importIds(J,!1)}importOldIds(j){for(let $ of j){let J;if(this.#J){if(!this.#j)throw Error("Type 42 parameters not initialized");J=new V({rootPk:this.#j},{},$.idSeed??"")}else{if(!this.#$)throw Error("HD private key not initialized");J=new V(this.#$,{},$.idSeed??"")}J.BAP_SERVER=this.#W,J.BAP_TOKEN=this.#q,J.import($),this.checkIdBelongs(J),this.#Q[J.getIdentityKey()]=J,this.#Z=J.currentPath}}exportIds(j,$=!0){let J={lastIdPath:this.#Z,ids:[]},q=j||Object.keys(this.#Q);for(let z of q){if(!this.#Q[z])throw Error(`Identity ${z} not found`);J.ids.push(this.#Q[z].export())}if($)return this.encrypt(JSON.stringify(J));return J}exportId(j,$=!0){let J={lastIdPath:this.#Z,ids:[]};if(J.ids.push(this.#Q[j].export()),$)return this.encrypt(JSON.stringify(J));return J}encrypt(j){if(this.#J){if(!this.#j)throw Error("Master private key not initialized");let J=this.#j.deriveChild(this.#j.toPublicKey(),F);return l(u(W(j),J.toPublicKey(),null))}if(!this.#$)throw Error("HD private key not initialized");let $=this.#$.derive(F);return l(u(W(j),$.pubKey,null))}decrypt(j){if(this.#J){if(!this.#j)throw Error("Master private key not initialized");let J=this.#j.deriveChild(this.#j.toPublicKey(),F);return E(d(W(j,"base64"),J))}if(!this.#$)throw Error("HD private key not initialized");let $=this.#$.derive(F);return E(d(W(j,"base64"),$.privKey))}signAttestationWithAIP(j,$,J=0,q=""){let z=this.getId($);if(!z)throw Error("Could not find identity to attest with");let Q=this.getAttestationBuffer(j,J,q),{address:L,signature:w}=z.signMessage(Q);return this.createAttestationTransaction(j,J,L,w,q)}verifyAttestationWithAIP(j){if(!j.every((q)=>Array.isArray(q))||j[0][0]!==G.OP.OP_RETURN||I(j[1])!==p)throw Error("Not a valid BAP transaction");let $=I(j[7])==="44415441"?5:0,J={type:E(j[2]),hash:I(j[3]),sequence:E(j[4]),signingProtocol:E(j[7+$]),signingAddress:E(j[8+$]),signature:l(j[9+$])};if($&&j[3]===j[8])J.data=I(j[9]);console.log({attestation:J});try{let q=[];for(let z=0;z<6+$;z++)q.push(j[z]);J.verified=this.verifySignature(q.flat(),J.signingAddress,J.signature)}catch{J.verified=!1}return J}createAttestationTransaction(j,$,J,q,z=""){let Q=[[G.OP.OP_RETURN],W(k),W("ATTEST"),W(j),W(`${$}`),W("|")];if(z)Q.push(W(k),W("DATA"),W(j),W(z),W("|"));return Q.push(W(B),W("BITCOIN_ECDSA"),W(J),W(q,"base64")),console.log({elements:Q}),Q}getAttestationBuffer(j,$=0,J=""){let q=[[G.OP.OP_RETURN],W(k),W("ATTEST"),W(j),W(`${$}`),W("|")];if(J)q.push(W(k),W("DATA"),W(j),W(J),W("|"));return q.flat()}verifySignature(j,$,J){let q;if(Array.isArray(j))q=j;else if(Buffer.isBuffer(j))q=[...j];else q=W(j,"utf8");let z=G.Signature.fromCompact(J,"base64"),Q;for(let L=0;L<4;L++)try{if(Q=z.RecoverPublicKey(L,new G.BigNumber(G.BSM.magicHash(q))),G.BSM.verify(q,z,Q)&&Q.toAddress()===$)return!0}catch{}return!1}async verifyChallengeSignature(j,$,J,q){if(!this.verifySignature(J,$,q))return!1;try{let Q=await this.getApiData("/attestation/valid",{idKey:j,address:$,challenge:J,signature:q});if(Q?.status==="success"&&Q?.result?.valid===!0)return!0;return!1}catch(Q){return console.error("API call failed:",Q),!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})}exportForBackup(j,$,J){let z={ids:this.exportIds(),...j&&{label:j},createdAt:new Date().toISOString()};if(this.#J){if(!this.#j)throw Error("Type 42 parameters not initialized");return{...z,rootPk:this.#j.toWif()}}if(!this.#$)throw Error("HD private key not initialized");return{...z,xprv:$||this.#$.toString(),mnemonic:J||""}}exportMemberForBackup(j,$){let J=this.#Q[j];if(!J)throw Error(`Identity ${j} not found`);let q=J.exportMember();return{wif:q.wif,id:q.encryptedData,...$&&{label:$},createdAt:new Date().toISOString()}}}})
|
|
7
7
|
|
|
8
|
-
//# debugId=
|
|
8
|
+
//# debugId=38F34D7DB4E839A964756E2164756E21
|
package/dist/index.d.ts
CHANGED
package/dist/index.modern.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{BSM as l,BigNumber as
|
|
2
|
+
import{BSM as l,BigNumber as kj,ECIES as Oj,HD as _j,OP as K,Signature as Rj,PrivateKey as xj}from"@bsv/sdk";import{Utils as Ej}from"@bsv/sdk";var r=async(j,$,J,q)=>{let z=`${J}${j}`;return(await fetch(z,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:q,format:"json"},body:JSON.stringify($)})).json()},T=(j,$)=>async(J,q)=>{return r(J,q,j,$)};import{Utils as a}from"@bsv/sdk";var{toHex:m,toArray:b}=a,C="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",p=m(b(C)),R="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva",Dj=m(b(R)),S="https://api.sigmaidentity.com/v1",F=2147483647,k="m/424150'/0'/0'",Y=`m/424150'/${F}'/${F}'`;import{BSM as E,Utils as fj,ECIES as Uj,Hash as f,PublicKey as H,BigNumber as n,HD as Mj}from"@bsv/sdk";var G={getRandomBytes(j=32){if(typeof globalThis<"u"&&globalThis.crypto&&globalThis.crypto.getRandomValues){let $=new Uint8Array(j);return globalThis.crypto.getRandomValues($),$}throw Error("Secure random number generation not available. crypto.getRandomValues() is required for cryptographic operations. This environment may not be suitable for secure key generation.")},getRandomString(j=32){let $=this.getRandomBytes(j);return Array.from($,(J)=>J.toString(16).padStart(2,"0")).join("")},getSigningPathFromHex(j,$=!0){let J="m",q=j.match(/.{1,8}/g);if(!q)throw Error("Invalid hex string");let z=2147483647;for(let Q of q){let W=Number(`0x${Q}`);if(W>z)W-=z;J+=`/${W}${$?"'":""}`}return J},getNextIdentityPath(j){let $=j.split("/"),J=$[$.length-2],q=!1;if(J.match("'"))q=!0;let z=(Number(J.replace(/[^0-9]/g,""))+1).toString();return $[$.length-2]=z+(q?"'":""),$[$.length-1]=`0${q?"'":""}`,$.join("/")},getNextPath(j){let $=j.split("/"),J=$[$.length-1],q=!1;if(J.match("'"))q=!0;let z=(Number(J.replace(/[^0-9]/g,""))+1).toString();return $[$.length-1]=z+(q?"'":""),$.join("/")}};import{BSM as g,PublicKey as zj,PrivateKey as I,BigNumber as Qj,Hash as Zj,Utils as Wj,ECIES as Lj}from"@bsv/sdk";import{ECIES as e,Utils as t,OP as h,PublicKey as o}from"@bsv/sdk";var{toArray:M,toUTF8:jj,toBase64:$j}=t,{electrumDecrypt:Jj,electrumEncrypt:qj}=e;class x{identityAttributes={};encrypt(j,$){let{privKey:J,pubKey:q}=this.getEncryptionKey(),z=$?o.fromString($):q;return $j(qj(M(j),z,J))}decrypt(j,$){let{privKey:J}=this.getEncryptionKey(),q;if($)q=o.fromString($);return jj(Jj(M(j,"base64"),J,q))}signOpReturnWithAIP(j,$){let J=this.getAIPMessageBuffer(j),{address:q,signature:z}=this.signMessage(J.flat(),$);return this.formatAIPOutput(J,q,z)}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,$)}unsetAttribute(j){delete this.identityAttributes[j]}addAttribute(j,$,J=""){let q=J;if(!J)q=G.getRandomString();this.identityAttributes[j]={value:$,nonce:q}}getAttributeUrns(){let j="";for(let $ in this.identityAttributes){let J=this.getAttributeUrn($);if(J)j+=`${J}
|
|
3
3
|
`}return j}getAttributeUrn(j){let $=this.identityAttributes[j];if($)return`urn:bap:id:${j}:${$.value}:${$.nonce}`;return null}parseStringUrns(j){let $={},J=j.replace(/^\s+/g,"").replace(/\r/gm,"").split(`
|
|
4
|
-
`);for(let q of J){let Q=q.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(Q[0]==="urn"&&Q[1]==="bap"&&Q[2]==="id"&&Q[3]&&Q[4]&&Q[5])$[Q[3]]={value:Q[4],nonce:Q[5]}}return $}parseAttributes(j){if(typeof j==="string")return this.parseStringUrns(j);for(let $ in j)if(!j[$].value||!j[$].nonce)throw
|
|
5
|
-
`);for(let q of J){let Q=q.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(Q[0]==="urn"&&Q[1]==="bap"&&Q[2]==="id"&&Q[3]&&Q[4]&&Q[5])$[Q[3]]={value:Q[4],nonce:Q[5]}}return $}getIdentityKey(){return this.identityKey}set rootPath(j){if(this.#J){if(this.#q=j,!this.#j)throw new Error("Master private key not initialized");let $=this.#j.deriveChild(this.#j.toPublicKey(),j);this.rootAddress=$.toPublicKey().toAddress(),this.#Z=j,this.#z=j}else{let $=j;if(j.split("/").length<5)$=`${k}${j}`;if(!this.validatePath($))throw new Error(`invalid signing path given ${$}`);if(this.#q=$,!this.#$)throw new Error("HD private key not initialized");let J=this.#$.derive($);this.rootAddress=J.pubKey.toAddress(),this.#Z=$,this.#z=$}this.identityKey=this.deriveIdentityKey(this.rootAddress)}get rootPath(){return this.#q}getRootPath(){return this.#q}set currentPath(j){if(this.#J)this.#Z=this.#z,this.#z=j;else{let $=j;if(j.split("/").length<5)$=`${k}${j}`;if(!this.validatePath($))throw new Error("invalid signing path given");this.#Z=this.#z,this.#z=$}}get currentPath(){return this.#z}get previousPath(){return this.#Z}get idSeed(){return this.#L}incrementPath(){this.currentPath=G.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.#q)}getIdTransaction(j=""){if(this.#z===this.#q)throw new Error("Current path equals rootPath. ID was probably not initialized properly");let $=[X(C),X("ID"),X(this.identityKey),X(this.getCurrentAddress())];return this.signOpReturnWithAIP($,j||this.#Z)}getAddress(j){if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");return this.#j.deriveChild(this.#j.toPublicKey(),j).toPublicKey().toAddress()}if(!this.#$)throw new Error("HD private key not initialized");return this.#$.derive(j).privKey.toPublicKey().toAddress()}getCurrentAddress(){return this.getAddress(this.#z)}getEncryptionKey(){if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");let J=this.#j.deriveChild(this.#j.toPublicKey(),this.#q),q=J.deriveChild(J.toPublicKey(),Y);return{privKey:q,pubKey:q.toPublicKey()}}if(!this.#$)throw new Error("HD private key not initialized");let $=this.#$.derive(this.#q).derive(Y).privKey;return{privKey:$,pubKey:$.toPublicKey()}}getEncryptionKeyType42(){if(this.#J)return this.getEncryptionKey();if(!this.#$)throw new Error("HD private key not initialized");let j=this.#$.derive(this.#q),$=j.privKey.deriveChild(j.toPublic().pubKey,Y);return{privKey:$,pubKey:$.toPublicKey()}}getEncryptionPublicKey(){let{pubKey:j}=this.getEncryptionKey();return j.toString()}getEncryptionPublicKeyWithSeed(j){return this.getEncryptionPrivateKeyWithSeed(j).toPublicKey().toString()}encrypt(j,$){let{privKey:J,pubKey:q}=this.getEncryptionKey(),z=$?S.fromString($):q;return v(A(X(j),z,null))}decrypt(j,$){let{privKey:J}=this.getEncryptionKey(),q=void 0;if($)q=S.fromString($);return n(u(X(j,"base64"),J,q))}encryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z=q.toPublicKey(),Q=J?S.fromString(J):z;return v(A(X(j),Q,q))}decryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z=void 0;if(J)z=S.fromString(J);return n(u(X(j,"base64"),q,z))}getEncryptionPrivateKeyWithSeed(j){let $=V(U.sha256(j,"utf8"));if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");let z=this.#j.deriveChild(this.#j.toPublicKey(),this.#q);return z.deriveChild(z.toPublicKey(),$)}if(!this.#$)throw new Error("HD private key not initialized");let J=G.getSigningPathFromHex($);return this.#$.derive(this.#q).derive(J).privKey}getAttestation(j){let $=U.sha256(j,"utf8");return`bap:attest:${V($)}:${this.getIdentityKey()}`}getAttestationHash(j){let $=this.getAttributeUrn(j);if(!$)return null;let J=this.getAttestation($),q=U.sha256(J,"utf8");return V(q)}signMessage(j,$){let J=$||this.#z,q;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");q=this.#j.deriveChild(this.#j.toPublicKey(),J)}else{if(!this.#$)throw new Error("HD private key not initialized");q=this.#$.derive(J).privKey}let z=q.toAddress(),Q=E.sign(j,q,"raw"),W=new o(d(j)),L=Q.CalculateRecoveryFactor(q.toPublicKey(),W),w=E.sign(j,q,"raw").toCompact(L,!0,"base64");return{address:z,signature:w}}signMessageWithSeed(j,$){let J=V(U.sha256($,"utf8")),q;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");let N=this.#j.deriveChild(this.#j.toPublicKey(),this.#q);q=N.deriveChild(N.toPublicKey(),J)}else{if(!this.#$)throw new Error("HD private key not initialized");let N=G.getSigningPathFromHex(J);q=this.#$.derive(this.#q).derive(N).privKey}let z=q.toPublicKey().toAddress(),Q=X(j,"utf8"),W=E.sign(Q,q,"raw"),L=new o(d(Q)),w=W.CalculateRecoveryFactor(q.toPublicKey(),L),B=E.sign(Q,q,"raw").toCompact(w,!0,"base64");return{address:z,signature:B}}signOpReturnWithAIP(j,$=""){let J=this.getAIPMessageBuffer(j),{address:q,signature:z}=this.signMessage(J.flat(),$);return this.formatAIPOutput(j,q,z)}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),J=await this.getApiData("/attestation/get",{hash:$});return console.log("getAttestations",j,$,J),J}import(j){this.idName=j.name,this.description=j.description||"",this.identityKey=j.identityKey,this.#q=j.rootPath,this.rootAddress=j.rootAddress,this.#Z=j.previousPath,this.#z=j.currentPath,this.#L=("idSeed"in j?j.idSeed:"")||"",this.identityAttributes=this.parseAttributes(j.identityAttributes)}export(){return{name:this.idName,description:this.description,identityKey:this.identityKey,rootPath:this.#q,rootAddress:this.rootAddress,previousPath:this.#Z,currentPath:this.#z,idSeed:this.#L,identityAttributes:this.getAttributes(),lastIdPath:""}}exportMemberBackup(){let j;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");j=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw new Error("HD private key not initialized");j=this.#$.derive(this.#z).privKey}return{name:this.idName,description:this.description,derivedPrivateKey:j.toWif(),address:j.toPublicKey().toAddress(),identityAttributes:this.getAttributes(),identityKey:this.identityKey}}newId(){this.incrementPath();let j;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");j=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw new Error("HD private key not initialized");j=this.#$.derive(this.#z).privKey}return new O(j)}exportMember(){let j=this.exportMemberBackup(),$;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");$=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw new Error("HD private key not initialized");$=this.#$.derive(this.#z).privKey}let J=v(A(X(JSON.stringify(j)),$.toPublicKey()));return{wif:j.derivedPrivateKey,encryptedData:J}}}var{toArray:Z,toUTF8:_,toBase64:c,toHex:D}=Cj,{electrumEncrypt:y,electrumDecrypt:s}=Yj;class Uj{#$;#j;#J;#Q={};#W=H;#q="";#Z="";#z=0;getApiData;constructor(j,$="",J=""){if(!j)throw new Error("No key source given");if(typeof j==="string")this.#$=Gj.fromString(j),this.#J=!1;else this.#j=Fj.fromWif(j.rootPk),this.#J=!0;if($)this.#q=$;if(J)this.#W=J;this.getApiData=T(this.#W,this.#q)}get lastIdPath(){return this.#Z}getPublicKey(j=""){if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");if(j)return this.#j.deriveChild(this.#j.toPublicKey(),j).toPublicKey().toString();return this.#j.toPublicKey().toString()}if(!this.#$)throw new Error("HD private key not initialized");if(j)return this.#$.derive(j).pubKey.toString();return this.#$.pubKey.toString()}getHdPublicKey(j=""){if(this.#J)throw new Error("HD public keys are not available in Type 42 mode");if(!this.#$)throw new Error("HD private key not initialized");if(j)return this.#$.derive(j).toPublic().toString();return this.#$.toPublic().toString()}set BAP_SERVER(j){this.#W=j;for(let $ in this.#Q)this.#Q[$].BAP_SERVER=j}get BAP_SERVER(){return this.#W}set BAP_TOKEN(j){this.#q=j;for(let $ in this.#Q)this.#Q[$].BAP_TOKEN=j}get BAP_TOKEN(){return this.#q}checkIdBelongs(j){let $;if(this.#J){if(!this.#j)throw new Error("Master private key not initialized");$=this.#j.deriveChild(this.#j.toPublicKey(),j.rootPath).toPublicKey().toAddress()}else{if(!this.#$)throw new Error("HD private key not initialized");$=this.#$.derive(j.rootPath).pubKey.toAddress()}if($!==j.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#Q)}newId(j,$,J={},q=""){let z,Q,W;if(typeof j==="object"||j===void 0||typeof j==="string"&&j.startsWith("/"))Q=typeof j==="string"?j:void 0,W=typeof j==="object"?j:typeof $==="object"?$:{},z="Default Identity";else z=j,Q=typeof $==="string"?$:void 0,W=typeof $==="object"?$:J;let L;if(Q)L=Q;else if(this.#J)L=`bap:${this.#z}`,this.#z++;else L=this.getNextValidPath();let w;if(this.#J){if(!this.#j)throw new Error("Type 42 parameters not initialized");w=new f({rootPk:this.#j},W,q)}else{if(!this.#$)throw new Error("HD private key not initialized");w=new f(this.#$,W,q)}if(w.BAP_SERVER=this.#W,w.BAP_TOKEN=this.#q,w.idName=z,w.rootPath=L,this.#J)w.currentPath=L;else w.currentPath=G.getNextPath(L);let B=w.getIdentityKey();return this.#Q[B]=w,this.#Z=L,this.#Q[B]}removeId(j){delete this.#Q[j]}getNextValidPath(){if(this.#Z)return G.getNextIdentityPath(this.#Z);return`/0'/${Object.keys(this.#Q).length}'/0'`}newIdWithCounter(j,$=`Identity ${j}`){if(!this.#J)throw new Error("newIdWithCounter only works in Type 42 mode");let J=`bap:${j}`;return this.newId($,J)}getId(j){return this.#Q[j]||null}setId(j){this.checkIdBelongs(j),this.#Q[j.getIdentityKey()]=j}importIds(j,$=!0){if($&&typeof j==="string"){this.importEncryptedIds(j);return}let J=j;if(!J.lastIdPath)throw new Error("ID cannot be imported as it is not complete");if(!J.ids)throw new Error(`ID data is not in the correct format: ${j}`);let q=j.lastIdPath;for(let z of J.ids){if(!z.identityKey||!z.identityAttributes||!z.rootAddress)throw new Error("ID cannot be imported as it is not complete");let Q;if(this.#J){if(!this.#j)throw new Error("Type 42 parameters not initialized");Q=new f({rootPk:this.#j},{},z.idSeed)}else{if(!this.#$)throw new Error("HD private key not initialized");Q=new f(this.#$,{},z.idSeed)}if(Q.BAP_SERVER=this.#W,Q.BAP_TOKEN=this.#q,Q.import(z),q==="")q=Q.currentPath;if(this.checkIdBelongs(Q),this.#Q[Q.getIdentityKey()]=Q,this.#J&&Q.rootPath.startsWith("bap:")){let W=Q.rootPath.split(":");if(W.length>=2){let L=parseInt(W[1],10);if(!isNaN(L))this.#z=Math.max(this.#z,L+1)}}}this.#Z=q}importEncryptedIds(j){let $=this.decrypt(j),J=JSON.parse($);if(Array.isArray(J)){console.log(`Importing old format:
|
|
6
|
-
`,J),this.importOldIds(J);return}if(typeof J!=="object")throw
|
|
4
|
+
`);for(let q of J){let Q=q.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(Q[0]==="urn"&&Q[1]==="bap"&&Q[2]==="id"&&Q[3]&&Q[4]&&Q[5])$[Q[3]]={value:Q[4],nonce:Q[5]}}return $}parseAttributes(j){if(typeof j==="string")return this.parseStringUrns(j);for(let $ in j)if(!j[$].value||!j[$].nonce)throw Error("Invalid identity attribute");return 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)}getAIPMessageBuffer(j,$){let J=j.findIndex((z)=>z[0]===h.OP_RETURN),q=[];if(J===-1)q.push([h.OP_RETURN]),J=0;if($)for(let z of $)q.push(j[J+z]);else for(let z of j)q.push(z);return q}formatAIPOutput(j,$,J){let q=[M("|"),M(R),M("BITCOIN_ECDSA"),M($),M(J,"base64")];return[...j,...q]}}var{magicHash:wj}=g,{toArray:P,toUTF8:Yj,toBase64:Gj,toHex:Xj}=Wj,{electrumDecrypt:Fj,electrumEncrypt:Cj}=Lj;class O extends x{key;idName;description;address;identityKey;constructor(j,$={}){super();this.key=j,this.address=j.toAddress(),this.idName="Member ID 1",this.description="",this.identityKey="",this.identityAttributes=this.parseAttributes($)}signMessage(j,$){let J=this.key,q=J.toAddress(),z=g.sign(j,J,"raw"),Q=new Qj(wj(j)),W=z.CalculateRecoveryFactor(J.toPublicKey(),Q),L=g.sign(j,J,"raw").toCompact(W,!0,"base64");return{address:q,signature:L}}signOpReturnWithAIP(j){let $=this.getAIPMessageBuffer(j),{address:J,signature:q}=this.signMessage($.flat());return this.formatAIPOutput($,J,q)}getPublicKey(){return this.key.toPublicKey().toString()}import(j){this.idName=j.name,this.description=j.description,this.key=I.fromWif(j.derivedPrivateKey),this.address=this.key.toAddress(),this.identityAttributes=j.identityAttributes||{},this.identityKey=j.identityKey}static fromMemberIdentity(j){let $=new O(I.fromWif(j.derivedPrivateKey));return $.import(j),$}static fromBackup(j){let $=new O(I.fromWif(j.wif)),J=JSON.parse($.decrypt(j.id));return $.import(J),$}export(){return{name:this.idName,description:this.description,derivedPrivateKey:this.key.toWif(),address:this.address,identityAttributes:this.getAttributes(),identityKey:this.identityKey}}getEncryptionKey(){return{privKey:this.key.deriveChild(this.key.toPublicKey(),Y),pubKey:this.key.deriveChild(this.key.toPublicKey(),Y).toPublicKey()}}getEncryptionPublicKey(){let{pubKey:j}=this.getEncryptionKey();return j.toString()}getEncryptionPrivateKeyWithSeed(j){let $=Xj(Zj.sha256(j,"utf8"));return this.key.deriveChild(this.key.toPublicKey(),$)}getEncryptionKeyWithSeed(j){let $=this.getEncryptionPrivateKeyWithSeed(j);return{privKey:$,pubKey:$.toPublicKey()}}getEncryptionPublicKeyWithSeed(j){return this.getEncryptionPrivateKeyWithSeed(j).toPublicKey().toString()}encryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z=q.toPublicKey(),Q=this.key.toPublicKey().constructor,W=J?Q.fromString(J):z;return Gj(Cj(P(j),W,q))}decryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z;if(J)z=zj.fromString(J);return Yj(Fj(P(j,"base64"),q,z))}exportForBackup(j){let $=this.export(),J=this.encrypt(JSON.stringify($));return{wif:this.key.toWif(),id:J,...j&&{label:j},createdAt:new Date().toISOString()}}}var{toArray:X,toHex:V,toBase58:Vj,toUTF8:u,toBase64:v}=fj,{electrumDecrypt:d,electrumEncrypt:A}=Uj,{magicHash:y}=E;class U extends x{#$;#j;#J;#Q=S;#W="";#q;#Z;#z;#L;idName;description;rootAddress;identityKey;identityAttributes;getApiData;constructor(j,$={},J=""){super();if(j instanceof Mj)if(this.#J=!1,J){let z=V(f.sha256(J,"utf8")),Q=G.getSigningPathFromHex(z);this.#$=j.derive(Q)}else this.#$=j;else if(this.#J=!0,this.#j=j.rootPk,J){let z=V(f.sha256(J,"utf8"));this.#j=this.#j.deriveChild(this.#j.toPublicKey(),z)}if(this.#L=J,this.idName="ID 1",this.description="",this.#q=`${k}/0/0/0`,this.#Z=`${k}/0/0/0`,this.#z=`${k}/0/0/1`,this.#J){if(!this.#j)throw Error("Master private key not initialized");let z=this.#j.deriveChild(this.#j.toPublicKey(),this.#q);this.rootAddress=z.toPublicKey().toAddress()}else{if(!this.#$)throw Error("HD private key not initialized");let z=this.#$.derive(this.#q);this.rootAddress=z.privKey.toPublicKey().toAddress()}this.identityKey=this.deriveIdentityKey(this.rootAddress);let q={...$};this.identityAttributes=this.parseAttributes(q),this.getApiData=T(this.#Q,this.#W)}set BAP_SERVER(j){this.#Q=j}get BAP_SERVER(){return this.#Q}set BAP_TOKEN(j){this.#W=j}get BAP_TOKEN(){return this.#W}deriveIdentityKey(j){let $=V(f.sha256(j,"utf8"));return Vj(f.ripemd160($,"hex"))}parseAttributes(j){if(typeof j==="string")return this.parseStringUrns(j);for(let $ in j)if(!j[$].value||!j[$].nonce)throw Error("Invalid identity attribute");return j||{}}parseStringUrns(j){let $={},J=j.replace(/^\s+/g,"").replace(/\r/gm,"").split(`
|
|
5
|
+
`);for(let q of J){let Q=q.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(Q[0]==="urn"&&Q[1]==="bap"&&Q[2]==="id"&&Q[3]&&Q[4]&&Q[5])$[Q[3]]={value:Q[4],nonce:Q[5]}}return $}getIdentityKey(){return this.identityKey}set rootPath(j){if(this.#J){if(this.#q=j,!this.#j)throw Error("Master private key not initialized");let $=this.#j.deriveChild(this.#j.toPublicKey(),j);this.rootAddress=$.toPublicKey().toAddress(),this.#Z=j,this.#z=j}else{let $=j;if(j.split("/").length<5)$=`${k}${j}`;if(!this.validatePath($))throw Error(`invalid signing path given ${$}`);if(this.#q=$,!this.#$)throw Error("HD private key not initialized");let J=this.#$.derive($);this.rootAddress=J.pubKey.toAddress(),this.#Z=$,this.#z=$}this.identityKey=this.deriveIdentityKey(this.rootAddress)}get rootPath(){return this.#q}getRootPath(){return this.#q}set currentPath(j){if(this.#J)this.#Z=this.#z,this.#z=j;else{let $=j;if(j.split("/").length<5)$=`${k}${j}`;if(!this.validatePath($))throw Error("invalid signing path given");this.#Z=this.#z,this.#z=$}}get currentPath(){return this.#z}get previousPath(){return this.#Z}get idSeed(){return this.#L}incrementPath(){this.currentPath=G.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.#q)}getIdTransaction(j=""){if(this.#z===this.#q)throw Error("Current path equals rootPath. ID was probably not initialized properly");let $=[X(C),X("ID"),X(this.identityKey),X(this.getCurrentAddress())];return this.signOpReturnWithAIP($,j||this.#Z)}getAddress(j){if(this.#J){if(!this.#j)throw Error("Master private key not initialized");return this.#j.deriveChild(this.#j.toPublicKey(),j).toPublicKey().toAddress()}if(!this.#$)throw Error("HD private key not initialized");return this.#$.derive(j).privKey.toPublicKey().toAddress()}getCurrentAddress(){return this.getAddress(this.#z)}getEncryptionKey(){if(this.#J){if(!this.#j)throw Error("Master private key not initialized");let J=this.#j.deriveChild(this.#j.toPublicKey(),this.#q),q=J.deriveChild(J.toPublicKey(),Y);return{privKey:q,pubKey:q.toPublicKey()}}if(!this.#$)throw Error("HD private key not initialized");let $=this.#$.derive(this.#q).derive(Y).privKey;return{privKey:$,pubKey:$.toPublicKey()}}getEncryptionKeyType42(){if(this.#J)return this.getEncryptionKey();if(!this.#$)throw Error("HD private key not initialized");let j=this.#$.derive(this.#q),$=j.privKey.deriveChild(j.toPublic().pubKey,Y);return{privKey:$,pubKey:$.toPublicKey()}}getEncryptionPublicKey(){let{pubKey:j}=this.getEncryptionKey();return j.toString()}getEncryptionPublicKeyWithSeed(j){return this.getEncryptionPrivateKeyWithSeed(j).toPublicKey().toString()}encrypt(j,$){let{privKey:J,pubKey:q}=this.getEncryptionKey(),z=$?H.fromString($):q;return v(A(X(j),z,J))}decrypt(j,$){let{privKey:J}=this.getEncryptionKey(),q;if($)q=H.fromString($);return u(d(X(j,"base64"),J,q))}encryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z=q.toPublicKey(),Q=J?H.fromString(J):z;return v(A(X(j),Q,q))}decryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),z;if(J)z=H.fromString(J);return u(d(X(j,"base64"),q,z))}getEncryptionPrivateKeyWithSeed(j){let $=V(f.sha256(j,"utf8"));if(this.#J){if(!this.#j)throw Error("Master private key not initialized");let z=this.#j.deriveChild(this.#j.toPublicKey(),this.#q);return z.deriveChild(z.toPublicKey(),$)}if(!this.#$)throw Error("HD private key not initialized");let J=G.getSigningPathFromHex($);return this.#$.derive(this.#q).derive(J).privKey}getAttestation(j){let $=f.sha256(j,"utf8");return`bap:attest:${V($)}:${this.getIdentityKey()}`}getAttestationHash(j){let $=this.getAttributeUrn(j);if(!$)return null;let J=this.getAttestation($),q=f.sha256(J,"utf8");return V(q)}signMessage(j,$){let J=$||this.#z,q;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");q=this.#j.deriveChild(this.#j.toPublicKey(),J)}else{if(!this.#$)throw Error("HD private key not initialized");q=this.#$.derive(J).privKey}let z=q.toAddress(),Q=E.sign(j,q,"raw"),W=new n(y(j)),L=Q.CalculateRecoveryFactor(q.toPublicKey(),W),w=E.sign(j,q,"raw").toCompact(L,!0,"base64");return{address:z,signature:w}}signMessageWithSeed(j,$){let J=V(f.sha256($,"utf8")),q;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");let N=this.#j.deriveChild(this.#j.toPublicKey(),this.#q);q=N.deriveChild(N.toPublicKey(),J)}else{if(!this.#$)throw Error("HD private key not initialized");let N=G.getSigningPathFromHex(J);q=this.#$.derive(this.#q).derive(N).privKey}let z=q.toPublicKey().toAddress(),Q=X(j,"utf8"),W=E.sign(Q,q,"raw"),L=new n(y(Q)),w=W.CalculateRecoveryFactor(q.toPublicKey(),L),B=E.sign(Q,q,"raw").toCompact(w,!0,"base64");return{address:z,signature:B}}signOpReturnWithAIP(j,$=""){let J=this.getAIPMessageBuffer(j),{address:q,signature:z}=this.signMessage(J.flat(),$);return this.formatAIPOutput(j,q,z)}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),J=await this.getApiData("/attestation/get",{hash:$});return console.log("getAttestations",j,$,J),J}import(j){this.idName=j.name,this.description=j.description||"",this.identityKey=j.identityKey,this.#q=j.rootPath,this.rootAddress=j.rootAddress,this.#Z=j.previousPath,this.#z=j.currentPath,this.#L=("idSeed"in j?j.idSeed:"")||"",this.identityAttributes=this.parseAttributes(j.identityAttributes)}export(){return{name:this.idName,description:this.description,identityKey:this.identityKey,rootPath:this.#q,rootAddress:this.rootAddress,previousPath:this.#Z,currentPath:this.#z,idSeed:this.#L,identityAttributes:this.getAttributes(),lastIdPath:""}}exportMemberBackup(){let j;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");j=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw Error("HD private key not initialized");j=this.#$.derive(this.#z).privKey}return{name:this.idName,description:this.description,derivedPrivateKey:j.toWif(),address:j.toPublicKey().toAddress(),identityAttributes:this.getAttributes(),identityKey:this.identityKey}}newId(){this.incrementPath();let j;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");j=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw Error("HD private key not initialized");j=this.#$.derive(this.#z).privKey}return new O(j)}exportMember(){let j=this.exportMemberBackup(),$;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");$=this.#j.deriveChild(this.#j.toPublicKey(),this.#z)}else{if(!this.#$)throw Error("HD private key not initialized");$=this.#$.derive(this.#z).privKey}let J=v(A(X(JSON.stringify(j)),$.toPublicKey()));return{wif:j.derivedPrivateKey,encryptedData:J}}}var{toArray:Z,toUTF8:_,toBase64:c,toHex:D}=Ej,{electrumEncrypt:s,electrumDecrypt:i}=Oj;class Bj{#$;#j;#J;#Q={};#W=S;#q="";#Z="";#z=0;getApiData;constructor(j,$="",J=""){if(!j)throw Error("No key source given");if(typeof j==="string")this.#$=_j.fromString(j),this.#J=!1;else this.#j=xj.fromWif(j.rootPk),this.#J=!0;if($)this.#q=$;if(J)this.#W=J;this.getApiData=T(this.#W,this.#q)}get lastIdPath(){return this.#Z}getPublicKey(j=""){if(this.#J){if(!this.#j)throw Error("Master private key not initialized");if(j)return this.#j.deriveChild(this.#j.toPublicKey(),j).toPublicKey().toString();return this.#j.toPublicKey().toString()}if(!this.#$)throw Error("HD private key not initialized");if(j)return this.#$.derive(j).pubKey.toString();return this.#$.pubKey.toString()}getHdPublicKey(j=""){if(this.#J)throw Error("HD public keys are not available in Type 42 mode");if(!this.#$)throw Error("HD private key not initialized");if(j)return this.#$.derive(j).toPublic().toString();return this.#$.toPublic().toString()}set BAP_SERVER(j){this.#W=j;for(let $ in this.#Q)this.#Q[$].BAP_SERVER=j}get BAP_SERVER(){return this.#W}set BAP_TOKEN(j){this.#q=j;for(let $ in this.#Q)this.#Q[$].BAP_TOKEN=j}get BAP_TOKEN(){return this.#q}checkIdBelongs(j){let $;if(this.#J){if(!this.#j)throw Error("Master private key not initialized");$=this.#j.deriveChild(this.#j.toPublicKey(),j.rootPath).toPublicKey().toAddress()}else{if(!this.#$)throw Error("HD private key not initialized");$=this.#$.derive(j.rootPath).pubKey.toAddress()}if($!==j.rootAddress)throw Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#Q)}newId(j,$,J={},q=""){let z,Q,W;if(typeof j==="object"||j===void 0||typeof j==="string"&&j.startsWith("/"))Q=typeof j==="string"?j:void 0,W=typeof j==="object"?j:typeof $==="object"?$:{},z="Default Identity";else z=j,Q=typeof $==="string"?$:void 0,W=typeof $==="object"?$:J;let L;if(Q)L=Q;else if(this.#J)L=`bap:${this.#z}`,this.#z++;else L=this.getNextValidPath();let w;if(this.#J){if(!this.#j)throw Error("Type 42 parameters not initialized");w=new U({rootPk:this.#j},W,q)}else{if(!this.#$)throw Error("HD private key not initialized");w=new U(this.#$,W,q)}if(w.BAP_SERVER=this.#W,w.BAP_TOKEN=this.#q,w.idName=z,w.rootPath=L,this.#J)w.currentPath=L;else w.currentPath=G.getNextPath(L);let B=w.getIdentityKey();return this.#Q[B]=w,this.#Z=L,this.#Q[B]}removeId(j){delete this.#Q[j]}getNextValidPath(){if(this.#Z)return G.getNextIdentityPath(this.#Z);return`/0'/${Object.keys(this.#Q).length}'/0'`}newIdWithCounter(j,$=`Identity ${j}`){if(!this.#J)throw Error("newIdWithCounter only works in Type 42 mode");let J=`bap:${j}`;return this.newId($,J)}getId(j){return this.#Q[j]||null}setId(j){this.checkIdBelongs(j),this.#Q[j.getIdentityKey()]=j}importIds(j,$=!0){if($&&typeof j==="string"){this.importEncryptedIds(j);return}let J=j;if(!J.lastIdPath)throw Error("ID cannot be imported as it is not complete");if(!J.ids)throw Error(`ID data is not in the correct format: ${j}`);let q=j.lastIdPath;for(let z of J.ids){if(!z.identityKey||!z.identityAttributes||!z.rootAddress)throw Error("ID cannot be imported as it is not complete");let Q;if(this.#J){if(!this.#j)throw Error("Type 42 parameters not initialized");Q=new U({rootPk:this.#j},{},z.idSeed)}else{if(!this.#$)throw Error("HD private key not initialized");Q=new U(this.#$,{},z.idSeed)}if(Q.BAP_SERVER=this.#W,Q.BAP_TOKEN=this.#q,Q.import(z),q==="")q=Q.currentPath;if(this.checkIdBelongs(Q),this.#Q[Q.getIdentityKey()]=Q,this.#J&&Q.rootPath.startsWith("bap:")){let W=Q.rootPath.split(":");if(W.length>=2){let L=Number.parseInt(W[1],10);if(!Number.isNaN(L))this.#z=Math.max(this.#z,L+1)}}}this.#Z=q}importEncryptedIds(j){let $=this.decrypt(j),J=JSON.parse($);if(Array.isArray(J)){console.log(`Importing old format:
|
|
6
|
+
`,J),this.importOldIds(J);return}if(typeof J!=="object")throw Error("decrypted, but found unrecognized identities format");this.importIds(J,!1)}importOldIds(j){for(let $ of j){let J;if(this.#J){if(!this.#j)throw Error("Type 42 parameters not initialized");J=new U({rootPk:this.#j},{},$.idSeed??"")}else{if(!this.#$)throw Error("HD private key not initialized");J=new U(this.#$,{},$.idSeed??"")}J.BAP_SERVER=this.#W,J.BAP_TOKEN=this.#q,J.import($),this.checkIdBelongs(J),this.#Q[J.getIdentityKey()]=J,this.#Z=J.currentPath}}exportIds(j,$=!0){let J={lastIdPath:this.#Z,ids:[]},q=j||Object.keys(this.#Q);for(let z of q){if(!this.#Q[z])throw Error(`Identity ${z} not found`);J.ids.push(this.#Q[z].export())}if($)return this.encrypt(JSON.stringify(J));return J}exportId(j,$=!0){let J={lastIdPath:this.#Z,ids:[]};if(J.ids.push(this.#Q[j].export()),$)return this.encrypt(JSON.stringify(J));return J}encrypt(j){if(this.#J){if(!this.#j)throw Error("Master private key not initialized");let J=this.#j.deriveChild(this.#j.toPublicKey(),Y);return c(s(Z(j),J.toPublicKey(),null))}if(!this.#$)throw Error("HD private key not initialized");let $=this.#$.derive(Y);return c(s(Z(j),$.pubKey,null))}decrypt(j){if(this.#J){if(!this.#j)throw Error("Master private key not initialized");let J=this.#j.deriveChild(this.#j.toPublicKey(),Y);return _(i(Z(j,"base64"),J))}if(!this.#$)throw Error("HD private key not initialized");let $=this.#$.derive(Y);return _(i(Z(j,"base64"),$.privKey))}signAttestationWithAIP(j,$,J=0,q=""){let z=this.getId($);if(!z)throw Error("Could not find identity to attest with");let Q=this.getAttestationBuffer(j,J,q),{address:W,signature:L}=z.signMessage(Q);return this.createAttestationTransaction(j,J,W,L,q)}verifyAttestationWithAIP(j){if(!j.every((q)=>Array.isArray(q))||j[0][0]!==K.OP_RETURN||D(j[1])!==p)throw Error("Not a valid BAP transaction");let $=D(j[7])==="44415441"?5:0,J={type:_(j[2]),hash:D(j[3]),sequence:_(j[4]),signingProtocol:_(j[7+$]),signingAddress:_(j[8+$]),signature:c(j[9+$])};if($&&j[3]===j[8])J.data=D(j[9]);console.log({attestation:J});try{let q=[];for(let z=0;z<6+$;z++)q.push(j[z]);J.verified=this.verifySignature(q.flat(),J.signingAddress,J.signature)}catch{J.verified=!1}return J}createAttestationTransaction(j,$,J,q,z=""){let Q=[[K.OP_RETURN],Z(C),Z("ATTEST"),Z(j),Z(`${$}`),Z("|")];if(z)Q.push(Z(C),Z("DATA"),Z(j),Z(z),Z("|"));return Q.push(Z(R),Z("BITCOIN_ECDSA"),Z(J),Z(q,"base64")),console.log({elements:Q}),Q}getAttestationBuffer(j,$=0,J=""){let q=[[K.OP_RETURN],Z(C),Z("ATTEST"),Z(j),Z(`${$}`),Z("|")];if(J)q.push(Z(C),Z("DATA"),Z(j),Z(J),Z("|"));return q.flat()}verifySignature(j,$,J){let q;if(Array.isArray(j))q=j;else if(Buffer.isBuffer(j))q=[...j];else q=Z(j,"utf8");let z=Rj.fromCompact(J,"base64"),Q;for(let W=0;W<4;W++)try{if(Q=z.RecoverPublicKey(W,new kj(l.magicHash(q))),l.verify(q,z,Q)&&Q.toAddress()===$)return!0}catch{}return!1}async verifyChallengeSignature(j,$,J,q){if(!this.verifySignature(J,$,q))return!1;try{let Q=await this.getApiData("/attestation/valid",{idKey:j,address:$,challenge:J,signature:q});if(Q?.status==="success"&&Q?.result?.valid===!0)return!0;return!1}catch(Q){return console.error("API call failed:",Q),!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})}exportForBackup(j,$,J){let z={ids:this.exportIds(),...j&&{label:j},createdAt:new Date().toISOString()};if(this.#J){if(!this.#j)throw Error("Type 42 parameters not initialized");return{...z,rootPk:this.#j.toWif()}}if(!this.#$)throw Error("HD private key not initialized");return{...z,xprv:$||this.#$.toString(),mnemonic:J||""}}exportMemberForBackup(j,$){let J=this.#Q[j];if(!J)throw Error(`Identity ${j} not found`);let q=J.exportMember();return{wif:q.wif,id:q.encryptedData,...$&&{label:$},createdAt:new Date().toISOString()}}}export{O as MemberID,U as MasterID,Bj as BAP};
|
|
7
7
|
|
|
8
|
-
//# debugId=
|
|
8
|
+
//# debugId=7C675258BEF437DC64756E2164756E21
|