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/index.module.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=4BA596E1716B79D264756E2164756E21
|