bsv-bap 0.1.0 → 0.1.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.
@@ -1,30 +1,28 @@
1
- import { HD, type PrivateKey } from "@bsv/sdk";
1
+ import { type HD } from "@bsv/sdk";
2
2
  import { type APIFetcher } from "./api";
3
3
  import type { GetAttestationResponse, GetSigningKeysResponse } from "./apiTypes";
4
4
  import type { Identity, IdentityAttribute, IdentityAttributes, OldIdentity } from "./interface";
5
+ import { MemberID, type MemberIdentity } from './MemberID';
5
6
  /**
6
- * BAP_ID class
7
+ * MasterID class
7
8
  *
8
9
  * This class should be used in conjunction with the BAP class
9
10
  *
10
- * @type {BAP_ID}
11
+ * @type {MasterID}
11
12
  */
12
- export declare class BAP_ID {
13
+ declare class MasterID {
13
14
  #private;
14
- lastIdPath: string;
15
- name: string;
15
+ idName: string;
16
16
  description: string;
17
- identityKey: string;
18
17
  rootAddress: string;
18
+ identityKey: string;
19
19
  identityAttributes: IdentityAttributes;
20
- private BAP_SERVER_;
21
- private BAP_TOKEN_;
22
20
  getApiData: APIFetcher;
23
- constructor(key: HD | PrivateKey, identityAttributes?: IdentityAttributes, idSeed?: string);
21
+ constructor(HDPrivateKey: HD, identityAttributes?: IdentityAttributes, idSeed?: string);
22
+ set BAP_SERVER(bapServer: string);
24
23
  get BAP_SERVER(): string;
25
- set BAP_SERVER(value: string);
24
+ set BAP_TOKEN(token: string);
26
25
  get BAP_TOKEN(): string;
27
- set BAP_TOKEN(value: string);
28
26
  deriveIdentityKey(address: string): string;
29
27
  /**
30
28
  * Helper function to parse identity attributes
@@ -153,7 +151,7 @@ export declare class BAP_ID {
153
151
  */
154
152
  getIdTransaction(previousPath?: string): string[];
155
153
  /**
156
- * Get address for given path. Only works if HDPrivateKey is set
154
+ * Get address for given path
157
155
  *
158
156
  * @param path
159
157
  * @returns {*}
@@ -166,29 +164,38 @@ export declare class BAP_ID {
166
164
  */
167
165
  getCurrentAddress(): string;
168
166
  /**
169
- * Get the encryption public key for this identity
170
- * This key is derived from the identity's root path + ENCRYPTION_PATH
167
+ * Get the public key for encrypting data for this identity
171
168
  */
172
169
  getEncryptionPublicKey(): string;
173
170
  /**
174
- * Get the encryption public key for this identity with a seed
175
- * This key is derived from the identity's root path + ENCRYPTION_PATH + seed path
171
+ * Get the public key for encrypting data for this identity, using a seed for the encryption
176
172
  */
177
173
  getEncryptionPublicKeyWithSeed(seed: string): string;
178
174
  /**
179
- * Encrypt data using this identity's encryption key
175
+ * Encrypt the given string data with the identity encryption key
176
+ * @param stringData
177
+ * @param counterPartyPublicKey Optional public key of the counterparty
178
+ * @return string Base64
180
179
  */
181
180
  encrypt(stringData: string, counterPartyPublicKey?: string): string;
182
181
  /**
183
- * Decrypt data using this identity's encryption key
182
+ * Decrypt the given ciphertext with the identity encryption key
183
+ * @param ciphertext
184
184
  */
185
185
  decrypt(ciphertext: string, counterPartyPublicKey?: string): string;
186
186
  /**
187
- * Encrypt data using this identity's encryption key with a seed
187
+ * Encrypt the given string data with the identity encryption key
188
+ * @param stringData
189
+ * @param seed String seed
190
+ * @param counterPartyPublicKey Optional public key of the counterparty
191
+ * @return string Base64
188
192
  */
189
193
  encryptWithSeed(stringData: string, seed: string, counterPartyPublicKey?: string): string;
190
194
  /**
191
- * Decrypt data using this identity's encryption key with a seed
195
+ * Decrypt the given ciphertext with the identity encryption key
196
+ * @param ciphertext
197
+ * @param seed String seed
198
+ // * @param counterPartyPublicKey Public key of the counterparty
192
199
  */
193
200
  decryptWithSeed(ciphertext: string, seed: string, counterPartyPublicKey?: string): string;
194
201
  private getEncryptionPrivateKeyWithSeed;
@@ -213,7 +220,7 @@ export declare class BAP_ID {
213
220
  * @param signingPath
214
221
  * @returns {{address: string, signature: string}}
215
222
  */
216
- signMessage(msg: string | Buffer, signingPath?: string): {
223
+ signMessage(message: string | Buffer, signingPath?: string): {
217
224
  address: string;
218
225
  signature: string;
219
226
  };
@@ -262,10 +269,13 @@ export declare class BAP_ID {
262
269
  *
263
270
  * @param identity{{}}
264
271
  */
265
- import(id: Identity | OldIdentity): void;
272
+ import(identity: Identity | OldIdentity): void;
266
273
  /**
267
274
  * Export this identity to a JSON object
268
275
  * @returns {{}}
269
276
  */
270
277
  export(): Identity;
278
+ exportMemberBackup(): MemberIdentity;
279
+ newId(): MemberID;
271
280
  }
281
+ export { MasterID };
@@ -0,0 +1,27 @@
1
+ import { PrivateKey } from "@bsv/sdk";
2
+ import type { IdentityAttributes } from "./interface";
3
+ export interface MemberIdentity {
4
+ name: string;
5
+ description: string;
6
+ derivedPrivateKey: string;
7
+ address: string;
8
+ identityAttributes: IdentityAttributes;
9
+ }
10
+ declare class MemberID {
11
+ private key;
12
+ identityAttributes: IdentityAttributes;
13
+ address: string;
14
+ idName: string;
15
+ description: string;
16
+ constructor(key: PrivateKey, identityAttributes?: IdentityAttributes | string);
17
+ signMessage(message: string | Buffer): {
18
+ address: string;
19
+ signature: string;
20
+ };
21
+ getPublicKey(): string;
22
+ import(identity: MemberIdentity): void;
23
+ static fromImport(identity: MemberIdentity): MemberID;
24
+ export(): MemberIdentity;
25
+ private parseStringUrns;
26
+ }
27
+ export { MemberID };
package/dist/index.d.ts CHANGED
@@ -1,14 +1,12 @@
1
- import { HD, PrivateKey } from "@bsv/sdk";
2
1
  import { type APIFetcher } from "./api";
3
2
  import type { AttestationValidResponse, GetAttestationResponse, GetIdentityByAddressResponse, GetIdentityResponse } from "./apiTypes";
4
- import { BAP_ID } from "./id";
5
- import type { Attestation, HDIdentity, Identity, IdentityAttributes, OldIdentity, PathPrefix, SingleKeyIdentity } from "./interface";
3
+ import { MasterID } from "./MasterID";
4
+ import type { Attestation, Identity, IdentityAttributes, OldIdentity, PathPrefix } from "./interface";
5
+ import { MemberID } from "./MemberID";
6
6
  type Identities = {
7
7
  lastIdPath: string;
8
8
  ids: Identity[];
9
9
  };
10
- export type { HDIdentity, SingleKeyIdentity, Attestation, Identity, IdentityAttributes, PathPrefix };
11
- export { BAP_ID };
12
10
  /**
13
11
  * BAP class
14
12
  *
@@ -18,22 +16,21 @@ export { BAP_ID };
18
16
  */
19
17
  export declare class BAP {
20
18
  #private;
21
- get lastIdPath(): string;
22
19
  getApiData: APIFetcher;
23
- constructor(key: string | HD | PrivateKey, token?: string);
24
- private isHD;
20
+ constructor(HDPrivateKey: string, token?: string, server?: string);
21
+ get lastIdPath(): string;
25
22
  /**
26
- * Get the public key of the given childPath, or of the current HDPrivateKey if childPath is empty
23
+ * Get the public key of the given childPath, or of the current HDPrivateKey of childPath is empty
27
24
  *
28
25
  * @param childPath Full derivation path for this child
29
- * @returns {string}
26
+ * @returns {*}
30
27
  */
31
28
  getPublicKey(childPath?: string): string;
32
29
  /**
33
- * Get the HD public key (xpub) of the given childPath, or of the current HDPrivateKey if childPath is empty
30
+ * Get the public key of the given childPath, or of the current HDPrivateKey of childPath is empty
34
31
  *
35
32
  * @param childPath Full derivation path for this child
36
- * @returns {string}
33
+ * @returns {*}
37
34
  */
38
35
  getHdPublicKey(childPath?: string): string;
39
36
  set BAP_SERVER(bapServer: string);
@@ -44,9 +41,9 @@ export declare class BAP {
44
41
  * This function verifies that the given bapId matches the given root address
45
42
  * This is used as a data integrity check
46
43
  *
47
- * @param bapId BAP_ID instance
44
+ * @param bapId MasterID instance
48
45
  */
49
- checkIdBelongs(bapId: BAP_ID): boolean;
46
+ checkIdBelongs(bapId: MasterID): boolean;
50
47
  /**
51
48
  * Returns a list of all the identity keys that are stored in this instance
52
49
  *
@@ -65,7 +62,7 @@ export declare class BAP {
65
62
  * @param idSeed
66
63
  * @returns {*}
67
64
  */
68
- newId(path?: string, identityAttributes?: IdentityAttributes, idSeed?: string): BAP_ID;
65
+ newId(path?: string, identityAttributes?: IdentityAttributes, idSeed?: string): MasterID;
69
66
  /**
70
67
  * Remove identity
71
68
  *
@@ -85,7 +82,7 @@ export declare class BAP {
85
82
  * @param identityKey
86
83
  * @returns {null}
87
84
  */
88
- getId(identityKey: string): BAP_ID | null;
85
+ getId(identityKey: string): MasterID | null;
89
86
  /**
90
87
  * This function is used when manipulating ID's, adding or removing attributes etc
91
88
  * First create an id through this class and then use getId to get it. Then you can add/edit or
@@ -97,7 +94,7 @@ export declare class BAP {
97
94
  *
98
95
  * @param bapId
99
96
  */
100
- setId(bapId: BAP_ID): void;
97
+ setId(bapId: MasterID): void;
101
98
  /**
102
99
  * This function is used to import IDs and attributes from some external storage
103
100
  *
@@ -111,12 +108,22 @@ export declare class BAP {
111
108
  importOldIds(idData: OldIdentity[]): void;
112
109
  /**
113
110
  * Export identities. If no idKeys are provided, exports all identities.
114
- * @param encrypted Whether to encrypt the export. Defaults to true
115
- * @param idKeys Optional array of identity keys to export
116
- * @returns A string if encrypted is true, otherwise an Identities object
111
+ * @param idKeys Optional array of identity keys to export. If omitted, exports all identities.
112
+ * @param encrypted Whether to encrypt the export data
113
+ */
114
+ exportIds(idKeys?: string[], encrypted?: true): string;
115
+ exportIds(idKeys: string[] | undefined, encrypted: false): Identities;
116
+ /**
117
+ * Export a given ID from this instance for external storage
118
+ *
119
+ * By default this function will encrypt the data, using a derivative child of the main HD key
120
+ *
121
+ * @param idKey The key of the identity to export
122
+ * @param encrypted Whether the data should be encrypted (default true)
123
+ * @returns {[]|*}
117
124
  */
118
- exportIds(encrypted?: true, idKeys?: string[]): string;
119
- exportIds(encrypted: false, idKeys?: string[]): Identities;
125
+ exportId(idKey: string, encrypted?: true): string;
126
+ exportId(idKey: string, encrypted: false): Identities;
120
127
  /**
121
128
  * Encrypt a string of data
122
129
  *
@@ -134,7 +141,7 @@ export declare class BAP {
134
141
  /**
135
142
  * Sign an attestation for a user
136
143
  *
137
- * @param attestationHash The computed attestation hash for the user - this should be calculated with the BAP_ID class for an identity for the user
144
+ * @param attestationHash The computed attestation hash for the user - this should be calculated with the MasterID class for an identity for the user
138
145
  * @param identityKey The identity key we are using for the signing
139
146
  * @param counter
140
147
  * @param dataString Optional data string that will be appended to the BAP attestation
@@ -232,5 +239,5 @@ export declare class BAP {
232
239
  */
233
240
  getAttestationsForHash(attestationHash: string): Promise<GetAttestationResponse>;
234
241
  }
235
- export declare function isSingleKeyIdentity(id: Identity): id is SingleKeyIdentity;
236
- export declare function isHDIdentity(id: Identity): id is HDIdentity;
242
+ export { MasterID, MemberID };
243
+ export type { Attestation, Identity, IdentityAttributes, PathPrefix };
@@ -1,7 +1,8 @@
1
1
  // @bun
2
- import{BSM as N,Utils as d,BigNumber as s,ECIES as r,HD as v,PrivateKey as g,Signature as i}from"@bsv/sdk";var P=async(j,$,q,J)=>{let Q=`${q}${j}`;return(await fetch(Q,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:J,format:"json"},body:JSON.stringify($)})).json()},M=(j,$)=>async(q,J)=>{return P(q,J,j,$)};var Y="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",A=`0x${Buffer.from("1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT").toString("hex")}`,E="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva",Jj=`0x${Buffer.from("15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva").toString("hex")}`,V="https://api.sigmaidentity.com/v1",F=2147483647,U="m/424150'/0'/0'",G="m/424150'/2147483647'/2147483647'";import{BSM as C,Utils as o,BigNumber as B,ECIES as y,HD as n,Hash as X,PublicKey as x}from"@bsv/sdk";import{randomBytes as h}from"crypto";var W={hexEncode(j){return`0x${Buffer.from(j).toString("hex")}`},hexDecode(j,$="utf8"){return Buffer.from(j.replace("0x",""),"hex").toString($)},getRandomString(j=32){return h(j).toString("hex")},isHex(j){if(typeof j!=="string")return!1;return/^[0-9a-fA-F]+$/.test(j)},getSigningPathFromHex(j,$=!0){let q="m",J=j.match(/.{1,8}/g);if(!J)throw new Error("Invalid hex string");let Q=2147483647;for(let z of J){let Z=Number(`0x${z}`);if(Z>Q)Z-=Q;q+=`/${Z}${$?"'":""}`}return q},getNextIdentityPath(j){let $=j.split("/"),q=$[$.length-2],J=!1;if(q.match("'"))J=!0;let Q=(Number(q.replace(/[^0-9]/g,""))+1).toString();return $[$.length-2]=Q+(J?"'":""),$[$.length-1]=`0${J?"'":""}`,$.join("/")},getNextPath(j){let $=j.split("/"),q=$[$.length-1],J=!1;if(q.match("'"))J=!0;let Q=(Number(q.replace(/[^0-9]/g,""))+1).toString();return $[$.length-1]=Q+(J?"'":""),$.join("/")}};var{toArray:w,toHex:f,toBase58:u,toUTF8:I,toBase64:S}=o,{electrumDecrypt:m,electrumEncrypt:H}=y,{magicHash:T}=C;class R{#j;#z;#$;#q;#J;lastIdPath="";#Q;name;description;identityKey;rootAddress;identityAttributes;BAP_SERVER_;BAP_TOKEN_;getApiData;constructor(j,$={},q=""){if(this.#Q=q,this.BAP_SERVER_=V,this.BAP_TOKEN_="",this.getApiData=M(this.BAP_SERVER_,this.BAP_TOKEN_),this.name="ID 1",this.description="",j instanceof n){if(this.#j=j,q){let z=f(X.sha256(q,"utf8")),Z=W.getSigningPathFromHex(z);this.#j=j.derive(Z)}this.rootPath=`${U}/0/0/0`,this.#J=this.rootPath,this.#q=`${U}/0/0/1`;let Q=this.#j.derive(this.rootPath);this.rootAddress=Q.privKey.toPublicKey().toAddress()}else this.#z=j,this.rootAddress=j.toPublicKey().toAddress();this.identityKey=this.deriveIdentityKey(this.rootAddress);let J=JSON.parse(JSON.stringify($));this.identityAttributes=this.parseAttributes(J)}get BAP_SERVER(){return this.BAP_SERVER_}set BAP_SERVER(j){this.BAP_SERVER_=j,this.getApiData=M(this.BAP_SERVER_,this.BAP_TOKEN_)}get BAP_TOKEN(){return this.BAP_TOKEN_}set BAP_TOKEN(j){this.BAP_TOKEN_=j,this.getApiData=M(this.BAP_SERVER_,this.BAP_TOKEN_)}deriveIdentityKey(j){let $=f(X.sha256(j,"utf8"));return u(X.ripemd160($,"hex"))}parseAttributes(j){if(typeof j==="string")return this.parseStringUrns(j);for(let $ in j)if(!j[$].value||!j[$].nonce)throw new Error("Invalid identity attribute");return j||{}}parseStringUrns(j){let $={},q=j.replace(/^\s+/g,"").replace(/\r/gm,"").split(`
3
- `);for(let J of q){let z=J.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(z[0]==="urn"&&z[1]==="bap"&&z[2]==="id"&&z[3]&&z[4]&&z[5])$[z[3]]={value:z[4],nonce:z[5]}}return $}getIdentityKey(){return this.identityKey}getAttributes(){return this.identityAttributes}getAttribute(j){if(this.identityAttributes[j])return this.identityAttributes[j];return null}setAttribute(j,$){if(!$)return;if(this.identityAttributes[j])this.updateExistingAttribute(j,$);else this.createNewAttribute(j,$)}updateExistingAttribute(j,$){if(typeof $==="string"){this.identityAttributes[j].value=$;return}if(this.identityAttributes[j].value=$.value||"",$.nonce)this.identityAttributes[j].nonce=$.nonce}createNewAttribute(j,$){if(typeof $==="string"){this.addAttribute(j,$);return}this.addAttribute(j,$.value||"",$.nonce)}unsetAttribute(j){delete this.identityAttributes[j]}getAttributeUrns(){let j="";for(let $ in this.identityAttributes){let q=this.getAttributeUrn($);if(q)j+=`${q}
4
- `}return j}getAttributeUrn(j){let $=this.identityAttributes[j];if($)return`urn:bap:id:${j}:${$.value}:${$.nonce}`;return null}addAttribute(j,$,q=""){let J=q;if(!q)J=W.getRandomString();this.identityAttributes[j]={value:$,nonce:J}}set rootPath(j){if(this.#j){let $=j;if(j.split("/").length<5)$=`${U}${j}`;if(!this.validatePath($))throw new Error(`invalid signing path given ${$}`);this.#$=$;let q=this.#j.derive($);this.rootAddress=q.pubKey.toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress),this.#J=$,this.#q=$}}get rootPath(){if(!this.#$)throw new Error("rootPath not set");return this.#$}getRootPath(){if(!this.#$)throw new Error("rootPath not set");return this.#$}set currentPath(j){let $=j;if(j.split("/").length<5)$=`${U}${j}`;if(!this.validatePath($))throw new Error("invalid signing path given");this.#J=this.#q,this.#q=$}get currentPath(){if(!this.#q)throw new Error("currentPath not set");return this.#q}get previousPath(){if(!this.#J)throw new Error("previousPath not set");return this.#J}get idSeed(){return this.#Q}incrementPath(){this.currentPath=W.getNextPath(this.currentPath)}validatePath(j){if(j.match(/\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?/)){let $=j.split("/");if($.length===7&&Number($[1].replace("'",""))<=F&&Number($[2].replace("'",""))<=F&&Number($[3].replace("'",""))<=F&&Number($[4].replace("'",""))<=F&&Number($[5].replace("'",""))<=F&&Number($[6].replace("'",""))<=F)return!0}return!1}getInitialIdTransaction(){return this.getIdTransaction(this.#$)}getIdTransaction(j=""){if(this.#q===this.#$)throw new Error("Current path equals rootPath. ID was probably not initialized properly");let $=[Buffer.from(Y).toString("hex"),Buffer.from("ID").toString("hex"),Buffer.from(this.identityKey).toString("hex"),Buffer.from(this.getCurrentAddress()).toString("hex")];return this.signOpReturnWithAIP($,j||this.#J)}getAddress(j){if(!this.#j)throw new Error("HDPrivateKey not set");return this.#j.derive(j).privKey.toPublicKey().toAddress()}getCurrentAddress(){if(!this.#q){if(!this.#z)throw new Error("currentPath not set");return this.#z.toPublicKey().toAddress()}return this.getAddress(this.#q)}getEncryptionPublicKey(){if(this.#j)return this.#j.derive(this.rootPath).derive(G).pubKey.toString();if(!this.#z)throw new Error("No private key available for encryption");return this.#z.toPublicKey().toString()}getEncryptionPublicKeyWithSeed(j){return this.getEncryptionPrivateKeyWithSeed(j).toPublicKey().toString()}encrypt(j,$){if(!this.#j)throw new Error("HDPrivateKey not set");let J=this.#j.derive(this.rootPath).derive(G).privKey,Q=J.toPublicKey(),z=$?x.fromString($):Q;return S(H(w(j),z,J))}decrypt(j,$){if(!this.#j)throw new Error("HDPrivateKey not set");let J=this.#j.derive(this.rootPath).derive(G).privKey,Q;if($)Q=x.fromString($);return I(m(w(j,"base64"),J,Q))}encryptWithSeed(j,$,q){let J=this.getEncryptionPrivateKeyWithSeed($),Q=J.toPublicKey(),z=q?x.fromString(q):Q;return S(H(w(j),z,J))}decryptWithSeed(j,$,q){let J=this.getEncryptionPrivateKeyWithSeed($),z=J.toPublicKey();if(q)z=x.fromString(q);return I(m(w(j,"base64"),J,z))}getEncryptionPrivateKeyWithSeed(j){if(!this.#j)throw new Error("HDPrivateKey not set");if(!this.#$)throw new Error("rootPath not set");let $=f(X.sha256(j,"utf8")),q=W.getSigningPathFromHex($);return this.#j.derive(this.rootPath).derive(q).privKey}getAttestation(j){let $=X.sha256(j,"utf8");return`bap:attest:${f($)}:${this.getIdentityKey()}`}getAttestationHash(j){let $=this.getAttributeUrn(j);if(!$)return null;let q=this.getAttestation($),J=X.sha256(q,"utf8");return f(J)}signMessage(j,$=""){if(!this.#j&&!this.#z)throw new Error("No private key available");if(this.#j){if(!this.#q)throw new Error("currentPath not set");let k=$||this.#q,O=this.#j.derive(k).privKey,_=O.toPublicKey().toAddress(),c=C.sign(w(j),O,"raw"),b=new B(T(w(j,"utf8"))),l=c.CalculateRecoveryFactor(O.toPublicKey(),b),p=C.sign(w(j),O,"raw").toCompact(l,!0,"base64");return{address:_,signature:p}}let q=this.#z,J=q.toPublicKey().toAddress(),Q=C.sign(w(j),q,"raw"),z=new B(T(w(j,"utf8"))),Z=Q.CalculateRecoveryFactor(q.toPublicKey(),z),L=C.sign(w(j),q,"raw").toCompact(Z,!0,"base64");return{address:J,signature:L}}signMessageWithSeed(j,$){if(!this.#j)throw new Error("HDPrivateKey not set");if(!this.#$)throw new Error("rootPath not set");let q=f(X.sha256($,"utf8")),J=W.getSigningPathFromHex(q),z=this.#j.derive(this.#$).derive(J),Z=z.privKey.toPublicKey().toAddress(),L=C.sign(w(j),z.privKey,"raw"),k=new B(T(w(j,"utf8"))),O=L.CalculateRecoveryFactor(z.privKey.toPublicKey(),k),_=C.sign(w(Buffer.from(j)),z.privKey,"raw").toCompact(O,!0,"base64");return{address:Z,signature:_}}signOpReturnWithAIP(j,$="",q="hex"){let J=this.getAIPMessageBuffer(j),{address:Q,signature:z}=this.signMessage(J,$);return j.concat([Buffer.from("|").toString(q),Buffer.from(E).toString(q),Buffer.from("BITCOIN_ECDSA").toString(q),Buffer.from(Q).toString(q),Buffer.from(z,"base64").toString(q)])}getAIPMessageBuffer(j){let $=[];if(j[0].replace("0x","")!=="6a")$.push(Buffer.from("6a","hex"));for(let q of j)$.push(Buffer.from(q.replace("0x",""),"hex"));return $.push(Buffer.from("|")),Buffer.concat([...$])}async getIdSigningKeys(){let j=await this.getApiData("/signing-keys",{idKey:this.identityKey});return console.log("getIdSigningKeys",j),j}async getAttributeAttestations(j){let $=this.getAttestationHash(j),q=await this.getApiData("/attestation/get",{hash:$});return console.log("getAttestations",j,$,q),q}import(j){if(this.name="name"in j&&typeof j.name==="string"?j.name:"ID 1",this.description=j.description||"",this.identityKey=j.identityKey,this.rootAddress=j.rootAddress,"rootPath"in j&&"currentPath"in j&&"previousPath"in j)this.#$=j.rootPath,this.#q=j.currentPath,this.#J=j.previousPath;this.#Q=j.idSeed||"",this.identityAttributes=this.parseAttributes(j.identityAttributes)}export(){if(this.#j){if(!this.#$||!this.#q||!this.#J)throw new Error("Required paths are not set");return{rootPath:this.#$,currentPath:this.#q,previousPath:this.#J,lastIdPath:this.lastIdPath,idSeed:this.#Q,name:this.name,description:this.description,identityKey:this.identityKey,rootAddress:this.rootAddress,identityAttributes:this.identityAttributes}}if(!this.#z)throw new Error("Neither HDPrivateKey nor singlePrivateKey is set");return{derivedPrivateKey:this.#z.toString(),idSeed:this.#Q,name:this.name,description:this.description,identityKey:this.identityKey,rootAddress:this.rootAddress,identityAttributes:this.identityAttributes}}}var{toArray:D,toUTF8:a,toBase64:e}=d,{electrumEncrypt:t,electrumDecrypt:jj}=r;class $j{#j;#z="";get lastIdPath(){return this.#z}#$={};#q=V;#J="";getApiData;constructor(j,$){if(!j)throw new Error("Key is required for BAP initialization");if(typeof j==="string")try{this.#j=v.fromString(j)}catch(q){try{this.#j=g.fromWif(j)}catch(J){throw new Error("Invalid private key format")}}else this.#j=j;if($!==void 0)this.#J=$;this.getApiData=M(this.#q,this.#J)}isHD(j){return"depth"in j&&"parentFingerPrint"in j}getPublicKey(j=""){if(this.isHD(this.#j)){if(j!=="")return this.#j.derive(j).pubKey.toString();return this.#j.pubKey.toString()}return this.#j.toPublicKey().toString()}getHdPublicKey(j=""){if(!this.isHD(this.#j))throw new Error("Not an HD key");if(j)return this.#j.derive(j).toPublic().toString();return this.#j.toPublic().toString()}set BAP_SERVER(j){this.#q=j;for(let $ in this.#$)this.#$[$].BAP_SERVER=j}get BAP_SERVER(){return this.#q}set BAP_TOKEN(j){this.#J=j;for(let $ in this.#$)this.#$[$].BAP_TOKEN=j}get BAP_TOKEN(){return this.#J}checkIdBelongs(j){if(!this.isHD(this.#j))throw new Error("checkIdBelongs can only be used in HD mode");if(this.#j.derive(j.rootPath).pubKey.toAddress()!==j.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#$)}newId(j,$={},q=""){let J;if(!j)J=this.getNextValidPath();else J=j;let Q=new R(this.#j,$,q);Q.BAP_SERVER=this.#q,Q.BAP_TOKEN=this.#J,Q.rootPath=J,Q.currentPath=W.getNextPath(J);let z=Q.getIdentityKey();return this.#$[z]=Q,this.#z=J,this.#$[z]}removeId(j){delete this.#$[j]}getNextValidPath(){if(this.#z)return W.getNextIdentityPath(this.#z);return`/0'/${Object.keys(this.#$).length}'/0'`}getId(j){return this.#$[j]||null}setId(j){this.checkIdBelongs(j),this.#$[j.getIdentityKey()]=j}importIds(j,$=!0){if($&&typeof j==="string"){this.importEncryptedIds(j);return}let q=j;if(!q.lastIdPath||!Array.isArray(q.ids))throw new Error("ID data is not in the correct format");let J=!(this.#j instanceof v);if(J&&q.ids.length>1)throw new Error("Cannot import multiple IDs in single key mode");let Q=q.lastIdPath;for(let z of q.ids){if(!z.identityKey||!z.identityAttributes||!z.rootAddress)throw new Error("ID cannot be imported as it is not complete");let Z;if(qj(z)){if(!J)throw new Error("Cannot import single key identity in HD mode");let L=g.fromString(z.derivedPrivateKey,"hex");Z=new R(L,z.identityAttributes,z.idSeed)}else if(K(z)){if(J)throw new Error("Cannot import HD identity in single key mode");let L=this.#j;Z=new R(L,z.identityAttributes,z.idSeed),Z.rootPath=z.rootPath,Z.currentPath=z.currentPath}else throw new Error("Invalid identity format");if(Z.BAP_SERVER=this.#q,Z.BAP_TOKEN=this.#J,Z.import(z),!J&&K(z)){if(Q==="")Q=z.currentPath;this.checkIdBelongs(Z)}this.#$[Z.getIdentityKey()]=Z}if(!J)this.#z=Q}importEncryptedIds(j){let $=this.decrypt(j),q=JSON.parse($);if(Array.isArray(q)){console.log(`Importing old format:
5
- `,q),this.importOldIds(q);return}if(typeof q!=="object")throw new Error("decrypted, but found unrecognized identities format");this.importIds(q,!1)}importOldIds(j){for(let $ of j){let q=new R(this.#j,{},$.idSeed??"");if(q.BAP_SERVER=this.#q,q.BAP_TOKEN=this.#J,q.import($),this.checkIdBelongs(q),this.#$[q.getIdentityKey()]=q,"currentPath"in $&&typeof $.currentPath==="string")this.#z=$.currentPath;else this.#z=""}}exportIds(j=!0,$){let q={lastIdPath:this.#z,ids:[]},J=$||Object.keys(this.#$);for(let Q of J){if(!this.#$[Q])throw new Error(`Identity ${Q} not found`);q.ids.push(this.#$[Q].export())}if(j)return this.encrypt(JSON.stringify(q));return q}encrypt(j){if(!this.isHD(this.#j))throw new Error("Encryption not supported in single key mode");let $=this.#j.derive(G);return e(t(D(j),$.pubKey))}decrypt(j){if(!this.isHD(this.#j))throw new Error("Decryption not supported in single key mode");let $=this.#j.derive(G);return a(jj(D(j,"base64"),$.privKey))}signAttestationWithAIP(j,$,q=0,J=""){let Q=this.getId($);if(!Q)throw new Error("Could not find identity to attest with");let z=this.getAttestationBuffer(j,q,J),{address:Z,signature:L}=Q.signMessage(z);return this.createAttestationTransaction(j,q,Z,L,J)}verifyAttestationWithAIP(j){if(!Array.isArray(j)||j[0]!=="0x6a"||j[1]!==A)throw new Error("Not a valid BAP transaction");let $=j[7]==="0x44415441"?5:0,q={type:W.hexDecode(j[2]),hash:W.hexDecode(j[3]),sequence:W.hexDecode(j[4]),signingProtocol:W.hexDecode(j[7+$]),signingAddress:W.hexDecode(j[8+$]),signature:W.hexDecode(j[9+$],"base64")};if($&&j[3]===j[8])q.data=W.hexDecode(j[9]);try{let J=[];for(let z=0;z<6+$;z++)J.push(Buffer.from(j[z].replace("0x",""),"hex"));let Q=Buffer.concat(J);q.verified=this.verifySignature(Q,q.signingAddress,q.signature)}catch(J){q.verified=!1}return q}createAttestationTransaction(j,$,q,J,Q=""){let z=["0x6a",W.hexEncode(Y)];if(z.push(W.hexEncode("ATTEST")),z.push(W.hexEncode(j)),z.push(W.hexEncode(`${$}`)),z.push("0x7c"),Q)z.push(W.hexEncode(Y)),z.push(W.hexEncode("DATA")),z.push(W.hexEncode(j)),z.push(W.hexEncode(Q)),z.push("0x7c");return z.push(W.hexEncode(E)),z.push(W.hexEncode("BITCOIN_ECDSA")),z.push(W.hexEncode(q)),z.push(`0x${Buffer.from(J,"base64").toString("hex")}`),z}getAttestationBuffer(j,$=0,q=""){let J=Buffer.from("");if(q)J=Buffer.concat([Buffer.from(Y),Buffer.from("DATA"),Buffer.from(j),Buffer.from(q),Buffer.from("7c","hex")]);return Buffer.concat([Buffer.from("6a","hex"),Buffer.from(Y),Buffer.from("ATTEST"),Buffer.from(j),Buffer.from(`${$}`),Buffer.from("7c","hex"),J])}verifySignature(j,$,q){let J=Buffer.isBuffer(j)?j:Buffer.from(j),Q=i.fromCompact(q,"base64"),z,Z=D(J.toString("hex"),"hex");for(let L=0;L<4;L++)try{if(z=Q.RecoverPublicKey(L,new s(N.magicHash(Z))),N.verify(Z,Q,z)&&z.toAddress()===$)return!0}catch(k){}return!1}async verifyChallengeSignature(j,$,q,J){if(!this.verifySignature(q,$,J))return!1;try{let z=await this.getApiData("/attestation/valid",{idKey:j,address:$,challenge:q,signature:J});if(z?.status==="success"&&z?.result?.valid===!0)return!0;return!1}catch(z){return console.error("API call failed:",z),!1}}async isValidAttestationTransaction(j){if(this.verifyAttestationWithAIP(j))return this.getApiData("/attestation/valid",{tx:j});return!1}async getIdentityFromAddress(j){return this.getApiData("/identity/from-address",{address:j})}async getIdentity(j){return this.getApiData("/identity/get",{idKey:j})}async getAttestationsForHash(j){return this.getApiData("/attestations",{hash:j})}}function qj(j){return"derivedPrivateKey"in j}function K(j){return"rootPath"in j&&"currentPath"in j&&"previousPath"in j}export{qj as isSingleKeyIdentity,K as isHDIdentity,R as BAP_ID,$j as BAP};
2
+ import{BSM as N,BigNumber as n,ECIES as d,HD as s,Signature as r}from"@bsv/sdk";import{Utils as i}from"@bsv/sdk";var l=async(j,$,J,q)=>{let Q=`${J}${j}`;return(await fetch(Q,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:q,format:"json"},body:JSON.stringify($)})).json()},R=(j,$)=>async(J,q)=>{return l(J,q,j,$)};var Y="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",H=`0x${Buffer.from("1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT").toString("hex")}`,x="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva",qj=`0x${Buffer.from("15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva").toString("hex")}`,V="https://api.sigmaidentity.com/v1",F=2147483647,C="m/424150'/0'/0'",G="m/424150'/2147483647'/2147483647'";import{BSM as M,Utils as h,BigNumber as D,ECIES as y,Hash as X,PublicKey as _}from"@bsv/sdk";import{randomBytes as b}from"crypto";var W={hexEncode(j){return`0x${Buffer.from(j).toString("hex")}`},hexDecode(j,$="utf8"){return Buffer.from(j.replace("0x",""),"hex").toString($)},getRandomString(j=32){return b(j).toString("hex")},isHex(j){if(typeof j!=="string")return!1;return/^[0-9a-fA-F]+$/.test(j)},getSigningPathFromHex(j,$=!0){let J="m",q=j.match(/.{1,8}/g);if(!q)throw new Error("Invalid hex string");let Q=2147483647;for(let z of q){let Z=Number(`0x${z}`);if(Z>Q)Z-=Q;J+=`/${Z}${$?"'":""}`}return J},getNextIdentityPath(j){let $=j.split("/"),J=$[$.length-2],q=!1;if(J.match("'"))q=!0;let Q=(Number(J.replace(/[^0-9]/g,""))+1).toString();return $[$.length-2]=Q+(q?"'":""),$[$.length-1]=`0${q?"'":""}`,$.join("/")},getNextPath(j){let $=j.split("/"),J=$[$.length-1],q=!1;if(J.match("'"))q=!0;let Q=(Number(J.replace(/[^0-9]/g,""))+1).toString();return $[$.length-1]=Q+(q?"'":""),$.join("/")}};import{BSM as T,BigNumber as p,PrivateKey as S,Utils as P}from"@bsv/sdk";var{toHex:wj,toBase58:Yj,toArray:B}=P,{magicHash:o}=T;class f{key;identityAttributes;address;idName;description;constructor(j,$={}){this.key=j,this.identityAttributes=typeof $==="string"?this.parseStringUrns($):$,this.address=this.key.toAddress(),this.idName="Member ID 1",this.description=""}signMessage(j){let $=typeof j==="string"?Buffer.from(j):j,J=this.key,q=J.toPublicKey().toString(),Q=T.sign(B($),J,"raw"),z=new p(o(B($,"utf8"))),Z=Q.CalculateRecoveryFactor(J.toPublicKey(),z),L=T.sign(B($),J,"raw").toCompact(Z,!0,"base64");return{address:q,signature:L}}getPublicKey(){return this.key.toPublicKey().toString()}import(j){this.idName=j.name,this.description=j.description,this.key=S.fromString(j.derivedPrivateKey),this.address=this.key.toAddress(),this.identityAttributes=j.identityAttributes}static fromImport(j){let $=new f(S.fromString(j.derivedPrivateKey));return $.import(j),$}export(){return{name:this.idName,description:this.description,derivedPrivateKey:this.key.toString(),address:this.address,identityAttributes:this.identityAttributes}}parseStringUrns(j){let $={},J=j.replace(/^[ \t]+/gm,"").trim().split(`
3
+ `);for(let q of J){let Q=q.split(":");if(Q.length>=6&&Q[0]==="urn"&&Q[1]==="bap"&&Q[2]==="id")$[Q[3]]={value:Q[4],nonce:Q[5]}}return $}}var{toArray:w,toHex:O,toBase58:u,toUTF8:I,toBase64:A}=h,{electrumDecrypt:K,electrumEncrypt:g}=y,{magicHash:m}=M;class U{#j;#J=V;#Q="";#$;#q;#z;#W;idName;description;rootAddress;identityKey;identityAttributes;getApiData;constructor(j,$={},J=""){if(this.#W=J,J){let z=O(X.sha256(J,"utf8")),Z=W.getSigningPathFromHex(z);this.#j=j.derive(Z)}else this.#j=j;this.idName="ID 1",this.description="",this.#$=`${C}/0/0/0`,this.#q=`${C}/0/0/0`,this.#z=`${C}/0/0/1`;let q=this.#j.derive(this.#$);this.rootAddress=q.privKey.toPublicKey().toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress);let Q={...$};this.identityAttributes=this.parseAttributes(Q),this.getApiData=R(this.#J,this.#Q)}set BAP_SERVER(j){this.#J=j}get BAP_SERVER(){return this.#J}set BAP_TOKEN(j){this.#Q=j}get BAP_TOKEN(){return this.#Q}deriveIdentityKey(j){let $=O(X.sha256(j,"utf8"));return u(X.ripemd160($,"hex"))}parseAttributes(j){if(typeof j==="string")return this.parseStringUrns(j);for(let $ in j)if(!j[$].value||!j[$].nonce)throw new Error("Invalid identity attribute");return j||{}}parseStringUrns(j){let $={},J=j.replace(/^\s+/g,"").replace(/\r/gm,"").split(`
4
+ `);for(let q of J){let z=q.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(z[0]==="urn"&&z[1]==="bap"&&z[2]==="id"&&z[3]&&z[4]&&z[5])$[z[3]]={value:z[4],nonce:z[5]}}return $}getIdentityKey(){return this.identityKey}getAttributes(){return this.identityAttributes}getAttribute(j){if(this.identityAttributes[j])return this.identityAttributes[j];return null}setAttribute(j,$){if(!$)return;if(this.identityAttributes[j])this.updateExistingAttribute(j,$);else this.createNewAttribute(j,$)}updateExistingAttribute(j,$){if(typeof $==="string"){this.identityAttributes[j].value=$;return}if(this.identityAttributes[j].value=$.value||"",$.nonce)this.identityAttributes[j].nonce=$.nonce}createNewAttribute(j,$){if(typeof $==="string"){this.addAttribute(j,$);return}this.addAttribute(j,$.value||"",$.nonce)}unsetAttribute(j){delete this.identityAttributes[j]}getAttributeUrns(){let j="";for(let $ in this.identityAttributes){let J=this.getAttributeUrn($);if(J)j+=`${J}
5
+ `}return j}getAttributeUrn(j){let $=this.identityAttributes[j];if($)return`urn:bap:id:${j}:${$.value}:${$.nonce}`;return null}addAttribute(j,$,J=""){let q=J;if(!J)q=W.getRandomString();this.identityAttributes[j]={value:$,nonce:q}}set rootPath(j){if(this.#j){let $=j;if(j.split("/").length<5)$=`${C}${j}`;if(!this.validatePath($))throw new Error(`invalid signing path given ${$}`);this.#$=$;let J=this.#j.derive($);this.rootAddress=J.pubKey.toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress),this.#q=$,this.#z=$}}get rootPath(){return this.#$}getRootPath(){return this.#$}set currentPath(j){let $=j;if(j.split("/").length<5)$=`${C}${j}`;if(!this.validatePath($))throw new Error("invalid signing path given");this.#q=this.#z,this.#z=$}get currentPath(){return this.#z}get previousPath(){return this.#q}get idSeed(){return this.#W}incrementPath(){this.currentPath=W.getNextPath(this.currentPath)}validatePath(j){if(j.match(/\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?/)){let $=j.split("/");if($.length===7&&Number($[1].replace("'",""))<=F&&Number($[2].replace("'",""))<=F&&Number($[3].replace("'",""))<=F&&Number($[4].replace("'",""))<=F&&Number($[5].replace("'",""))<=F&&Number($[6].replace("'",""))<=F)return!0}return!1}getInitialIdTransaction(){return this.getIdTransaction(this.#$)}getIdTransaction(j=""){if(this.#z===this.#$)throw new Error("Current path equals rootPath. ID was probably not initialized properly");let $=[Buffer.from(Y).toString("hex"),Buffer.from("ID").toString("hex"),Buffer.from(this.identityKey).toString("hex"),Buffer.from(this.getCurrentAddress()).toString("hex")];return this.signOpReturnWithAIP($,j||this.#q)}getAddress(j){return this.#j.derive(j).privKey.toPublicKey().toAddress()}getCurrentAddress(){return this.getAddress(this.#z)}getEncryptionPublicKey(){return this.#j.derive(this.#$).derive(G).privKey.toPublicKey().toString()}getEncryptionPublicKeyWithSeed(j){return this.getEncryptionPrivateKeyWithSeed(j).toPublicKey().toString("hex")}encrypt(j,$){let Q=this.#j.derive(this.#$).derive(G).privKey.toPublicKey(),z=$?_.fromString($):Q;return A(g(w(j),z,null))}decrypt(j,$){let q=this.#j.derive(this.#$).derive(G).privKey,Q=void 0;if($)Q=_.fromString($);return I(K(w(j,"base64"),q,Q))}encryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),Q=q.toPublicKey(),z=J?_.fromString(J):Q;return A(g(w(j),z,q))}decryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),Q=void 0;if(J)Q=_.fromString(J);return I(K(w(j,"base64"),q,Q))}getEncryptionPrivateKeyWithSeed(j){let $=O(X.sha256(j,"utf8")),J=W.getSigningPathFromHex($);return this.#j.derive(this.#$).derive(J).privKey}getAttestation(j){let $=X.sha256(j,"utf8");return`bap:attest:${O($)}:${this.getIdentityKey()}`}getAttestationHash(j){let $=this.getAttributeUrn(j);if(!$)return null;let J=this.getAttestation($),q=X.sha256(J,"utf8");return O(q)}signMessage(j,$=""){let J;if(!(j instanceof Buffer))J=Buffer.from(j);else J=j;let q=$||this.#z,Q=this.#j.derive(q).privKey,z=Q.toAddress(),Z=M.sign(w(j),Q,"raw"),L=new D(m(w(j,"utf8"))),k=Z.CalculateRecoveryFactor(Q.toPublicKey(),L),E=M.sign(w(J),Q,"raw").toCompact(k,!0,"base64");return{address:z,signature:E}}signMessageWithSeed(j,$){let J=O(X.sha256($,"utf8")),q=W.getSigningPathFromHex(J),z=this.#j.derive(this.#$).derive(q),Z=z.privKey.toPublicKey().toAddress(),L=M.sign(w(j),z.privKey,"raw"),k=new D(m(w(j,"utf8"))),E=L.CalculateRecoveryFactor(z.privKey.toPublicKey(),k),c=M.sign(w(Buffer.from(j)),z.privKey,"raw").toCompact(E,!0,"base64");return{address:Z,signature:c}}signOpReturnWithAIP(j,$="",J="hex"){let q=this.getAIPMessageBuffer(j),{address:Q,signature:z}=this.signMessage(q,$);return j.concat([Buffer.from("|").toString(J),Buffer.from(x).toString(J),Buffer.from("BITCOIN_ECDSA").toString(J),Buffer.from(Q).toString(J),Buffer.from(z,"base64").toString(J)])}getAIPMessageBuffer(j){let $=[];if(j[0].replace("0x","")!=="6a")$.push(Buffer.from("6a","hex"));for(let J of j)$.push(Buffer.from(J.replace("0x",""),"hex"));return $.push(Buffer.from("|")),Buffer.concat([...$])}async getIdSigningKeys(){let j=await this.getApiData("/signing-keys",{idKey:this.identityKey});return console.log("getIdSigningKeys",j),j}async getAttributeAttestations(j){let $=this.getAttestationHash(j),J=await this.getApiData("/attestation/get",{hash:$});return console.log("getAttestations",j,$,J),J}import(j){this.idName=j.name,this.description=j.description||"",this.identityKey=j.identityKey,this.#$=j.rootPath,this.rootAddress=j.rootAddress,this.#q=j.previousPath,this.#z=j.currentPath,this.#W=("idSeed"in j?j.idSeed:"")||"",this.identityAttributes=this.parseAttributes(j.identityAttributes)}export(){return{name:this.idName,description:this.description,identityKey:this.identityKey,rootPath:this.#$,rootAddress:this.rootAddress,previousPath:this.#q,currentPath:this.#z,idSeed:this.#W,identityAttributes:this.getAttributes(),lastIdPath:""}}exportMemberBackup(){let j=this.#j.derive(this.#z).privKey;return{name:this.idName,description:this.description,derivedPrivateKey:j.toString(),address:j.toPublicKey().toAddress(),identityAttributes:this.getAttributes()}}newId(){this.incrementPath();let j=this.#j.derive(this.#z).privKey;return new f(j,this.getAttributes())}}var{toArray:v,toUTF8:a,toBase64:e}=i,{electrumEncrypt:t,electrumDecrypt:jj}=d;class $j{#j;#J={};#Q=V;#$="";#q="";getApiData;constructor(j,$="",J=""){if(!j)throw new Error("No HDPrivateKey given");if(this.#j=s.fromString(j),$)this.#$=$;if(J)this.#Q=J;this.getApiData=R(this.#Q,this.#$)}get lastIdPath(){return this.#q}getPublicKey(j=""){if(j)return this.#j.derive(j).pubKey.toString();return this.#j.pubKey.toString()}getHdPublicKey(j=""){if(j)return this.#j.derive(j).toPublic().toString();return this.#j.toPublic().toString()}set BAP_SERVER(j){this.#Q=j;for(let $ in this.#J)this.#J[$].BAP_SERVER=j}get BAP_SERVER(){return this.#Q}set BAP_TOKEN(j){this.#$=j;for(let $ in this.#J)this.#J[$].BAP_TOKEN=j}get BAP_TOKEN(){return this.#$}checkIdBelongs(j){if(this.#j.derive(j.rootPath).pubKey.toAddress()!==j.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#J)}newId(j,$={},J=""){let q;if(!j)q=this.getNextValidPath();else q=j;let Q=new U(this.#j,$,J);Q.BAP_SERVER=this.#Q,Q.BAP_TOKEN=this.#$,Q.rootPath=q,Q.currentPath=W.getNextPath(q);let z=Q.getIdentityKey();return this.#J[z]=Q,this.#q=q,this.#J[z]}removeId(j){delete this.#J[j]}getNextValidPath(){if(this.#q)return W.getNextIdentityPath(this.#q);return`/0'/${Object.keys(this.#J).length}'/0'`}getId(j){return this.#J[j]||null}setId(j){this.checkIdBelongs(j),this.#J[j.getIdentityKey()]=j}importIds(j,$=!0){if($&&typeof j==="string"){this.importEncryptedIds(j);return}let J=j;if(!J.lastIdPath)throw new Error("ID cannot be imported as it is not complete");if(!J.ids)throw new Error(`ID data is not in the correct format: ${j}`);let q=j.lastIdPath;for(let Q of J.ids){if(!Q.identityKey||!Q.identityAttributes||!Q.rootAddress)throw new Error("ID cannot be imported as it is not complete");let z=new U(this.#j,{},Q.idSeed);if(z.BAP_SERVER=this.#Q,z.BAP_TOKEN=this.#$,z.import(Q),q==="")q=z.currentPath;this.checkIdBelongs(z),this.#J[z.getIdentityKey()]=z}this.#q=q}importEncryptedIds(j){let $=this.decrypt(j),J=JSON.parse($);if(Array.isArray(J)){console.log(`Importing old format:
6
+ `,J),this.importOldIds(J);return}if(typeof J!=="object")throw new Error("decrypted, but found unrecognized identities format");this.importIds(J,!1)}importOldIds(j){for(let $ of j){let J=new U(this.#j,{},$.idSeed??"");J.BAP_SERVER=this.#Q,J.BAP_TOKEN=this.#$,J.import($),this.checkIdBelongs(J),this.#J[J.getIdentityKey()]=J,this.#q=J.currentPath}}exportIds(j,$=!0){let J={lastIdPath:this.#q,ids:[]},q=j||Object.keys(this.#J);for(let Q of q){if(!this.#J[Q])throw new Error(`Identity ${Q} not found`);J.ids.push(this.#J[Q].export())}if($)return this.encrypt(JSON.stringify(J));return J}exportId(j,$=!0){let J={lastIdPath:this.#q,ids:[]};if(J.ids.push(this.#J[j].export()),$)return this.encrypt(JSON.stringify(J));return J}encrypt(j){let $=this.#j.derive(G);return e(t(v(j),$.pubKey,null))}decrypt(j){let $=this.#j.derive(G);return a(jj(v(j,"base64"),$.privKey))}signAttestationWithAIP(j,$,J=0,q=""){let Q=this.getId($);if(!Q)throw new Error("Could not find identity to attest with");let z=this.getAttestationBuffer(j,J,q),{address:Z,signature:L}=Q.signMessage(z);return this.createAttestationTransaction(j,J,Z,L,q)}verifyAttestationWithAIP(j){if(!Array.isArray(j)||j[0]!=="0x6a"||j[1]!==H)throw new Error("Not a valid BAP transaction");let $=j[7]==="0x44415441"?5:0,J={type:W.hexDecode(j[2]),hash:W.hexDecode(j[3]),sequence:W.hexDecode(j[4]),signingProtocol:W.hexDecode(j[7+$]),signingAddress:W.hexDecode(j[8+$]),signature:W.hexDecode(j[9+$],"base64")};if($&&j[3]===j[8])J.data=W.hexDecode(j[9]);try{let q=[];for(let z=0;z<6+$;z++)q.push(Buffer.from(j[z].replace("0x",""),"hex"));let Q=Buffer.concat(q);J.verified=this.verifySignature(Q,J.signingAddress,J.signature)}catch(q){J.verified=!1}return J}createAttestationTransaction(j,$,J,q,Q=""){let z=["0x6a",W.hexEncode(Y)];if(z.push(W.hexEncode("ATTEST")),z.push(W.hexEncode(j)),z.push(W.hexEncode(`${$}`)),z.push("0x7c"),Q)z.push(W.hexEncode(Y)),z.push(W.hexEncode("DATA")),z.push(W.hexEncode(j)),z.push(W.hexEncode(Q)),z.push("0x7c");return z.push(W.hexEncode(x)),z.push(W.hexEncode("BITCOIN_ECDSA")),z.push(W.hexEncode(J)),z.push(`0x${Buffer.from(q,"base64").toString("hex")}`),z}getAttestationBuffer(j,$=0,J=""){let q=Buffer.from("");if(J)q=Buffer.concat([Buffer.from(Y),Buffer.from("DATA"),Buffer.from(j),Buffer.from(J),Buffer.from("7c","hex")]);return Buffer.concat([Buffer.from("6a","hex"),Buffer.from(Y),Buffer.from("ATTEST"),Buffer.from(j),Buffer.from(`${$}`),Buffer.from("7c","hex"),q])}verifySignature(j,$,J){let q=Buffer.isBuffer(j)?j:Buffer.from(j),Q=r.fromCompact(J,"base64"),z,Z=v(q.toString("hex"),"hex");for(let L=0;L<4;L++)try{if(z=Q.RecoverPublicKey(L,new n(N.magicHash(Z))),N.verify(Z,Q,z)&&z.toAddress()===$)return!0}catch(k){}return!1}async verifyChallengeSignature(j,$,J,q){if(!this.verifySignature(J,$,q))return!1;try{let z=await this.getApiData("/attestation/valid",{idKey:j,address:$,challenge:J,signature:q});if(z?.status==="success"&&z?.result?.valid===!0)return!0;return!1}catch(z){return console.error("API call failed:",z),!1}}async isValidAttestationTransaction(j){if(this.verifyAttestationWithAIP(j))return this.getApiData("/attestation/valid",{tx:j});return!1}async getIdentityFromAddress(j){return this.getApiData("/identity/from-address",{address:j})}async getIdentity(j){return this.getApiData("/identity/get",{idKey:j})}async getAttestationsForHash(j){return this.getApiData("/attestations",{hash:j})}}export{f as MemberID,U as MasterID,$j as BAP};
6
7
 
7
- //# debugId=4036FD6C9BC6FFC664756E2164756E21
8
+ //# debugId=6A60A376E5A4A51E64756E2164756E21