bsv-bap 0.2.0-alpha.0 → 0.2.0-alpha.2

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.
@@ -8,18 +8,13 @@ declare class MasterID {
8
8
  rootAddress: string;
9
9
  bapId: string;
10
10
  constructor(keySource: HD | Type42KeySource, idSeed?: string);
11
- /**
12
- * Get the account key (root key) for this identity.
13
- * This is the cold key used for BAP ID creation and revocation.
14
- */
15
- getAccountKey(): PrivateKey;
16
- private getPathDerivedKey;
17
11
  set rootPath(path: string);
18
12
  get rootPath(): string;
19
13
  set currentPath(path: string);
20
14
  get currentPath(): string;
21
15
  get previousPath(): string;
22
16
  get idSeed(): string;
17
+ getAccountKey(): PrivateKey;
23
18
  validatePath(path: string): boolean;
24
19
  import(identity: Identity | OldIdentity): void;
25
20
  export(): Identity;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { type APIFetcher } from "./api";
2
2
  import type { AttestationValidResponse, GetAttestationResponse, GetIdentityByAddressResponse, GetIdentityResponse } from "./apiTypes";
3
3
  import { MasterID } from "./MasterID";
4
- import { AccountID } from "./AccountID";
5
4
  import type { Attestation, Identity, OldIdentity, PathPrefix } from "./interface";
6
5
  type Identities = {
7
6
  lastIdPath: string;
@@ -44,11 +43,6 @@ export declare class BAP {
44
43
  getNextValidPath(): PathPrefix;
45
44
  newIdWithCounter(counter: number): MasterID;
46
45
  getId(bapId: string): MasterID | null;
47
- /**
48
- * Get an AccountID for the given BAP ID.
49
- * The AccountID holds the account key and can sign create/revoke transactions.
50
- */
51
- getAccountId(bapId: string): AccountID | null;
52
46
  setId(bapId: MasterID): void;
53
47
  importIds(idData: Identities | string, encrypted?: boolean): void;
54
48
  importEncryptedIds(idData: string): void;
@@ -59,10 +53,7 @@ export declare class BAP {
59
53
  exportId(idKey: string, encrypted: false): Identities;
60
54
  encrypt(string: string): string;
61
55
  decrypt(string: string): string;
62
- signAttestationWithAIP(attestationHash: string, bapId: string, counter?: number, dataString?: string): number[][];
63
56
  verifyAttestationWithAIP(tx: number[][]): Attestation;
64
- createAttestationTransaction(attestationHash: string, counter: number, address: string, signature: string, dataString?: string): number[][];
65
- getAttestationBuffer(attestationHash: string, counter?: number, dataString?: string): number[];
66
57
  verifySignature(message: string | number[], address: string, signature: string): boolean;
67
58
  verifyChallengeSignature(idKey: string, address: string, challenge: string, signature: string): Promise<boolean>;
68
59
  isValidAttestationTransaction(tx: number[][]): Promise<AttestationValidResponse | false>;
@@ -71,7 +62,7 @@ export declare class BAP {
71
62
  getAttestationsForHash(attestationHash: string): Promise<GetAttestationResponse>;
72
63
  exportForBackup(label?: string, xprv?: string, mnemonic?: string): Type42MasterBackup | Bip32MasterBackup;
73
64
  }
74
- export { MasterID, AccountID };
65
+ export { MasterID };
75
66
  export { bapIdFromAddress, bapIdFromPubkey } from "./utils";
76
67
  export type { Attestation, Identity, PathPrefix, Type42Params, };
77
68
  export * from "./apiTypes";
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{BSM as K,BigNumber as a,ECIES as e,HD as t,OP as E,Signature as ff,PrivateKey as Wf}from"@bsv/sdk";import{Utils as jf}from"@bsv/sdk";var I=async(f,W,j,$)=>{let J=`${j}${f}`;return(await fetch(J,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:$,format:"json"},body:JSON.stringify(W)})).json()},k=(f,W)=>async(j,$)=>{return I(j,$,f,W)};import{Utils as o}from"@bsv/sdk";var{toHex:_,toArray:u}=o,w="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",x=_(u(w)),R="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva",zf=_(u(R)),c="https://api.sigmaidentity.com/v1",Z=2147483647,O="m/424150'/0'/0'",C=`m/424150'/${Z}'/${Z}'`;import{Hash as m,HD as r,Utils as T}from"@bsv/sdk";import{Hash as A,PublicKey as p,Utils as P}from"@bsv/sdk";var{toHex:h,toBase58:s}=P;function X(f){let W=h(A.sha256(f,"utf8"));return s(A.ripemd160(W,"hex"))}function y(f){let W=p.fromString(f);return X(W.toAddress())}var g={getRandomBytes(f=32){if(typeof globalThis!=="undefined"&&globalThis.crypto&&globalThis.crypto.getRandomValues){let W=new Uint8Array(f);return globalThis.crypto.getRandomValues(W),W}throw new 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(f=32){let W=this.getRandomBytes(f);return Array.from(W,(j)=>j.toString(16).padStart(2,"0")).join("")},getSigningPathFromHex(f,W=!0){let j="m",$=f.match(/.{1,8}/g);if(!$)throw new Error("Invalid hex string");let J=2147483647;for(let z of $){let Q=Number(`0x${z}`);if(Q>J)Q-=J;j+=`/${Q}${W?"'":""}`}return j},getNextIdentityPath(f){let W=f.split("/"),j=W[W.length-2],$=!1;if(j.match("'"))$=!0;let J=(Number(j.replace(/[^0-9]/g,""))+1).toString();return W[W.length-2]=J+($?"'":""),W[W.length-1]=`0${$?"'":""}`,W.join("/")},getNextPath(f){let W=f.match(/^bap:(\d+)(?::(\d+))?$/);if(W){let Q=W[1],G=W[2];if(G===void 0)return`bap:${Q}:1`;return`bap:${Q}:${Number(G)+1}`}if(/^\d+$/.test(f))return(Number(f)+1).toString();if(!f.includes("/"))throw new Error(`Unsupported non-BIP32 path: ${f}`);let j=f.split("/"),$=j[j.length-1],J=!1;if($.match("'"))J=!0;let z=(Number($.replace(/[^0-9]/g,""))+1).toString();return j[j.length-1]=z+(J?"'":""),j.join("/")}};class L{#W;#f;#$;#j;#J;#q;#z;rootAddress;bapId;constructor(f,W=""){if(f instanceof r)if(this.#$=!1,W){let j=T.toHex(m.sha256(W,"utf8")),$=g.getSigningPathFromHex(j);this.#W=f.derive($)}else this.#W=f;else if(this.#$=!0,this.#f=f.rootPk,W){let j=T.toHex(m.sha256(W,"utf8"));this.#f=this.#f.deriveChild(this.#f.toPublicKey(),j)}if(this.#z=W,this.#j=`${O}/0/0/0`,this.#q=`${O}/0/0/0`,this.#J=`${O}/0/0/1`,this.#$){if(!this.#f)throw new Error("Master private key not initialized");let j=this.#f.deriveChild(this.#f.toPublicKey(),this.#j);this.rootAddress=j.toPublicKey().toAddress()}else{if(!this.#W)throw new Error("HD private key not initialized");let j=this.#W.derive(this.#j);this.rootAddress=j.privKey.toPublicKey().toAddress()}this.bapId=X(this.rootAddress)}getAccountKey(){return this.getPathDerivedKey(this.#j)}getPathDerivedKey(f){if(this.#$){if(!this.#f)throw new Error("Master private key not initialized");return this.#f.deriveChild(this.#f.toPublicKey(),f)}if(!this.#W)throw new Error("HD private key not initialized");return this.#W.derive(f).privKey}set rootPath(f){if(this.#$){if(this.#j=f,!this.#f)throw new Error("Master private key not initialized");let W=this.#f.deriveChild(this.#f.toPublicKey(),f);this.rootAddress=W.toPublicKey().toAddress(),this.#q=f,this.#J=f}else{let W=f;if(f.split("/").length<5)W=`${O}${f}`;if(!this.validatePath(W))throw new Error(`invalid signing path given ${W}`);if(this.#j=W,!this.#W)throw new Error("HD private key not initialized");let j=this.#W.derive(W);this.rootAddress=j.pubKey.toAddress(),this.#q=W,this.#J=W}this.bapId=X(this.rootAddress)}get rootPath(){return this.#j}set currentPath(f){if(this.#$)this.#q=this.#J,this.#J=f;else{let W=f;if(f.split("/").length<5)W=`${O}${f}`;if(!this.validatePath(W))throw new Error("invalid signing path given");this.#q=this.#J,this.#J=W}}get currentPath(){return this.#J}get previousPath(){return this.#q}get idSeed(){return this.#z}validatePath(f){if(f.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 W=f.split("/");if(W.length===7&&Number(W[1].replace("'",""))<=Z&&Number(W[2].replace("'",""))<=Z&&Number(W[3].replace("'",""))<=Z&&Number(W[4].replace("'",""))<=Z&&Number(W[5].replace("'",""))<=Z&&Number(W[6].replace("'",""))<=Z)return!0}return!1}import(f){this.bapId="bapId"in f?f.bapId:f.identityKey,this.#j=f.rootPath,this.rootAddress=f.rootAddress,this.#q=f.previousPath,this.#J=f.currentPath,this.#z=("idSeed"in f?f.idSeed:"")||""}export(){return{bapId:this.bapId,rootPath:this.#j,rootAddress:this.rootAddress,previousPath:this.#q,currentPath:this.#J,idSeed:this.#z,lastIdPath:""}}}import{Hash as S,Utils as l,OP as D}from"@bsv/sdk";import{Utils as d,OP as H,BSM as U,BigNumber as i}from"@bsv/sdk";var{toArray:M,toBase64:Cf}=d;class V{signWithBSM(f,W){let j=W.toPublicKey().toAddress(),$=U.sign(f,W,"raw"),J=new i(U.magicHash(f)),z=$.CalculateRecoveryFactor(W.toPublicKey(),J),Q=U.sign(f,W,"raw").toCompact(z,!0,"base64");return{address:j,signature:Q}}signOpReturnWithAIP(f){let W=this.getAIPMessageBuffer(f),{address:j,signature:$}=this.signMessage(W.flat());return this.formatAIPOutput(W,j,$)}getAIPMessageBuffer(f,W){let j=f.findIndex((J)=>J[0]===H.OP_RETURN),$=[];if(j===-1)$.push([H.OP_RETURN]),j=0;if(W)for(let J of W)$.push(f[j+J]);else for(let J of f)$.push(J);return $}formatAIPOutput(f,W,j){let $=[M("|"),M(R),M("BITCOIN_ECDSA"),M(W),M(j,"base64")];return[...f,...$]}}var{toArray:Y}=l;class N extends V{key;constructor(f){super();this.key=f}getBapId(){let f=Y(this.getRootAddress()),W=S.sha256(f),j=S.ripemd160(W);return l.toBase58(j)}getRootAddress(){return this.key.toPublicKey().toAddress()}getRootPublicKey(){return this.key.toPublicKey().toString()}signMessage(f){return this.signWithBSM(f,this.key)}getInitialIdTransaction(f){let W=[[D.OP_RETURN],Y(w),Y("ID"),Y(this.getBapId()),Y(f)];return this.signOpReturnWithAIP(W)}getRevocationTransaction(){let f=[[D.OP_RETURN],Y(w),Y("ID"),Y(this.getBapId()),Y("0")];return this.signOpReturnWithAIP(f)}}var{toArray:q,toUTF8:F,toBase64:b,toHex:B}=jf,{electrumEncrypt:n,electrumDecrypt:v}=e;class $f{#W;#f;#$;#j={};#J=c;#q="";#z="";#Q=0;getApiData;constructor(f,W="",j=""){if(!f)throw new Error("No key source given");if(typeof f==="string")this.#W=t.fromString(f),this.#$=!1;else this.#f=Wf.fromWif(f.rootPk),this.#$=!0;if(W)this.#q=W;if(j)this.#J=j;this.getApiData=k(this.#J,this.#q)}get lastIdPath(){return this.#z}getPublicKey(f=""){if(this.#$){if(!this.#f)throw new Error("Master private key not initialized");if(f)return this.#f.deriveChild(this.#f.toPublicKey(),f).toPublicKey().toString();return this.#f.toPublicKey().toString()}if(!this.#W)throw new Error("HD private key not initialized");if(f)return this.#W.derive(f).pubKey.toString();return this.#W.pubKey.toString()}getHdPublicKey(f=""){if(this.#$)throw new Error("HD public keys are not available in Type 42 mode");if(!this.#W)throw new Error("HD private key not initialized");if(f)return this.#W.derive(f).toPublic().toString();return this.#W.toPublic().toString()}set BAP_SERVER(f){this.#J=f}get BAP_SERVER(){return this.#J}set BAP_TOKEN(f){this.#q=f}get BAP_TOKEN(){return this.#q}checkIdBelongs(f){let W;if(this.#$){if(!this.#f)throw new Error("Master private key not initialized");W=this.#f.deriveChild(this.#f.toPublicKey(),f.rootPath).toPublicKey().toAddress()}else{if(!this.#W)throw new Error("HD private key not initialized");W=this.#W.derive(f.rootPath).pubKey.toAddress()}if(W!==f.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#j)}newId(f,W=""){let j;if(f)j=f;else if(this.#$)j=`bap:${this.#Q}`,this.#Q++;else j=this.getNextValidPath();let $;if(this.#$){if(!this.#f)throw new Error("Type 42 parameters not initialized");$=new L({rootPk:this.#f},W)}else{if(!this.#W)throw new Error("HD private key not initialized");$=new L(this.#W,W)}if($.rootPath=j,this.#$)$.currentPath=j;else $.currentPath=g.getNextPath(j);return this.#j[$.bapId]=$,this.#z=j,this.#j[$.bapId]}removeId(f){delete this.#j[f]}getNextValidPath(){if(this.#z)return g.getNextIdentityPath(this.#z);return`/0'/${Object.keys(this.#j).length}'/0'`}newIdWithCounter(f){if(!this.#$)throw new Error("newIdWithCounter only works in Type 42 mode");return this.newId(`bap:${f}`)}getId(f){return this.#j[f]||null}getAccountId(f){let W=this.#j[f];if(!W)return null;return new N(W.getAccountKey())}setId(f){this.checkIdBelongs(f),this.#j[f.bapId]=f}importIds(f,W=!0){if(W&&typeof f==="string"){this.importEncryptedIds(f);return}let j=f;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: ${f}`);let $=j.lastIdPath;for(let J of j.ids){if(!J.rootAddress)throw new Error("ID cannot be imported as it is not complete");let z;if(this.#$){if(!this.#f)throw new Error("Type 42 parameters not initialized");z=new L({rootPk:this.#f},J.idSeed)}else{if(!this.#W)throw new Error("HD private key not initialized");z=new L(this.#W,J.idSeed)}if(z.import(J),$==="")$=z.currentPath;if(this.checkIdBelongs(z),this.#j[z.bapId]=z,this.#$&&z.rootPath.startsWith("bap:")){let Q=z.rootPath.split(":");if(Q.length>=2){let G=Number.parseInt(Q[1],10);if(!Number.isNaN(G))this.#Q=Math.max(this.#Q,G+1)}}}this.#z=$}importEncryptedIds(f){let W=this.decrypt(f),j=JSON.parse(W);if(Array.isArray(j)){this.importOldIds(j);return}if(typeof j!=="object")throw new Error("decrypted, but found unrecognized identities format");this.importIds(j,!1)}importOldIds(f){for(let W of f){let j;if(this.#$){if(!this.#f)throw new Error("Type 42 parameters not initialized");j=new L({rootPk:this.#f},W.idSeed??"")}else{if(!this.#W)throw new Error("HD private key not initialized");j=new L(this.#W,W.idSeed??"")}j.import(W),this.checkIdBelongs(j),this.#j[j.bapId]=j,this.#z=j.currentPath}}exportIds(f,W=!0){let j={lastIdPath:this.#z,ids:[]},$=f||Object.keys(this.#j);for(let J of $){if(!this.#j[J])throw new Error(`Identity ${J} not found`);j.ids.push(this.#j[J].export())}if(W)return this.encrypt(JSON.stringify(j));return j}exportId(f,W=!0){let j={lastIdPath:this.#z,ids:[]};if(j.ids.push(this.#j[f].export()),W)return this.encrypt(JSON.stringify(j));return j}encrypt(f){if(this.#$){if(!this.#f)throw new Error("Master private key not initialized");let j=this.#f.deriveChild(this.#f.toPublicKey(),C);return b(n(q(f),j.toPublicKey()))}if(!this.#W)throw new Error("HD private key not initialized");let W=this.#W.derive(C);return b(n(q(f),W.pubKey))}decrypt(f){if(this.#$){if(!this.#f)throw new Error("Master private key not initialized");let j=this.#f.deriveChild(this.#f.toPublicKey(),C);return F(v(q(f,"base64"),j))}if(!this.#W)throw new Error("HD private key not initialized");let W=this.#W.derive(C);return F(v(q(f,"base64"),W.privKey))}signAttestationWithAIP(f,W,j=0,$=""){if(!this.getId(W))throw new Error("Could not find identity to attest with");let z=this.getAttestationBuffer(f,j,$);return this.createAttestationTransaction(f,j,"","",$)}verifyAttestationWithAIP(f){if(!f.every(($)=>Array.isArray($))||f[0][0]!==E.OP_RETURN||B(f[1])!==x)throw new Error("Not a valid BAP transaction");let W=B(f[7])==="44415441"?5:0,j={type:F(f[2]),hash:B(f[3]),sequence:F(f[4]),signingProtocol:F(f[7+W]),signingAddress:F(f[8+W]),signature:b(f[9+W])};if(W&&f[3]===f[8])j.data=B(f[9]);try{let $=[];for(let J=0;J<6+W;J++)$.push(f[J]);j.verified=this.verifySignature($.flat(),j.signingAddress,j.signature)}catch{j.verified=!1}return j}createAttestationTransaction(f,W,j,$,J=""){let z=[[E.OP_RETURN],q(w),q("ATTEST"),q(f),q(`${W}`),q("|")];if(J)z.push(q(w),q("DATA"),q(f),q(J),q("|"));return z.push(q(R),q("BITCOIN_ECDSA"),q(j),q($,"base64")),z}getAttestationBuffer(f,W=0,j=""){let $=[[E.OP_RETURN],q(w),q("ATTEST"),q(f),q(`${W}`),q("|")];if(j)$.push(q(w),q("DATA"),q(f),q(j),q("|"));return $.flat()}verifySignature(f,W,j){let $;if(Array.isArray(f))$=f;else if(Buffer.isBuffer(f))$=[...f];else $=q(f,"utf8");let J=ff.fromCompact(j,"base64");for(let z=0;z<4;z++)try{let Q=J.RecoverPublicKey(z,new a(K.magicHash($)));if(K.verify($,J,Q)&&Q.toAddress()===W)return!0}catch{}return!1}async verifyChallengeSignature(f,W,j,$){if(!this.verifySignature(j,W,$))return!1;try{let z=await this.getApiData("/attestation/valid",{idKey:f,address:W,challenge:j,signature:$});return z?.status==="success"&&z?.result?.valid===!0}catch{return!1}}async isValidAttestationTransaction(f){if(this.verifyAttestationWithAIP(f))return this.getApiData("/attestation/valid",{tx:f});return!1}async getIdentityFromAddress(f){return this.getApiData("/identity/validByAddress",{address:f})}async getIdentity(f){return this.getApiData("/identity/get",{idKey:f})}async getAttestationsForHash(f){return this.getApiData("/attestations",{hash:f})}exportForBackup(f,W,j){let J={ids:this.exportIds(),...f&&{label:f},createdAt:new Date().toISOString()};if(this.#$){if(!this.#f)throw new Error("Type 42 parameters not initialized");return{...J,rootPk:this.#f.toWif()}}if(!this.#W)throw new Error("HD private key not initialized");return{...J,xprv:W||this.#W.toString(),mnemonic:j||""}}}export{y as bapIdFromPubkey,X as bapIdFromAddress,L as MasterID,$f as BAP,N as AccountID};
2
+ import{BSM as V,BigNumber as r,ECIES as T,HD as K,OP as D,Signature as x,PrivateKey as s}from"@bsv/sdk";import{Utils as I}from"@bsv/sdk";var R=async(f,o,w,$)=>{let z=`${w}${f}`;return(await fetch(z,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:$,format:"json"},body:JSON.stringify(o)})).json()},N=(f,o)=>async(w,$)=>{return R(w,$,f,o)};import{Utils as _}from"@bsv/sdk";var{toHex:A,toArray:M}=_,k="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",n=A(M(k)),b="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva",y=A(M(b)),O="https://api.sigmaidentity.com/v1",J=2147483647,Q="m/424150'/0'/0'",X=`m/424150'/${J}'/${J}'`;import{Hash as g,HD as S,Utils as l}from"@bsv/sdk";import{Hash as U,PublicKey as B,Utils as H}from"@bsv/sdk";var{toHex:i,toBase58:c}=H;function h(f){let o=i(U.sha256(f,"utf8"));return c(U.ripemd160(o,"hex"))}function v(f){let o=B.fromString(f);return h(o.toAddress())}var F={getRandomBytes(f=32){if(typeof globalThis!=="undefined"&&globalThis.crypto&&globalThis.crypto.getRandomValues){let o=new Uint8Array(f);return globalThis.crypto.getRandomValues(o),o}throw new 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(f=32){let o=this.getRandomBytes(f);return Array.from(o,(w)=>w.toString(16).padStart(2,"0")).join("")},getSigningPathFromHex(f,o=!0){let w="m",$=f.match(/.{1,8}/g);if(!$)throw new Error("Invalid hex string");let z=2147483647;for(let j of $){let G=Number(`0x${j}`);if(G>z)G-=z;w+=`/${G}${o?"'":""}`}return w},getNextIdentityPath(f){let o=f.split("/"),w=o[o.length-2],$=!1;if(w.match("'"))$=!0;let z=(Number(w.replace(/[^0-9]/g,""))+1).toString();return o[o.length-2]=z+($?"'":""),o[o.length-1]=`0${$?"'":""}`,o.join("/")},getNextPath(f){let o=f.match(/^bap:(\d+)(?::(\d+))?$/);if(o){let G=o[1],Z=o[2];if(Z===void 0)return`bap:${G}:1`;return`bap:${G}:${Number(Z)+1}`}if(/^\d+$/.test(f))return(Number(f)+1).toString();if(!f.includes("/"))throw new Error(`Unsupported non-BIP32 path: ${f}`);let w=f.split("/"),$=w[w.length-1],z=!1;if($.match("'"))z=!0;let j=(Number($.replace(/[^0-9]/g,""))+1).toString();return w[w.length-1]=j+(z?"'":""),w.join("/")}};class q{#o;#f;#w;#$;#z;#j;#G;rootAddress;bapId;constructor(f,o=""){if(f instanceof S)if(this.#w=!1,o){let w=l.toHex(g.sha256(o,"utf8")),$=F.getSigningPathFromHex(w);this.#o=f.derive($)}else this.#o=f;else if(this.#w=!0,this.#f=f.rootPk,o){let w=l.toHex(g.sha256(o,"utf8"));this.#f=this.#f.deriveChild(this.#f.toPublicKey(),w)}if(this.#G=o,this.#$=`${Q}/0/0/0`,this.#j=`${Q}/0/0/0`,this.#z=`${Q}/0/0/1`,this.#w){if(!this.#f)throw new Error("Master private key not initialized");let w=this.#f.deriveChild(this.#f.toPublicKey(),this.#$);this.rootAddress=w.toPublicKey().toAddress()}else{if(!this.#o)throw new Error("HD private key not initialized");let w=this.#o.derive(this.#$);this.rootAddress=w.privKey.toPublicKey().toAddress()}this.bapId=h(this.rootAddress)}set rootPath(f){if(this.#w){if(this.#$=f,!this.#f)throw new Error("Master private key not initialized");let o=this.#f.deriveChild(this.#f.toPublicKey(),f);this.rootAddress=o.toPublicKey().toAddress(),this.#j=f,this.#z=f}else{let o=f;if(f.split("/").length<5)o=`${Q}${f}`;if(!this.validatePath(o))throw new Error(`invalid signing path given ${o}`);if(this.#$=o,!this.#o)throw new Error("HD private key not initialized");let w=this.#o.derive(o);this.rootAddress=w.pubKey.toAddress(),this.#j=o,this.#z=o}this.bapId=h(this.rootAddress)}get rootPath(){return this.#$}set currentPath(f){if(this.#w)this.#j=this.#z,this.#z=f;else{let o=f;if(f.split("/").length<5)o=`${Q}${f}`;if(!this.validatePath(o))throw new Error("invalid signing path given");this.#j=this.#z,this.#z=o}}get currentPath(){return this.#z}get previousPath(){return this.#j}get idSeed(){return this.#G}getAccountKey(){if(this.#w){if(!this.#f)throw new Error("Master private key not initialized");return this.#f}if(!this.#o)throw new Error("HD private key not initialized");return this.#o.privKey}validatePath(f){if(f.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 o=f.split("/");if(o.length===7&&Number(o[1].replace("'",""))<=J&&Number(o[2].replace("'",""))<=J&&Number(o[3].replace("'",""))<=J&&Number(o[4].replace("'",""))<=J&&Number(o[5].replace("'",""))<=J&&Number(o[6].replace("'",""))<=J)return!0}return!1}import(f){this.bapId="bapId"in f?f.bapId:f.identityKey,this.#$=f.rootPath,this.rootAddress=f.rootAddress,this.#j=f.previousPath,this.#z=f.currentPath,this.#G=("idSeed"in f?f.idSeed:"")||""}export(){return{bapId:this.bapId,rootPath:this.#$,rootAddress:this.rootAddress,previousPath:this.#j,currentPath:this.#z,idSeed:this.#G,lastIdPath:""}}}var{toArray:Y,toUTF8:W,toBase64:C,toHex:L}=I,{electrumEncrypt:u,electrumDecrypt:E}=T;class m{#o;#f;#w;#$={};#z=O;#j="";#G="";#J=0;getApiData;constructor(f,o="",w=""){if(!f)throw new Error("No key source given");if(typeof f==="string")this.#o=K.fromString(f),this.#w=!1;else this.#f=s.fromWif(f.rootPk),this.#w=!0;if(o)this.#j=o;if(w)this.#z=w;this.getApiData=N(this.#z,this.#j)}get lastIdPath(){return this.#G}getPublicKey(f=""){if(this.#w){if(!this.#f)throw new Error("Master private key not initialized");if(f)return this.#f.deriveChild(this.#f.toPublicKey(),f).toPublicKey().toString();return this.#f.toPublicKey().toString()}if(!this.#o)throw new Error("HD private key not initialized");if(f)return this.#o.derive(f).pubKey.toString();return this.#o.pubKey.toString()}getHdPublicKey(f=""){if(this.#w)throw new Error("HD public keys are not available in Type 42 mode");if(!this.#o)throw new Error("HD private key not initialized");if(f)return this.#o.derive(f).toPublic().toString();return this.#o.toPublic().toString()}set BAP_SERVER(f){this.#z=f}get BAP_SERVER(){return this.#z}set BAP_TOKEN(f){this.#j=f}get BAP_TOKEN(){return this.#j}checkIdBelongs(f){let o;if(this.#w){if(!this.#f)throw new Error("Master private key not initialized");o=this.#f.deriveChild(this.#f.toPublicKey(),f.rootPath).toPublicKey().toAddress()}else{if(!this.#o)throw new Error("HD private key not initialized");o=this.#o.derive(f.rootPath).pubKey.toAddress()}if(o!==f.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#$)}newId(f,o=""){let w;if(f)w=f;else if(this.#w)w=`bap:${this.#J}`,this.#J++;else w=this.getNextValidPath();let $;if(this.#w){if(!this.#f)throw new Error("Type 42 parameters not initialized");$=new q({rootPk:this.#f},o)}else{if(!this.#o)throw new Error("HD private key not initialized");$=new q(this.#o,o)}if($.rootPath=w,this.#w)$.currentPath=w;else $.currentPath=F.getNextPath(w);return this.#$[$.bapId]=$,this.#G=w,this.#$[$.bapId]}removeId(f){delete this.#$[f]}getNextValidPath(){if(this.#G)return F.getNextIdentityPath(this.#G);return`/0'/${Object.keys(this.#$).length}'/0'`}newIdWithCounter(f){if(!this.#w)throw new Error("newIdWithCounter only works in Type 42 mode");return this.newId(`bap:${f}`)}getId(f){return this.#$[f]||null}setId(f){this.checkIdBelongs(f),this.#$[f.bapId]=f}importIds(f,o=!0){if(o&&typeof f==="string"){this.importEncryptedIds(f);return}let w=f;if(!w.lastIdPath)throw new Error("ID cannot be imported as it is not complete");if(!w.ids)throw new Error(`ID data is not in the correct format: ${f}`);let $=w.lastIdPath;for(let z of w.ids){if(!z.rootAddress)throw new Error("ID cannot be imported as it is not complete");let j;if(this.#w){if(!this.#f)throw new Error("Type 42 parameters not initialized");j=new q({rootPk:this.#f},z.idSeed)}else{if(!this.#o)throw new Error("HD private key not initialized");j=new q(this.#o,z.idSeed)}if(j.import(z),$==="")$=j.currentPath;if(this.checkIdBelongs(j),this.#$[j.bapId]=j,this.#w&&j.rootPath.startsWith("bap:")){let G=j.rootPath.split(":");if(G.length>=2){let Z=Number.parseInt(G[1],10);if(!Number.isNaN(Z))this.#J=Math.max(this.#J,Z+1)}}}this.#G=$}importEncryptedIds(f){let o=this.decrypt(f),w=JSON.parse(o);if(Array.isArray(w)){this.importOldIds(w);return}if(typeof w!=="object")throw new Error("decrypted, but found unrecognized identities format");this.importIds(w,!1)}importOldIds(f){for(let o of f){let w;if(this.#w){if(!this.#f)throw new Error("Type 42 parameters not initialized");w=new q({rootPk:this.#f},o.idSeed??"")}else{if(!this.#o)throw new Error("HD private key not initialized");w=new q(this.#o,o.idSeed??"")}w.import(o),this.checkIdBelongs(w),this.#$[w.bapId]=w,this.#G=w.currentPath}}exportIds(f,o=!0){let w={lastIdPath:this.#G,ids:[]},$=f||Object.keys(this.#$);for(let z of $){if(!this.#$[z])throw new Error(`Identity ${z} not found`);w.ids.push(this.#$[z].export())}if(o)return this.encrypt(JSON.stringify(w));return w}exportId(f,o=!0){let w={lastIdPath:this.#G,ids:[]};if(w.ids.push(this.#$[f].export()),o)return this.encrypt(JSON.stringify(w));return w}encrypt(f){if(this.#w){if(!this.#f)throw new Error("Master private key not initialized");let w=this.#f.deriveChild(this.#f.toPublicKey(),X);return C(u(Y(f),w.toPublicKey()))}if(!this.#o)throw new Error("HD private key not initialized");let o=this.#o.derive(X);return C(u(Y(f),o.pubKey))}decrypt(f){if(this.#w){if(!this.#f)throw new Error("Master private key not initialized");let w=this.#f.deriveChild(this.#f.toPublicKey(),X);return W(E(Y(f,"base64"),w))}if(!this.#o)throw new Error("HD private key not initialized");let o=this.#o.derive(X);return W(E(Y(f,"base64"),o.privKey))}verifyAttestationWithAIP(f){if(!f.every(($)=>Array.isArray($))||f[0][0]!==D.OP_RETURN||L(f[1])!==n)throw new Error("Not a valid BAP transaction");let o=L(f[7])==="44415441"?5:0,w={type:W(f[2]),hash:L(f[3]),sequence:W(f[4]),signingProtocol:W(f[7+o]),signingAddress:W(f[8+o]),signature:C(f[9+o])};if(o&&f[3]===f[8])w.data=L(f[9]);try{let $=[];for(let z=0;z<6+o;z++)$.push(f[z]);w.verified=this.verifySignature($.flat(),w.signingAddress,w.signature)}catch{w.verified=!1}return w}verifySignature(f,o,w){let $;if(Array.isArray(f))$=f;else if(Buffer.isBuffer(f))$=[...f];else $=Y(f,"utf8");let z=x.fromCompact(w,"base64");for(let j=0;j<4;j++)try{let G=z.RecoverPublicKey(j,new r(V.magicHash($)));if(V.verify($,z,G)&&G.toAddress()===o)return!0}catch{}return!1}async verifyChallengeSignature(f,o,w,$){if(!this.verifySignature(w,o,$))return!1;try{let j=await this.getApiData("/attestation/valid",{idKey:f,address:o,challenge:w,signature:$});return j?.status==="success"&&j?.result?.valid===!0}catch{return!1}}async isValidAttestationTransaction(f){if(this.verifyAttestationWithAIP(f))return this.getApiData("/attestation/valid",{tx:f});return!1}async getIdentityFromAddress(f){return this.getApiData("/identity/validByAddress",{address:f})}async getIdentity(f){return this.getApiData("/identity/get",{idKey:f})}async getAttestationsForHash(f){return this.getApiData("/attestations",{hash:f})}exportForBackup(f,o,w){let z={ids:this.exportIds(),...f&&{label:f},createdAt:new Date().toISOString()};if(this.#w){if(!this.#f)throw new Error("Type 42 parameters not initialized");return{...z,rootPk:this.#f.toWif()}}if(!this.#o)throw new Error("HD private key not initialized");return{...z,xprv:o||this.#o.toString(),mnemonic:w||""}}}export{v as bapIdFromPubkey,h as bapIdFromAddress,q as MasterID,m as BAP};
3
3
 
4
- //# debugId=CE6EBB069BD6BC1764756E2164756E21
4
+ //# debugId=23864B19C0C06C4464756E2164756E21
@@ -1,16 +1,14 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/api.ts", "../src/constants.ts", "../src/MasterID.ts", "../src/utils.ts", "../src/AccountID.ts", "../src/BaseClass.ts"],
3
+ "sources": ["../src/index.ts", "../src/api.ts", "../src/constants.ts", "../src/MasterID.ts", "../src/utils.ts"],
4
4
  "sourcesContent": [
5
- "import {\n BSM,\n BigNumber,\n ECIES,\n HD,\n OP,\n Signature,\n PrivateKey,\n} from \"@bsv/sdk\";\n\nimport { Utils as BSVUtils } from \"@bsv/sdk\";\nimport { type APIFetcher, apiFetcher } from \"./api\";\nimport type {\n AttestationValidResponse,\n GetAttestationResponse,\n GetIdentityByAddressResponse,\n GetIdentityResponse,\n} from \"./apiTypes\";\nimport {\n AIP_BITCOM_ADDRESS,\n BAP_BITCOM_ADDRESS,\n BAP_BITCOM_ADDRESS_HEX,\n BAP_SERVER,\n ENCRYPTION_PATH,\n} from \"./constants\";\nimport { MasterID } from \"./MasterID\";\nimport { AccountID } from \"./AccountID\";\nimport type {\n Attestation,\n Identity,\n OldIdentity,\n PathPrefix,\n} from \"./interface\";\nimport { Utils } from \"./utils\";\nconst { toArray, toUTF8, toBase64, toHex } = BSVUtils;\nconst { electrumEncrypt, electrumDecrypt } = ECIES;\n\ntype Identities = { lastIdPath: string; ids: Identity[] };\n\n/** Backup format for Type 42 mode (rootPk-based) */\nexport interface Type42MasterBackup {\n ids: string;\n rootPk: string;\n mnemonic?: string;\n label?: string;\n createdAt: string;\n}\n\n/** Backup format for BIP32 mode (xprv-based, legacy) */\nexport interface Bip32MasterBackup {\n ids: string;\n xprv: string;\n mnemonic?: string;\n label?: string;\n createdAt: string;\n}\n\ninterface Type42Params {\n rootPk: string;\n}\n\nexport class BAP {\n #HDPrivateKey: HD | undefined;\n #masterPrivateKey: PrivateKey | undefined;\n #isType42: boolean;\n #ids: { [key: string]: MasterID } = {};\n #BAP_SERVER = BAP_SERVER;\n #BAP_TOKEN = \"\";\n #lastIdPath = \"\";\n #identityCounter = 0;\n getApiData: APIFetcher;\n\n constructor(keySource: string | Type42Params, token = \"\", server = \"\") {\n if (!keySource) {\n throw new Error(\"No key source given\");\n }\n\n if (typeof keySource === \"string\") {\n this.#HDPrivateKey = HD.fromString(keySource);\n this.#isType42 = false;\n } else {\n this.#masterPrivateKey = PrivateKey.fromWif(keySource.rootPk);\n this.#isType42 = true;\n }\n\n if (token) this.#BAP_TOKEN = token;\n if (server) this.#BAP_SERVER = server;\n\n this.getApiData = apiFetcher(this.#BAP_SERVER, this.#BAP_TOKEN);\n }\n\n get lastIdPath(): string {\n return this.#lastIdPath;\n }\n\n getPublicKey(childPath = \"\"): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n if (childPath) {\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n childPath\n );\n return derivedKey.toPublicKey().toString();\n }\n return this.#masterPrivateKey.toPublicKey().toString();\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n if (childPath) {\n return this.#HDPrivateKey.derive(childPath).pubKey.toString();\n }\n return this.#HDPrivateKey.pubKey.toString();\n }\n\n getHdPublicKey(childPath = \"\"): string {\n if (this.#isType42) {\n throw new Error(\"HD public keys are not available in Type 42 mode\");\n }\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n if (childPath) {\n return this.#HDPrivateKey.derive(childPath).toPublic().toString();\n }\n return this.#HDPrivateKey.toPublic().toString();\n }\n\n set BAP_SERVER(bapServer) {\n this.#BAP_SERVER = bapServer;\n }\n\n get BAP_SERVER(): string {\n return this.#BAP_SERVER;\n }\n\n set BAP_TOKEN(token) {\n this.#BAP_TOKEN = token;\n }\n\n get BAP_TOKEN(): string {\n return this.#BAP_TOKEN;\n }\n\n checkIdBelongs(bapId: MasterID): boolean {\n let checkRootAddress: string;\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n bapId.rootPath\n );\n checkRootAddress = derivedKey.toPublicKey().toAddress();\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(bapId.rootPath);\n checkRootAddress = derivedChild.pubKey.toAddress();\n }\n\n if (checkRootAddress !== bapId.rootAddress) {\n throw new Error(\"ID does not belong to this private key\");\n }\n\n return true;\n }\n\n listIds(): string[] {\n return Object.keys(this.#ids);\n }\n\n newId(customPath?: string, idSeed = \"\"): MasterID {\n\n let pathToUse: string;\n if (customPath) {\n pathToUse = customPath;\n } else if (this.#isType42) {\n pathToUse = `bap:${this.#identityCounter}`;\n this.#identityCounter++;\n } else {\n pathToUse = this.getNextValidPath();\n }\n\n let newIdentity: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n newIdentity = new MasterID({ rootPk: this.#masterPrivateKey }, idSeed);\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n newIdentity = new MasterID(this.#HDPrivateKey, idSeed);\n }\n\n newIdentity.rootPath = pathToUse;\n\n if (this.#isType42) {\n newIdentity.currentPath = pathToUse;\n } else {\n newIdentity.currentPath = Utils.getNextPath(pathToUse);\n }\n\n this.#ids[newIdentity.bapId] = newIdentity;\n this.#lastIdPath = pathToUse;\n\n return this.#ids[newIdentity.bapId];\n }\n\n removeId(bapId: string): void {\n delete this.#ids[bapId];\n }\n\n getNextValidPath(): PathPrefix {\n if (this.#lastIdPath) {\n return Utils.getNextIdentityPath(this.#lastIdPath);\n }\n return `/0'/${Object.keys(this.#ids).length}'/0'`;\n }\n\n newIdWithCounter(counter: number): MasterID {\n if (!this.#isType42) {\n throw new Error(\"newIdWithCounter only works in Type 42 mode\");\n }\n return this.newId(`bap:${counter}`);\n }\n\n getId(bapId: string): MasterID | null {\n return this.#ids[bapId] || null;\n }\n\n /**\n * Get an AccountID for the given BAP ID.\n * The AccountID holds the account key and can sign create/revoke transactions.\n */\n getAccountId(bapId: string): AccountID | null {\n const masterId = this.#ids[bapId];\n if (!masterId) return null;\n return new AccountID(masterId.getAccountKey());\n }\n\n setId(bapId: MasterID): void {\n this.checkIdBelongs(bapId);\n this.#ids[bapId.bapId] = bapId;\n }\n\n importIds(idData: Identities | string, encrypted = true): void {\n if (encrypted && typeof idData === \"string\") {\n this.importEncryptedIds(idData);\n return;\n }\n const identity = idData as Identities;\n if (!identity.lastIdPath) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n if (!identity.ids) {\n throw new Error(`ID data is not in the correct format: ${idData}`);\n }\n\n let lastIdPath = identity.lastIdPath;\n for (const id of identity.ids) {\n if (!id.rootAddress) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n\n let importId: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n importId = new MasterID({ rootPk: this.#masterPrivateKey }, id.idSeed);\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n importId = new MasterID(this.#HDPrivateKey, id.idSeed);\n }\n\n importId.import(id);\n if (lastIdPath === \"\") {\n lastIdPath = importId.currentPath;\n }\n\n this.checkIdBelongs(importId);\n this.#ids[importId.bapId] = importId;\n\n if (this.#isType42 && importId.rootPath.startsWith('bap:')) {\n const pathParts = importId.rootPath.split(':');\n if (pathParts.length >= 2) {\n const counter = Number.parseInt(pathParts[1], 10);\n if (!Number.isNaN(counter)) {\n this.#identityCounter = Math.max(this.#identityCounter, counter + 1);\n }\n }\n }\n }\n\n this.#lastIdPath = lastIdPath;\n }\n\n importEncryptedIds(idData: string): void {\n const decrypted = this.decrypt(idData);\n const ids = JSON.parse(decrypted) as Identities;\n\n const isOldFormat = Array.isArray(ids);\n if (isOldFormat) {\n this.importOldIds(ids);\n return;\n }\n if (typeof ids !== \"object\") {\n throw new Error(\"decrypted, but found unrecognized identities format\");\n }\n this.importIds(ids, false);\n }\n\n importOldIds(idData: OldIdentity[]): void {\n for (const id of idData) {\n let importId: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n importId = new MasterID({ rootPk: this.#masterPrivateKey }, id.idSeed ?? \"\");\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n importId = new MasterID(this.#HDPrivateKey, id.idSeed ?? \"\");\n }\n\n importId.import(id);\n this.checkIdBelongs(importId);\n this.#ids[importId.bapId] = importId;\n this.#lastIdPath = importId.currentPath;\n }\n }\n\n exportIds(idKeys?: string[], encrypted?: true): string;\n exportIds(idKeys: string[] | undefined, encrypted: false): Identities;\n exportIds(idKeys?: string[], encrypted = true): Identities | string {\n const idData: Identities = {\n lastIdPath: this.#lastIdPath,\n ids: [] as Identity[],\n };\n\n const keysToExport = idKeys || Object.keys(this.#ids);\n for (const key of keysToExport) {\n if (!this.#ids[key]) throw new Error(`Identity ${key} not found`);\n idData.ids.push(this.#ids[key].export());\n }\n\n if (encrypted) {\n return this.encrypt(JSON.stringify(idData));\n }\n return idData;\n }\n\n exportId(idKey: string, encrypted?: true): string;\n exportId(idKey: string, encrypted: false): Identities;\n exportId(idKey: string, encrypted = true): Identities | string {\n const idData: Identities = {\n lastIdPath: this.#lastIdPath,\n ids: [] as Identity[],\n };\n idData.ids.push(this.#ids[idKey].export());\n if (encrypted) {\n return this.encrypt(JSON.stringify(idData));\n }\n return idData;\n }\n\n // Master-level encryption for the ids blob in the backup\n encrypt(string: string): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const encryptionKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n ENCRYPTION_PATH\n );\n return toBase64(\n electrumEncrypt(toArray(string), encryptionKey.toPublicKey())\n );\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n return toBase64(\n electrumEncrypt(toArray(string), derivedChild.pubKey)\n );\n }\n\n decrypt(string: string): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const encryptionKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n ENCRYPTION_PATH\n );\n return toUTF8(\n electrumDecrypt(toArray(string, \"base64\"), encryptionKey)\n );\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n return toUTF8(\n electrumDecrypt(toArray(string, \"base64\"), derivedChild.privKey)\n );\n }\n\n signAttestationWithAIP(\n attestationHash: string,\n bapId: string,\n counter = 0,\n dataString = \"\"\n ) {\n const id = this.getId(bapId);\n if (!id) throw new Error(\"Could not find identity to attest with\");\n\n // Attestation signing now needs to go through the wallet.\n // This method builds the transaction data but signing should be\n // delegated to the BRC-100 wallet in the calling code.\n const attestationBuffer = this.getAttestationBuffer(\n attestationHash,\n counter,\n dataString\n );\n\n return this.createAttestationTransaction(\n attestationHash,\n counter,\n \"\", // address — caller must provide from wallet\n \"\", // signature — caller must provide from wallet\n dataString\n );\n }\n\n verifyAttestationWithAIP(tx: number[][]): Attestation {\n if (\n !tx.every((t) => Array.isArray(t)) ||\n tx[0][0] !== OP.OP_RETURN ||\n toHex(tx[1]) !== BAP_BITCOM_ADDRESS_HEX\n ) {\n throw new Error(\"Not a valid BAP transaction\");\n }\n const dataOffset = toHex(tx[7]) === \"44415441\" ? 5 : 0;\n const attestation: Attestation = {\n type: toUTF8(tx[2]),\n hash: toHex(tx[3]),\n sequence: toUTF8(tx[4]),\n signingProtocol: toUTF8(tx[7 + dataOffset]),\n signingAddress: toUTF8(tx[8 + dataOffset]),\n signature: toBase64(tx[9 + dataOffset]),\n };\n\n if (dataOffset && tx[3] === tx[8]) {\n attestation.data = toHex(tx[9]);\n }\n\n try {\n const signatureBufferStatements: number[][] = [];\n for (let i = 0; i < 6 + dataOffset; i++) {\n signatureBufferStatements.push(tx[i]);\n }\n attestation.verified = this.verifySignature(\n signatureBufferStatements.flat(),\n attestation.signingAddress,\n attestation.signature\n );\n } catch {\n attestation.verified = false;\n }\n\n return attestation;\n }\n\n createAttestationTransaction(\n attestationHash: string,\n counter: number,\n address: string,\n signature: string,\n dataString = \"\"\n ): number[][] {\n const elements: number[][] = [\n [OP.OP_RETURN],\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"ATTEST\"),\n toArray(attestationHash),\n toArray(`${counter}`),\n toArray(\"|\"),\n ];\n\n if (dataString) {\n elements.push(\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"DATA\"),\n toArray(attestationHash),\n toArray(dataString),\n toArray(\"|\")\n );\n }\n\n elements.push(\n toArray(AIP_BITCOM_ADDRESS),\n toArray(\"BITCOIN_ECDSA\"),\n toArray(address),\n toArray(signature, \"base64\")\n );\n\n return elements;\n }\n\n getAttestationBuffer(\n attestationHash: string,\n counter = 0,\n dataString = \"\"\n ): number[] {\n const elements = [\n [OP.OP_RETURN],\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"ATTEST\"),\n toArray(attestationHash),\n toArray(`${counter}`),\n toArray(\"|\"),\n ];\n\n if (dataString) {\n elements.push(\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"DATA\"),\n toArray(attestationHash),\n toArray(dataString),\n toArray(\"|\")\n );\n }\n\n return elements.flat();\n }\n\n verifySignature(\n message: string | number[],\n address: string,\n signature: string\n ): boolean {\n let msg: number[];\n if (Array.isArray(message)) {\n msg = message;\n } else if (Buffer.isBuffer(message)) {\n msg = [...message];\n } else {\n msg = toArray(message, \"utf8\");\n }\n\n const sig = Signature.fromCompact(signature, \"base64\");\n\n for (let recovery = 0; recovery < 4; recovery++) {\n try {\n const publicKey = sig.RecoverPublicKey(\n recovery,\n new BigNumber(BSM.magicHash(msg))\n );\n if (BSM.verify(msg, sig, publicKey) && publicKey.toAddress() === address) {\n return true;\n }\n } catch {\n // try next recovery\n }\n }\n return false;\n }\n\n async verifyChallengeSignature(\n idKey: string,\n address: string,\n challenge: string,\n signature: string\n ): Promise<boolean> {\n const localVerification = this.verifySignature(challenge, address, signature);\n if (!localVerification) return false;\n\n try {\n const response = await this.getApiData<AttestationValidResponse>(\n \"/attestation/valid\",\n { idKey, address, challenge, signature }\n );\n return response?.status === \"success\" && response?.result?.valid === true;\n } catch {\n return false;\n }\n }\n\n async isValidAttestationTransaction(\n tx: number[][]\n ): Promise<AttestationValidResponse | false> {\n if (this.verifyAttestationWithAIP(tx)) {\n return this.getApiData<AttestationValidResponse>(\"/attestation/valid\", { tx });\n }\n return false;\n }\n\n async getIdentityFromAddress(address: string): Promise<GetIdentityByAddressResponse> {\n return this.getApiData<GetIdentityByAddressResponse>(\"/identity/validByAddress\", { address });\n }\n\n async getIdentity(idKey: string): Promise<GetIdentityResponse> {\n return this.getApiData<GetIdentityResponse>(\"/identity/get\", { idKey });\n }\n\n async getAttestationsForHash(attestationHash: string): Promise<GetAttestationResponse> {\n return this.getApiData<GetAttestationResponse>(\"/attestations\", { hash: attestationHash });\n }\n\n exportForBackup(\n label?: string,\n xprv?: string,\n mnemonic?: string\n ): Type42MasterBackup | Bip32MasterBackup {\n const ids = this.exportIds();\n const baseBackup = {\n ids,\n ...(label && { label }),\n createdAt: new Date().toISOString(),\n };\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n return { ...baseBackup, rootPk: this.#masterPrivateKey.toWif() };\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n return {\n ...baseBackup,\n xprv: xprv || this.#HDPrivateKey.toString(),\n mnemonic: mnemonic || \"\",\n };\n }\n}\n\nexport { MasterID, AccountID };\nexport { bapIdFromAddress, bapIdFromPubkey } from \"./utils\";\nexport type {\n Attestation,\n Identity,\n PathPrefix,\n Type42Params,\n};\nexport * from \"./apiTypes\";\n",
5
+ "import {\n BSM,\n BigNumber,\n ECIES,\n HD,\n OP,\n Signature,\n PrivateKey,\n} from \"@bsv/sdk\";\n\nimport { Utils as BSVUtils } from \"@bsv/sdk\";\nimport { type APIFetcher, apiFetcher } from \"./api\";\nimport type {\n AttestationValidResponse,\n GetAttestationResponse,\n GetIdentityByAddressResponse,\n GetIdentityResponse,\n} from \"./apiTypes\";\nimport {\n AIP_BITCOM_ADDRESS,\n BAP_BITCOM_ADDRESS_HEX,\n BAP_SERVER,\n ENCRYPTION_PATH,\n} from \"./constants\";\nimport { MasterID } from \"./MasterID\";\nimport type {\n Attestation,\n Identity,\n OldIdentity,\n PathPrefix,\n} from \"./interface\";\nimport { Utils } from \"./utils\";\nconst { toArray, toUTF8, toBase64, toHex } = BSVUtils;\nconst { electrumEncrypt, electrumDecrypt } = ECIES;\n\ntype Identities = { lastIdPath: string; ids: Identity[] };\n\n/** Backup format for Type 42 mode (rootPk-based) */\nexport interface Type42MasterBackup {\n ids: string;\n rootPk: string;\n mnemonic?: string;\n label?: string;\n createdAt: string;\n}\n\n/** Backup format for BIP32 mode (xprv-based, legacy) */\nexport interface Bip32MasterBackup {\n ids: string;\n xprv: string;\n mnemonic?: string;\n label?: string;\n createdAt: string;\n}\n\ninterface Type42Params {\n rootPk: string;\n}\n\nexport class BAP {\n #HDPrivateKey: HD | undefined;\n #masterPrivateKey: PrivateKey | undefined;\n #isType42: boolean;\n #ids: { [key: string]: MasterID } = {};\n #BAP_SERVER = BAP_SERVER;\n #BAP_TOKEN = \"\";\n #lastIdPath = \"\";\n #identityCounter = 0;\n getApiData: APIFetcher;\n\n constructor(keySource: string | Type42Params, token = \"\", server = \"\") {\n if (!keySource) {\n throw new Error(\"No key source given\");\n }\n\n if (typeof keySource === \"string\") {\n this.#HDPrivateKey = HD.fromString(keySource);\n this.#isType42 = false;\n } else {\n this.#masterPrivateKey = PrivateKey.fromWif(keySource.rootPk);\n this.#isType42 = true;\n }\n\n if (token) this.#BAP_TOKEN = token;\n if (server) this.#BAP_SERVER = server;\n\n this.getApiData = apiFetcher(this.#BAP_SERVER, this.#BAP_TOKEN);\n }\n\n get lastIdPath(): string {\n return this.#lastIdPath;\n }\n\n getPublicKey(childPath = \"\"): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n if (childPath) {\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n childPath\n );\n return derivedKey.toPublicKey().toString();\n }\n return this.#masterPrivateKey.toPublicKey().toString();\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n if (childPath) {\n return this.#HDPrivateKey.derive(childPath).pubKey.toString();\n }\n return this.#HDPrivateKey.pubKey.toString();\n }\n\n getHdPublicKey(childPath = \"\"): string {\n if (this.#isType42) {\n throw new Error(\"HD public keys are not available in Type 42 mode\");\n }\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n if (childPath) {\n return this.#HDPrivateKey.derive(childPath).toPublic().toString();\n }\n return this.#HDPrivateKey.toPublic().toString();\n }\n\n set BAP_SERVER(bapServer) {\n this.#BAP_SERVER = bapServer;\n }\n\n get BAP_SERVER(): string {\n return this.#BAP_SERVER;\n }\n\n set BAP_TOKEN(token) {\n this.#BAP_TOKEN = token;\n }\n\n get BAP_TOKEN(): string {\n return this.#BAP_TOKEN;\n }\n\n checkIdBelongs(bapId: MasterID): boolean {\n let checkRootAddress: string;\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n bapId.rootPath\n );\n checkRootAddress = derivedKey.toPublicKey().toAddress();\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(bapId.rootPath);\n checkRootAddress = derivedChild.pubKey.toAddress();\n }\n\n if (checkRootAddress !== bapId.rootAddress) {\n throw new Error(\"ID does not belong to this private key\");\n }\n\n return true;\n }\n\n listIds(): string[] {\n return Object.keys(this.#ids);\n }\n\n newId(customPath?: string, idSeed = \"\"): MasterID {\n\n let pathToUse: string;\n if (customPath) {\n pathToUse = customPath;\n } else if (this.#isType42) {\n pathToUse = `bap:${this.#identityCounter}`;\n this.#identityCounter++;\n } else {\n pathToUse = this.getNextValidPath();\n }\n\n let newIdentity: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n newIdentity = new MasterID({ rootPk: this.#masterPrivateKey }, idSeed);\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n newIdentity = new MasterID(this.#HDPrivateKey, idSeed);\n }\n\n newIdentity.rootPath = pathToUse;\n\n if (this.#isType42) {\n newIdentity.currentPath = pathToUse;\n } else {\n newIdentity.currentPath = Utils.getNextPath(pathToUse);\n }\n\n this.#ids[newIdentity.bapId] = newIdentity;\n this.#lastIdPath = pathToUse;\n\n return this.#ids[newIdentity.bapId];\n }\n\n removeId(bapId: string): void {\n delete this.#ids[bapId];\n }\n\n getNextValidPath(): PathPrefix {\n if (this.#lastIdPath) {\n return Utils.getNextIdentityPath(this.#lastIdPath);\n }\n return `/0'/${Object.keys(this.#ids).length}'/0'`;\n }\n\n newIdWithCounter(counter: number): MasterID {\n if (!this.#isType42) {\n throw new Error(\"newIdWithCounter only works in Type 42 mode\");\n }\n return this.newId(`bap:${counter}`);\n }\n\n getId(bapId: string): MasterID | null {\n return this.#ids[bapId] || null;\n }\n\n setId(bapId: MasterID): void {\n this.checkIdBelongs(bapId);\n this.#ids[bapId.bapId] = bapId;\n }\n\n importIds(idData: Identities | string, encrypted = true): void {\n if (encrypted && typeof idData === \"string\") {\n this.importEncryptedIds(idData);\n return;\n }\n const identity = idData as Identities;\n if (!identity.lastIdPath) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n if (!identity.ids) {\n throw new Error(`ID data is not in the correct format: ${idData}`);\n }\n\n let lastIdPath = identity.lastIdPath;\n for (const id of identity.ids) {\n if (!id.rootAddress) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n\n let importId: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n importId = new MasterID({ rootPk: this.#masterPrivateKey }, id.idSeed);\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n importId = new MasterID(this.#HDPrivateKey, id.idSeed);\n }\n\n importId.import(id);\n if (lastIdPath === \"\") {\n lastIdPath = importId.currentPath;\n }\n\n this.checkIdBelongs(importId);\n this.#ids[importId.bapId] = importId;\n\n if (this.#isType42 && importId.rootPath.startsWith('bap:')) {\n const pathParts = importId.rootPath.split(':');\n if (pathParts.length >= 2) {\n const counter = Number.parseInt(pathParts[1], 10);\n if (!Number.isNaN(counter)) {\n this.#identityCounter = Math.max(this.#identityCounter, counter + 1);\n }\n }\n }\n }\n\n this.#lastIdPath = lastIdPath;\n }\n\n importEncryptedIds(idData: string): void {\n const decrypted = this.decrypt(idData);\n const ids = JSON.parse(decrypted) as Identities;\n\n const isOldFormat = Array.isArray(ids);\n if (isOldFormat) {\n this.importOldIds(ids);\n return;\n }\n if (typeof ids !== \"object\") {\n throw new Error(\"decrypted, but found unrecognized identities format\");\n }\n this.importIds(ids, false);\n }\n\n importOldIds(idData: OldIdentity[]): void {\n for (const id of idData) {\n let importId: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n importId = new MasterID({ rootPk: this.#masterPrivateKey }, id.idSeed ?? \"\");\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n importId = new MasterID(this.#HDPrivateKey, id.idSeed ?? \"\");\n }\n\n importId.import(id);\n this.checkIdBelongs(importId);\n this.#ids[importId.bapId] = importId;\n this.#lastIdPath = importId.currentPath;\n }\n }\n\n exportIds(idKeys?: string[], encrypted?: true): string;\n exportIds(idKeys: string[] | undefined, encrypted: false): Identities;\n exportIds(idKeys?: string[], encrypted = true): Identities | string {\n const idData: Identities = {\n lastIdPath: this.#lastIdPath,\n ids: [] as Identity[],\n };\n\n const keysToExport = idKeys || Object.keys(this.#ids);\n for (const key of keysToExport) {\n if (!this.#ids[key]) throw new Error(`Identity ${key} not found`);\n idData.ids.push(this.#ids[key].export());\n }\n\n if (encrypted) {\n return this.encrypt(JSON.stringify(idData));\n }\n return idData;\n }\n\n exportId(idKey: string, encrypted?: true): string;\n exportId(idKey: string, encrypted: false): Identities;\n exportId(idKey: string, encrypted = true): Identities | string {\n const idData: Identities = {\n lastIdPath: this.#lastIdPath,\n ids: [] as Identity[],\n };\n idData.ids.push(this.#ids[idKey].export());\n if (encrypted) {\n return this.encrypt(JSON.stringify(idData));\n }\n return idData;\n }\n\n encrypt(string: string): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const encryptionKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n ENCRYPTION_PATH\n );\n return toBase64(\n electrumEncrypt(toArray(string), encryptionKey.toPublicKey())\n );\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n return toBase64(\n electrumEncrypt(toArray(string), derivedChild.pubKey)\n );\n }\n\n decrypt(string: string): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const encryptionKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n ENCRYPTION_PATH\n );\n return toUTF8(\n electrumDecrypt(toArray(string, \"base64\"), encryptionKey)\n );\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n return toUTF8(\n electrumDecrypt(toArray(string, \"base64\"), derivedChild.privKey)\n );\n }\n\n verifyAttestationWithAIP(tx: number[][]): Attestation {\n if (\n !tx.every((t) => Array.isArray(t)) ||\n tx[0][0] !== OP.OP_RETURN ||\n toHex(tx[1]) !== BAP_BITCOM_ADDRESS_HEX\n ) {\n throw new Error(\"Not a valid BAP transaction\");\n }\n const dataOffset = toHex(tx[7]) === \"44415441\" ? 5 : 0;\n const attestation: Attestation = {\n type: toUTF8(tx[2]),\n hash: toHex(tx[3]),\n sequence: toUTF8(tx[4]),\n signingProtocol: toUTF8(tx[7 + dataOffset]),\n signingAddress: toUTF8(tx[8 + dataOffset]),\n signature: toBase64(tx[9 + dataOffset]),\n };\n\n if (dataOffset && tx[3] === tx[8]) {\n attestation.data = toHex(tx[9]);\n }\n\n try {\n const signatureBufferStatements: number[][] = [];\n for (let i = 0; i < 6 + dataOffset; i++) {\n signatureBufferStatements.push(tx[i]);\n }\n attestation.verified = this.verifySignature(\n signatureBufferStatements.flat(),\n attestation.signingAddress,\n attestation.signature\n );\n } catch {\n attestation.verified = false;\n }\n\n return attestation;\n }\n\n verifySignature(\n message: string | number[],\n address: string,\n signature: string\n ): boolean {\n let msg: number[];\n if (Array.isArray(message)) {\n msg = message;\n } else if (Buffer.isBuffer(message)) {\n msg = [...message];\n } else {\n msg = toArray(message, \"utf8\");\n }\n\n const sig = Signature.fromCompact(signature, \"base64\");\n\n for (let recovery = 0; recovery < 4; recovery++) {\n try {\n const publicKey = sig.RecoverPublicKey(\n recovery,\n new BigNumber(BSM.magicHash(msg))\n );\n if (BSM.verify(msg, sig, publicKey) && publicKey.toAddress() === address) {\n return true;\n }\n } catch {\n // try next recovery\n }\n }\n return false;\n }\n\n async verifyChallengeSignature(\n idKey: string,\n address: string,\n challenge: string,\n signature: string\n ): Promise<boolean> {\n const localVerification = this.verifySignature(challenge, address, signature);\n if (!localVerification) return false;\n\n try {\n const response = await this.getApiData<AttestationValidResponse>(\n \"/attestation/valid\",\n { idKey, address, challenge, signature }\n );\n return response?.status === \"success\" && response?.result?.valid === true;\n } catch {\n return false;\n }\n }\n\n async isValidAttestationTransaction(\n tx: number[][]\n ): Promise<AttestationValidResponse | false> {\n if (this.verifyAttestationWithAIP(tx)) {\n return this.getApiData<AttestationValidResponse>(\"/attestation/valid\", { tx });\n }\n return false;\n }\n\n async getIdentityFromAddress(address: string): Promise<GetIdentityByAddressResponse> {\n return this.getApiData<GetIdentityByAddressResponse>(\"/identity/validByAddress\", { address });\n }\n\n async getIdentity(idKey: string): Promise<GetIdentityResponse> {\n return this.getApiData<GetIdentityResponse>(\"/identity/get\", { idKey });\n }\n\n async getAttestationsForHash(attestationHash: string): Promise<GetAttestationResponse> {\n return this.getApiData<GetAttestationResponse>(\"/attestations\", { hash: attestationHash });\n }\n\n exportForBackup(\n label?: string,\n xprv?: string,\n mnemonic?: string\n ): Type42MasterBackup | Bip32MasterBackup {\n const ids = this.exportIds();\n const baseBackup = {\n ids,\n ...(label && { label }),\n createdAt: new Date().toISOString(),\n };\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n return { ...baseBackup, rootPk: this.#masterPrivateKey.toWif() };\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n return {\n ...baseBackup,\n xprv: xprv || this.#HDPrivateKey.toString(),\n mnemonic: mnemonic || \"\",\n };\n }\n}\n\nexport { MasterID };\nexport { bapIdFromAddress, bapIdFromPubkey } from \"./utils\";\nexport type {\n Attestation,\n Identity,\n PathPrefix,\n Type42Params,\n};\nexport * from \"./apiTypes\";\n",
6
6
  "/**\n * Helper function to get attestation from a BAP API server\n *\n * @param apiUrl\n * @param apiData\n * @returns {Promise<any>}\n */\nexport const getApiData = async <T>(\n apiUrl: string,\n apiData: unknown,\n server: string,\n token: string\n): Promise<T> => {\n const url = `${server}${apiUrl}`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-type\": \"application/json; charset=utf-8\",\n token,\n format: \"json\",\n },\n body: JSON.stringify(apiData),\n });\n\n return response.json();\n};\n\nexport type APIFetcher = <T>(url: string, data: unknown) => Promise<T>;\n\nexport const apiFetcher =\n (host: string, token: string): APIFetcher =>\n async <T>(url: string, data: unknown): Promise<T> => {\n return getApiData<T>(url, data, host, token);\n };\n",
7
7
  "import { Utils } from \"@bsv/sdk\";\nconst { toHex, toArray } = Utils;\n\nexport const BAP_BITCOM_ADDRESS = \"1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT\";\nexport const BAP_BITCOM_ADDRESS_HEX = toHex(toArray(BAP_BITCOM_ADDRESS));\nexport const AIP_BITCOM_ADDRESS = \"15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva\";\nexport const AIP_BITCOM_ADDRESS_HEX = toHex(toArray(AIP_BITCOM_ADDRESS));\nexport const BAP_SERVER = \"https://api.sigmaidentity.com/v1\";\nexport const MAX_INT = 2147483648 - 1; // 0x80000000\n\nexport const SIGNING_PATH_PREFIX = \"m/424150'/0'/0'\"; // BAP in hex\n\n// Used by the BAP class for encrypting the identity list in the master backup\nexport const ENCRYPTION_PATH = `m/424150'/${MAX_INT}'/${MAX_INT}'`;\n",
8
- "import {\n Hash,\n type PrivateKey,\n HD,\n Utils as BSVUtils,\n} from \"@bsv/sdk\";\n\nimport {\n SIGNING_PATH_PREFIX,\n MAX_INT,\n} from \"./constants\";\nimport type {\n Identity,\n OldIdentity,\n} from \"./interface\";\nimport { Utils, bapIdFromAddress } from \"./utils\";\n\ninterface Type42KeySource {\n rootPk: PrivateKey;\n}\n\nclass MasterID {\n #HDPrivateKey: HD | undefined;\n #masterPrivateKey: PrivateKey | undefined;\n #isType42: boolean;\n #rootPath: string;\n #currentPath: string;\n #previousPath: string;\n #idSeed: string;\n\n rootAddress: string;\n bapId: string;\n\n constructor(\n keySource: HD | Type42KeySource,\n idSeed = \"\"\n ) {\n if (keySource instanceof HD) {\n this.#isType42 = false;\n if (idSeed) {\n const seedHex = BSVUtils.toHex(Hash.sha256(idSeed, \"utf8\"));\n const seedPath = Utils.getSigningPathFromHex(seedHex);\n this.#HDPrivateKey = keySource.derive(seedPath);\n } else {\n this.#HDPrivateKey = keySource;\n }\n } else {\n this.#isType42 = true;\n this.#masterPrivateKey = keySource.rootPk;\n if (idSeed) {\n const seedHex = BSVUtils.toHex(Hash.sha256(idSeed, \"utf8\"));\n this.#masterPrivateKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n seedHex\n );\n }\n }\n\n this.#idSeed = idSeed;\n\n this.#rootPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n this.#previousPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n this.#currentPath = `${SIGNING_PATH_PREFIX}/0/0/1`;\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const rootKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n this.#rootPath\n );\n this.rootAddress = rootKey.toPublicKey().toAddress();\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const rootChild = this.#HDPrivateKey.derive(this.#rootPath);\n this.rootAddress = rootChild.privKey.toPublicKey().toAddress();\n }\n\n this.bapId = bapIdFromAddress(this.rootAddress);\n }\n\n /**\n * Get the account key (root key) for this identity.\n * This is the cold key used for BAP ID creation and revocation.\n */\n getAccountKey(): PrivateKey {\n return this.getPathDerivedKey(this.#rootPath);\n }\n\n private getPathDerivedKey(path: string): PrivateKey {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n return this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n path\n );\n }\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n return this.#HDPrivateKey.derive(path).privKey;\n }\n\n set rootPath(path: string) {\n if (this.#isType42) {\n this.#rootPath = path;\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n path\n );\n this.rootAddress = derivedKey.toPublicKey().toAddress();\n this.#previousPath = path;\n this.#currentPath = path;\n } else {\n let pathToUse = path;\n if (path.split(\"/\").length < 5) {\n pathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n }\n if (!this.validatePath(pathToUse)) {\n throw new Error(`invalid signing path given ${pathToUse}`);\n }\n this.#rootPath = pathToUse;\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(pathToUse);\n this.rootAddress = derivedChild.pubKey.toAddress();\n this.#previousPath = pathToUse;\n this.#currentPath = pathToUse;\n }\n this.bapId = bapIdFromAddress(this.rootAddress);\n }\n\n get rootPath(): string {\n return this.#rootPath;\n }\n\n set currentPath(path: string) {\n if (this.#isType42) {\n this.#previousPath = this.#currentPath;\n this.#currentPath = path;\n } else {\n let pathToUse = path;\n if (path.split(\"/\").length < 5) {\n pathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n }\n if (!this.validatePath(pathToUse)) {\n throw new Error(\"invalid signing path given\");\n }\n this.#previousPath = this.#currentPath;\n this.#currentPath = pathToUse;\n }\n }\n\n get currentPath(): string {\n return this.#currentPath;\n }\n\n get previousPath(): string {\n return this.#previousPath;\n }\n\n get idSeed(): string {\n return this.#idSeed;\n }\n\n validatePath(path: string): boolean {\n if (\n path.match(\n /\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?/\n )\n ) {\n const pathValues = path.split(\"/\");\n if (\n pathValues.length === 7 &&\n Number(pathValues[1].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[2].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[3].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[4].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[5].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[6].replace(\"'\", \"\")) <= MAX_INT\n ) {\n return true;\n }\n }\n return false;\n }\n\n import(identity: Identity | OldIdentity): void {\n this.bapId = \"bapId\" in identity ? identity.bapId : (identity as OldIdentity).identityKey;\n this.#rootPath = identity.rootPath;\n this.rootAddress = identity.rootAddress;\n this.#previousPath = identity.previousPath;\n this.#currentPath = identity.currentPath;\n this.#idSeed = (\"idSeed\" in identity ? identity.idSeed : \"\") || \"\";\n }\n\n export(): Identity {\n return {\n bapId: this.bapId,\n rootPath: this.#rootPath,\n rootAddress: this.rootAddress,\n previousPath: this.#previousPath,\n currentPath: this.#currentPath,\n idSeed: this.#idSeed,\n lastIdPath: \"\",\n };\n }\n}\n\nexport { MasterID };\n",
9
- "import { Hash, PublicKey, Utils as BSVUtils } from \"@bsv/sdk\";\nimport type { PathPrefix } from \"./interface.js\";\n\nconst { toHex, toBase58 } = BSVUtils;\n\n/**\n * Derive a BAP ID from a Bitcoin address (rootAddress).\n *\n * BAP ID = base58(ripemd160(sha256(rootAddress)))\n *\n * This is the canonical derivation used by MasterID.deriveIdentityKey().\n * The address MUST be the rootAddress (from the BAP member key), not a\n * signing key address.\n */\nexport function bapIdFromAddress(address: string): string {\n const rootAddressHash = toHex(Hash.sha256(address, \"utf8\"));\n return toBase58(Hash.ripemd160(rootAddressHash, \"hex\"));\n}\n\n/**\n * Derive a BAP ID from a compressed public key (hex).\n *\n * Converts the pubkey to a Bitcoin address, then derives the BAP ID.\n *\n * IMPORTANT: This only produces a correct BAP ID when the pubkey is the\n * BAP member key's public key. It does NOT work with signing keys or\n * arbitrary public keys.\n *\n * In BRC-100 wallets, the BRC-31 identity key IS the member key's pubkey,\n * so this correctly bridges BRC-31 auth to BAP identity lookups.\n */\nexport function bapIdFromPubkey(pubkeyHex: string): string {\n const pubkey = PublicKey.fromString(pubkeyHex);\n return bapIdFromAddress(pubkey.toAddress());\n}\n\nexport const Utils = {\n /**\n * Helper function to generate cryptographically secure random bytes\n * \n * This follows the pattern used by BSV SDK and other Bitcoin libraries.\n * Uses crypto.getRandomValues() which is available in browsers and modern Node.js.\n *\n * @param {number} byteLength - Number of random bytes to generate (default: 32)\n * @returns {Uint8Array} Array of cryptographically secure random bytes\n */\n getRandomBytes(byteLength = 32): Uint8Array {\n // Use crypto.getRandomValues() - available in browsers and Node.js 15+\n if (typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.getRandomValues) {\n const array = new Uint8Array(byteLength);\n globalThis.crypto.getRandomValues(array);\n return array;\n }\n\n // Fallback error - crypto operations require secure randomness\n throw new Error(\n 'Secure random number generation not available. ' +\n 'crypto.getRandomValues() is required for cryptographic operations. ' +\n 'This environment may not be suitable for secure key generation.'\n );\n },\n\n /**\n * Helper function to generate a random hex string\n *\n * @param {number} byteLength - Number of random bytes to generate (default: 32)\n * @returns {string} Hex string of random bytes\n */\n getRandomString(byteLength = 32): string {\n const bytes = this.getRandomBytes(byteLength);\n return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');\n },\n\n /**\n * Get a signing path from a hex number\n *\n * @param hexString {string}\n * @param hardened {boolean} Whether to return a hardened path\n * @returns {string}\n */\n getSigningPathFromHex(hexString: string, hardened = true) {\n // \"m/0/0/1\"\n let signingPath = \"m\";\n const signingHex = hexString.match(/.{1,8}/g);\n if (!signingHex) {\n throw new Error(\"Invalid hex string\");\n }\n const maxNumber = 2147483648 - 1; // 0x80000000\n for (const hexNumber of signingHex) {\n let number = Number(`0x${hexNumber}`);\n if (number > maxNumber) number -= maxNumber;\n signingPath += `/${number}${hardened ? \"'\" : \"\"}`;\n }\n\n return signingPath;\n },\n\n /**\n * Increment that second to last part from the given part, set the last part to 0\n *\n * @param path string\n * @returns {*}\n */\n getNextIdentityPath(path: string): PathPrefix {\n const pathValues = path.split(\"/\");\n const secondToLastPart = pathValues[pathValues.length - 2];\n\n let hardened = false;\n if (secondToLastPart.match(\"'\")) {\n hardened = true;\n }\n\n const nextPath = (\n Number(secondToLastPart.replace(/[^0-9]/g, \"\")) + 1\n ).toString();\n pathValues[pathValues.length - 2] = nextPath + (hardened ? \"'\" : \"\");\n pathValues[pathValues.length - 1] = `0${hardened ? \"'\" : \"\"}`;\n\n return pathValues.join(\"/\") as PathPrefix;\n },\n\n /**\n * Increment that last part of the given path\n *\n * @param path string\n * @returns {*}\n */\n getNextPath(path: string) {\n const type42Path = path.match(/^bap:(\\d+)(?::(\\d+))?$/);\n if (type42Path) {\n const identityIndex = type42Path[1];\n const rotationIndex = type42Path[2];\n\n if (rotationIndex === undefined) {\n return `bap:${identityIndex}:1`;\n }\n\n return `bap:${identityIndex}:${Number(rotationIndex) + 1}`;\n }\n\n // Backward compatibility for Type 42 backups created before the\n // `bap:<identity>:<rotation>` format was fixed. Those backups stored\n // bare numeric rotation paths like \"1\", and must keep rotating within\n // that legacy namespace so previously derived keys remain valid.\n if (/^\\d+$/.test(path)) {\n return (Number(path) + 1).toString();\n }\n\n if (!path.includes(\"/\")) {\n throw new Error(`Unsupported non-BIP32 path: ${path}`);\n }\n\n const pathValues = path.split(\"/\");\n const lastPart = pathValues[pathValues.length - 1];\n let hardened = false;\n if (lastPart.match(\"'\")) {\n hardened = true;\n }\n const nextPath = (Number(lastPart.replace(/[^0-9]/g, \"\")) + 1).toString();\n pathValues[pathValues.length - 1] = nextPath + (hardened ? \"'\" : \"\");\n return pathValues.join(\"/\");\n },\n};\n",
10
- "import {\n PrivateKey,\n Hash,\n Utils as BSVUtils,\n OP,\n} from \"@bsv/sdk\";\nimport { BaseClass } from \"./BaseClass\";\nimport { BAP_BITCOM_ADDRESS } from \"./constants\";\nconst { toArray } = BSVUtils;\n\nexport class AccountID extends BaseClass {\n private key: PrivateKey;\n\n constructor(key: PrivateKey) {\n super();\n this.key = key;\n }\n\n getBapId(): string {\n const addressBytes = toArray(this.getRootAddress());\n const sha = Hash.sha256(addressBytes);\n const ripe = Hash.ripemd160(sha);\n return BSVUtils.toBase58(ripe);\n }\n\n getRootAddress(): string {\n return this.key.toPublicKey().toAddress();\n }\n\n getRootPublicKey(): string {\n return this.key.toPublicKey().toString();\n }\n\n signMessage(message: number[]): { address: string; signature: string } {\n return this.signWithBSM(message, this.key);\n }\n\n getInitialIdTransaction(firstSigningAddress: string): number[][] {\n const opReturn = [\n [OP.OP_RETURN],\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"ID\"),\n toArray(this.getBapId()),\n toArray(firstSigningAddress),\n ];\n\n return this.signOpReturnWithAIP(opReturn);\n }\n\n getRevocationTransaction(): number[][] {\n const opReturn = [\n [OP.OP_RETURN],\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"ID\"),\n toArray(this.getBapId()),\n toArray(\"0\"),\n ];\n\n return this.signOpReturnWithAIP(opReturn);\n }\n}\n",
11
- "import { Utils as BSVUtils, OP, BSM, BigNumber } from \"@bsv/sdk\";\nimport type { PrivateKey, Signature } from \"@bsv/sdk\";\nimport { AIP_BITCOM_ADDRESS } from \"./constants\";\nconst { toArray, toBase64 } = BSVUtils;\n\nabstract class BaseClass {\n abstract signMessage(\n message: number[],\n ): { address: string; signature: string };\n\n protected signWithBSM(\n message: number[],\n signingKey: PrivateKey\n ): { address: string; signature: string } {\n const address = signingKey.toPublicKey().toAddress();\n const dummySig = BSM.sign(message, signingKey, \"raw\") as Signature;\n const h = new BigNumber(BSM.magicHash(message));\n const r = dummySig.CalculateRecoveryFactor(signingKey.toPublicKey(), h);\n const signature = (\n BSM.sign(message, signingKey, \"raw\") as Signature\n ).toCompact(r, true, \"base64\") as string;\n\n return { address, signature };\n }\n\n signOpReturnWithAIP(opReturn: number[][]): number[][] {\n const aipMessageBuffer = this.getAIPMessageBuffer(opReturn);\n const { address, signature } = this.signMessage(\n aipMessageBuffer.flat(),\n );\n return this.formatAIPOutput(aipMessageBuffer, address, signature);\n }\n\n protected getAIPMessageBuffer(\n opReturn: number[][],\n indicies?: number[]\n ): number[][] {\n let opReturnIndex = opReturn.findIndex((op) => op[0] === OP.OP_RETURN);\n const buffers: number[][] = [];\n\n if (opReturnIndex === -1) {\n buffers.push([OP.OP_RETURN]);\n opReturnIndex = 0;\n }\n\n if (indicies) {\n for (const index of indicies) {\n buffers.push(opReturn[opReturnIndex + index]);\n }\n } else {\n for (const op of opReturn) {\n buffers.push(op);\n }\n }\n\n return buffers;\n }\n\n protected formatAIPOutput(\n opReturnBuffers: number[][],\n address: string,\n signature: string\n ): number[][] {\n const aipElements = [\n toArray(\"|\"),\n toArray(AIP_BITCOM_ADDRESS),\n toArray(\"BITCOIN_ECDSA\"),\n toArray(address),\n toArray(signature, \"base64\"),\n ];\n\n return [...opReturnBuffers, ...aipElements];\n }\n}\n\nexport { BaseClass };\n"
8
+ "import {\n Hash,\n type PrivateKey,\n HD,\n Utils as BSVUtils,\n} from \"@bsv/sdk\";\n\nimport {\n SIGNING_PATH_PREFIX,\n MAX_INT,\n} from \"./constants\";\nimport type {\n Identity,\n OldIdentity,\n} from \"./interface\";\nimport { Utils, bapIdFromAddress } from \"./utils\";\n\ninterface Type42KeySource {\n rootPk: PrivateKey;\n}\n\nclass MasterID {\n #HDPrivateKey: HD | undefined;\n #masterPrivateKey: PrivateKey | undefined;\n #isType42: boolean;\n #rootPath: string;\n #currentPath: string;\n #previousPath: string;\n #idSeed: string;\n\n rootAddress: string;\n bapId: string;\n\n constructor(\n keySource: HD | Type42KeySource,\n idSeed = \"\"\n ) {\n if (keySource instanceof HD) {\n this.#isType42 = false;\n if (idSeed) {\n const seedHex = BSVUtils.toHex(Hash.sha256(idSeed, \"utf8\"));\n const seedPath = Utils.getSigningPathFromHex(seedHex);\n this.#HDPrivateKey = keySource.derive(seedPath);\n } else {\n this.#HDPrivateKey = keySource;\n }\n } else {\n this.#isType42 = true;\n this.#masterPrivateKey = keySource.rootPk;\n if (idSeed) {\n const seedHex = BSVUtils.toHex(Hash.sha256(idSeed, \"utf8\"));\n this.#masterPrivateKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n seedHex\n );\n }\n }\n\n this.#idSeed = idSeed;\n\n this.#rootPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n this.#previousPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n this.#currentPath = `${SIGNING_PATH_PREFIX}/0/0/1`;\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const rootKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n this.#rootPath\n );\n this.rootAddress = rootKey.toPublicKey().toAddress();\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const rootChild = this.#HDPrivateKey.derive(this.#rootPath);\n this.rootAddress = rootChild.privKey.toPublicKey().toAddress();\n }\n\n this.bapId = bapIdFromAddress(this.rootAddress);\n }\n\n set rootPath(path: string) {\n if (this.#isType42) {\n this.#rootPath = path;\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n path\n );\n this.rootAddress = derivedKey.toPublicKey().toAddress();\n this.#previousPath = path;\n this.#currentPath = path;\n } else {\n let pathToUse = path;\n if (path.split(\"/\").length < 5) {\n pathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n }\n if (!this.validatePath(pathToUse)) {\n throw new Error(`invalid signing path given ${pathToUse}`);\n }\n this.#rootPath = pathToUse;\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(pathToUse);\n this.rootAddress = derivedChild.pubKey.toAddress();\n this.#previousPath = pathToUse;\n this.#currentPath = pathToUse;\n }\n this.bapId = bapIdFromAddress(this.rootAddress);\n }\n\n get rootPath(): string {\n return this.#rootPath;\n }\n\n set currentPath(path: string) {\n if (this.#isType42) {\n this.#previousPath = this.#currentPath;\n this.#currentPath = path;\n } else {\n let pathToUse = path;\n if (path.split(\"/\").length < 5) {\n pathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n }\n if (!this.validatePath(pathToUse)) {\n throw new Error(\"invalid signing path given\");\n }\n this.#previousPath = this.#currentPath;\n this.#currentPath = pathToUse;\n }\n }\n\n get currentPath(): string {\n return this.#currentPath;\n }\n\n get previousPath(): string {\n return this.#previousPath;\n }\n\n get idSeed(): string {\n return this.#idSeed;\n }\n\n getAccountKey(): PrivateKey {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n return this.#masterPrivateKey;\n }\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n return this.#HDPrivateKey.privKey;\n }\n\n validatePath(path: string): boolean {\n if (\n path.match(\n /\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?/\n )\n ) {\n const pathValues = path.split(\"/\");\n if (\n pathValues.length === 7 &&\n Number(pathValues[1].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[2].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[3].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[4].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[5].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[6].replace(\"'\", \"\")) <= MAX_INT\n ) {\n return true;\n }\n }\n return false;\n }\n\n import(identity: Identity | OldIdentity): void {\n this.bapId = \"bapId\" in identity ? identity.bapId : (identity as OldIdentity).identityKey;\n this.#rootPath = identity.rootPath;\n this.rootAddress = identity.rootAddress;\n this.#previousPath = identity.previousPath;\n this.#currentPath = identity.currentPath;\n this.#idSeed = (\"idSeed\" in identity ? identity.idSeed : \"\") || \"\";\n }\n\n export(): Identity {\n return {\n bapId: this.bapId,\n rootPath: this.#rootPath,\n rootAddress: this.rootAddress,\n previousPath: this.#previousPath,\n currentPath: this.#currentPath,\n idSeed: this.#idSeed,\n lastIdPath: \"\",\n };\n }\n}\n\nexport { MasterID };\n",
9
+ "import { Hash, PublicKey, Utils as BSVUtils } from \"@bsv/sdk\";\nimport type { PathPrefix } from \"./interface.js\";\n\nconst { toHex, toBase58 } = BSVUtils;\n\n/**\n * Derive a BAP ID from a Bitcoin address (rootAddress).\n *\n * BAP ID = base58(ripemd160(sha256(rootAddress)))\n *\n * This is the canonical derivation used by MasterID.deriveIdentityKey().\n * The address MUST be the rootAddress (from the BAP member key), not a\n * signing key address.\n */\nexport function bapIdFromAddress(address: string): string {\n const rootAddressHash = toHex(Hash.sha256(address, \"utf8\"));\n return toBase58(Hash.ripemd160(rootAddressHash, \"hex\"));\n}\n\n/**\n * Derive a BAP ID from a compressed public key (hex).\n *\n * Converts the pubkey to a Bitcoin address, then derives the BAP ID.\n *\n * IMPORTANT: This only produces a correct BAP ID when the pubkey is the\n * BAP member key's public key. It does NOT work with signing keys or\n * arbitrary public keys.\n *\n * In BRC-100 wallets, the BRC-31 identity key IS the member key's pubkey,\n * so this correctly bridges BRC-31 auth to BAP identity lookups.\n */\nexport function bapIdFromPubkey(pubkeyHex: string): string {\n const pubkey = PublicKey.fromString(pubkeyHex);\n return bapIdFromAddress(pubkey.toAddress());\n}\n\nexport const Utils = {\n /**\n * Helper function to generate cryptographically secure random bytes\n * \n * This follows the pattern used by BSV SDK and other Bitcoin libraries.\n * Uses crypto.getRandomValues() which is available in browsers and modern Node.js.\n *\n * @param {number} byteLength - Number of random bytes to generate (default: 32)\n * @returns {Uint8Array} Array of cryptographically secure random bytes\n */\n getRandomBytes(byteLength = 32): Uint8Array {\n // Use crypto.getRandomValues() - available in browsers and Node.js 15+\n if (typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.getRandomValues) {\n const array = new Uint8Array(byteLength);\n globalThis.crypto.getRandomValues(array);\n return array;\n }\n\n // Fallback error - crypto operations require secure randomness\n throw new Error(\n 'Secure random number generation not available. ' +\n 'crypto.getRandomValues() is required for cryptographic operations. ' +\n 'This environment may not be suitable for secure key generation.'\n );\n },\n\n /**\n * Helper function to generate a random hex string\n *\n * @param {number} byteLength - Number of random bytes to generate (default: 32)\n * @returns {string} Hex string of random bytes\n */\n getRandomString(byteLength = 32): string {\n const bytes = this.getRandomBytes(byteLength);\n return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');\n },\n\n /**\n * Get a signing path from a hex number\n *\n * @param hexString {string}\n * @param hardened {boolean} Whether to return a hardened path\n * @returns {string}\n */\n getSigningPathFromHex(hexString: string, hardened = true) {\n // \"m/0/0/1\"\n let signingPath = \"m\";\n const signingHex = hexString.match(/.{1,8}/g);\n if (!signingHex) {\n throw new Error(\"Invalid hex string\");\n }\n const maxNumber = 2147483648 - 1; // 0x80000000\n for (const hexNumber of signingHex) {\n let number = Number(`0x${hexNumber}`);\n if (number > maxNumber) number -= maxNumber;\n signingPath += `/${number}${hardened ? \"'\" : \"\"}`;\n }\n\n return signingPath;\n },\n\n /**\n * Increment that second to last part from the given part, set the last part to 0\n *\n * @param path string\n * @returns {*}\n */\n getNextIdentityPath(path: string): PathPrefix {\n const pathValues = path.split(\"/\");\n const secondToLastPart = pathValues[pathValues.length - 2];\n\n let hardened = false;\n if (secondToLastPart.match(\"'\")) {\n hardened = true;\n }\n\n const nextPath = (\n Number(secondToLastPart.replace(/[^0-9]/g, \"\")) + 1\n ).toString();\n pathValues[pathValues.length - 2] = nextPath + (hardened ? \"'\" : \"\");\n pathValues[pathValues.length - 1] = `0${hardened ? \"'\" : \"\"}`;\n\n return pathValues.join(\"/\") as PathPrefix;\n },\n\n /**\n * Increment that last part of the given path\n *\n * @param path string\n * @returns {*}\n */\n getNextPath(path: string) {\n const type42Path = path.match(/^bap:(\\d+)(?::(\\d+))?$/);\n if (type42Path) {\n const identityIndex = type42Path[1];\n const rotationIndex = type42Path[2];\n\n if (rotationIndex === undefined) {\n return `bap:${identityIndex}:1`;\n }\n\n return `bap:${identityIndex}:${Number(rotationIndex) + 1}`;\n }\n\n // Backward compatibility for Type 42 backups created before the\n // `bap:<identity>:<rotation>` format was fixed. Those backups stored\n // bare numeric rotation paths like \"1\", and must keep rotating within\n // that legacy namespace so previously derived keys remain valid.\n if (/^\\d+$/.test(path)) {\n return (Number(path) + 1).toString();\n }\n\n if (!path.includes(\"/\")) {\n throw new Error(`Unsupported non-BIP32 path: ${path}`);\n }\n\n const pathValues = path.split(\"/\");\n const lastPart = pathValues[pathValues.length - 1];\n let hardened = false;\n if (lastPart.match(\"'\")) {\n hardened = true;\n }\n const nextPath = (Number(lastPart.replace(/[^0-9]/g, \"\")) + 1).toString();\n pathValues[pathValues.length - 1] = nextPath + (hardened ? \"'\" : \"\");\n return pathValues.join(\"/\");\n },\n};\n"
12
10
  ],
13
- "mappings": ";AAAA,cACE,eACA,WACA,QACA,QACA,eACA,iBACA,kBAGF,gBAAS,kBCHF,IAAM,EAAa,MACxB,EACA,EACA,EACA,IACe,CACf,IAAM,EAAM,GAAG,IAAS,IAWxB,OAViB,MAAM,MAAM,EAAK,CAChC,OAAQ,OACR,QAAS,CACP,eAAgB,kCAChB,QACA,OAAQ,MACV,EACA,KAAM,KAAK,UAAU,CAAO,CAC9B,CAAC,GAEe,KAAK,GAKV,EACX,CAAC,EAAc,IACf,MAAU,EAAa,IAA8B,CACnD,OAAO,EAAc,EAAK,EAAM,EAAM,CAAK,GChC/C,gBAAS,iBACT,IAAQ,QAAO,WAAY,EAEd,EAAqB,qCACrB,EAAyB,EAAM,EAAQ,CAAkB,CAAC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B,KAAK,gBAAgB,EAAW,EAAS,CAAS,EACpD,MAAO,GAE/B,GAAI,CACF,IAAM,EAAW,MAAM,KAAK,WAC1B,qBACA,CAAE,QAAO,UAAS,YAAW,WAAU,CACzC,EACA,OAAO,GAAU,SAAW,WAAa,GAAU,QAAQ,QAAU,GACrE,KAAM,CACN,MAAO,SAIL,8BAA6B,CACjC,EAC2C,CAC3C,GAAI,KAAK,yBAAyB,CAAE,EAClC,OAAO,KAAK,WAAqC,qBAAsB,CAAE,IAAG,CAAC,EAE/E,MAAO,QAGH,uBAAsB,CAAC,EAAwD,CACnF,OAAO,KAAK,WAAyC,2BAA4B,CAAE,SAAQ,CAAC,OAGxF,YAAW,CAAC,EAA6C,CAC7D,OAAO,KAAK,WAAgC,gBAAiB,CAAE,OAAM,CAAC,OAGlE,uBAAsB,CAAC,EAA0D,CACrF,OAAO,KAAK,WAAmC,gBAAiB,CAAE,KAAM,CAAgB,CAAC,EAG3F,eAAe,CACb,EACA,EACA,EACwC,CAExC,IAAM,EAAa,CACjB,IAFU,KAAK,UAAU,KAGrB,GAAS,CAAE,OAAM,EACrB,UAAW,IAAI,KAAK,EAAE,YAAY,CACpC,EAEA,GAAI,KAAK,GAAW,CAClB,IAAK,KAAK,GAAmB,MAAM,IAAI,MAAM,oCAAoC,EACjF,MAAO,IAAK,EAAY,OAAQ,KAAK,GAAkB,MAAM,CAAE,EAGjE,IAAK,KAAK,GAAe,MAAM,IAAI,MAAM,gCAAgC,EACzE,MAAO,IACF,EACH,KAAM,GAAQ,KAAK,GAAc,SAAS,EAC1C,SAAU,GAAY,EACxB,EAEJ",
12
+ "debugId": "23864B19C0C06C4464756E2164756E21",
15
13
  "names": []
16
14
  }
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{BSM as K,BigNumber as a,ECIES as e,HD as t,OP as E,Signature as ff,PrivateKey as Wf}from"@bsv/sdk";import{Utils as jf}from"@bsv/sdk";var I=async(f,W,j,$)=>{let J=`${j}${f}`;return(await fetch(J,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:$,format:"json"},body:JSON.stringify(W)})).json()},k=(f,W)=>async(j,$)=>{return I(j,$,f,W)};import{Utils as o}from"@bsv/sdk";var{toHex:_,toArray:u}=o,w="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",x=_(u(w)),R="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva",zf=_(u(R)),c="https://api.sigmaidentity.com/v1",Z=2147483647,O="m/424150'/0'/0'",C=`m/424150'/${Z}'/${Z}'`;import{Hash as m,HD as r,Utils as T}from"@bsv/sdk";import{Hash as A,PublicKey as p,Utils as P}from"@bsv/sdk";var{toHex:h,toBase58:s}=P;function X(f){let W=h(A.sha256(f,"utf8"));return s(A.ripemd160(W,"hex"))}function y(f){let W=p.fromString(f);return X(W.toAddress())}var g={getRandomBytes(f=32){if(typeof globalThis!=="undefined"&&globalThis.crypto&&globalThis.crypto.getRandomValues){let W=new Uint8Array(f);return globalThis.crypto.getRandomValues(W),W}throw new 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(f=32){let W=this.getRandomBytes(f);return Array.from(W,(j)=>j.toString(16).padStart(2,"0")).join("")},getSigningPathFromHex(f,W=!0){let j="m",$=f.match(/.{1,8}/g);if(!$)throw new Error("Invalid hex string");let J=2147483647;for(let z of $){let Q=Number(`0x${z}`);if(Q>J)Q-=J;j+=`/${Q}${W?"'":""}`}return j},getNextIdentityPath(f){let W=f.split("/"),j=W[W.length-2],$=!1;if(j.match("'"))$=!0;let J=(Number(j.replace(/[^0-9]/g,""))+1).toString();return W[W.length-2]=J+($?"'":""),W[W.length-1]=`0${$?"'":""}`,W.join("/")},getNextPath(f){let W=f.match(/^bap:(\d+)(?::(\d+))?$/);if(W){let Q=W[1],G=W[2];if(G===void 0)return`bap:${Q}:1`;return`bap:${Q}:${Number(G)+1}`}if(/^\d+$/.test(f))return(Number(f)+1).toString();if(!f.includes("/"))throw new Error(`Unsupported non-BIP32 path: ${f}`);let j=f.split("/"),$=j[j.length-1],J=!1;if($.match("'"))J=!0;let z=(Number($.replace(/[^0-9]/g,""))+1).toString();return j[j.length-1]=z+(J?"'":""),j.join("/")}};class L{#W;#f;#$;#j;#J;#q;#z;rootAddress;bapId;constructor(f,W=""){if(f instanceof r)if(this.#$=!1,W){let j=T.toHex(m.sha256(W,"utf8")),$=g.getSigningPathFromHex(j);this.#W=f.derive($)}else this.#W=f;else if(this.#$=!0,this.#f=f.rootPk,W){let j=T.toHex(m.sha256(W,"utf8"));this.#f=this.#f.deriveChild(this.#f.toPublicKey(),j)}if(this.#z=W,this.#j=`${O}/0/0/0`,this.#q=`${O}/0/0/0`,this.#J=`${O}/0/0/1`,this.#$){if(!this.#f)throw new Error("Master private key not initialized");let j=this.#f.deriveChild(this.#f.toPublicKey(),this.#j);this.rootAddress=j.toPublicKey().toAddress()}else{if(!this.#W)throw new Error("HD private key not initialized");let j=this.#W.derive(this.#j);this.rootAddress=j.privKey.toPublicKey().toAddress()}this.bapId=X(this.rootAddress)}getAccountKey(){return this.getPathDerivedKey(this.#j)}getPathDerivedKey(f){if(this.#$){if(!this.#f)throw new Error("Master private key not initialized");return this.#f.deriveChild(this.#f.toPublicKey(),f)}if(!this.#W)throw new Error("HD private key not initialized");return this.#W.derive(f).privKey}set rootPath(f){if(this.#$){if(this.#j=f,!this.#f)throw new Error("Master private key not initialized");let W=this.#f.deriveChild(this.#f.toPublicKey(),f);this.rootAddress=W.toPublicKey().toAddress(),this.#q=f,this.#J=f}else{let W=f;if(f.split("/").length<5)W=`${O}${f}`;if(!this.validatePath(W))throw new Error(`invalid signing path given ${W}`);if(this.#j=W,!this.#W)throw new Error("HD private key not initialized");let j=this.#W.derive(W);this.rootAddress=j.pubKey.toAddress(),this.#q=W,this.#J=W}this.bapId=X(this.rootAddress)}get rootPath(){return this.#j}set currentPath(f){if(this.#$)this.#q=this.#J,this.#J=f;else{let W=f;if(f.split("/").length<5)W=`${O}${f}`;if(!this.validatePath(W))throw new Error("invalid signing path given");this.#q=this.#J,this.#J=W}}get currentPath(){return this.#J}get previousPath(){return this.#q}get idSeed(){return this.#z}validatePath(f){if(f.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 W=f.split("/");if(W.length===7&&Number(W[1].replace("'",""))<=Z&&Number(W[2].replace("'",""))<=Z&&Number(W[3].replace("'",""))<=Z&&Number(W[4].replace("'",""))<=Z&&Number(W[5].replace("'",""))<=Z&&Number(W[6].replace("'",""))<=Z)return!0}return!1}import(f){this.bapId="bapId"in f?f.bapId:f.identityKey,this.#j=f.rootPath,this.rootAddress=f.rootAddress,this.#q=f.previousPath,this.#J=f.currentPath,this.#z=("idSeed"in f?f.idSeed:"")||""}export(){return{bapId:this.bapId,rootPath:this.#j,rootAddress:this.rootAddress,previousPath:this.#q,currentPath:this.#J,idSeed:this.#z,lastIdPath:""}}}import{Hash as S,Utils as l,OP as D}from"@bsv/sdk";import{Utils as d,OP as H,BSM as U,BigNumber as i}from"@bsv/sdk";var{toArray:M,toBase64:Cf}=d;class V{signWithBSM(f,W){let j=W.toPublicKey().toAddress(),$=U.sign(f,W,"raw"),J=new i(U.magicHash(f)),z=$.CalculateRecoveryFactor(W.toPublicKey(),J),Q=U.sign(f,W,"raw").toCompact(z,!0,"base64");return{address:j,signature:Q}}signOpReturnWithAIP(f){let W=this.getAIPMessageBuffer(f),{address:j,signature:$}=this.signMessage(W.flat());return this.formatAIPOutput(W,j,$)}getAIPMessageBuffer(f,W){let j=f.findIndex((J)=>J[0]===H.OP_RETURN),$=[];if(j===-1)$.push([H.OP_RETURN]),j=0;if(W)for(let J of W)$.push(f[j+J]);else for(let J of f)$.push(J);return $}formatAIPOutput(f,W,j){let $=[M("|"),M(R),M("BITCOIN_ECDSA"),M(W),M(j,"base64")];return[...f,...$]}}var{toArray:Y}=l;class N extends V{key;constructor(f){super();this.key=f}getBapId(){let f=Y(this.getRootAddress()),W=S.sha256(f),j=S.ripemd160(W);return l.toBase58(j)}getRootAddress(){return this.key.toPublicKey().toAddress()}getRootPublicKey(){return this.key.toPublicKey().toString()}signMessage(f){return this.signWithBSM(f,this.key)}getInitialIdTransaction(f){let W=[[D.OP_RETURN],Y(w),Y("ID"),Y(this.getBapId()),Y(f)];return this.signOpReturnWithAIP(W)}getRevocationTransaction(){let f=[[D.OP_RETURN],Y(w),Y("ID"),Y(this.getBapId()),Y("0")];return this.signOpReturnWithAIP(f)}}var{toArray:q,toUTF8:F,toBase64:b,toHex:B}=jf,{electrumEncrypt:n,electrumDecrypt:v}=e;class $f{#W;#f;#$;#j={};#J=c;#q="";#z="";#Q=0;getApiData;constructor(f,W="",j=""){if(!f)throw new Error("No key source given");if(typeof f==="string")this.#W=t.fromString(f),this.#$=!1;else this.#f=Wf.fromWif(f.rootPk),this.#$=!0;if(W)this.#q=W;if(j)this.#J=j;this.getApiData=k(this.#J,this.#q)}get lastIdPath(){return this.#z}getPublicKey(f=""){if(this.#$){if(!this.#f)throw new Error("Master private key not initialized");if(f)return this.#f.deriveChild(this.#f.toPublicKey(),f).toPublicKey().toString();return this.#f.toPublicKey().toString()}if(!this.#W)throw new Error("HD private key not initialized");if(f)return this.#W.derive(f).pubKey.toString();return this.#W.pubKey.toString()}getHdPublicKey(f=""){if(this.#$)throw new Error("HD public keys are not available in Type 42 mode");if(!this.#W)throw new Error("HD private key not initialized");if(f)return this.#W.derive(f).toPublic().toString();return this.#W.toPublic().toString()}set BAP_SERVER(f){this.#J=f}get BAP_SERVER(){return this.#J}set BAP_TOKEN(f){this.#q=f}get BAP_TOKEN(){return this.#q}checkIdBelongs(f){let W;if(this.#$){if(!this.#f)throw new Error("Master private key not initialized");W=this.#f.deriveChild(this.#f.toPublicKey(),f.rootPath).toPublicKey().toAddress()}else{if(!this.#W)throw new Error("HD private key not initialized");W=this.#W.derive(f.rootPath).pubKey.toAddress()}if(W!==f.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#j)}newId(f,W=""){let j;if(f)j=f;else if(this.#$)j=`bap:${this.#Q}`,this.#Q++;else j=this.getNextValidPath();let $;if(this.#$){if(!this.#f)throw new Error("Type 42 parameters not initialized");$=new L({rootPk:this.#f},W)}else{if(!this.#W)throw new Error("HD private key not initialized");$=new L(this.#W,W)}if($.rootPath=j,this.#$)$.currentPath=j;else $.currentPath=g.getNextPath(j);return this.#j[$.bapId]=$,this.#z=j,this.#j[$.bapId]}removeId(f){delete this.#j[f]}getNextValidPath(){if(this.#z)return g.getNextIdentityPath(this.#z);return`/0'/${Object.keys(this.#j).length}'/0'`}newIdWithCounter(f){if(!this.#$)throw new Error("newIdWithCounter only works in Type 42 mode");return this.newId(`bap:${f}`)}getId(f){return this.#j[f]||null}getAccountId(f){let W=this.#j[f];if(!W)return null;return new N(W.getAccountKey())}setId(f){this.checkIdBelongs(f),this.#j[f.bapId]=f}importIds(f,W=!0){if(W&&typeof f==="string"){this.importEncryptedIds(f);return}let j=f;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: ${f}`);let $=j.lastIdPath;for(let J of j.ids){if(!J.rootAddress)throw new Error("ID cannot be imported as it is not complete");let z;if(this.#$){if(!this.#f)throw new Error("Type 42 parameters not initialized");z=new L({rootPk:this.#f},J.idSeed)}else{if(!this.#W)throw new Error("HD private key not initialized");z=new L(this.#W,J.idSeed)}if(z.import(J),$==="")$=z.currentPath;if(this.checkIdBelongs(z),this.#j[z.bapId]=z,this.#$&&z.rootPath.startsWith("bap:")){let Q=z.rootPath.split(":");if(Q.length>=2){let G=Number.parseInt(Q[1],10);if(!Number.isNaN(G))this.#Q=Math.max(this.#Q,G+1)}}}this.#z=$}importEncryptedIds(f){let W=this.decrypt(f),j=JSON.parse(W);if(Array.isArray(j)){this.importOldIds(j);return}if(typeof j!=="object")throw new Error("decrypted, but found unrecognized identities format");this.importIds(j,!1)}importOldIds(f){for(let W of f){let j;if(this.#$){if(!this.#f)throw new Error("Type 42 parameters not initialized");j=new L({rootPk:this.#f},W.idSeed??"")}else{if(!this.#W)throw new Error("HD private key not initialized");j=new L(this.#W,W.idSeed??"")}j.import(W),this.checkIdBelongs(j),this.#j[j.bapId]=j,this.#z=j.currentPath}}exportIds(f,W=!0){let j={lastIdPath:this.#z,ids:[]},$=f||Object.keys(this.#j);for(let J of $){if(!this.#j[J])throw new Error(`Identity ${J} not found`);j.ids.push(this.#j[J].export())}if(W)return this.encrypt(JSON.stringify(j));return j}exportId(f,W=!0){let j={lastIdPath:this.#z,ids:[]};if(j.ids.push(this.#j[f].export()),W)return this.encrypt(JSON.stringify(j));return j}encrypt(f){if(this.#$){if(!this.#f)throw new Error("Master private key not initialized");let j=this.#f.deriveChild(this.#f.toPublicKey(),C);return b(n(q(f),j.toPublicKey()))}if(!this.#W)throw new Error("HD private key not initialized");let W=this.#W.derive(C);return b(n(q(f),W.pubKey))}decrypt(f){if(this.#$){if(!this.#f)throw new Error("Master private key not initialized");let j=this.#f.deriveChild(this.#f.toPublicKey(),C);return F(v(q(f,"base64"),j))}if(!this.#W)throw new Error("HD private key not initialized");let W=this.#W.derive(C);return F(v(q(f,"base64"),W.privKey))}signAttestationWithAIP(f,W,j=0,$=""){if(!this.getId(W))throw new Error("Could not find identity to attest with");let z=this.getAttestationBuffer(f,j,$);return this.createAttestationTransaction(f,j,"","",$)}verifyAttestationWithAIP(f){if(!f.every(($)=>Array.isArray($))||f[0][0]!==E.OP_RETURN||B(f[1])!==x)throw new Error("Not a valid BAP transaction");let W=B(f[7])==="44415441"?5:0,j={type:F(f[2]),hash:B(f[3]),sequence:F(f[4]),signingProtocol:F(f[7+W]),signingAddress:F(f[8+W]),signature:b(f[9+W])};if(W&&f[3]===f[8])j.data=B(f[9]);try{let $=[];for(let J=0;J<6+W;J++)$.push(f[J]);j.verified=this.verifySignature($.flat(),j.signingAddress,j.signature)}catch{j.verified=!1}return j}createAttestationTransaction(f,W,j,$,J=""){let z=[[E.OP_RETURN],q(w),q("ATTEST"),q(f),q(`${W}`),q("|")];if(J)z.push(q(w),q("DATA"),q(f),q(J),q("|"));return z.push(q(R),q("BITCOIN_ECDSA"),q(j),q($,"base64")),z}getAttestationBuffer(f,W=0,j=""){let $=[[E.OP_RETURN],q(w),q("ATTEST"),q(f),q(`${W}`),q("|")];if(j)$.push(q(w),q("DATA"),q(f),q(j),q("|"));return $.flat()}verifySignature(f,W,j){let $;if(Array.isArray(f))$=f;else if(Buffer.isBuffer(f))$=[...f];else $=q(f,"utf8");let J=ff.fromCompact(j,"base64");for(let z=0;z<4;z++)try{let Q=J.RecoverPublicKey(z,new a(K.magicHash($)));if(K.verify($,J,Q)&&Q.toAddress()===W)return!0}catch{}return!1}async verifyChallengeSignature(f,W,j,$){if(!this.verifySignature(j,W,$))return!1;try{let z=await this.getApiData("/attestation/valid",{idKey:f,address:W,challenge:j,signature:$});return z?.status==="success"&&z?.result?.valid===!0}catch{return!1}}async isValidAttestationTransaction(f){if(this.verifyAttestationWithAIP(f))return this.getApiData("/attestation/valid",{tx:f});return!1}async getIdentityFromAddress(f){return this.getApiData("/identity/validByAddress",{address:f})}async getIdentity(f){return this.getApiData("/identity/get",{idKey:f})}async getAttestationsForHash(f){return this.getApiData("/attestations",{hash:f})}exportForBackup(f,W,j){let J={ids:this.exportIds(),...f&&{label:f},createdAt:new Date().toISOString()};if(this.#$){if(!this.#f)throw new Error("Type 42 parameters not initialized");return{...J,rootPk:this.#f.toWif()}}if(!this.#W)throw new Error("HD private key not initialized");return{...J,xprv:W||this.#W.toString(),mnemonic:j||""}}}export{y as bapIdFromPubkey,X as bapIdFromAddress,L as MasterID,$f as BAP,N as AccountID};
2
+ import{BSM as V,BigNumber as r,ECIES as T,HD as K,OP as D,Signature as x,PrivateKey as s}from"@bsv/sdk";import{Utils as I}from"@bsv/sdk";var R=async(f,o,w,$)=>{let z=`${w}${f}`;return(await fetch(z,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:$,format:"json"},body:JSON.stringify(o)})).json()},N=(f,o)=>async(w,$)=>{return R(w,$,f,o)};import{Utils as _}from"@bsv/sdk";var{toHex:A,toArray:M}=_,k="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",n=A(M(k)),b="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva",y=A(M(b)),O="https://api.sigmaidentity.com/v1",J=2147483647,Q="m/424150'/0'/0'",X=`m/424150'/${J}'/${J}'`;import{Hash as g,HD as S,Utils as l}from"@bsv/sdk";import{Hash as U,PublicKey as B,Utils as H}from"@bsv/sdk";var{toHex:i,toBase58:c}=H;function h(f){let o=i(U.sha256(f,"utf8"));return c(U.ripemd160(o,"hex"))}function v(f){let o=B.fromString(f);return h(o.toAddress())}var F={getRandomBytes(f=32){if(typeof globalThis!=="undefined"&&globalThis.crypto&&globalThis.crypto.getRandomValues){let o=new Uint8Array(f);return globalThis.crypto.getRandomValues(o),o}throw new 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(f=32){let o=this.getRandomBytes(f);return Array.from(o,(w)=>w.toString(16).padStart(2,"0")).join("")},getSigningPathFromHex(f,o=!0){let w="m",$=f.match(/.{1,8}/g);if(!$)throw new Error("Invalid hex string");let z=2147483647;for(let j of $){let G=Number(`0x${j}`);if(G>z)G-=z;w+=`/${G}${o?"'":""}`}return w},getNextIdentityPath(f){let o=f.split("/"),w=o[o.length-2],$=!1;if(w.match("'"))$=!0;let z=(Number(w.replace(/[^0-9]/g,""))+1).toString();return o[o.length-2]=z+($?"'":""),o[o.length-1]=`0${$?"'":""}`,o.join("/")},getNextPath(f){let o=f.match(/^bap:(\d+)(?::(\d+))?$/);if(o){let G=o[1],Z=o[2];if(Z===void 0)return`bap:${G}:1`;return`bap:${G}:${Number(Z)+1}`}if(/^\d+$/.test(f))return(Number(f)+1).toString();if(!f.includes("/"))throw new Error(`Unsupported non-BIP32 path: ${f}`);let w=f.split("/"),$=w[w.length-1],z=!1;if($.match("'"))z=!0;let j=(Number($.replace(/[^0-9]/g,""))+1).toString();return w[w.length-1]=j+(z?"'":""),w.join("/")}};class q{#o;#f;#w;#$;#z;#j;#G;rootAddress;bapId;constructor(f,o=""){if(f instanceof S)if(this.#w=!1,o){let w=l.toHex(g.sha256(o,"utf8")),$=F.getSigningPathFromHex(w);this.#o=f.derive($)}else this.#o=f;else if(this.#w=!0,this.#f=f.rootPk,o){let w=l.toHex(g.sha256(o,"utf8"));this.#f=this.#f.deriveChild(this.#f.toPublicKey(),w)}if(this.#G=o,this.#$=`${Q}/0/0/0`,this.#j=`${Q}/0/0/0`,this.#z=`${Q}/0/0/1`,this.#w){if(!this.#f)throw new Error("Master private key not initialized");let w=this.#f.deriveChild(this.#f.toPublicKey(),this.#$);this.rootAddress=w.toPublicKey().toAddress()}else{if(!this.#o)throw new Error("HD private key not initialized");let w=this.#o.derive(this.#$);this.rootAddress=w.privKey.toPublicKey().toAddress()}this.bapId=h(this.rootAddress)}set rootPath(f){if(this.#w){if(this.#$=f,!this.#f)throw new Error("Master private key not initialized");let o=this.#f.deriveChild(this.#f.toPublicKey(),f);this.rootAddress=o.toPublicKey().toAddress(),this.#j=f,this.#z=f}else{let o=f;if(f.split("/").length<5)o=`${Q}${f}`;if(!this.validatePath(o))throw new Error(`invalid signing path given ${o}`);if(this.#$=o,!this.#o)throw new Error("HD private key not initialized");let w=this.#o.derive(o);this.rootAddress=w.pubKey.toAddress(),this.#j=o,this.#z=o}this.bapId=h(this.rootAddress)}get rootPath(){return this.#$}set currentPath(f){if(this.#w)this.#j=this.#z,this.#z=f;else{let o=f;if(f.split("/").length<5)o=`${Q}${f}`;if(!this.validatePath(o))throw new Error("invalid signing path given");this.#j=this.#z,this.#z=o}}get currentPath(){return this.#z}get previousPath(){return this.#j}get idSeed(){return this.#G}getAccountKey(){if(this.#w){if(!this.#f)throw new Error("Master private key not initialized");return this.#f}if(!this.#o)throw new Error("HD private key not initialized");return this.#o.privKey}validatePath(f){if(f.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 o=f.split("/");if(o.length===7&&Number(o[1].replace("'",""))<=J&&Number(o[2].replace("'",""))<=J&&Number(o[3].replace("'",""))<=J&&Number(o[4].replace("'",""))<=J&&Number(o[5].replace("'",""))<=J&&Number(o[6].replace("'",""))<=J)return!0}return!1}import(f){this.bapId="bapId"in f?f.bapId:f.identityKey,this.#$=f.rootPath,this.rootAddress=f.rootAddress,this.#j=f.previousPath,this.#z=f.currentPath,this.#G=("idSeed"in f?f.idSeed:"")||""}export(){return{bapId:this.bapId,rootPath:this.#$,rootAddress:this.rootAddress,previousPath:this.#j,currentPath:this.#z,idSeed:this.#G,lastIdPath:""}}}var{toArray:Y,toUTF8:W,toBase64:C,toHex:L}=I,{electrumEncrypt:u,electrumDecrypt:E}=T;class m{#o;#f;#w;#$={};#z=O;#j="";#G="";#J=0;getApiData;constructor(f,o="",w=""){if(!f)throw new Error("No key source given");if(typeof f==="string")this.#o=K.fromString(f),this.#w=!1;else this.#f=s.fromWif(f.rootPk),this.#w=!0;if(o)this.#j=o;if(w)this.#z=w;this.getApiData=N(this.#z,this.#j)}get lastIdPath(){return this.#G}getPublicKey(f=""){if(this.#w){if(!this.#f)throw new Error("Master private key not initialized");if(f)return this.#f.deriveChild(this.#f.toPublicKey(),f).toPublicKey().toString();return this.#f.toPublicKey().toString()}if(!this.#o)throw new Error("HD private key not initialized");if(f)return this.#o.derive(f).pubKey.toString();return this.#o.pubKey.toString()}getHdPublicKey(f=""){if(this.#w)throw new Error("HD public keys are not available in Type 42 mode");if(!this.#o)throw new Error("HD private key not initialized");if(f)return this.#o.derive(f).toPublic().toString();return this.#o.toPublic().toString()}set BAP_SERVER(f){this.#z=f}get BAP_SERVER(){return this.#z}set BAP_TOKEN(f){this.#j=f}get BAP_TOKEN(){return this.#j}checkIdBelongs(f){let o;if(this.#w){if(!this.#f)throw new Error("Master private key not initialized");o=this.#f.deriveChild(this.#f.toPublicKey(),f.rootPath).toPublicKey().toAddress()}else{if(!this.#o)throw new Error("HD private key not initialized");o=this.#o.derive(f.rootPath).pubKey.toAddress()}if(o!==f.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#$)}newId(f,o=""){let w;if(f)w=f;else if(this.#w)w=`bap:${this.#J}`,this.#J++;else w=this.getNextValidPath();let $;if(this.#w){if(!this.#f)throw new Error("Type 42 parameters not initialized");$=new q({rootPk:this.#f},o)}else{if(!this.#o)throw new Error("HD private key not initialized");$=new q(this.#o,o)}if($.rootPath=w,this.#w)$.currentPath=w;else $.currentPath=F.getNextPath(w);return this.#$[$.bapId]=$,this.#G=w,this.#$[$.bapId]}removeId(f){delete this.#$[f]}getNextValidPath(){if(this.#G)return F.getNextIdentityPath(this.#G);return`/0'/${Object.keys(this.#$).length}'/0'`}newIdWithCounter(f){if(!this.#w)throw new Error("newIdWithCounter only works in Type 42 mode");return this.newId(`bap:${f}`)}getId(f){return this.#$[f]||null}setId(f){this.checkIdBelongs(f),this.#$[f.bapId]=f}importIds(f,o=!0){if(o&&typeof f==="string"){this.importEncryptedIds(f);return}let w=f;if(!w.lastIdPath)throw new Error("ID cannot be imported as it is not complete");if(!w.ids)throw new Error(`ID data is not in the correct format: ${f}`);let $=w.lastIdPath;for(let z of w.ids){if(!z.rootAddress)throw new Error("ID cannot be imported as it is not complete");let j;if(this.#w){if(!this.#f)throw new Error("Type 42 parameters not initialized");j=new q({rootPk:this.#f},z.idSeed)}else{if(!this.#o)throw new Error("HD private key not initialized");j=new q(this.#o,z.idSeed)}if(j.import(z),$==="")$=j.currentPath;if(this.checkIdBelongs(j),this.#$[j.bapId]=j,this.#w&&j.rootPath.startsWith("bap:")){let G=j.rootPath.split(":");if(G.length>=2){let Z=Number.parseInt(G[1],10);if(!Number.isNaN(Z))this.#J=Math.max(this.#J,Z+1)}}}this.#G=$}importEncryptedIds(f){let o=this.decrypt(f),w=JSON.parse(o);if(Array.isArray(w)){this.importOldIds(w);return}if(typeof w!=="object")throw new Error("decrypted, but found unrecognized identities format");this.importIds(w,!1)}importOldIds(f){for(let o of f){let w;if(this.#w){if(!this.#f)throw new Error("Type 42 parameters not initialized");w=new q({rootPk:this.#f},o.idSeed??"")}else{if(!this.#o)throw new Error("HD private key not initialized");w=new q(this.#o,o.idSeed??"")}w.import(o),this.checkIdBelongs(w),this.#$[w.bapId]=w,this.#G=w.currentPath}}exportIds(f,o=!0){let w={lastIdPath:this.#G,ids:[]},$=f||Object.keys(this.#$);for(let z of $){if(!this.#$[z])throw new Error(`Identity ${z} not found`);w.ids.push(this.#$[z].export())}if(o)return this.encrypt(JSON.stringify(w));return w}exportId(f,o=!0){let w={lastIdPath:this.#G,ids:[]};if(w.ids.push(this.#$[f].export()),o)return this.encrypt(JSON.stringify(w));return w}encrypt(f){if(this.#w){if(!this.#f)throw new Error("Master private key not initialized");let w=this.#f.deriveChild(this.#f.toPublicKey(),X);return C(u(Y(f),w.toPublicKey()))}if(!this.#o)throw new Error("HD private key not initialized");let o=this.#o.derive(X);return C(u(Y(f),o.pubKey))}decrypt(f){if(this.#w){if(!this.#f)throw new Error("Master private key not initialized");let w=this.#f.deriveChild(this.#f.toPublicKey(),X);return W(E(Y(f,"base64"),w))}if(!this.#o)throw new Error("HD private key not initialized");let o=this.#o.derive(X);return W(E(Y(f,"base64"),o.privKey))}verifyAttestationWithAIP(f){if(!f.every(($)=>Array.isArray($))||f[0][0]!==D.OP_RETURN||L(f[1])!==n)throw new Error("Not a valid BAP transaction");let o=L(f[7])==="44415441"?5:0,w={type:W(f[2]),hash:L(f[3]),sequence:W(f[4]),signingProtocol:W(f[7+o]),signingAddress:W(f[8+o]),signature:C(f[9+o])};if(o&&f[3]===f[8])w.data=L(f[9]);try{let $=[];for(let z=0;z<6+o;z++)$.push(f[z]);w.verified=this.verifySignature($.flat(),w.signingAddress,w.signature)}catch{w.verified=!1}return w}verifySignature(f,o,w){let $;if(Array.isArray(f))$=f;else if(Buffer.isBuffer(f))$=[...f];else $=Y(f,"utf8");let z=x.fromCompact(w,"base64");for(let j=0;j<4;j++)try{let G=z.RecoverPublicKey(j,new r(V.magicHash($)));if(V.verify($,z,G)&&G.toAddress()===o)return!0}catch{}return!1}async verifyChallengeSignature(f,o,w,$){if(!this.verifySignature(w,o,$))return!1;try{let j=await this.getApiData("/attestation/valid",{idKey:f,address:o,challenge:w,signature:$});return j?.status==="success"&&j?.result?.valid===!0}catch{return!1}}async isValidAttestationTransaction(f){if(this.verifyAttestationWithAIP(f))return this.getApiData("/attestation/valid",{tx:f});return!1}async getIdentityFromAddress(f){return this.getApiData("/identity/validByAddress",{address:f})}async getIdentity(f){return this.getApiData("/identity/get",{idKey:f})}async getAttestationsForHash(f){return this.getApiData("/attestations",{hash:f})}exportForBackup(f,o,w){let z={ids:this.exportIds(),...f&&{label:f},createdAt:new Date().toISOString()};if(this.#w){if(!this.#f)throw new Error("Type 42 parameters not initialized");return{...z,rootPk:this.#f.toWif()}}if(!this.#o)throw new Error("HD private key not initialized");return{...z,xprv:o||this.#o.toString(),mnemonic:w||""}}}export{v as bapIdFromPubkey,h as bapIdFromAddress,q as MasterID,m as BAP};
3
3
 
4
- //# debugId=1EB6D950A04428A264756E2164756E21
4
+ //# debugId=F80B3402BB5DBC1764756E2164756E21
@@ -1,16 +1,14 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/api.ts", "../src/constants.ts", "../src/MasterID.ts", "../src/utils.ts", "../src/AccountID.ts", "../src/BaseClass.ts"],
3
+ "sources": ["../src/index.ts", "../src/api.ts", "../src/constants.ts", "../src/MasterID.ts", "../src/utils.ts"],
4
4
  "sourcesContent": [
5
- "import {\n BSM,\n BigNumber,\n ECIES,\n HD,\n OP,\n Signature,\n PrivateKey,\n} from \"@bsv/sdk\";\n\nimport { Utils as BSVUtils } from \"@bsv/sdk\";\nimport { type APIFetcher, apiFetcher } from \"./api\";\nimport type {\n AttestationValidResponse,\n GetAttestationResponse,\n GetIdentityByAddressResponse,\n GetIdentityResponse,\n} from \"./apiTypes\";\nimport {\n AIP_BITCOM_ADDRESS,\n BAP_BITCOM_ADDRESS,\n BAP_BITCOM_ADDRESS_HEX,\n BAP_SERVER,\n ENCRYPTION_PATH,\n} from \"./constants\";\nimport { MasterID } from \"./MasterID\";\nimport { AccountID } from \"./AccountID\";\nimport type {\n Attestation,\n Identity,\n OldIdentity,\n PathPrefix,\n} from \"./interface\";\nimport { Utils } from \"./utils\";\nconst { toArray, toUTF8, toBase64, toHex } = BSVUtils;\nconst { electrumEncrypt, electrumDecrypt } = ECIES;\n\ntype Identities = { lastIdPath: string; ids: Identity[] };\n\n/** Backup format for Type 42 mode (rootPk-based) */\nexport interface Type42MasterBackup {\n ids: string;\n rootPk: string;\n mnemonic?: string;\n label?: string;\n createdAt: string;\n}\n\n/** Backup format for BIP32 mode (xprv-based, legacy) */\nexport interface Bip32MasterBackup {\n ids: string;\n xprv: string;\n mnemonic?: string;\n label?: string;\n createdAt: string;\n}\n\ninterface Type42Params {\n rootPk: string;\n}\n\nexport class BAP {\n #HDPrivateKey: HD | undefined;\n #masterPrivateKey: PrivateKey | undefined;\n #isType42: boolean;\n #ids: { [key: string]: MasterID } = {};\n #BAP_SERVER = BAP_SERVER;\n #BAP_TOKEN = \"\";\n #lastIdPath = \"\";\n #identityCounter = 0;\n getApiData: APIFetcher;\n\n constructor(keySource: string | Type42Params, token = \"\", server = \"\") {\n if (!keySource) {\n throw new Error(\"No key source given\");\n }\n\n if (typeof keySource === \"string\") {\n this.#HDPrivateKey = HD.fromString(keySource);\n this.#isType42 = false;\n } else {\n this.#masterPrivateKey = PrivateKey.fromWif(keySource.rootPk);\n this.#isType42 = true;\n }\n\n if (token) this.#BAP_TOKEN = token;\n if (server) this.#BAP_SERVER = server;\n\n this.getApiData = apiFetcher(this.#BAP_SERVER, this.#BAP_TOKEN);\n }\n\n get lastIdPath(): string {\n return this.#lastIdPath;\n }\n\n getPublicKey(childPath = \"\"): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n if (childPath) {\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n childPath\n );\n return derivedKey.toPublicKey().toString();\n }\n return this.#masterPrivateKey.toPublicKey().toString();\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n if (childPath) {\n return this.#HDPrivateKey.derive(childPath).pubKey.toString();\n }\n return this.#HDPrivateKey.pubKey.toString();\n }\n\n getHdPublicKey(childPath = \"\"): string {\n if (this.#isType42) {\n throw new Error(\"HD public keys are not available in Type 42 mode\");\n }\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n if (childPath) {\n return this.#HDPrivateKey.derive(childPath).toPublic().toString();\n }\n return this.#HDPrivateKey.toPublic().toString();\n }\n\n set BAP_SERVER(bapServer) {\n this.#BAP_SERVER = bapServer;\n }\n\n get BAP_SERVER(): string {\n return this.#BAP_SERVER;\n }\n\n set BAP_TOKEN(token) {\n this.#BAP_TOKEN = token;\n }\n\n get BAP_TOKEN(): string {\n return this.#BAP_TOKEN;\n }\n\n checkIdBelongs(bapId: MasterID): boolean {\n let checkRootAddress: string;\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n bapId.rootPath\n );\n checkRootAddress = derivedKey.toPublicKey().toAddress();\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(bapId.rootPath);\n checkRootAddress = derivedChild.pubKey.toAddress();\n }\n\n if (checkRootAddress !== bapId.rootAddress) {\n throw new Error(\"ID does not belong to this private key\");\n }\n\n return true;\n }\n\n listIds(): string[] {\n return Object.keys(this.#ids);\n }\n\n newId(customPath?: string, idSeed = \"\"): MasterID {\n\n let pathToUse: string;\n if (customPath) {\n pathToUse = customPath;\n } else if (this.#isType42) {\n pathToUse = `bap:${this.#identityCounter}`;\n this.#identityCounter++;\n } else {\n pathToUse = this.getNextValidPath();\n }\n\n let newIdentity: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n newIdentity = new MasterID({ rootPk: this.#masterPrivateKey }, idSeed);\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n newIdentity = new MasterID(this.#HDPrivateKey, idSeed);\n }\n\n newIdentity.rootPath = pathToUse;\n\n if (this.#isType42) {\n newIdentity.currentPath = pathToUse;\n } else {\n newIdentity.currentPath = Utils.getNextPath(pathToUse);\n }\n\n this.#ids[newIdentity.bapId] = newIdentity;\n this.#lastIdPath = pathToUse;\n\n return this.#ids[newIdentity.bapId];\n }\n\n removeId(bapId: string): void {\n delete this.#ids[bapId];\n }\n\n getNextValidPath(): PathPrefix {\n if (this.#lastIdPath) {\n return Utils.getNextIdentityPath(this.#lastIdPath);\n }\n return `/0'/${Object.keys(this.#ids).length}'/0'`;\n }\n\n newIdWithCounter(counter: number): MasterID {\n if (!this.#isType42) {\n throw new Error(\"newIdWithCounter only works in Type 42 mode\");\n }\n return this.newId(`bap:${counter}`);\n }\n\n getId(bapId: string): MasterID | null {\n return this.#ids[bapId] || null;\n }\n\n /**\n * Get an AccountID for the given BAP ID.\n * The AccountID holds the account key and can sign create/revoke transactions.\n */\n getAccountId(bapId: string): AccountID | null {\n const masterId = this.#ids[bapId];\n if (!masterId) return null;\n return new AccountID(masterId.getAccountKey());\n }\n\n setId(bapId: MasterID): void {\n this.checkIdBelongs(bapId);\n this.#ids[bapId.bapId] = bapId;\n }\n\n importIds(idData: Identities | string, encrypted = true): void {\n if (encrypted && typeof idData === \"string\") {\n this.importEncryptedIds(idData);\n return;\n }\n const identity = idData as Identities;\n if (!identity.lastIdPath) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n if (!identity.ids) {\n throw new Error(`ID data is not in the correct format: ${idData}`);\n }\n\n let lastIdPath = identity.lastIdPath;\n for (const id of identity.ids) {\n if (!id.rootAddress) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n\n let importId: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n importId = new MasterID({ rootPk: this.#masterPrivateKey }, id.idSeed);\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n importId = new MasterID(this.#HDPrivateKey, id.idSeed);\n }\n\n importId.import(id);\n if (lastIdPath === \"\") {\n lastIdPath = importId.currentPath;\n }\n\n this.checkIdBelongs(importId);\n this.#ids[importId.bapId] = importId;\n\n if (this.#isType42 && importId.rootPath.startsWith('bap:')) {\n const pathParts = importId.rootPath.split(':');\n if (pathParts.length >= 2) {\n const counter = Number.parseInt(pathParts[1], 10);\n if (!Number.isNaN(counter)) {\n this.#identityCounter = Math.max(this.#identityCounter, counter + 1);\n }\n }\n }\n }\n\n this.#lastIdPath = lastIdPath;\n }\n\n importEncryptedIds(idData: string): void {\n const decrypted = this.decrypt(idData);\n const ids = JSON.parse(decrypted) as Identities;\n\n const isOldFormat = Array.isArray(ids);\n if (isOldFormat) {\n this.importOldIds(ids);\n return;\n }\n if (typeof ids !== \"object\") {\n throw new Error(\"decrypted, but found unrecognized identities format\");\n }\n this.importIds(ids, false);\n }\n\n importOldIds(idData: OldIdentity[]): void {\n for (const id of idData) {\n let importId: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n importId = new MasterID({ rootPk: this.#masterPrivateKey }, id.idSeed ?? \"\");\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n importId = new MasterID(this.#HDPrivateKey, id.idSeed ?? \"\");\n }\n\n importId.import(id);\n this.checkIdBelongs(importId);\n this.#ids[importId.bapId] = importId;\n this.#lastIdPath = importId.currentPath;\n }\n }\n\n exportIds(idKeys?: string[], encrypted?: true): string;\n exportIds(idKeys: string[] | undefined, encrypted: false): Identities;\n exportIds(idKeys?: string[], encrypted = true): Identities | string {\n const idData: Identities = {\n lastIdPath: this.#lastIdPath,\n ids: [] as Identity[],\n };\n\n const keysToExport = idKeys || Object.keys(this.#ids);\n for (const key of keysToExport) {\n if (!this.#ids[key]) throw new Error(`Identity ${key} not found`);\n idData.ids.push(this.#ids[key].export());\n }\n\n if (encrypted) {\n return this.encrypt(JSON.stringify(idData));\n }\n return idData;\n }\n\n exportId(idKey: string, encrypted?: true): string;\n exportId(idKey: string, encrypted: false): Identities;\n exportId(idKey: string, encrypted = true): Identities | string {\n const idData: Identities = {\n lastIdPath: this.#lastIdPath,\n ids: [] as Identity[],\n };\n idData.ids.push(this.#ids[idKey].export());\n if (encrypted) {\n return this.encrypt(JSON.stringify(idData));\n }\n return idData;\n }\n\n // Master-level encryption for the ids blob in the backup\n encrypt(string: string): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const encryptionKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n ENCRYPTION_PATH\n );\n return toBase64(\n electrumEncrypt(toArray(string), encryptionKey.toPublicKey())\n );\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n return toBase64(\n electrumEncrypt(toArray(string), derivedChild.pubKey)\n );\n }\n\n decrypt(string: string): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const encryptionKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n ENCRYPTION_PATH\n );\n return toUTF8(\n electrumDecrypt(toArray(string, \"base64\"), encryptionKey)\n );\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n return toUTF8(\n electrumDecrypt(toArray(string, \"base64\"), derivedChild.privKey)\n );\n }\n\n signAttestationWithAIP(\n attestationHash: string,\n bapId: string,\n counter = 0,\n dataString = \"\"\n ) {\n const id = this.getId(bapId);\n if (!id) throw new Error(\"Could not find identity to attest with\");\n\n // Attestation signing now needs to go through the wallet.\n // This method builds the transaction data but signing should be\n // delegated to the BRC-100 wallet in the calling code.\n const attestationBuffer = this.getAttestationBuffer(\n attestationHash,\n counter,\n dataString\n );\n\n return this.createAttestationTransaction(\n attestationHash,\n counter,\n \"\", // address — caller must provide from wallet\n \"\", // signature — caller must provide from wallet\n dataString\n );\n }\n\n verifyAttestationWithAIP(tx: number[][]): Attestation {\n if (\n !tx.every((t) => Array.isArray(t)) ||\n tx[0][0] !== OP.OP_RETURN ||\n toHex(tx[1]) !== BAP_BITCOM_ADDRESS_HEX\n ) {\n throw new Error(\"Not a valid BAP transaction\");\n }\n const dataOffset = toHex(tx[7]) === \"44415441\" ? 5 : 0;\n const attestation: Attestation = {\n type: toUTF8(tx[2]),\n hash: toHex(tx[3]),\n sequence: toUTF8(tx[4]),\n signingProtocol: toUTF8(tx[7 + dataOffset]),\n signingAddress: toUTF8(tx[8 + dataOffset]),\n signature: toBase64(tx[9 + dataOffset]),\n };\n\n if (dataOffset && tx[3] === tx[8]) {\n attestation.data = toHex(tx[9]);\n }\n\n try {\n const signatureBufferStatements: number[][] = [];\n for (let i = 0; i < 6 + dataOffset; i++) {\n signatureBufferStatements.push(tx[i]);\n }\n attestation.verified = this.verifySignature(\n signatureBufferStatements.flat(),\n attestation.signingAddress,\n attestation.signature\n );\n } catch {\n attestation.verified = false;\n }\n\n return attestation;\n }\n\n createAttestationTransaction(\n attestationHash: string,\n counter: number,\n address: string,\n signature: string,\n dataString = \"\"\n ): number[][] {\n const elements: number[][] = [\n [OP.OP_RETURN],\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"ATTEST\"),\n toArray(attestationHash),\n toArray(`${counter}`),\n toArray(\"|\"),\n ];\n\n if (dataString) {\n elements.push(\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"DATA\"),\n toArray(attestationHash),\n toArray(dataString),\n toArray(\"|\")\n );\n }\n\n elements.push(\n toArray(AIP_BITCOM_ADDRESS),\n toArray(\"BITCOIN_ECDSA\"),\n toArray(address),\n toArray(signature, \"base64\")\n );\n\n return elements;\n }\n\n getAttestationBuffer(\n attestationHash: string,\n counter = 0,\n dataString = \"\"\n ): number[] {\n const elements = [\n [OP.OP_RETURN],\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"ATTEST\"),\n toArray(attestationHash),\n toArray(`${counter}`),\n toArray(\"|\"),\n ];\n\n if (dataString) {\n elements.push(\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"DATA\"),\n toArray(attestationHash),\n toArray(dataString),\n toArray(\"|\")\n );\n }\n\n return elements.flat();\n }\n\n verifySignature(\n message: string | number[],\n address: string,\n signature: string\n ): boolean {\n let msg: number[];\n if (Array.isArray(message)) {\n msg = message;\n } else if (Buffer.isBuffer(message)) {\n msg = [...message];\n } else {\n msg = toArray(message, \"utf8\");\n }\n\n const sig = Signature.fromCompact(signature, \"base64\");\n\n for (let recovery = 0; recovery < 4; recovery++) {\n try {\n const publicKey = sig.RecoverPublicKey(\n recovery,\n new BigNumber(BSM.magicHash(msg))\n );\n if (BSM.verify(msg, sig, publicKey) && publicKey.toAddress() === address) {\n return true;\n }\n } catch {\n // try next recovery\n }\n }\n return false;\n }\n\n async verifyChallengeSignature(\n idKey: string,\n address: string,\n challenge: string,\n signature: string\n ): Promise<boolean> {\n const localVerification = this.verifySignature(challenge, address, signature);\n if (!localVerification) return false;\n\n try {\n const response = await this.getApiData<AttestationValidResponse>(\n \"/attestation/valid\",\n { idKey, address, challenge, signature }\n );\n return response?.status === \"success\" && response?.result?.valid === true;\n } catch {\n return false;\n }\n }\n\n async isValidAttestationTransaction(\n tx: number[][]\n ): Promise<AttestationValidResponse | false> {\n if (this.verifyAttestationWithAIP(tx)) {\n return this.getApiData<AttestationValidResponse>(\"/attestation/valid\", { tx });\n }\n return false;\n }\n\n async getIdentityFromAddress(address: string): Promise<GetIdentityByAddressResponse> {\n return this.getApiData<GetIdentityByAddressResponse>(\"/identity/validByAddress\", { address });\n }\n\n async getIdentity(idKey: string): Promise<GetIdentityResponse> {\n return this.getApiData<GetIdentityResponse>(\"/identity/get\", { idKey });\n }\n\n async getAttestationsForHash(attestationHash: string): Promise<GetAttestationResponse> {\n return this.getApiData<GetAttestationResponse>(\"/attestations\", { hash: attestationHash });\n }\n\n exportForBackup(\n label?: string,\n xprv?: string,\n mnemonic?: string\n ): Type42MasterBackup | Bip32MasterBackup {\n const ids = this.exportIds();\n const baseBackup = {\n ids,\n ...(label && { label }),\n createdAt: new Date().toISOString(),\n };\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n return { ...baseBackup, rootPk: this.#masterPrivateKey.toWif() };\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n return {\n ...baseBackup,\n xprv: xprv || this.#HDPrivateKey.toString(),\n mnemonic: mnemonic || \"\",\n };\n }\n}\n\nexport { MasterID, AccountID };\nexport { bapIdFromAddress, bapIdFromPubkey } from \"./utils\";\nexport type {\n Attestation,\n Identity,\n PathPrefix,\n Type42Params,\n};\nexport * from \"./apiTypes\";\n",
5
+ "import {\n BSM,\n BigNumber,\n ECIES,\n HD,\n OP,\n Signature,\n PrivateKey,\n} from \"@bsv/sdk\";\n\nimport { Utils as BSVUtils } from \"@bsv/sdk\";\nimport { type APIFetcher, apiFetcher } from \"./api\";\nimport type {\n AttestationValidResponse,\n GetAttestationResponse,\n GetIdentityByAddressResponse,\n GetIdentityResponse,\n} from \"./apiTypes\";\nimport {\n AIP_BITCOM_ADDRESS,\n BAP_BITCOM_ADDRESS_HEX,\n BAP_SERVER,\n ENCRYPTION_PATH,\n} from \"./constants\";\nimport { MasterID } from \"./MasterID\";\nimport type {\n Attestation,\n Identity,\n OldIdentity,\n PathPrefix,\n} from \"./interface\";\nimport { Utils } from \"./utils\";\nconst { toArray, toUTF8, toBase64, toHex } = BSVUtils;\nconst { electrumEncrypt, electrumDecrypt } = ECIES;\n\ntype Identities = { lastIdPath: string; ids: Identity[] };\n\n/** Backup format for Type 42 mode (rootPk-based) */\nexport interface Type42MasterBackup {\n ids: string;\n rootPk: string;\n mnemonic?: string;\n label?: string;\n createdAt: string;\n}\n\n/** Backup format for BIP32 mode (xprv-based, legacy) */\nexport interface Bip32MasterBackup {\n ids: string;\n xprv: string;\n mnemonic?: string;\n label?: string;\n createdAt: string;\n}\n\ninterface Type42Params {\n rootPk: string;\n}\n\nexport class BAP {\n #HDPrivateKey: HD | undefined;\n #masterPrivateKey: PrivateKey | undefined;\n #isType42: boolean;\n #ids: { [key: string]: MasterID } = {};\n #BAP_SERVER = BAP_SERVER;\n #BAP_TOKEN = \"\";\n #lastIdPath = \"\";\n #identityCounter = 0;\n getApiData: APIFetcher;\n\n constructor(keySource: string | Type42Params, token = \"\", server = \"\") {\n if (!keySource) {\n throw new Error(\"No key source given\");\n }\n\n if (typeof keySource === \"string\") {\n this.#HDPrivateKey = HD.fromString(keySource);\n this.#isType42 = false;\n } else {\n this.#masterPrivateKey = PrivateKey.fromWif(keySource.rootPk);\n this.#isType42 = true;\n }\n\n if (token) this.#BAP_TOKEN = token;\n if (server) this.#BAP_SERVER = server;\n\n this.getApiData = apiFetcher(this.#BAP_SERVER, this.#BAP_TOKEN);\n }\n\n get lastIdPath(): string {\n return this.#lastIdPath;\n }\n\n getPublicKey(childPath = \"\"): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n if (childPath) {\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n childPath\n );\n return derivedKey.toPublicKey().toString();\n }\n return this.#masterPrivateKey.toPublicKey().toString();\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n if (childPath) {\n return this.#HDPrivateKey.derive(childPath).pubKey.toString();\n }\n return this.#HDPrivateKey.pubKey.toString();\n }\n\n getHdPublicKey(childPath = \"\"): string {\n if (this.#isType42) {\n throw new Error(\"HD public keys are not available in Type 42 mode\");\n }\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n if (childPath) {\n return this.#HDPrivateKey.derive(childPath).toPublic().toString();\n }\n return this.#HDPrivateKey.toPublic().toString();\n }\n\n set BAP_SERVER(bapServer) {\n this.#BAP_SERVER = bapServer;\n }\n\n get BAP_SERVER(): string {\n return this.#BAP_SERVER;\n }\n\n set BAP_TOKEN(token) {\n this.#BAP_TOKEN = token;\n }\n\n get BAP_TOKEN(): string {\n return this.#BAP_TOKEN;\n }\n\n checkIdBelongs(bapId: MasterID): boolean {\n let checkRootAddress: string;\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n bapId.rootPath\n );\n checkRootAddress = derivedKey.toPublicKey().toAddress();\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(bapId.rootPath);\n checkRootAddress = derivedChild.pubKey.toAddress();\n }\n\n if (checkRootAddress !== bapId.rootAddress) {\n throw new Error(\"ID does not belong to this private key\");\n }\n\n return true;\n }\n\n listIds(): string[] {\n return Object.keys(this.#ids);\n }\n\n newId(customPath?: string, idSeed = \"\"): MasterID {\n\n let pathToUse: string;\n if (customPath) {\n pathToUse = customPath;\n } else if (this.#isType42) {\n pathToUse = `bap:${this.#identityCounter}`;\n this.#identityCounter++;\n } else {\n pathToUse = this.getNextValidPath();\n }\n\n let newIdentity: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n newIdentity = new MasterID({ rootPk: this.#masterPrivateKey }, idSeed);\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n newIdentity = new MasterID(this.#HDPrivateKey, idSeed);\n }\n\n newIdentity.rootPath = pathToUse;\n\n if (this.#isType42) {\n newIdentity.currentPath = pathToUse;\n } else {\n newIdentity.currentPath = Utils.getNextPath(pathToUse);\n }\n\n this.#ids[newIdentity.bapId] = newIdentity;\n this.#lastIdPath = pathToUse;\n\n return this.#ids[newIdentity.bapId];\n }\n\n removeId(bapId: string): void {\n delete this.#ids[bapId];\n }\n\n getNextValidPath(): PathPrefix {\n if (this.#lastIdPath) {\n return Utils.getNextIdentityPath(this.#lastIdPath);\n }\n return `/0'/${Object.keys(this.#ids).length}'/0'`;\n }\n\n newIdWithCounter(counter: number): MasterID {\n if (!this.#isType42) {\n throw new Error(\"newIdWithCounter only works in Type 42 mode\");\n }\n return this.newId(`bap:${counter}`);\n }\n\n getId(bapId: string): MasterID | null {\n return this.#ids[bapId] || null;\n }\n\n setId(bapId: MasterID): void {\n this.checkIdBelongs(bapId);\n this.#ids[bapId.bapId] = bapId;\n }\n\n importIds(idData: Identities | string, encrypted = true): void {\n if (encrypted && typeof idData === \"string\") {\n this.importEncryptedIds(idData);\n return;\n }\n const identity = idData as Identities;\n if (!identity.lastIdPath) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n if (!identity.ids) {\n throw new Error(`ID data is not in the correct format: ${idData}`);\n }\n\n let lastIdPath = identity.lastIdPath;\n for (const id of identity.ids) {\n if (!id.rootAddress) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n\n let importId: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n importId = new MasterID({ rootPk: this.#masterPrivateKey }, id.idSeed);\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n importId = new MasterID(this.#HDPrivateKey, id.idSeed);\n }\n\n importId.import(id);\n if (lastIdPath === \"\") {\n lastIdPath = importId.currentPath;\n }\n\n this.checkIdBelongs(importId);\n this.#ids[importId.bapId] = importId;\n\n if (this.#isType42 && importId.rootPath.startsWith('bap:')) {\n const pathParts = importId.rootPath.split(':');\n if (pathParts.length >= 2) {\n const counter = Number.parseInt(pathParts[1], 10);\n if (!Number.isNaN(counter)) {\n this.#identityCounter = Math.max(this.#identityCounter, counter + 1);\n }\n }\n }\n }\n\n this.#lastIdPath = lastIdPath;\n }\n\n importEncryptedIds(idData: string): void {\n const decrypted = this.decrypt(idData);\n const ids = JSON.parse(decrypted) as Identities;\n\n const isOldFormat = Array.isArray(ids);\n if (isOldFormat) {\n this.importOldIds(ids);\n return;\n }\n if (typeof ids !== \"object\") {\n throw new Error(\"decrypted, but found unrecognized identities format\");\n }\n this.importIds(ids, false);\n }\n\n importOldIds(idData: OldIdentity[]): void {\n for (const id of idData) {\n let importId: MasterID;\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n importId = new MasterID({ rootPk: this.#masterPrivateKey }, id.idSeed ?? \"\");\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n importId = new MasterID(this.#HDPrivateKey, id.idSeed ?? \"\");\n }\n\n importId.import(id);\n this.checkIdBelongs(importId);\n this.#ids[importId.bapId] = importId;\n this.#lastIdPath = importId.currentPath;\n }\n }\n\n exportIds(idKeys?: string[], encrypted?: true): string;\n exportIds(idKeys: string[] | undefined, encrypted: false): Identities;\n exportIds(idKeys?: string[], encrypted = true): Identities | string {\n const idData: Identities = {\n lastIdPath: this.#lastIdPath,\n ids: [] as Identity[],\n };\n\n const keysToExport = idKeys || Object.keys(this.#ids);\n for (const key of keysToExport) {\n if (!this.#ids[key]) throw new Error(`Identity ${key} not found`);\n idData.ids.push(this.#ids[key].export());\n }\n\n if (encrypted) {\n return this.encrypt(JSON.stringify(idData));\n }\n return idData;\n }\n\n exportId(idKey: string, encrypted?: true): string;\n exportId(idKey: string, encrypted: false): Identities;\n exportId(idKey: string, encrypted = true): Identities | string {\n const idData: Identities = {\n lastIdPath: this.#lastIdPath,\n ids: [] as Identity[],\n };\n idData.ids.push(this.#ids[idKey].export());\n if (encrypted) {\n return this.encrypt(JSON.stringify(idData));\n }\n return idData;\n }\n\n encrypt(string: string): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const encryptionKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n ENCRYPTION_PATH\n );\n return toBase64(\n electrumEncrypt(toArray(string), encryptionKey.toPublicKey())\n );\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n return toBase64(\n electrumEncrypt(toArray(string), derivedChild.pubKey)\n );\n }\n\n decrypt(string: string): string {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const encryptionKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n ENCRYPTION_PATH\n );\n return toUTF8(\n electrumDecrypt(toArray(string, \"base64\"), encryptionKey)\n );\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n return toUTF8(\n electrumDecrypt(toArray(string, \"base64\"), derivedChild.privKey)\n );\n }\n\n verifyAttestationWithAIP(tx: number[][]): Attestation {\n if (\n !tx.every((t) => Array.isArray(t)) ||\n tx[0][0] !== OP.OP_RETURN ||\n toHex(tx[1]) !== BAP_BITCOM_ADDRESS_HEX\n ) {\n throw new Error(\"Not a valid BAP transaction\");\n }\n const dataOffset = toHex(tx[7]) === \"44415441\" ? 5 : 0;\n const attestation: Attestation = {\n type: toUTF8(tx[2]),\n hash: toHex(tx[3]),\n sequence: toUTF8(tx[4]),\n signingProtocol: toUTF8(tx[7 + dataOffset]),\n signingAddress: toUTF8(tx[8 + dataOffset]),\n signature: toBase64(tx[9 + dataOffset]),\n };\n\n if (dataOffset && tx[3] === tx[8]) {\n attestation.data = toHex(tx[9]);\n }\n\n try {\n const signatureBufferStatements: number[][] = [];\n for (let i = 0; i < 6 + dataOffset; i++) {\n signatureBufferStatements.push(tx[i]);\n }\n attestation.verified = this.verifySignature(\n signatureBufferStatements.flat(),\n attestation.signingAddress,\n attestation.signature\n );\n } catch {\n attestation.verified = false;\n }\n\n return attestation;\n }\n\n verifySignature(\n message: string | number[],\n address: string,\n signature: string\n ): boolean {\n let msg: number[];\n if (Array.isArray(message)) {\n msg = message;\n } else if (Buffer.isBuffer(message)) {\n msg = [...message];\n } else {\n msg = toArray(message, \"utf8\");\n }\n\n const sig = Signature.fromCompact(signature, \"base64\");\n\n for (let recovery = 0; recovery < 4; recovery++) {\n try {\n const publicKey = sig.RecoverPublicKey(\n recovery,\n new BigNumber(BSM.magicHash(msg))\n );\n if (BSM.verify(msg, sig, publicKey) && publicKey.toAddress() === address) {\n return true;\n }\n } catch {\n // try next recovery\n }\n }\n return false;\n }\n\n async verifyChallengeSignature(\n idKey: string,\n address: string,\n challenge: string,\n signature: string\n ): Promise<boolean> {\n const localVerification = this.verifySignature(challenge, address, signature);\n if (!localVerification) return false;\n\n try {\n const response = await this.getApiData<AttestationValidResponse>(\n \"/attestation/valid\",\n { idKey, address, challenge, signature }\n );\n return response?.status === \"success\" && response?.result?.valid === true;\n } catch {\n return false;\n }\n }\n\n async isValidAttestationTransaction(\n tx: number[][]\n ): Promise<AttestationValidResponse | false> {\n if (this.verifyAttestationWithAIP(tx)) {\n return this.getApiData<AttestationValidResponse>(\"/attestation/valid\", { tx });\n }\n return false;\n }\n\n async getIdentityFromAddress(address: string): Promise<GetIdentityByAddressResponse> {\n return this.getApiData<GetIdentityByAddressResponse>(\"/identity/validByAddress\", { address });\n }\n\n async getIdentity(idKey: string): Promise<GetIdentityResponse> {\n return this.getApiData<GetIdentityResponse>(\"/identity/get\", { idKey });\n }\n\n async getAttestationsForHash(attestationHash: string): Promise<GetAttestationResponse> {\n return this.getApiData<GetAttestationResponse>(\"/attestations\", { hash: attestationHash });\n }\n\n exportForBackup(\n label?: string,\n xprv?: string,\n mnemonic?: string\n ): Type42MasterBackup | Bip32MasterBackup {\n const ids = this.exportIds();\n const baseBackup = {\n ids,\n ...(label && { label }),\n createdAt: new Date().toISOString(),\n };\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Type 42 parameters not initialized\");\n return { ...baseBackup, rootPk: this.#masterPrivateKey.toWif() };\n }\n\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n return {\n ...baseBackup,\n xprv: xprv || this.#HDPrivateKey.toString(),\n mnemonic: mnemonic || \"\",\n };\n }\n}\n\nexport { MasterID };\nexport { bapIdFromAddress, bapIdFromPubkey } from \"./utils\";\nexport type {\n Attestation,\n Identity,\n PathPrefix,\n Type42Params,\n};\nexport * from \"./apiTypes\";\n",
6
6
  "/**\n * Helper function to get attestation from a BAP API server\n *\n * @param apiUrl\n * @param apiData\n * @returns {Promise<any>}\n */\nexport const getApiData = async <T>(\n apiUrl: string,\n apiData: unknown,\n server: string,\n token: string\n): Promise<T> => {\n const url = `${server}${apiUrl}`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-type\": \"application/json; charset=utf-8\",\n token,\n format: \"json\",\n },\n body: JSON.stringify(apiData),\n });\n\n return response.json();\n};\n\nexport type APIFetcher = <T>(url: string, data: unknown) => Promise<T>;\n\nexport const apiFetcher =\n (host: string, token: string): APIFetcher =>\n async <T>(url: string, data: unknown): Promise<T> => {\n return getApiData<T>(url, data, host, token);\n };\n",
7
7
  "import { Utils } from \"@bsv/sdk\";\nconst { toHex, toArray } = Utils;\n\nexport const BAP_BITCOM_ADDRESS = \"1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT\";\nexport const BAP_BITCOM_ADDRESS_HEX = toHex(toArray(BAP_BITCOM_ADDRESS));\nexport const AIP_BITCOM_ADDRESS = \"15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva\";\nexport const AIP_BITCOM_ADDRESS_HEX = toHex(toArray(AIP_BITCOM_ADDRESS));\nexport const BAP_SERVER = \"https://api.sigmaidentity.com/v1\";\nexport const MAX_INT = 2147483648 - 1; // 0x80000000\n\nexport const SIGNING_PATH_PREFIX = \"m/424150'/0'/0'\"; // BAP in hex\n\n// Used by the BAP class for encrypting the identity list in the master backup\nexport const ENCRYPTION_PATH = `m/424150'/${MAX_INT}'/${MAX_INT}'`;\n",
8
- "import {\n Hash,\n type PrivateKey,\n HD,\n Utils as BSVUtils,\n} from \"@bsv/sdk\";\n\nimport {\n SIGNING_PATH_PREFIX,\n MAX_INT,\n} from \"./constants\";\nimport type {\n Identity,\n OldIdentity,\n} from \"./interface\";\nimport { Utils, bapIdFromAddress } from \"./utils\";\n\ninterface Type42KeySource {\n rootPk: PrivateKey;\n}\n\nclass MasterID {\n #HDPrivateKey: HD | undefined;\n #masterPrivateKey: PrivateKey | undefined;\n #isType42: boolean;\n #rootPath: string;\n #currentPath: string;\n #previousPath: string;\n #idSeed: string;\n\n rootAddress: string;\n bapId: string;\n\n constructor(\n keySource: HD | Type42KeySource,\n idSeed = \"\"\n ) {\n if (keySource instanceof HD) {\n this.#isType42 = false;\n if (idSeed) {\n const seedHex = BSVUtils.toHex(Hash.sha256(idSeed, \"utf8\"));\n const seedPath = Utils.getSigningPathFromHex(seedHex);\n this.#HDPrivateKey = keySource.derive(seedPath);\n } else {\n this.#HDPrivateKey = keySource;\n }\n } else {\n this.#isType42 = true;\n this.#masterPrivateKey = keySource.rootPk;\n if (idSeed) {\n const seedHex = BSVUtils.toHex(Hash.sha256(idSeed, \"utf8\"));\n this.#masterPrivateKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n seedHex\n );\n }\n }\n\n this.#idSeed = idSeed;\n\n this.#rootPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n this.#previousPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n this.#currentPath = `${SIGNING_PATH_PREFIX}/0/0/1`;\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const rootKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n this.#rootPath\n );\n this.rootAddress = rootKey.toPublicKey().toAddress();\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const rootChild = this.#HDPrivateKey.derive(this.#rootPath);\n this.rootAddress = rootChild.privKey.toPublicKey().toAddress();\n }\n\n this.bapId = bapIdFromAddress(this.rootAddress);\n }\n\n /**\n * Get the account key (root key) for this identity.\n * This is the cold key used for BAP ID creation and revocation.\n */\n getAccountKey(): PrivateKey {\n return this.getPathDerivedKey(this.#rootPath);\n }\n\n private getPathDerivedKey(path: string): PrivateKey {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n return this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n path\n );\n }\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n return this.#HDPrivateKey.derive(path).privKey;\n }\n\n set rootPath(path: string) {\n if (this.#isType42) {\n this.#rootPath = path;\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n path\n );\n this.rootAddress = derivedKey.toPublicKey().toAddress();\n this.#previousPath = path;\n this.#currentPath = path;\n } else {\n let pathToUse = path;\n if (path.split(\"/\").length < 5) {\n pathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n }\n if (!this.validatePath(pathToUse)) {\n throw new Error(`invalid signing path given ${pathToUse}`);\n }\n this.#rootPath = pathToUse;\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(pathToUse);\n this.rootAddress = derivedChild.pubKey.toAddress();\n this.#previousPath = pathToUse;\n this.#currentPath = pathToUse;\n }\n this.bapId = bapIdFromAddress(this.rootAddress);\n }\n\n get rootPath(): string {\n return this.#rootPath;\n }\n\n set currentPath(path: string) {\n if (this.#isType42) {\n this.#previousPath = this.#currentPath;\n this.#currentPath = path;\n } else {\n let pathToUse = path;\n if (path.split(\"/\").length < 5) {\n pathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n }\n if (!this.validatePath(pathToUse)) {\n throw new Error(\"invalid signing path given\");\n }\n this.#previousPath = this.#currentPath;\n this.#currentPath = pathToUse;\n }\n }\n\n get currentPath(): string {\n return this.#currentPath;\n }\n\n get previousPath(): string {\n return this.#previousPath;\n }\n\n get idSeed(): string {\n return this.#idSeed;\n }\n\n validatePath(path: string): boolean {\n if (\n path.match(\n /\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?/\n )\n ) {\n const pathValues = path.split(\"/\");\n if (\n pathValues.length === 7 &&\n Number(pathValues[1].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[2].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[3].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[4].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[5].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[6].replace(\"'\", \"\")) <= MAX_INT\n ) {\n return true;\n }\n }\n return false;\n }\n\n import(identity: Identity | OldIdentity): void {\n this.bapId = \"bapId\" in identity ? identity.bapId : (identity as OldIdentity).identityKey;\n this.#rootPath = identity.rootPath;\n this.rootAddress = identity.rootAddress;\n this.#previousPath = identity.previousPath;\n this.#currentPath = identity.currentPath;\n this.#idSeed = (\"idSeed\" in identity ? identity.idSeed : \"\") || \"\";\n }\n\n export(): Identity {\n return {\n bapId: this.bapId,\n rootPath: this.#rootPath,\n rootAddress: this.rootAddress,\n previousPath: this.#previousPath,\n currentPath: this.#currentPath,\n idSeed: this.#idSeed,\n lastIdPath: \"\",\n };\n }\n}\n\nexport { MasterID };\n",
9
- "import { Hash, PublicKey, Utils as BSVUtils } from \"@bsv/sdk\";\nimport type { PathPrefix } from \"./interface.js\";\n\nconst { toHex, toBase58 } = BSVUtils;\n\n/**\n * Derive a BAP ID from a Bitcoin address (rootAddress).\n *\n * BAP ID = base58(ripemd160(sha256(rootAddress)))\n *\n * This is the canonical derivation used by MasterID.deriveIdentityKey().\n * The address MUST be the rootAddress (from the BAP member key), not a\n * signing key address.\n */\nexport function bapIdFromAddress(address: string): string {\n const rootAddressHash = toHex(Hash.sha256(address, \"utf8\"));\n return toBase58(Hash.ripemd160(rootAddressHash, \"hex\"));\n}\n\n/**\n * Derive a BAP ID from a compressed public key (hex).\n *\n * Converts the pubkey to a Bitcoin address, then derives the BAP ID.\n *\n * IMPORTANT: This only produces a correct BAP ID when the pubkey is the\n * BAP member key's public key. It does NOT work with signing keys or\n * arbitrary public keys.\n *\n * In BRC-100 wallets, the BRC-31 identity key IS the member key's pubkey,\n * so this correctly bridges BRC-31 auth to BAP identity lookups.\n */\nexport function bapIdFromPubkey(pubkeyHex: string): string {\n const pubkey = PublicKey.fromString(pubkeyHex);\n return bapIdFromAddress(pubkey.toAddress());\n}\n\nexport const Utils = {\n /**\n * Helper function to generate cryptographically secure random bytes\n * \n * This follows the pattern used by BSV SDK and other Bitcoin libraries.\n * Uses crypto.getRandomValues() which is available in browsers and modern Node.js.\n *\n * @param {number} byteLength - Number of random bytes to generate (default: 32)\n * @returns {Uint8Array} Array of cryptographically secure random bytes\n */\n getRandomBytes(byteLength = 32): Uint8Array {\n // Use crypto.getRandomValues() - available in browsers and Node.js 15+\n if (typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.getRandomValues) {\n const array = new Uint8Array(byteLength);\n globalThis.crypto.getRandomValues(array);\n return array;\n }\n\n // Fallback error - crypto operations require secure randomness\n throw new Error(\n 'Secure random number generation not available. ' +\n 'crypto.getRandomValues() is required for cryptographic operations. ' +\n 'This environment may not be suitable for secure key generation.'\n );\n },\n\n /**\n * Helper function to generate a random hex string\n *\n * @param {number} byteLength - Number of random bytes to generate (default: 32)\n * @returns {string} Hex string of random bytes\n */\n getRandomString(byteLength = 32): string {\n const bytes = this.getRandomBytes(byteLength);\n return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');\n },\n\n /**\n * Get a signing path from a hex number\n *\n * @param hexString {string}\n * @param hardened {boolean} Whether to return a hardened path\n * @returns {string}\n */\n getSigningPathFromHex(hexString: string, hardened = true) {\n // \"m/0/0/1\"\n let signingPath = \"m\";\n const signingHex = hexString.match(/.{1,8}/g);\n if (!signingHex) {\n throw new Error(\"Invalid hex string\");\n }\n const maxNumber = 2147483648 - 1; // 0x80000000\n for (const hexNumber of signingHex) {\n let number = Number(`0x${hexNumber}`);\n if (number > maxNumber) number -= maxNumber;\n signingPath += `/${number}${hardened ? \"'\" : \"\"}`;\n }\n\n return signingPath;\n },\n\n /**\n * Increment that second to last part from the given part, set the last part to 0\n *\n * @param path string\n * @returns {*}\n */\n getNextIdentityPath(path: string): PathPrefix {\n const pathValues = path.split(\"/\");\n const secondToLastPart = pathValues[pathValues.length - 2];\n\n let hardened = false;\n if (secondToLastPart.match(\"'\")) {\n hardened = true;\n }\n\n const nextPath = (\n Number(secondToLastPart.replace(/[^0-9]/g, \"\")) + 1\n ).toString();\n pathValues[pathValues.length - 2] = nextPath + (hardened ? \"'\" : \"\");\n pathValues[pathValues.length - 1] = `0${hardened ? \"'\" : \"\"}`;\n\n return pathValues.join(\"/\") as PathPrefix;\n },\n\n /**\n * Increment that last part of the given path\n *\n * @param path string\n * @returns {*}\n */\n getNextPath(path: string) {\n const type42Path = path.match(/^bap:(\\d+)(?::(\\d+))?$/);\n if (type42Path) {\n const identityIndex = type42Path[1];\n const rotationIndex = type42Path[2];\n\n if (rotationIndex === undefined) {\n return `bap:${identityIndex}:1`;\n }\n\n return `bap:${identityIndex}:${Number(rotationIndex) + 1}`;\n }\n\n // Backward compatibility for Type 42 backups created before the\n // `bap:<identity>:<rotation>` format was fixed. Those backups stored\n // bare numeric rotation paths like \"1\", and must keep rotating within\n // that legacy namespace so previously derived keys remain valid.\n if (/^\\d+$/.test(path)) {\n return (Number(path) + 1).toString();\n }\n\n if (!path.includes(\"/\")) {\n throw new Error(`Unsupported non-BIP32 path: ${path}`);\n }\n\n const pathValues = path.split(\"/\");\n const lastPart = pathValues[pathValues.length - 1];\n let hardened = false;\n if (lastPart.match(\"'\")) {\n hardened = true;\n }\n const nextPath = (Number(lastPart.replace(/[^0-9]/g, \"\")) + 1).toString();\n pathValues[pathValues.length - 1] = nextPath + (hardened ? \"'\" : \"\");\n return pathValues.join(\"/\");\n },\n};\n",
10
- "import {\n PrivateKey,\n Hash,\n Utils as BSVUtils,\n OP,\n} from \"@bsv/sdk\";\nimport { BaseClass } from \"./BaseClass\";\nimport { BAP_BITCOM_ADDRESS } from \"./constants\";\nconst { toArray } = BSVUtils;\n\nexport class AccountID extends BaseClass {\n private key: PrivateKey;\n\n constructor(key: PrivateKey) {\n super();\n this.key = key;\n }\n\n getBapId(): string {\n const addressBytes = toArray(this.getRootAddress());\n const sha = Hash.sha256(addressBytes);\n const ripe = Hash.ripemd160(sha);\n return BSVUtils.toBase58(ripe);\n }\n\n getRootAddress(): string {\n return this.key.toPublicKey().toAddress();\n }\n\n getRootPublicKey(): string {\n return this.key.toPublicKey().toString();\n }\n\n signMessage(message: number[]): { address: string; signature: string } {\n return this.signWithBSM(message, this.key);\n }\n\n getInitialIdTransaction(firstSigningAddress: string): number[][] {\n const opReturn = [\n [OP.OP_RETURN],\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"ID\"),\n toArray(this.getBapId()),\n toArray(firstSigningAddress),\n ];\n\n return this.signOpReturnWithAIP(opReturn);\n }\n\n getRevocationTransaction(): number[][] {\n const opReturn = [\n [OP.OP_RETURN],\n toArray(BAP_BITCOM_ADDRESS),\n toArray(\"ID\"),\n toArray(this.getBapId()),\n toArray(\"0\"),\n ];\n\n return this.signOpReturnWithAIP(opReturn);\n }\n}\n",
11
- "import { Utils as BSVUtils, OP, BSM, BigNumber } from \"@bsv/sdk\";\nimport type { PrivateKey, Signature } from \"@bsv/sdk\";\nimport { AIP_BITCOM_ADDRESS } from \"./constants\";\nconst { toArray, toBase64 } = BSVUtils;\n\nabstract class BaseClass {\n abstract signMessage(\n message: number[],\n ): { address: string; signature: string };\n\n protected signWithBSM(\n message: number[],\n signingKey: PrivateKey\n ): { address: string; signature: string } {\n const address = signingKey.toPublicKey().toAddress();\n const dummySig = BSM.sign(message, signingKey, \"raw\") as Signature;\n const h = new BigNumber(BSM.magicHash(message));\n const r = dummySig.CalculateRecoveryFactor(signingKey.toPublicKey(), h);\n const signature = (\n BSM.sign(message, signingKey, \"raw\") as Signature\n ).toCompact(r, true, \"base64\") as string;\n\n return { address, signature };\n }\n\n signOpReturnWithAIP(opReturn: number[][]): number[][] {\n const aipMessageBuffer = this.getAIPMessageBuffer(opReturn);\n const { address, signature } = this.signMessage(\n aipMessageBuffer.flat(),\n );\n return this.formatAIPOutput(aipMessageBuffer, address, signature);\n }\n\n protected getAIPMessageBuffer(\n opReturn: number[][],\n indicies?: number[]\n ): number[][] {\n let opReturnIndex = opReturn.findIndex((op) => op[0] === OP.OP_RETURN);\n const buffers: number[][] = [];\n\n if (opReturnIndex === -1) {\n buffers.push([OP.OP_RETURN]);\n opReturnIndex = 0;\n }\n\n if (indicies) {\n for (const index of indicies) {\n buffers.push(opReturn[opReturnIndex + index]);\n }\n } else {\n for (const op of opReturn) {\n buffers.push(op);\n }\n }\n\n return buffers;\n }\n\n protected formatAIPOutput(\n opReturnBuffers: number[][],\n address: string,\n signature: string\n ): number[][] {\n const aipElements = [\n toArray(\"|\"),\n toArray(AIP_BITCOM_ADDRESS),\n toArray(\"BITCOIN_ECDSA\"),\n toArray(address),\n toArray(signature, \"base64\"),\n ];\n\n return [...opReturnBuffers, ...aipElements];\n }\n}\n\nexport { BaseClass };\n"
8
+ "import {\n Hash,\n type PrivateKey,\n HD,\n Utils as BSVUtils,\n} from \"@bsv/sdk\";\n\nimport {\n SIGNING_PATH_PREFIX,\n MAX_INT,\n} from \"./constants\";\nimport type {\n Identity,\n OldIdentity,\n} from \"./interface\";\nimport { Utils, bapIdFromAddress } from \"./utils\";\n\ninterface Type42KeySource {\n rootPk: PrivateKey;\n}\n\nclass MasterID {\n #HDPrivateKey: HD | undefined;\n #masterPrivateKey: PrivateKey | undefined;\n #isType42: boolean;\n #rootPath: string;\n #currentPath: string;\n #previousPath: string;\n #idSeed: string;\n\n rootAddress: string;\n bapId: string;\n\n constructor(\n keySource: HD | Type42KeySource,\n idSeed = \"\"\n ) {\n if (keySource instanceof HD) {\n this.#isType42 = false;\n if (idSeed) {\n const seedHex = BSVUtils.toHex(Hash.sha256(idSeed, \"utf8\"));\n const seedPath = Utils.getSigningPathFromHex(seedHex);\n this.#HDPrivateKey = keySource.derive(seedPath);\n } else {\n this.#HDPrivateKey = keySource;\n }\n } else {\n this.#isType42 = true;\n this.#masterPrivateKey = keySource.rootPk;\n if (idSeed) {\n const seedHex = BSVUtils.toHex(Hash.sha256(idSeed, \"utf8\"));\n this.#masterPrivateKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n seedHex\n );\n }\n }\n\n this.#idSeed = idSeed;\n\n this.#rootPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n this.#previousPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n this.#currentPath = `${SIGNING_PATH_PREFIX}/0/0/1`;\n\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const rootKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n this.#rootPath\n );\n this.rootAddress = rootKey.toPublicKey().toAddress();\n } else {\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const rootChild = this.#HDPrivateKey.derive(this.#rootPath);\n this.rootAddress = rootChild.privKey.toPublicKey().toAddress();\n }\n\n this.bapId = bapIdFromAddress(this.rootAddress);\n }\n\n set rootPath(path: string) {\n if (this.#isType42) {\n this.#rootPath = path;\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n const derivedKey = this.#masterPrivateKey.deriveChild(\n this.#masterPrivateKey.toPublicKey(),\n path\n );\n this.rootAddress = derivedKey.toPublicKey().toAddress();\n this.#previousPath = path;\n this.#currentPath = path;\n } else {\n let pathToUse = path;\n if (path.split(\"/\").length < 5) {\n pathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n }\n if (!this.validatePath(pathToUse)) {\n throw new Error(`invalid signing path given ${pathToUse}`);\n }\n this.#rootPath = pathToUse;\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n const derivedChild = this.#HDPrivateKey.derive(pathToUse);\n this.rootAddress = derivedChild.pubKey.toAddress();\n this.#previousPath = pathToUse;\n this.#currentPath = pathToUse;\n }\n this.bapId = bapIdFromAddress(this.rootAddress);\n }\n\n get rootPath(): string {\n return this.#rootPath;\n }\n\n set currentPath(path: string) {\n if (this.#isType42) {\n this.#previousPath = this.#currentPath;\n this.#currentPath = path;\n } else {\n let pathToUse = path;\n if (path.split(\"/\").length < 5) {\n pathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n }\n if (!this.validatePath(pathToUse)) {\n throw new Error(\"invalid signing path given\");\n }\n this.#previousPath = this.#currentPath;\n this.#currentPath = pathToUse;\n }\n }\n\n get currentPath(): string {\n return this.#currentPath;\n }\n\n get previousPath(): string {\n return this.#previousPath;\n }\n\n get idSeed(): string {\n return this.#idSeed;\n }\n\n getAccountKey(): PrivateKey {\n if (this.#isType42) {\n if (!this.#masterPrivateKey) throw new Error(\"Master private key not initialized\");\n return this.#masterPrivateKey;\n }\n if (!this.#HDPrivateKey) throw new Error(\"HD private key not initialized\");\n return this.#HDPrivateKey.privKey;\n }\n\n validatePath(path: string): boolean {\n if (\n path.match(\n /\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?/\n )\n ) {\n const pathValues = path.split(\"/\");\n if (\n pathValues.length === 7 &&\n Number(pathValues[1].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[2].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[3].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[4].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[5].replace(\"'\", \"\")) <= MAX_INT &&\n Number(pathValues[6].replace(\"'\", \"\")) <= MAX_INT\n ) {\n return true;\n }\n }\n return false;\n }\n\n import(identity: Identity | OldIdentity): void {\n this.bapId = \"bapId\" in identity ? identity.bapId : (identity as OldIdentity).identityKey;\n this.#rootPath = identity.rootPath;\n this.rootAddress = identity.rootAddress;\n this.#previousPath = identity.previousPath;\n this.#currentPath = identity.currentPath;\n this.#idSeed = (\"idSeed\" in identity ? identity.idSeed : \"\") || \"\";\n }\n\n export(): Identity {\n return {\n bapId: this.bapId,\n rootPath: this.#rootPath,\n rootAddress: this.rootAddress,\n previousPath: this.#previousPath,\n currentPath: this.#currentPath,\n idSeed: this.#idSeed,\n lastIdPath: \"\",\n };\n }\n}\n\nexport { MasterID };\n",
9
+ "import { Hash, PublicKey, Utils as BSVUtils } from \"@bsv/sdk\";\nimport type { PathPrefix } from \"./interface.js\";\n\nconst { toHex, toBase58 } = BSVUtils;\n\n/**\n * Derive a BAP ID from a Bitcoin address (rootAddress).\n *\n * BAP ID = base58(ripemd160(sha256(rootAddress)))\n *\n * This is the canonical derivation used by MasterID.deriveIdentityKey().\n * The address MUST be the rootAddress (from the BAP member key), not a\n * signing key address.\n */\nexport function bapIdFromAddress(address: string): string {\n const rootAddressHash = toHex(Hash.sha256(address, \"utf8\"));\n return toBase58(Hash.ripemd160(rootAddressHash, \"hex\"));\n}\n\n/**\n * Derive a BAP ID from a compressed public key (hex).\n *\n * Converts the pubkey to a Bitcoin address, then derives the BAP ID.\n *\n * IMPORTANT: This only produces a correct BAP ID when the pubkey is the\n * BAP member key's public key. It does NOT work with signing keys or\n * arbitrary public keys.\n *\n * In BRC-100 wallets, the BRC-31 identity key IS the member key's pubkey,\n * so this correctly bridges BRC-31 auth to BAP identity lookups.\n */\nexport function bapIdFromPubkey(pubkeyHex: string): string {\n const pubkey = PublicKey.fromString(pubkeyHex);\n return bapIdFromAddress(pubkey.toAddress());\n}\n\nexport const Utils = {\n /**\n * Helper function to generate cryptographically secure random bytes\n * \n * This follows the pattern used by BSV SDK and other Bitcoin libraries.\n * Uses crypto.getRandomValues() which is available in browsers and modern Node.js.\n *\n * @param {number} byteLength - Number of random bytes to generate (default: 32)\n * @returns {Uint8Array} Array of cryptographically secure random bytes\n */\n getRandomBytes(byteLength = 32): Uint8Array {\n // Use crypto.getRandomValues() - available in browsers and Node.js 15+\n if (typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.getRandomValues) {\n const array = new Uint8Array(byteLength);\n globalThis.crypto.getRandomValues(array);\n return array;\n }\n\n // Fallback error - crypto operations require secure randomness\n throw new Error(\n 'Secure random number generation not available. ' +\n 'crypto.getRandomValues() is required for cryptographic operations. ' +\n 'This environment may not be suitable for secure key generation.'\n );\n },\n\n /**\n * Helper function to generate a random hex string\n *\n * @param {number} byteLength - Number of random bytes to generate (default: 32)\n * @returns {string} Hex string of random bytes\n */\n getRandomString(byteLength = 32): string {\n const bytes = this.getRandomBytes(byteLength);\n return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');\n },\n\n /**\n * Get a signing path from a hex number\n *\n * @param hexString {string}\n * @param hardened {boolean} Whether to return a hardened path\n * @returns {string}\n */\n getSigningPathFromHex(hexString: string, hardened = true) {\n // \"m/0/0/1\"\n let signingPath = \"m\";\n const signingHex = hexString.match(/.{1,8}/g);\n if (!signingHex) {\n throw new Error(\"Invalid hex string\");\n }\n const maxNumber = 2147483648 - 1; // 0x80000000\n for (const hexNumber of signingHex) {\n let number = Number(`0x${hexNumber}`);\n if (number > maxNumber) number -= maxNumber;\n signingPath += `/${number}${hardened ? \"'\" : \"\"}`;\n }\n\n return signingPath;\n },\n\n /**\n * Increment that second to last part from the given part, set the last part to 0\n *\n * @param path string\n * @returns {*}\n */\n getNextIdentityPath(path: string): PathPrefix {\n const pathValues = path.split(\"/\");\n const secondToLastPart = pathValues[pathValues.length - 2];\n\n let hardened = false;\n if (secondToLastPart.match(\"'\")) {\n hardened = true;\n }\n\n const nextPath = (\n Number(secondToLastPart.replace(/[^0-9]/g, \"\")) + 1\n ).toString();\n pathValues[pathValues.length - 2] = nextPath + (hardened ? \"'\" : \"\");\n pathValues[pathValues.length - 1] = `0${hardened ? \"'\" : \"\"}`;\n\n return pathValues.join(\"/\") as PathPrefix;\n },\n\n /**\n * Increment that last part of the given path\n *\n * @param path string\n * @returns {*}\n */\n getNextPath(path: string) {\n const type42Path = path.match(/^bap:(\\d+)(?::(\\d+))?$/);\n if (type42Path) {\n const identityIndex = type42Path[1];\n const rotationIndex = type42Path[2];\n\n if (rotationIndex === undefined) {\n return `bap:${identityIndex}:1`;\n }\n\n return `bap:${identityIndex}:${Number(rotationIndex) + 1}`;\n }\n\n // Backward compatibility for Type 42 backups created before the\n // `bap:<identity>:<rotation>` format was fixed. Those backups stored\n // bare numeric rotation paths like \"1\", and must keep rotating within\n // that legacy namespace so previously derived keys remain valid.\n if (/^\\d+$/.test(path)) {\n return (Number(path) + 1).toString();\n }\n\n if (!path.includes(\"/\")) {\n throw new Error(`Unsupported non-BIP32 path: ${path}`);\n }\n\n const pathValues = path.split(\"/\");\n const lastPart = pathValues[pathValues.length - 1];\n let hardened = false;\n if (lastPart.match(\"'\")) {\n hardened = true;\n }\n const nextPath = (Number(lastPart.replace(/[^0-9]/g, \"\")) + 1).toString();\n pathValues[pathValues.length - 1] = nextPath + (hardened ? \"'\" : \"\");\n return pathValues.join(\"/\");\n },\n};\n"
12
10
  ],
13
- "mappings": ";AAA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AAI,MAAM,oCAAoC,EACjF,MAAO,IAAK,EAAY,OAAQ,KAAK,GAAkB,MAAM,CAAE,EAGjE,IAAK,KAAK,GAAe,MAAM,IAAI,MAAM,gCAAgC,EACzE,MAAO,IACF,EACH,KAAM,GAAQ,KAAK,GAAc,SAAS,EAC1C,SAAU,GAAY,EACxB,EAEJ",
12
+ "debugId": "F80B3402BB5DBC1764756E2164756E21",
15
13
  "names": []
16
14
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bsv-bap",
3
- "version": "0.2.0-alpha.0",
3
+ "version": "0.2.0-alpha.2",
4
4
  "description": "BAP npm module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,15 +0,0 @@
1
- import { PrivateKey } from "@bsv/sdk";
2
- import { BaseClass } from "./BaseClass";
3
- export declare class AccountID extends BaseClass {
4
- private key;
5
- constructor(key: PrivateKey);
6
- getBapId(): string;
7
- getRootAddress(): string;
8
- getRootPublicKey(): string;
9
- signMessage(message: number[]): {
10
- address: string;
11
- signature: string;
12
- };
13
- getInitialIdTransaction(firstSigningAddress: string): number[][];
14
- getRevocationTransaction(): number[][];
15
- }
@@ -1,15 +0,0 @@
1
- import type { PrivateKey } from "@bsv/sdk";
2
- declare abstract class BaseClass {
3
- abstract signMessage(message: number[]): {
4
- address: string;
5
- signature: string;
6
- };
7
- protected signWithBSM(message: number[], signingKey: PrivateKey): {
8
- address: string;
9
- signature: string;
10
- };
11
- signOpReturnWithAIP(opReturn: number[][]): number[][];
12
- protected getAIPMessageBuffer(opReturn: number[][], indicies?: number[]): number[][];
13
- protected formatAIPOutput(opReturnBuffers: number[][], address: string, signature: string): number[][];
14
- }
15
- export { BaseClass };