bsv-bap 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Helper function to get attestation from a BAP API server
3
+ *
4
+ * @param apiUrl
5
+ * @param apiData
6
+ * @returns {Promise<any>}
7
+ */
8
+ export declare const getApiData: <T>(apiUrl: string, apiData: unknown, server: string, token: string) => Promise<T>;
9
+ export type APIFetcher = <T>(url: string, data: unknown) => Promise<T>;
10
+ export declare const apiFetcher: (host: string, token: string) => APIFetcher;
@@ -0,0 +1,36 @@
1
+ import type { Attestation, Identity } from "./interface";
2
+ export interface APIResponse<T = Attestation | Identity> {
3
+ status: string;
4
+ result?: T;
5
+ message?: string;
6
+ }
7
+ export type GetAttestationResponse = APIResponse<Attestation>;
8
+ export type GetIdentityResponse = APIResponse<Identity>;
9
+ export type GetIdentityByAddressResponse = APIResponse<Identity>;
10
+ export type GetIdentityDIDResponse = string;
11
+ export type GetIdentityDIDByAddressResponse = string;
12
+ export interface AttestationValidParams {
13
+ address: string;
14
+ idKey: string;
15
+ attribute: string;
16
+ value: string;
17
+ nonce: string;
18
+ urn: string;
19
+ hash: string;
20
+ block: number;
21
+ timestamp: number;
22
+ }
23
+ export interface IdentityValidByAddressParams {
24
+ address: string;
25
+ block: number;
26
+ timestamp: number;
27
+ }
28
+ export interface ValidityRecord {
29
+ valid: boolean;
30
+ block: number;
31
+ timestamp: number;
32
+ }
33
+ export interface AttestationValidResponse extends ValidityRecord {
34
+ }
35
+ export interface IdentityValidResponse extends Identity, ValidityRecord {
36
+ }
package/dist/id.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type HD } from "@bsv/sdk";
2
+ import { type APIFetcher } from "./api";
2
3
  import type { Identity, IdentityAttribute, IdentityAttributes } from "./interface";
4
+ import type { GetAttestationResponse } from "./apiTypes";
3
5
  /**
4
6
  * BAP_ID class
5
7
  *
@@ -14,6 +16,7 @@ declare class BAP_ID {
14
16
  rootAddress: string;
15
17
  identityKey: string;
16
18
  identityAttributes: IdentityAttributes;
19
+ getApiData: APIFetcher;
17
20
  constructor(HDPrivateKey: HD, identityAttributes?: IdentityAttributes, idSeed?: string);
18
21
  set BAP_SERVER(bapServer: string);
19
22
  get BAP_SERVER(): string;
@@ -65,7 +68,7 @@ declare class BAP_ID {
65
68
  * @param attributeValue any
66
69
  * @returns {{}|null}
67
70
  */
68
- setAttribute(attributeName: string, attributeValue: any): void;
71
+ setAttribute(attributeName: string, attributeValue: string | Record<string, string>): void;
69
72
  /**
70
73
  * Unset the given attribute from the ID
71
74
  *
@@ -257,15 +260,7 @@ declare class BAP_ID {
257
260
  *
258
261
  * @param attribute
259
262
  */
260
- getAttributeAttestations(attribute: string): Promise<any>;
261
- /**
262
- * Helper function to get attestation from a BAP API server
263
- *
264
- * @param apiUrl
265
- * @param apiData
266
- * @returns {Promise<any>}
267
- */
268
- getApiData(apiUrl: string, apiData: any): Promise<any>;
263
+ getAttributeAttestations(attribute: string): Promise<GetAttestationResponse>;
269
264
  /**
270
265
  * Import an identity from a JSON object
271
266
  *
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var t=require("@bsv/sdk");function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var r=/*#__PURE__*/e(require("randombytes"));function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,i=Array(e);r<e;r++)i[r]=t[r];return i}function n(t,e){if(!{}.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}var o=0;function s(t){return"__private_"+o+++"_"+t}function a(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,c(i.key),i)}}function u(t,e,r){return e&&a(t.prototype,e),r&&a(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function h(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(t){if("string"==typeof t)return i(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function f(){return f=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)({}).hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t},f.apply(null,arguments)}function c(t){var e=function(t){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var r=e.call(t,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==typeof e?e:e+""}var d=function(t){return"0x"+Buffer.from(t).toString("hex")},v=function(t,e){return void 0===e&&(e="utf8"),Buffer.from(t.replace("0x",""),"hex").toString(e)},y=function(t,e){void 0===e&&(e=!0);var r="m",i=t.match(/.{1,8}/g);if(!i)throw new Error("Invalid hex string");for(var n,o=2147483647,s=h(i);!(n=s()).done;){var a=Number("0x"+n.value);a>o&&(a-=o),r+="/"+a+(e?"'":"")}return r},l=function(t){var e=t.split("/"),r=e[e.length-1],i=!1;r.match("'")&&(i=!0);var n=(Number(r.replace(/[^0-9]/g,""))+1).toString();return e[e.length-1]=n+(i?"'":""),e.join("/")},g="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",p="0x"+Buffer.from(g).toString("hex"),b="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva";Buffer.from(b).toString("hex");var m,P,A,S,B,K="https://api.sigmaidentity.com/api/v1",I=2147483647,E="m/424150'/0'/0'",w="m/424150'/"+I+"'/"+I+"'",x=t.Utils.toArray,j=t.Utils.toHex,O=t.Utils.toBase58,N=t.Utils.toUTF8,T=t.Utils.toBase64,D=t.ECIES.electrumDecrypt,k=t.ECIES.electrumEncrypt,C=t.BSM.magicHash,R=/*#__PURE__*/s("HDPrivateKey"),_=/*#__PURE__*/s("BAP_SERVER"),H=/*#__PURE__*/s("BAP_TOKEN"),U=/*#__PURE__*/s("rootPath"),M=/*#__PURE__*/s("previousPath"),W=/*#__PURE__*/s("currentPath"),V=/*#__PURE__*/s("idSeed"),F=/*#__PURE__*/function(){function e(e,r,i){if(void 0===r&&(r={}),void 0===i&&(i=""),Object.defineProperty(this,R,{writable:!0,value:void 0}),Object.defineProperty(this,_,{writable:!0,value:K}),Object.defineProperty(this,H,{writable:!0,value:""}),Object.defineProperty(this,U,{writable:!0,value:void 0}),Object.defineProperty(this,M,{writable:!0,value:void 0}),Object.defineProperty(this,W,{writable:!0,value:void 0}),Object.defineProperty(this,V,{writable:!0,value:void 0}),this.idName=void 0,this.description=void 0,this.rootAddress=void 0,this.identityKey=void 0,this.identityAttributes=void 0,n(this,V)[V]=i,i){var o=j(t.Hash.sha256(i,"utf8")),s=y(o);n(this,R)[R]=e.derive(s)}else n(this,R)[R]=e;this.idName="ID 1",this.description="",n(this,U)[U]=E+"/0/0/0",n(this,M)[M]=E+"/0/0/0",n(this,W)[W]=E+"/0/0/1";var a=n(this,R)[R].derive(n(this,U)[U]);this.rootAddress=a.privKey.toPublicKey().toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress);var u=f({},r);this.identityAttributes=this.parseAttributes(u)}var i=e.prototype;return i.deriveIdentityKey=function(e){var r=j(t.Hash.sha256(e,"utf8"));return O(t.Hash.ripemd160(r,"hex"))},i.parseAttributes=function(t){if("string"==typeof t)return this.parseStringUrns(t);for(var e in t)if(!t[e].value||!t[e].nonce)throw new Error("Invalid identity attribute");return t||{}},i.parseStringUrns=function(t){for(var e,r={},i=h(t.replace(/^\s+/g,"").replace(/\r/gm,"").split("\n"));!(e=i()).done;){var n=e.value.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");"urn"===n[0]&&"bap"===n[1]&&"id"===n[2]&&n[3]&&n[4]&&n[5]&&(r[n[3]]={value:n[4],nonce:n[5]})}return r},i.getIdentityKey=function(){return this.identityKey},i.getAttributes=function(){return this.identityAttributes},i.getAttribute=function(t){return this.identityAttributes[t]?this.identityAttributes[t]:null},i.setAttribute=function(t,e){e&&(this.identityAttributes[t]?this.identityAttributes[t].value=e:this.addAttribute(t,e))},i.unsetAttribute=function(t){delete this.identityAttributes[t]},i.getAttributeUrns=function(){var t="";for(var e in this.identityAttributes){var r=this.getAttributeUrn(e);r&&(t+=r+"\n")}return t},i.getAttributeUrn=function(t){var e=this.identityAttributes[t];return e?"urn:bap:id:"+t+":"+e.value+":"+e.nonce:null},i.addAttribute=function(t,e,i){void 0===i&&(i="");var n,o=i;i||(void 0===n&&(n=32),o=r.default(n).toString("hex")),this.identityAttributes[t]={value:e,nonce:o}},i.getRootPath=function(){return n(this,U)[U]},i.incrementPath=function(){this.currentPath=l(this.currentPath)},i.validatePath=function(t){if(t.match(/\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?/)){var e=t.split("/");if(7===e.length&&Number(e[1].replace("'",""))<=I&&Number(e[2].replace("'",""))<=I&&Number(e[3].replace("'",""))<=I&&Number(e[4].replace("'",""))<=I&&Number(e[5].replace("'",""))<=I&&Number(e[6].replace("'",""))<=I)return!0}return!1},i.getInitialIdTransaction=function(){return this.getIdTransaction(n(this,U)[U])},i.getIdTransaction=function(t){if(void 0===t&&(t=""),n(this,W)[W]===n(this,U)[U])throw new Error("Current path equals rootPath. ID was probably not initialized properly");var e=[Buffer.from(g).toString("hex"),Buffer.from("ID").toString("hex"),Buffer.from(this.identityKey).toString("hex"),Buffer.from(this.getCurrentAddress()).toString("hex")];return this.signOpReturnWithAIP(e,t||n(this,M)[M])},i.getAddress=function(t){return n(this,R)[R].derive(t).privKey.toPublicKey().toAddress()},i.getCurrentAddress=function(){return this.getAddress(n(this,W)[W])},i.getEncryptionPublicKey=function(){return n(this,R)[R].derive(n(this,U)[U]).derive(w).privKey.toPublicKey().toString()},i.getEncryptionPublicKeyWithSeed=function(t){return this.getEncryptionPrivateKeyWithSeed(t).toPublicKey().toString("hex")},i.encrypt=function(e,r){var i=n(this,R)[R].derive(n(this,U)[U]).derive(w).privKey.toPublicKey(),o=r?t.PublicKey.fromString(r):i;return T(k(x(e),o,null))},i.decrypt=function(e,r){var i=n(this,R)[R].derive(n(this,U)[U]).derive(w).privKey,o=void 0;return r&&(o=t.PublicKey.fromString(r)),N(D(x(e,"base64"),i,o))},i.encryptWithSeed=function(e,r,i){var n=this.getEncryptionPrivateKeyWithSeed(r),o=n.toPublicKey(),s=i?t.PublicKey.fromString(i):o;return T(k(x(e),s,n))},i.decryptWithSeed=function(e,r,i){var n=this.getEncryptionPrivateKeyWithSeed(r),o=void 0;return i&&(o=t.PublicKey.fromString(i)),N(D(x(e,"base64"),n,o))},i.getEncryptionPrivateKeyWithSeed=function(e){var r=j(t.Hash.sha256(e,"utf8")),i=y(r);return n(this,R)[R].derive(n(this,U)[U]).derive(i).privKey},i.getAttestation=function(e){var r=t.Hash.sha256(e,"utf8");return"bap:attest:"+j(r)+":"+this.getIdentityKey()},i.getAttestationHash=function(e){var r=this.getAttributeUrn(e);if(!r)return null;var i=this.getAttestation(r),n=t.Hash.sha256(i,"utf8");return j(n)},i.signMessage=function(e,r){var i;void 0===r&&(r=""),i=e instanceof Buffer?e:Buffer.from(e);var o=r||n(this,W)[W],s=n(this,R)[R].derive(o).privKey,a=s.toAddress(),u=t.BSM.sign(x(e),s),h=new t.BigNumber(C(x(e,"utf8"))),f=u.CalculateRecoveryFactor(s.toPublicKey(),h);return{address:a,signature:t.BSM.sign(x(i),s).toCompact(f,!0,"base64")}},i.signMessageWithSeed=function(e,r){var i=j(t.Hash.sha256(r,"utf8")),o=y(i),s=n(this,R)[R].derive(n(this,U)[U]).derive(o),a=s.privKey.toPublicKey().toAddress(),u=t.BSM.sign(x(e),s.privKey),h=new t.BigNumber(C(x(e,"utf8"))),f=u.CalculateRecoveryFactor(s.privKey.toPublicKey(),h);return{address:a,signature:t.BSM.sign(x(Buffer.from(e)),s.privKey).toCompact(f,!0,"base64")}},i.signOpReturnWithAIP=function(t,e,r){void 0===e&&(e=""),void 0===r&&(r="hex");var i=this.getAIPMessageBuffer(t),n=this.signMessage(i,e),o=n.address,s=n.signature;return t.concat([Buffer.from("|").toString(r),Buffer.from(b).toString(r),Buffer.from("BITCOIN_ECDSA").toString(r),Buffer.from(o).toString(r),Buffer.from(s,"base64").toString(r)])},i.getAIPMessageBuffer=function(t){var e=[];"6a"!==t[0].replace("0x","")&&e.push(Buffer.from("6a","hex"));for(var r,i=h(t);!(r=i()).done;)e.push(Buffer.from(r.value.replace("0x",""),"hex"));return e.push(Buffer.from("|")),Buffer.concat([].concat(e))},i.getIdSigningKeys=function(){try{return Promise.resolve(this.getApiData("/signing-keys",{idKey:this.identityKey})).then(function(t){return console.log("getIdSigningKeys",t),t})}catch(t){return Promise.reject(t)}},i.getAttributeAttestations=function(t){try{var e=this.getAttestationHash(t);return Promise.resolve(this.getApiData("/attestations",{hash:e})).then(function(r){return console.log("getAttestations",t,e,r),r})}catch(t){return Promise.reject(t)}},i.getApiData=function(t,e){try{var r=""+n(this,_)[_]+t;return Promise.resolve(fetch(r,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:n(this,H)[H],format:"json"},body:JSON.stringify(e)})).then(function(t){return t.json()})}catch(t){return Promise.reject(t)}},i.import=function(t){this.idName=t.name,this.description=t.description||"",this.identityKey=t.identityKey,n(this,U)[U]=t.rootPath,this.rootAddress=t.rootAddress,n(this,M)[M]=t.previousPath,n(this,W)[W]=t.currentPath,n(this,V)[V]=t.idSeed||"",this.identityAttributes=this.parseAttributes(t.identityAttributes)},i.export=function(){return{name:this.idName,description:this.description,identityKey:this.identityKey,rootPath:n(this,U)[U],rootAddress:this.rootAddress,previousPath:n(this,M)[M],currentPath:n(this,W)[W],idSeed:n(this,V)[V],identityAttributes:this.getAttributes(),lastIdPath:""}},u(e,[{key:"BAP_SERVER",get:function(){return n(this,_)[_]},set:function(t){n(this,_)[_]=t}},{key:"BAP_TOKEN",get:function(){return n(this,H)[H]},set:function(t){n(this,H)[H]=t}},{key:"rootPath",get:function(){return n(this,U)[U]},set:function(t){if(n(this,R)[R]){var e=t;if(t.split("/").length<5&&(e=""+E+t),!this.validatePath(e))throw new Error("invalid signing path given "+e);n(this,U)[U]=e;var r=n(this,R)[R].derive(e);this.rootAddress=r.pubKey.toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress),n(this,M)[M]=e,n(this,W)[W]=e}}},{key:"currentPath",get:function(){return n(this,W)[W]},set:function(t){var e=t;if(t.split("/").length<5&&(e=""+E+t),!this.validatePath(e))throw new Error("invalid signing path given");n(this,M)[M]=n(this,W)[W],n(this,W)[W]=e}},{key:"previousPath",get:function(){return n(this,M)[M]}},{key:"idSeed",get:function(){return n(this,V)[V]}}])}(),q=t.Utils.toArray,J=t.Utils.toUTF8,G=t.Utils.toBase64,z=t.ECIES.electrumEncrypt,L=t.ECIES.electrumDecrypt,$=(m=/*#__PURE__*/s("HDPrivateKey"),P=/*#__PURE__*/s("ids"),A=/*#__PURE__*/s("BAP_SERVER"),S=/*#__PURE__*/s("BAP_TOKEN"),B=/*#__PURE__*/s("lastIdPath"),/*#__PURE__*/function(){function e(e,r){if(void 0===r&&(r=""),Object.defineProperty(this,m,{writable:!0,value:void 0}),Object.defineProperty(this,P,{writable:!0,value:{}}),Object.defineProperty(this,A,{writable:!0,value:K}),Object.defineProperty(this,S,{writable:!0,value:""}),Object.defineProperty(this,B,{writable:!0,value:""}),!e)throw new Error("No HDPrivateKey given");n(this,m)[m]=t.HD.fromString(e),r&&(n(this,S)[S]=r)}var r=e.prototype;return r.getPublicKey=function(t){return void 0===t&&(t=""),t?n(this,m)[m].derive(t).pubKey.toString():n(this,m)[m].pubKey.toString()},r.getHdPublicKey=function(t){return void 0===t&&(t=""),t?n(this,m)[m].derive(t).toPublic().toString():n(this,m)[m].toPublic().toString()},r.checkIdBelongs=function(t){if(n(this,m)[m].derive(t.rootPath).pubKey.toAddress()!==t.rootAddress)throw new Error("ID does not belong to this private key");return!0},r.listIds=function(){return Object.keys(n(this,P)[P])},r.newId=function(t,e,r){var i;void 0===e&&(e={}),void 0===r&&(r=""),i=t||this.getNextValidPath();var o=new F(n(this,m)[m],e,r);o.BAP_SERVER=n(this,A)[A],o.BAP_TOKEN=n(this,S)[S],o.rootPath=i,o.currentPath=l(i);var s=o.getIdentityKey();return n(this,P)[P][s]=o,n(this,B)[B]=i,n(this,P)[P][s]},r.removeId=function(t){delete n(this,P)[P][t]},r.getNextValidPath=function(){return n(this,B)[B]?function(t){var e=t.split("/"),r=e[e.length-2],i=!1;r.match("'")&&(i=!0);var n=(Number(r.replace(/[^0-9]/g,""))+1).toString();return e[e.length-2]=n+(i?"'":""),e[e.length-1]="0"+(i?"'":""),e.join("/")}(n(this,B)[B]):"/0'/"+Object.keys(n(this,P)[P]).length+"'/0'"},r.getId=function(t){return n(this,P)[P][t]||null},r.setId=function(t){this.checkIdBelongs(t),n(this,P)[P][t.getIdentityKey()]=t},r.importIds=function(t,e){if(void 0===e&&(e=!0),e&&"string"==typeof t)this.importEncryptedIds(t);else{var r=t;if(!r.lastIdPath)throw new Error("ID cannot be imported as it is not complete");if(!r.ids)throw new Error("ID data is not in the correct format: "+t);for(var i,o=t.lastIdPath,s=h(r.ids);!(i=s()).done;){var a=i.value;if(!a.identityKey||!a.identityAttributes||!a.rootAddress)throw new Error("ID cannot be imported as it is not complete");var u=new F(n(this,m)[m],{},a.idSeed);u.BAP_SERVER=n(this,A)[A],u.BAP_TOKEN=n(this,S)[S],u.import(a),""===o&&(o=u.currentPath),this.checkIdBelongs(u),n(this,P)[P][u.getIdentityKey()]=u}n(this,B)[B]=o}},r.importEncryptedIds=function(t){var e=this.decrypt(t),r=JSON.parse(e);if(Array.isArray(r))return console.log("Importing old format:\n",r),void this.importOldIds(r);if("object"!=typeof r)throw new Error("decrypted, but found unrecognized identities format");this.importIds(r,!1)},r.importOldIds=function(t){for(var e,r=h(t);!(e=r()).done;){var i=e.value,o=new F(n(this,m)[m],{},i.idSeed);o.BAP_SERVER=n(this,A)[A],o.BAP_TOKEN=n(this,S)[S],o.import(i),this.checkIdBelongs(o),n(this,P)[P][o.getIdentityKey()]=o,n(this,B)[B]=o.currentPath}},r.exportIds=function(t){void 0===t&&(t=!0);for(var e={lastIdPath:n(this,B)[B],ids:[]},r=0,i=Object.keys(n(this,P)[P]);r<i.length;r++){var o=i[r];e.ids.push(n(this,P)[P][o].export())}return t?this.encrypt(JSON.stringify(e)):e},r.encrypt=function(t){var e=n(this,m)[m].derive(w);return G(z(q(t),e.pubKey,null))},r.decrypt=function(t){var e=n(this,m)[m].derive(w);return J(L(q(t,"base64"),e.privKey))},r.signAttestationWithAIP=function(t,e,r,i){void 0===r&&(r=0),void 0===i&&(i="");var n=this.getId(e);if(!n)throw new Error("Could not find identity to attest with");var o=this.getAttestationBuffer(t,r,i),s=n.signMessage(o);return this.createAttestationTransaction(t,r,s.address,s.signature,i)},r.verifyAttestationWithAIP=function(t){if(!Array.isArray(t)||"0x6a"!==t[0]||t[1]!==p)throw new Error("Not a valid BAP transaction");var e="0x44415441"===t[7]?5:0,r={type:v(t[2]),hash:v(t[3]),sequence:v(t[4]),signingProtocol:v(t[7+e]),signingAddress:v(t[8+e]),signature:v(t[9+e],"base64")};e&&t[3]===t[8]&&(r.data=v(t[9]));try{for(var i=[],n=0;n<6+e;n++)i.push(Buffer.from(t[n].replace("0x",""),"hex"));var o=Buffer.concat([].concat(i));r.verified=this.verifySignature(o,r.signingAddress,r.signature)}catch(t){r.verified=!1}return r},r.createAttestationTransaction=function(t,e,r,i,n){void 0===n&&(n="");var o=["0x6a",d(g)];return o.push(d("ATTEST")),o.push(d(t)),o.push(d(""+e)),o.push("0x7c"),n&&(o.push(d(g)),o.push(d("DATA")),o.push(d(t)),o.push(d(n)),o.push("0x7c")),o.push(d(b)),o.push(d("BITCOIN_ECDSA")),o.push(d(r)),o.push("0x"+Buffer.from(i,"base64").toString("hex")),o},r.getAttestationBuffer=function(t,e,r){void 0===e&&(e=0),void 0===r&&(r="");var i=Buffer.from("");return r&&(i=Buffer.concat([Buffer.from(g),Buffer.from("DATA"),Buffer.from(t),Buffer.from(r),Buffer.from("7c","hex")])),Buffer.concat([Buffer.from("6a","hex"),Buffer.from(g),Buffer.from("ATTEST"),Buffer.from(t),Buffer.from(""+e),Buffer.from("7c","hex"),i])},r.verifySignature=function(e,r,i){for(var n,o=Buffer.isBuffer(e)?e:Buffer.from(e),s=t.Signature.fromCompact(i,"base64"),a=q(o.toString("hex"),"hex"),u=0;u<4;u++)try{if(n=s.RecoverPublicKey(u,new t.BigNumber(t.BSM.magicHash(a))),t.BSM.verify(a,s,n)&&n.toAddress()===r)return!0}catch(t){}return!1},r.verifyChallengeSignature=function(t,e,r,i){try{var n,o=this,s=function(){if(o.verifySignature(r,e,i))return Promise.resolve(o.getApiData("/attestation/valid",{idKey:t,challenge:r,signature:i})).then(function(t){return n=1,t.data})}();return Promise.resolve(s&&s.then?s.then(function(t){return!!n&&t}):!!n&&s)}catch(t){return Promise.reject(t)}},r.isValidAttestationTransaction=function(t){try{return this.verifyAttestationWithAIP(t)?Promise.resolve(this.getApiData("/attestation/valid",{tx:t})):Promise.resolve(!1)}catch(t){return Promise.reject(t)}},r.getIdentityFromAddress=function(t){try{return Promise.resolve(this.getApiData("/identity/from-address",{address:t}))}catch(t){return Promise.reject(t)}},r.getIdentity=function(t){try{return Promise.resolve(this.getApiData("/identity",{idKey:t}))}catch(t){return Promise.reject(t)}},r.getAttestationsForHash=function(t){try{return Promise.resolve(this.getApiData("/attestations",{hash:t}))}catch(t){return Promise.reject(t)}},r.getApiData=function(t,e){try{var r=""+n(this,A)[A]+t;return Promise.resolve(fetch(r,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:n(this,S)[S],format:"json"},body:JSON.stringify(e)})).then(function(t){return t.json()})}catch(t){return Promise.reject(t)}},u(e,[{key:"lastIdPath",get:function(){return n(this,B)[B]}},{key:"BAP_SERVER",get:function(){return n(this,A)[A]},set:function(t){n(this,A)[A]=t;for(var e=0,r=Object.keys(n(this,P)[P]);e<r.length;e++){var i=r[e];n(this,P)[P][i].BAP_SERVER=t}}},{key:"BAP_TOKEN",get:function(){return n(this,S)[S]},set:function(t){n(this,S)[S]=t;for(var e=0,r=Object.keys(n(this,P)[P]);e<r.length;e++){var i=r[e];n(this,P)[P][i].BAP_TOKEN=t}}}])}());exports.BAP=$;
1
+ var t=require("@bsv/sdk");function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var r=/*#__PURE__*/e(require("randombytes"));function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,i=Array(e);r<e;r++)i[r]=t[r];return i}function n(t,e){if(!{}.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}var o=0;function s(t){return"__private_"+o+++"_"+t}function a(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,c(i.key),i)}}function u(t,e,r){return e&&a(t.prototype,e),r&&a(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function h(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(t){if("string"==typeof t)return i(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function f(){return f=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)({}).hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t},f.apply(null,arguments)}function c(t){var e=function(t){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var r=e.call(t,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==typeof e?e:e+""}var d=function(t){return"0x"+Buffer.from(t).toString("hex")},v=function(t,e){return void 0===e&&(e="utf8"),Buffer.from(t.replace("0x",""),"hex").toString(e)},y=function(t,e){void 0===e&&(e=!0);var r="m",i=t.match(/.{1,8}/g);if(!i)throw new Error("Invalid hex string");for(var n,o=2147483647,s=h(i);!(n=s()).done;){var a=Number("0x"+n.value);a>o&&(a-=o),r+="/"+a+(e?"'":"")}return r},l=function(t){var e=t.split("/"),r=e[e.length-1],i=!1;r.match("'")&&(i=!0);var n=(Number(r.replace(/[^0-9]/g,""))+1).toString();return e[e.length-1]=n+(i?"'":""),e.join("/")},g="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",p="0x"+Buffer.from(g).toString("hex"),b="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva";Buffer.from(b).toString("hex");var m="https://api.sigmaidentity.com/api/v1",A=2147483647,P="m/424150'/0'/0'",S="m/424150'/"+A+"'/"+A+"'",B=function(t,e){return function(r,i){return function(t,e,r,i){try{return Promise.resolve(fetch(""+r+t,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:i,format:"json"},body:JSON.stringify(e)})).then(function(t){return t.json()})}catch(t){return Promise.reject(t)}}(r,i,t,e)}},K=t.Utils.toArray,I=t.Utils.toHex,E=t.Utils.toBase58,w=t.Utils.toUTF8,x=t.Utils.toBase64,O=t.ECIES.electrumDecrypt,j=t.ECIES.electrumEncrypt,N=t.BSM.magicHash,T=/*#__PURE__*/s("HDPrivateKey"),D=/*#__PURE__*/s("BAP_SERVER"),_=/*#__PURE__*/s("BAP_TOKEN"),R=/*#__PURE__*/s("rootPath"),C=/*#__PURE__*/s("previousPath"),k=/*#__PURE__*/s("currentPath"),H=/*#__PURE__*/s("idSeed"),U=/*#__PURE__*/function(){function e(e,r,i){if(void 0===r&&(r={}),void 0===i&&(i=""),Object.defineProperty(this,T,{writable:!0,value:void 0}),Object.defineProperty(this,D,{writable:!0,value:m}),Object.defineProperty(this,_,{writable:!0,value:""}),Object.defineProperty(this,R,{writable:!0,value:void 0}),Object.defineProperty(this,C,{writable:!0,value:void 0}),Object.defineProperty(this,k,{writable:!0,value:void 0}),Object.defineProperty(this,H,{writable:!0,value:void 0}),this.idName=void 0,this.description=void 0,this.rootAddress=void 0,this.identityKey=void 0,this.identityAttributes=void 0,this.getApiData=void 0,n(this,H)[H]=i,i){var o=I(t.Hash.sha256(i,"utf8")),s=y(o);n(this,T)[T]=e.derive(s)}else n(this,T)[T]=e;this.idName="ID 1",this.description="",n(this,R)[R]=P+"/0/0/0",n(this,C)[C]=P+"/0/0/0",n(this,k)[k]=P+"/0/0/1";var a=n(this,T)[T].derive(n(this,R)[R]);this.rootAddress=a.privKey.toPublicKey().toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress);var u=f({},r);this.identityAttributes=this.parseAttributes(u),this.getApiData=B(n(this,D)[D],n(this,_)[_])}var i=e.prototype;return i.deriveIdentityKey=function(e){var r=I(t.Hash.sha256(e,"utf8"));return E(t.Hash.ripemd160(r,"hex"))},i.parseAttributes=function(t){if("string"==typeof t)return this.parseStringUrns(t);for(var e in t)if(!t[e].value||!t[e].nonce)throw new Error("Invalid identity attribute");return t||{}},i.parseStringUrns=function(t){for(var e,r={},i=h(t.replace(/^\s+/g,"").replace(/\r/gm,"").split("\n"));!(e=i()).done;){var n=e.value.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");"urn"===n[0]&&"bap"===n[1]&&"id"===n[2]&&n[3]&&n[4]&&n[5]&&(r[n[3]]={value:n[4],nonce:n[5]})}return r},i.getIdentityKey=function(){return this.identityKey},i.getAttributes=function(){return this.identityAttributes},i.getAttribute=function(t){return this.identityAttributes[t]?this.identityAttributes[t]:null},i.setAttribute=function(t,e){e&&(this.identityAttributes[t]?this.identityAttributes[t].value=e:this.addAttribute(t,e))},i.unsetAttribute=function(t){delete this.identityAttributes[t]},i.getAttributeUrns=function(){var t="";for(var e in this.identityAttributes){var r=this.getAttributeUrn(e);r&&(t+=r+"\n")}return t},i.getAttributeUrn=function(t){var e=this.identityAttributes[t];return e?"urn:bap:id:"+t+":"+e.value+":"+e.nonce:null},i.addAttribute=function(t,e,i){void 0===i&&(i="");var n,o=i;i||(void 0===n&&(n=32),o=r.default(n).toString("hex")),this.identityAttributes[t]={value:e,nonce:o}},i.getRootPath=function(){return n(this,R)[R]},i.incrementPath=function(){this.currentPath=l(this.currentPath)},i.validatePath=function(t){if(t.match(/\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?/)){var e=t.split("/");if(7===e.length&&Number(e[1].replace("'",""))<=A&&Number(e[2].replace("'",""))<=A&&Number(e[3].replace("'",""))<=A&&Number(e[4].replace("'",""))<=A&&Number(e[5].replace("'",""))<=A&&Number(e[6].replace("'",""))<=A)return!0}return!1},i.getInitialIdTransaction=function(){return this.getIdTransaction(n(this,R)[R])},i.getIdTransaction=function(t){if(void 0===t&&(t=""),n(this,k)[k]===n(this,R)[R])throw new Error("Current path equals rootPath. ID was probably not initialized properly");var e=[Buffer.from(g).toString("hex"),Buffer.from("ID").toString("hex"),Buffer.from(this.identityKey).toString("hex"),Buffer.from(this.getCurrentAddress()).toString("hex")];return this.signOpReturnWithAIP(e,t||n(this,C)[C])},i.getAddress=function(t){return n(this,T)[T].derive(t).privKey.toPublicKey().toAddress()},i.getCurrentAddress=function(){return this.getAddress(n(this,k)[k])},i.getEncryptionPublicKey=function(){return n(this,T)[T].derive(n(this,R)[R]).derive(S).privKey.toPublicKey().toString()},i.getEncryptionPublicKeyWithSeed=function(t){return this.getEncryptionPrivateKeyWithSeed(t).toPublicKey().toString("hex")},i.encrypt=function(e,r){var i=n(this,T)[T].derive(n(this,R)[R]).derive(S).privKey.toPublicKey(),o=r?t.PublicKey.fromString(r):i;return x(j(K(e),o,null))},i.decrypt=function(e,r){var i=n(this,T)[T].derive(n(this,R)[R]).derive(S).privKey,o=void 0;return r&&(o=t.PublicKey.fromString(r)),w(O(K(e,"base64"),i,o))},i.encryptWithSeed=function(e,r,i){var n=this.getEncryptionPrivateKeyWithSeed(r),o=n.toPublicKey(),s=i?t.PublicKey.fromString(i):o;return x(j(K(e),s,n))},i.decryptWithSeed=function(e,r,i){var n=this.getEncryptionPrivateKeyWithSeed(r),o=void 0;return i&&(o=t.PublicKey.fromString(i)),w(O(K(e,"base64"),n,o))},i.getEncryptionPrivateKeyWithSeed=function(e){var r=I(t.Hash.sha256(e,"utf8")),i=y(r);return n(this,T)[T].derive(n(this,R)[R]).derive(i).privKey},i.getAttestation=function(e){var r=t.Hash.sha256(e,"utf8");return"bap:attest:"+I(r)+":"+this.getIdentityKey()},i.getAttestationHash=function(e){var r=this.getAttributeUrn(e);if(!r)return null;var i=this.getAttestation(r),n=t.Hash.sha256(i,"utf8");return I(n)},i.signMessage=function(e,r){var i;void 0===r&&(r=""),i=e instanceof Buffer?e:Buffer.from(e);var o=r||n(this,k)[k],s=n(this,T)[T].derive(o).privKey,a=s.toAddress(),u=t.BSM.sign(K(e),s),h=new t.BigNumber(N(K(e,"utf8"))),f=u.CalculateRecoveryFactor(s.toPublicKey(),h);return{address:a,signature:t.BSM.sign(K(i),s).toCompact(f,!0,"base64")}},i.signMessageWithSeed=function(e,r){var i=I(t.Hash.sha256(r,"utf8")),o=y(i),s=n(this,T)[T].derive(n(this,R)[R]).derive(o),a=s.privKey.toPublicKey().toAddress(),u=t.BSM.sign(K(e),s.privKey),h=new t.BigNumber(N(K(e,"utf8"))),f=u.CalculateRecoveryFactor(s.privKey.toPublicKey(),h);return{address:a,signature:t.BSM.sign(K(Buffer.from(e)),s.privKey).toCompact(f,!0,"base64")}},i.signOpReturnWithAIP=function(t,e,r){void 0===e&&(e=""),void 0===r&&(r="hex");var i=this.getAIPMessageBuffer(t),n=this.signMessage(i,e),o=n.address,s=n.signature;return t.concat([Buffer.from("|").toString(r),Buffer.from(b).toString(r),Buffer.from("BITCOIN_ECDSA").toString(r),Buffer.from(o).toString(r),Buffer.from(s,"base64").toString(r)])},i.getAIPMessageBuffer=function(t){var e=[];"6a"!==t[0].replace("0x","")&&e.push(Buffer.from("6a","hex"));for(var r,i=h(t);!(r=i()).done;)e.push(Buffer.from(r.value.replace("0x",""),"hex"));return e.push(Buffer.from("|")),Buffer.concat([].concat(e))},i.getIdSigningKeys=function(){try{return Promise.resolve(this.getApiData("/signing-keys",{idKey:this.identityKey})).then(function(t){return console.log("getIdSigningKeys",t),t})}catch(t){return Promise.reject(t)}},i.getAttributeAttestations=function(t){try{var e=this.getAttestationHash(t);return Promise.resolve(this.getApiData("/attestation/get",{hash:e})).then(function(r){return console.log("getAttestations",t,e,r),r})}catch(t){return Promise.reject(t)}},i.import=function(t){this.idName=t.name,this.description=t.description||"",this.identityKey=t.identityKey,n(this,R)[R]=t.rootPath,this.rootAddress=t.rootAddress,n(this,C)[C]=t.previousPath,n(this,k)[k]=t.currentPath,n(this,H)[H]=t.idSeed||"",this.identityAttributes=this.parseAttributes(t.identityAttributes)},i.export=function(){return{name:this.idName,description:this.description,identityKey:this.identityKey,rootPath:n(this,R)[R],rootAddress:this.rootAddress,previousPath:n(this,C)[C],currentPath:n(this,k)[k],idSeed:n(this,H)[H],identityAttributes:this.getAttributes(),lastIdPath:""}},u(e,[{key:"BAP_SERVER",get:function(){return n(this,D)[D]},set:function(t){n(this,D)[D]=t}},{key:"BAP_TOKEN",get:function(){return n(this,_)[_]},set:function(t){n(this,_)[_]=t}},{key:"rootPath",get:function(){return n(this,R)[R]},set:function(t){if(n(this,T)[T]){var e=t;if(t.split("/").length<5&&(e=""+P+t),!this.validatePath(e))throw new Error("invalid signing path given "+e);n(this,R)[R]=e;var r=n(this,T)[T].derive(e);this.rootAddress=r.pubKey.toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress),n(this,C)[C]=e,n(this,k)[k]=e}}},{key:"currentPath",get:function(){return n(this,k)[k]},set:function(t){var e=t;if(t.split("/").length<5&&(e=""+P+t),!this.validatePath(e))throw new Error("invalid signing path given");n(this,C)[C]=n(this,k)[k],n(this,k)[k]=e}},{key:"previousPath",get:function(){return n(this,C)[C]}},{key:"idSeed",get:function(){return n(this,H)[H]}}])}(),M=t.Utils.toArray,W=t.Utils.toUTF8,V=t.Utils.toBase64,F=t.ECIES.electrumEncrypt,q=t.ECIES.electrumDecrypt,G=/*#__PURE__*/s("HDPrivateKey"),J=/*#__PURE__*/s("ids"),z=/*#__PURE__*/s("BAP_SERVER"),L=/*#__PURE__*/s("BAP_TOKEN"),$=/*#__PURE__*/s("lastIdPath"),Q=/*#__PURE__*/function(){function e(e,r,i){if(void 0===r&&(r=""),void 0===i&&(i=""),Object.defineProperty(this,G,{writable:!0,value:void 0}),Object.defineProperty(this,J,{writable:!0,value:{}}),Object.defineProperty(this,z,{writable:!0,value:m}),Object.defineProperty(this,L,{writable:!0,value:""}),Object.defineProperty(this,$,{writable:!0,value:""}),this.getApiData=void 0,!e)throw new Error("No HDPrivateKey given");n(this,G)[G]=t.HD.fromString(e),r&&(n(this,L)[L]=r),i&&(n(this,z)[z]=i),this.getApiData=B(n(this,z)[z],n(this,L)[L])}var r=e.prototype;return r.getPublicKey=function(t){return void 0===t&&(t=""),t?n(this,G)[G].derive(t).pubKey.toString():n(this,G)[G].pubKey.toString()},r.getHdPublicKey=function(t){return void 0===t&&(t=""),t?n(this,G)[G].derive(t).toPublic().toString():n(this,G)[G].toPublic().toString()},r.checkIdBelongs=function(t){if(n(this,G)[G].derive(t.rootPath).pubKey.toAddress()!==t.rootAddress)throw new Error("ID does not belong to this private key");return!0},r.listIds=function(){return Object.keys(n(this,J)[J])},r.newId=function(t,e,r){var i;void 0===e&&(e={}),void 0===r&&(r=""),i=t||this.getNextValidPath();var o=new U(n(this,G)[G],e,r);o.BAP_SERVER=n(this,z)[z],o.BAP_TOKEN=n(this,L)[L],o.rootPath=i,o.currentPath=l(i);var s=o.getIdentityKey();return n(this,J)[J][s]=o,n(this,$)[$]=i,n(this,J)[J][s]},r.removeId=function(t){delete n(this,J)[J][t]},r.getNextValidPath=function(){return n(this,$)[$]?function(t){var e=t.split("/"),r=e[e.length-2],i=!1;r.match("'")&&(i=!0);var n=(Number(r.replace(/[^0-9]/g,""))+1).toString();return e[e.length-2]=n+(i?"'":""),e[e.length-1]="0"+(i?"'":""),e.join("/")}(n(this,$)[$]):"/0'/"+Object.keys(n(this,J)[J]).length+"'/0'"},r.getId=function(t){return n(this,J)[J][t]||null},r.setId=function(t){this.checkIdBelongs(t),n(this,J)[J][t.getIdentityKey()]=t},r.importIds=function(t,e){if(void 0===e&&(e=!0),e&&"string"==typeof t)this.importEncryptedIds(t);else{var r=t;if(!r.lastIdPath)throw new Error("ID cannot be imported as it is not complete");if(!r.ids)throw new Error("ID data is not in the correct format: "+t);for(var i,o=t.lastIdPath,s=h(r.ids);!(i=s()).done;){var a=i.value;if(!a.identityKey||!a.identityAttributes||!a.rootAddress)throw new Error("ID cannot be imported as it is not complete");var u=new U(n(this,G)[G],{},a.idSeed);u.BAP_SERVER=n(this,z)[z],u.BAP_TOKEN=n(this,L)[L],u.import(a),""===o&&(o=u.currentPath),this.checkIdBelongs(u),n(this,J)[J][u.getIdentityKey()]=u}n(this,$)[$]=o}},r.importEncryptedIds=function(t){var e=this.decrypt(t),r=JSON.parse(e);if(Array.isArray(r))return console.log("Importing old format:\n",r),void this.importOldIds(r);if("object"!=typeof r)throw new Error("decrypted, but found unrecognized identities format");this.importIds(r,!1)},r.importOldIds=function(t){for(var e,r=h(t);!(e=r()).done;){var i=e.value,o=new U(n(this,G)[G],{},i.idSeed);o.BAP_SERVER=n(this,z)[z],o.BAP_TOKEN=n(this,L)[L],o.import(i),this.checkIdBelongs(o),n(this,J)[J][o.getIdentityKey()]=o,n(this,$)[$]=o.currentPath}},r.exportIds=function(t){void 0===t&&(t=!0);var e={lastIdPath:n(this,$)[$],ids:[]};for(var r in n(this,J)[J])e.ids.push(n(this,J)[J][r].export());return t?this.encrypt(JSON.stringify(e)):e},r.encrypt=function(t){var e=n(this,G)[G].derive(S);return V(F(M(t),e.pubKey,null))},r.decrypt=function(t){var e=n(this,G)[G].derive(S);return W(q(M(t,"base64"),e.privKey))},r.signAttestationWithAIP=function(t,e,r,i){void 0===r&&(r=0),void 0===i&&(i="");var n=this.getId(e);if(!n)throw new Error("Could not find identity to attest with");var o=this.getAttestationBuffer(t,r,i),s=n.signMessage(o);return this.createAttestationTransaction(t,r,s.address,s.signature,i)},r.verifyAttestationWithAIP=function(t){if(!Array.isArray(t)||"0x6a"!==t[0]||t[1]!==p)throw new Error("Not a valid BAP transaction");var e="0x44415441"===t[7]?5:0,r={type:v(t[2]),hash:v(t[3]),sequence:v(t[4]),signingProtocol:v(t[7+e]),signingAddress:v(t[8+e]),signature:v(t[9+e],"base64")};e&&t[3]===t[8]&&(r.data=v(t[9]));try{for(var i=[],n=0;n<6+e;n++)i.push(Buffer.from(t[n].replace("0x",""),"hex"));var o=Buffer.concat([].concat(i));r.verified=this.verifySignature(o,r.signingAddress,r.signature)}catch(t){r.verified=!1}return r},r.createAttestationTransaction=function(t,e,r,i,n){void 0===n&&(n="");var o=["0x6a",d(g)];return o.push(d("ATTEST")),o.push(d(t)),o.push(d(""+e)),o.push("0x7c"),n&&(o.push(d(g)),o.push(d("DATA")),o.push(d(t)),o.push(d(n)),o.push("0x7c")),o.push(d(b)),o.push(d("BITCOIN_ECDSA")),o.push(d(r)),o.push("0x"+Buffer.from(i,"base64").toString("hex")),o},r.getAttestationBuffer=function(t,e,r){void 0===e&&(e=0),void 0===r&&(r="");var i=Buffer.from("");return r&&(i=Buffer.concat([Buffer.from(g),Buffer.from("DATA"),Buffer.from(t),Buffer.from(r),Buffer.from("7c","hex")])),Buffer.concat([Buffer.from("6a","hex"),Buffer.from(g),Buffer.from("ATTEST"),Buffer.from(t),Buffer.from(""+e),Buffer.from("7c","hex"),i])},r.verifySignature=function(e,r,i){for(var n,o=Buffer.isBuffer(e)?e:Buffer.from(e),s=t.Signature.fromCompact(i,"base64"),a=M(o.toString("hex"),"hex"),u=0;u<4;u++)try{if(n=s.RecoverPublicKey(u,new t.BigNumber(t.BSM.magicHash(a))),t.BSM.verify(a,s,n)&&n.toAddress()===r)return!0}catch(t){}return!1},r.verifyChallengeSignature=function(t,e,r,i){try{var n,o=this,s=function(){if(o.verifySignature(r,e,i))return Promise.resolve(o.getApiData("/attestation/valid",{idKey:t,challenge:r,signature:i})).then(function(t){return n=1,!!t&&t.valid})}();return Promise.resolve(s&&s.then?s.then(function(t){return!!n&&t}):!!n&&s)}catch(t){return Promise.reject(t)}},r.isValidAttestationTransaction=function(t){try{return this.verifyAttestationWithAIP(t)?Promise.resolve(this.getApiData("/attestation/valid",{tx:t})):Promise.resolve(!1)}catch(t){return Promise.reject(t)}},r.getIdentityFromAddress=function(t){try{return Promise.resolve(this.getApiData("/identity/from-address",{address:t}))}catch(t){return Promise.reject(t)}},r.getIdentity=function(t){try{return Promise.resolve(this.getApiData("/identity",{idKey:t}))}catch(t){return Promise.reject(t)}},r.getAttestationsForHash=function(t){try{return Promise.resolve(this.getApiData("/attestations",{hash:t}))}catch(t){return Promise.reject(t)}},u(e,[{key:"lastIdPath",get:function(){return n(this,$)[$]}},{key:"BAP_SERVER",get:function(){return n(this,z)[z]},set:function(t){for(var e in n(this,z)[z]=t,n(this,J)[J])n(this,J)[J][e].BAP_SERVER=t}},{key:"BAP_TOKEN",get:function(){return n(this,L)[L]},set:function(t){for(var e in n(this,L)[L]=t,n(this,J)[J])n(this,J)[J][e].BAP_TOKEN=t}}])}();exports.BAP=Q,exports.BAP_ID=U;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/utils.ts","../src/constants.ts","../src/index.ts","../src/id.ts"],"sourcesContent":["import randomBytes from \"randombytes\";\nimport type {PathPrefix} from \"./interface\";\n\nexport const Utils = {\n /**\n * Helper function for encoding strings to hex\n *\n * @param string\n * @returns {string}\n */\n hexEncode(string: string) {\n return `0x${Buffer.from(string).toString('hex')}`;\n },\n\n /**\n * Helper function for encoding strings to hex\n *\n * @param hexString string\n * @param encoding BufferEncoding\n * @returns {string}\n */\n hexDecode(hexString: string, encoding: BufferEncoding = 'utf8') {\n return Buffer.from(hexString.replace('0x', ''), 'hex').toString(encoding);\n },\n\n /**\n * Helper function to generate a random nonce\n *\n * @returns {string}\n */\n getRandomString(length = 32) {\n return randomBytes(length).toString('hex');\n },\n\n /**\n * Test whether the given string is hex\n *\n * @param value any\n * @returns {boolean}\n */\n isHex(value: string): boolean {\n if (typeof value !== 'string') {\n return false;\n }\n return /^[0-9a-fA-F]+$/.test(value);\n },\n\n /**\n * Get a signing path from a hex number\n *\n * @param hexString {string}\n * @param hardened {boolean} Whether to return a hardened path\n * @returns {string}\n */\n getSigningPathFromHex(hexString: string, hardened = true) {\n // \"m/0/0/1\"\n let signingPath = 'm';\n const signingHex = hexString.match(/.{1,8}/g);\n if (!signingHex) {\n throw new Error('Invalid hex string');\n }\n const maxNumber = 2147483648 - 1; // 0x80000000\n for (const hexNumber of signingHex) {\n let number = Number(`0x${hexNumber}`);\n if (number > maxNumber) number -= maxNumber;\n signingPath += `/${number}${(hardened ? \"'\" : '')}`;\n }\n\n return signingPath;\n },\n\n /**\n * Increment that second to last part from the given part, set the last part to 0\n *\n * @param path string\n * @returns {*}\n */\n getNextIdentityPath(path: string): PathPrefix {\n const pathValues = path.split('/');\n const secondToLastPart = pathValues[pathValues.length - 2];\n\n let hardened = false;\n if (secondToLastPart.match('\\'')) {\n hardened = true;\n }\n\n const nextPath = (Number(secondToLastPart.replace(/[^0-9]/g, '')) + 1).toString();\n pathValues[pathValues.length - 2] = nextPath + (hardened ? '\\'' : '');\n pathValues[pathValues.length - 1] = `0${hardened ? '\\'' : ''}`;\n\n return pathValues.join('/') as PathPrefix;\n },\n\n /**\n * Increment that last part of the given path\n *\n * @param path string\n * @returns {*}\n */\n getNextPath(path: string) {\n const pathValues = path.split('/');\n const lastPart = pathValues[pathValues.length - 1];\n let hardened = false;\n if (lastPart.match('\\'')) {\n hardened = true;\n }\n const nextPath = (Number(lastPart.replace(/[^0-9]/g, '')) + 1).toString();\n pathValues[pathValues.length - 1] = nextPath + (hardened ? '\\'' : '');\n return pathValues.join('/');\n },\n};\n","export const BAP_BITCOM_ADDRESS = '1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT';\nexport const BAP_BITCOM_ADDRESS_HEX = `0x${Buffer.from(BAP_BITCOM_ADDRESS).toString('hex')}`;\nexport const AIP_BITCOM_ADDRESS = '15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva';\nexport const AIP_BITCOM_ADDRESS_HEX = `0x${Buffer.from(AIP_BITCOM_ADDRESS).toString('hex')}`;\nexport const BAP_SERVER = 'https://api.sigmaidentity.com/api/v1';\nexport const MAX_INT = 2147483648 - 1; // 0x80000000\n\n// This is just a choice for this library and could be anything else if so needed/wanted\n// but it is advisable to use the same derivation between libraries for compatibility\nexport const SIGNING_PATH_PREFIX = 'm/424150\\'/0\\'/0\\''; // BAP in hex\nexport const ENCRYPTION_PATH = `m/424150'/${MAX_INT}'/${MAX_INT}'`;\n","import { BigNumber, BSM, HD, type PublicKey, Signature, ECIES } from \"@bsv/sdk\";\n\nimport { Utils } from \"./utils\";\nimport { BAP_ID } from \"./id\";\nimport {\n\tENCRYPTION_PATH,\n\tBAP_SERVER,\n\tBAP_BITCOM_ADDRESS,\n\tBAP_BITCOM_ADDRESS_HEX,\n\tAIP_BITCOM_ADDRESS,\n} from \"./constants\";\nimport type { Attestation, Identity, IdentityAttributes, PathPrefix } from \"./interface\";\nimport { Utils as BSVUtils } from \"@bsv/sdk\";\nimport { PrivateKey } from \"@bsv/sdk\";\nconst { toArray, toUTF8, toBase64 } = BSVUtils;\nconst { electrumEncrypt, electrumDecrypt } = ECIES;\n\ntype Identities = { lastIdPath: string; ids: Identity[] };\n\n/**\n * BAP class\n *\n * Creates an instance of the BAP class and uses the given HDPrivateKey for all BAP operations.\n *\n * @param HDPrivateKey\n */\nexport const BAP = class {\n\t#HDPrivateKey;\n\t#ids: { [key: string]: BAP_ID } = {};\n\t#BAP_SERVER = BAP_SERVER;\n\t#BAP_TOKEN = \"\";\n\t#lastIdPath = \"\";\n\n\tconstructor(HDPrivateKey: string, token = \"\") {\n\t\tif (!HDPrivateKey) {\n\t\t\tthrow new Error(\"No HDPrivateKey given\");\n\t\t}\n\t\tthis.#HDPrivateKey = HD.fromString(HDPrivateKey);\n\n\t\tif (token) {\n\t\t\tthis.#BAP_TOKEN = token;\n\t\t}\n\t}\n\n\tget lastIdPath(): string {\n\t\treturn this.#lastIdPath;\n\t}\n\n\t/**\n\t * Get the public key of the given childPath, or of the current HDPrivateKey of childPath is empty\n\t *\n\t * @param childPath Full derivation path for this child\n\t * @returns {*}\n\t */\n\tgetPublicKey(childPath = \"\"): string {\n\t\tif (childPath) {\n\t\t\treturn this.#HDPrivateKey.derive(childPath).pubKey.toString();\n\t\t}\n\n\t\treturn this.#HDPrivateKey.pubKey.toString();\n\t}\n\n\t/**\n\t * Get the public key of the given childPath, or of the current HDPrivateKey of childPath is empty\n\t *\n\t * @param childPath Full derivation path for this child\n\t * @returns {*}\n\t */\n\tgetHdPublicKey(childPath = \"\"): string {\n\t\tif (childPath) {\n\t\t\treturn this.#HDPrivateKey.derive(childPath).toPublic().toString();\n\t\t}\n\n\t\treturn this.#HDPrivateKey.toPublic().toString();\n\t}\n\n\tset BAP_SERVER(bapServer) {\n\t\tthis.#BAP_SERVER = bapServer;\n\t\tfor (const key of Object.keys(this.#ids)) {\n\t\t\tthis.#ids[key].BAP_SERVER = bapServer;\n\t\t}\n\t}\n\n\tget BAP_SERVER(): string {\n\t\treturn this.#BAP_SERVER;\n\t}\n\n\tset BAP_TOKEN(token) {\n\t\tthis.#BAP_TOKEN = token;\n\t\tfor (const key of Object.keys(this.#ids)) {\n\t\t\t// @ts-ignore - does not recognize private fields that can be set\n\t\t\tthis.#ids[key].BAP_TOKEN = token;\n\t\t}\n\t}\n\n\tget BAP_TOKEN(): string {\n\t\treturn this.#BAP_TOKEN;\n\t}\n\n\t/**\n\t * This function verifies that the given bapId matches the given root address\n\t * This is used as a data integrity check\n\t *\n\t * @param bapId BAP_ID instance\n\t */\n\tcheckIdBelongs(bapId: BAP_ID): boolean {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(bapId.rootPath);\n\t\tconst checkRootAddress = derivedChild.pubKey.toAddress();\n\t\tif (checkRootAddress !== bapId.rootAddress) {\n\t\t\tthrow new Error(\"ID does not belong to this private key\");\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns a list of all the identity keys that are stored in this instance\n\t *\n\t * @returns {string[]}\n\t */\n\tlistIds(): string[] {\n\t\treturn Object.keys(this.#ids);\n\t}\n\n\t/**\n\t * Create a new Id and link it to this BAP instance\n\t *\n\t * This function uses the length of the #ids of this class to determine the next valid path.\n\t * If not all ids related to this HDPrivateKey have been loaded, determine the path externally\n\t * and pass it to newId when creating a new ID.\n\t *\n\t * @param path\n\t * @param identityAttributes\n\t * @param idSeed\n\t * @returns {*}\n\t */\n\tnewId(path?: string, identityAttributes: IdentityAttributes = {}, idSeed = \"\"): BAP_ID {\n let pathToUse: string;\n\t\tif (!path) {\n\t\t\t// get next usable path for this key\n\t\t\tpathToUse = this.getNextValidPath();\n\t\t} else {\n pathToUse = path;\n }\n\n\t\tconst newIdentity = new BAP_ID(\n\t\t\tthis.#HDPrivateKey,\n\t\t\tidentityAttributes,\n\t\t\tidSeed,\n\t\t);\n\t\tnewIdentity.BAP_SERVER = this.#BAP_SERVER;\n\t\tnewIdentity.BAP_TOKEN = this.#BAP_TOKEN;\n\n\t\tnewIdentity.rootPath = pathToUse;\n\t\tnewIdentity.currentPath = Utils.getNextPath(pathToUse);\n\n\t\tconst idKey = newIdentity.getIdentityKey();\n\t\tthis.#ids[idKey] = newIdentity;\n\t\tthis.#lastIdPath = pathToUse;\n\n\t\treturn this.#ids[idKey];\n\t}\n\n\t/**\n\t * Remove identity\n\t *\n\t * @param idKey\n\t * @returns {*}\n\t */\n\tremoveId(idKey: string): void {\n\t\tdelete this.#ids[idKey];\n\t}\n\n\t/**\n\t * Get the next valid path for the used HDPrivateKey and loaded #ids\n\t *\n\t * @returns {string}\n\t */\n\tgetNextValidPath(): PathPrefix {\n\t\t// prefer hardened paths\n\t\tif (this.#lastIdPath) {\n\t\t\treturn Utils.getNextIdentityPath(this.#lastIdPath);\n\t\t}\n\n\t\treturn `/0'/${Object.keys(this.#ids).length}'/0'`;\n\t}\n\n\t/**\n\t * Get a certain Id\n\t *\n\t * @param identityKey\n\t * @returns {null}\n\t */\n\tgetId(identityKey: string): BAP_ID | null {\n\t\treturn this.#ids[identityKey] || null;\n\t}\n\n\t/**\n\t * This function is used when manipulating ID's, adding or removing attributes etc\n\t * First create an id through this class and then use getId to get it. Then you can add/edit or\n\t * increment the signing path and then re-set it with this function.\n\t *\n\t * Note: when you getId() from this class, you will be working on the same object as this class\n\t * has and any changes made will be propagated to the id in this class. When you call exportIds\n\t * your new changes will also be included, without having to setId().\n\t *\n\t * @param bapId\n\t */\n\tsetId(bapId: BAP_ID): void {\n\t\tthis.checkIdBelongs(bapId);\n\t\tthis.#ids[bapId.getIdentityKey()] = bapId;\n\t}\n\n\t/**\n\t * This function is used to import IDs and attributes from some external storage\n\t *\n\t * The ID information should NOT be stored together with the HD private key !\n\t *\n\t * @param idData Array of ids that have been exported\n\t * @param encrypted Whether the data should be treated as being encrypted (default true)\n\t */\n\timportIds(idData: Identities | string, encrypted = true): void {\n\t\tif (encrypted && typeof idData === \"string\") {\n\t\t\tthis.importEncryptedIds(idData);\n\t\t\treturn;\n\t\t}\n const identity = idData as Identities\n if (!identity.lastIdPath) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n\n if (!identity.ids) {\n throw new Error(`ID data is not in the correct format: ${idData}`);\n }\n \n\t\tlet lastIdPath = (idData as Identities).lastIdPath;\n\t\tfor (const id of identity.ids) {\n\t\t\tif (!id.identityKey || !id.identityAttributes || !id.rootAddress) {\n\t\t\t\tthrow new Error(\"ID cannot be imported as it is not complete\");\n\t\t\t}\n\t\t\tconst importId = new BAP_ID(this.#HDPrivateKey, {}, id.idSeed);\n\t\t\timportId.BAP_SERVER = this.#BAP_SERVER;\n\t\t\timportId.BAP_TOKEN = this.#BAP_TOKEN;\n\t\t\timportId.import(id);\n if (lastIdPath === \"\") {\n lastIdPath = importId.currentPath;\n }\n\n\t\t\tthis.checkIdBelongs(importId);\n\t\t\tthis.#ids[importId.getIdentityKey()] = importId;\n\t\t}\n\n\t\tthis.#lastIdPath = lastIdPath;\n\t}\n \n\timportEncryptedIds(idData: string): void {\n\t\t// decrypt the ids array using ECIES\n const decrypted = this.decrypt(idData);\n\t\tconst ids = JSON.parse(decrypted) as Identities;\n \n const isOldFormat = Array.isArray(ids)\n if (isOldFormat) {\n console.log(\"Importing old format:\\n\", ids)\n this.importOldIds(ids)\n return\n }\n if (typeof ids !== \"object\") {\n throw new Error(\"decrypted, but found unrecognized identities format\")\n }\n\t\tthis.importIds(ids, false);\n\t}\n\n\timportOldIds(idData: Identity[]): void {\n\t\tfor (const id of idData) {\n\t\t\tconst importId = new BAP_ID(this.#HDPrivateKey, {}, id.idSeed);\n\t\t\timportId.BAP_SERVER = this.#BAP_SERVER;\n\t\t\timportId.BAP_TOKEN = this.#BAP_TOKEN;\n\t\t\timportId.import(id);\n\n\t\t\tthis.checkIdBelongs(importId);\n\n\t\t\tthis.#ids[importId.getIdentityKey()] = importId;\n\n\t\t\t// overwrite with the last value on this array\n\t\t\tthis.#lastIdPath = importId.currentPath;\n\t\t}\n\t}\n\t/**\n\t * Export all the IDs of this instance for external storage\n\t *\n\t * By default this function will encrypt the data, using a derivative child of the main HD key\n\t *\n\t * @param encrypted Whether the data should be encrypted (default true)\n\t * @returns {[]|*}\n\t */\n\texportIds(encrypted = true): Identities | string {\n\t\tconst idData: Identities = {\n\t\t\tlastIdPath: this.#lastIdPath,\n\t\t\tids: [] as Identity[],\n\t\t};\n\n\t\tfor (const key of Object.keys(this.#ids)) {\n\t\t\tidData.ids.push(this.#ids[key].export());\n\t\t}\n\n\t\tif (encrypted) {\n\t\t\treturn this.encrypt(JSON.stringify(idData));\n\t\t}\n\n\t\treturn idData \n\t}\n\n\t/**\n\t * Encrypt a string of data\n\t *\n\t * @param string\n\t * @returns {string}\n\t */\n\tencrypt(string: string): string {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n\t\treturn toBase64(\n // @ts-ignore - you can remove the null when this is merged https://github.com/bitcoin-sv/ts-sdk/pull/123\n\t\t\telectrumEncrypt(toArray(string), derivedChild.pubKey, null),\n\t\t);\n\t}\n\n\t/**\n\t * Decrypt a string of data\n\t *\n\t * @param string\n\t * @returns {string}\n\t */\n\tdecrypt(string: string): string {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n\t\treturn toUTF8(\n\t\t\telectrumDecrypt(toArray(string, \"base64\"), derivedChild.privKey),\n\t\t);\n\t}\n\n\t/**\n\t * Sign an attestation for a user\n\t *\n\t * @param attestationHash The computed attestation hash for the user - this should be calculated with the BAP_ID class for an identity for the user\n\t * @param identityKey The identity key we are using for the signing\n\t * @param counter\n\t * @param dataString Optional data string that will be appended to the BAP attestation\n\t * @returns {string[]}\n\t */\n\tsignAttestationWithAIP(\n\t\tattestationHash: string,\n\t\tidentityKey: string,\n\t\tcounter = 0,\n\t\tdataString = \"\",\n\t) {\n\t\tconst id = this.getId(identityKey);\n\t\tif (!id) {\n\t\t\tthrow new Error(\"Could not find identity to attest with\");\n\t\t}\n\n\t\tconst attestationBuffer = this.getAttestationBuffer(\n\t\t\tattestationHash,\n\t\t\tcounter,\n\t\t\tdataString,\n\t\t);\n\t\tconst { address, signature } = id.signMessage(attestationBuffer);\n\n\t\treturn this.createAttestationTransaction(\n\t\t\tattestationHash,\n\t\t\tcounter,\n\t\t\taddress,\n\t\t\tsignature,\n\t\t\tdataString,\n\t\t);\n\t}\n\n\t/**\n\t * Verify an AIP signed attestation for a user\n\t *\n\t * [\n\t * '0x6a',\n\t * '0x31424150537561506e66476e53424d33474c56397968785564596534764762644d54',\n\t * '0x415454455354',\n\t * '0x33656166366361396334313936356538353831366439336439643034333136393032376633396661623034386333633031333663343364663635376462383761',\n\t * '0x30',\n\t * '0x7c',\n\t * '0x313550636948473232534e4c514a584d6f5355615756693757537163376843667661',\n\t * '0x424954434f494e5f4543445341',\n\t * '0x31477531796d52567a595557634638776f6f506a7a4a4c764d383550795a64655876',\n\t * '0x20ef60c5555001ddb1039bb0f215e46571fcb39ee46f48b089d1c08b0304dbcb3366d8fdf8bafd82be24b5ac42dcd6a5e96c90705dd42e3ad918b1b47ac3ce6ac2'\n\t * ]\n\t *\n\t * @param tx Array of hex values for the OP_RETURN values\n\t * @returns {{}}\n\t */\n\tverifyAttestationWithAIP(tx: string[]): Attestation {\n\t\tif (\n\t\t\t!Array.isArray(tx) ||\n\t\t\ttx[0] !== \"0x6a\" ||\n\t\t\ttx[1] !== BAP_BITCOM_ADDRESS_HEX\n\t\t) {\n\t\t\tthrow new Error(\"Not a valid BAP transaction\");\n\t\t}\n\n\t\tconst dataOffset = tx[7] === \"0x44415441\" ? 5 : 0; // DATA\n\t\tconst attestation: Attestation = {\n\t\t\ttype: Utils.hexDecode(tx[2]),\n\t\t\thash: Utils.hexDecode(tx[3]),\n\t\t\tsequence: Utils.hexDecode(tx[4]),\n\t\t\tsigningProtocol: Utils.hexDecode(tx[7 + dataOffset]),\n\t\t\tsigningAddress: Utils.hexDecode(tx[8 + dataOffset]),\n\t\t\tsignature: Utils.hexDecode(tx[9 + dataOffset], \"base64\"),\n\t\t};\n\n\t\tif (dataOffset && tx[3] === tx[8]) {\n\t\t\t// valid data addition\n\t\t\tattestation.data = Utils.hexDecode(tx[9]);\n\t\t}\n\n\t\ttry {\n\t\t\tconst signatureBufferStatements = [];\n\t\t\tfor (let i = 0; i < 6 + dataOffset; i++) {\n\t\t\t\tsignatureBufferStatements.push(\n\t\t\t\t\tBuffer.from(tx[i].replace(\"0x\", \"\"), \"hex\"),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst attestationBuffer = Buffer.concat([...signatureBufferStatements]);\n\t\t\tattestation.verified = this.verifySignature(\n\t\t\t\tattestationBuffer,\n\t\t\t\tattestation.signingAddress,\n\t\t\t\tattestation.signature,\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tattestation.verified = false;\n\t\t}\n\n\t\treturn attestation;\n\t}\n\n\t/**\n\t * For BAP attestations we use all fields for the attestation\n\t *\n\t * @param attestationHash\n\t * @param counter\n\t * @param address\n\t * @param signature\n\t * @param dataString Optional data string that will be appended to the BAP attestation\n\t * @returns {[string]}\n\t */\n\tcreateAttestationTransaction(\n\t\tattestationHash: string,\n\t\tcounter: number,\n\t\taddress: string,\n\t\tsignature: string,\n\t\tdataString = \"\",\n\t): string[] {\n\t\tconst transaction = [\"0x6a\", Utils.hexEncode(BAP_BITCOM_ADDRESS)];\n\t\ttransaction.push(Utils.hexEncode(\"ATTEST\"));\n\t\ttransaction.push(Utils.hexEncode(attestationHash));\n\t\ttransaction.push(Utils.hexEncode(`${counter}`));\n\t\ttransaction.push(\"0x7c\"); // |\n\t\tif (dataString) {\n\t\t\t// data should be a string, either encrypted or stringified JSON if applicable\n\t\t\ttransaction.push(Utils.hexEncode(BAP_BITCOM_ADDRESS));\n\t\t\ttransaction.push(Utils.hexEncode(\"DATA\"));\n\t\t\ttransaction.push(Utils.hexEncode(attestationHash));\n\t\t\ttransaction.push(Utils.hexEncode(dataString));\n\t\t\ttransaction.push(\"0x7c\"); // |\n\t\t}\n\t\ttransaction.push(Utils.hexEncode(AIP_BITCOM_ADDRESS));\n\t\ttransaction.push(Utils.hexEncode(\"BITCOIN_ECDSA\"));\n\t\ttransaction.push(Utils.hexEncode(address));\n\t\ttransaction.push(`0x${Buffer.from(signature, \"base64\").toString(\"hex\")}`);\n\n\t\treturn transaction;\n\t}\n\n\t/**\n\t * This is a re-creation of how the bitcoinfiles-sdk creates a hash to sign for AIP\n\t *\n\t * @param attestationHash\n\t * @param counter\n\t * @param dataString Optional data string\n\t * @returns {Buffer}\n\t */\n\tgetAttestationBuffer(\n\t\tattestationHash: string,\n\t\tcounter = 0,\n\t\tdataString = \"\",\n\t): Buffer {\n\t\t// re-create how AIP creates the buffer to sign\n\t\tlet dataStringBuffer = Buffer.from(\"\");\n\t\tif (dataString) {\n\t\t\tdataStringBuffer = Buffer.concat([\n\t\t\t\tBuffer.from(BAP_BITCOM_ADDRESS),\n\t\t\t\tBuffer.from(\"DATA\"),\n\t\t\t\tBuffer.from(attestationHash),\n\t\t\t\tBuffer.from(dataString),\n\t\t\t\tBuffer.from(\"7c\", \"hex\"),\n\t\t\t]);\n\t\t}\n\t\treturn Buffer.concat([\n\t\t\tBuffer.from(\"6a\", \"hex\"), // OP_RETURN\n\t\t\tBuffer.from(BAP_BITCOM_ADDRESS),\n\t\t\tBuffer.from(\"ATTEST\"),\n\t\t\tBuffer.from(attestationHash),\n\t\t\tBuffer.from(`${counter}`),\n\t\t\tBuffer.from(\"7c\", \"hex\"),\n\t\t\tdataStringBuffer,\n\t\t]);\n\t}\n\n\t/**\n\t * Verify that the identity challenge is signed by the address\n\t *\n\t * @param message Buffer or utf-8 string\n\t * @param address Bitcoin address of signee\n\t * @param signature Signature base64 string\n\t *\n\t * @return boolean\n\t */\n\tverifySignature(\n\t\tmessage: string | Buffer,\n\t\taddress: string,\n\t\tsignature: string,\n\t): boolean {\n\t\t// check the signature against the challenge\n\t\tconst messageBuffer = Buffer.isBuffer(message)\n\t\t\t? message\n\t\t\t: Buffer.from(message);\n\t\tconst sig = Signature.fromCompact(signature, \"base64\");\n\t\tlet publicKey: PublicKey | undefined;\n\t\tconst msg = toArray(messageBuffer.toString(\"hex\"), \"hex\");\n\t\tfor (let recovery = 0; recovery < 4; recovery++) {\n\t\t\ttry {\n\t\t\t\tpublicKey = sig.RecoverPublicKey(\n\t\t\t\t\trecovery,\n\t\t\t\t\tnew BigNumber(BSM.magicHash(msg)),\n\t\t\t\t);\n\t\t\t\tconst sigFitsPubkey = BSM.verify(msg, sig, publicKey);\n\t\t\t\tif (sigFitsPubkey && publicKey.toAddress() === address) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\t// try next recovery\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Check whether the given transaction (BAP OP_RETURN) is valid, is signed and that the\n\t * identity signing is also valid at the time of signing\n\t *\n\t * @param idKey\n\t * @param address\n\t * @param challenge\n\t * @param signature\n\t *\n\t * @returns {Promise<boolean|*>}\n\t */\n\tasync verifyChallengeSignature(\n\t\tidKey: string,\n\t\taddress: string,\n\t\tchallenge: string,\n\t\tsignature: string,\n\t): Promise<boolean> {\n\t\t// first we test locally before sending to server\n\t\tif (this.verifySignature(challenge, address, signature)) {\n\t\t\tconst result = await this.getApiData(\"/attestation/valid\", {\n\t\t\t\tidKey,\n\t\t\t\tchallenge,\n\t\t\t\tsignature,\n\t\t\t});\n\t\t\treturn result.data;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Check whether the given transaction (BAP OP_RETURN) is valid, is signed and that the\n\t * identity signing is also valid at the time of signing\n\t *\n\t * @param tx\n\t * @returns {Promise<boolean|*>}\n\t */\n\tasync isValidAttestationTransaction(tx: string[]): Promise<any> {\n\t\t// first we test locally before sending to server\n\t\tif (this.verifyAttestationWithAIP(tx)) {\n\t\t\treturn this.getApiData(\"/attestation/valid\", {\n\t\t\t\ttx,\n\t\t\t});\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Get all signing keys for the given idKey\n\t *\n\t * @param address\n\t * @returns {Promise<*>}\n\t */\n\tasync getIdentityFromAddress(address: string): Promise<any> {\n\t\treturn this.getApiData(\"/identity/from-address\", {\n\t\t\taddress,\n\t\t});\n\t}\n\n\t/**\n\t * Get all signing keys for the given idKey\n\t *\n\t * @param idKey\n\t * @returns {Promise<*>}\n\t */\n\tasync getIdentity(idKey: string): Promise<any> {\n\t\treturn this.getApiData(\"/identity\", {\n\t\t\tidKey,\n\t\t});\n\t}\n\n\t/**\n\t * Get all attestations for the given attestation hash\n\t *\n\t * @param attestationHash\n\t */\n\tasync getAttestationsForHash(attestationHash: string): Promise<any> {\n\t\t// get all BAP ATTEST records for the given attestationHash\n\t\treturn this.getApiData(\"/attestations\", {\n\t\t\thash: attestationHash,\n\t\t});\n\t}\n\n\t/**\n\t * Helper function to get attestation from a BAP API server\n\t *\n\t * @param apiUrl\n\t * @param apiData\n\t * @returns {Promise<any>}\n\t */\n\tasync getApiData(apiUrl: string, apiData: any): Promise<any> {\n\t\tconst url = `${this.#BAP_SERVER}${apiUrl}`;\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"post\",\n\t\t\theaders: {\n\t\t\t\t\"Content-type\": \"application/json; charset=utf-8\",\n\t\t\t\ttoken: this.#BAP_TOKEN,\n\t\t\t\tformat: \"json\",\n\t\t\t},\n\t\t\tbody: JSON.stringify(apiData),\n\t\t});\n\n\t\treturn response.json();\n\t}\n};\n","import { BSM, Hash, type HD, ECIES, PublicKey, BigNumber } from \"@bsv/sdk\";\nimport {\n\tMAX_INT,\n\tSIGNING_PATH_PREFIX,\n\tBAP_SERVER,\n\tBAP_BITCOM_ADDRESS,\n\tAIP_BITCOM_ADDRESS,\n\tENCRYPTION_PATH,\n} from \"./constants\";\nimport { Utils } from \"./utils\";\nimport type {\n\tIdentity,\n\tIdentityAttribute,\n\tIdentityAttributes,\n} from \"./interface\";\nimport { Utils as BSVUtils } from \"@bsv/sdk\";\nconst { toArray, toHex, toBase58, toUTF8, toBase64 } = BSVUtils;\nconst { electrumDecrypt, electrumEncrypt } = ECIES;\nconst { magicHash } = BSM;\n/**\n * BAP_ID class\n *\n * This class should be used in conjunction with the BAP class\n *\n * @type {BAP_ID}\n */\nclass BAP_ID {\n\t#HDPrivateKey: HD;\n\t#BAP_SERVER: string = BAP_SERVER;\n\t#BAP_TOKEN = \"\";\n\t#rootPath: string;\n\t#previousPath: string;\n\t#currentPath: string;\n\t#idSeed: string;\n\n\tidName: string;\n\tdescription: string;\n\n\trootAddress: string;\n\tidentityKey: string;\n\tidentityAttributes: IdentityAttributes;\n\n\tconstructor(\n\t\tHDPrivateKey: HD,\n\t\tidentityAttributes: IdentityAttributes = {},\n\t\tidSeed = \"\",\n\t) {\n\t\tthis.#idSeed = idSeed;\n\t\tif (idSeed) {\n\t\t\t// create a new HDPrivateKey based on the seed\n\t\t\tconst seedHex = toHex(Hash.sha256(idSeed, \"utf8\"));\n\t\t\tconst seedPath = Utils.getSigningPathFromHex(seedHex);\n\t\t\tthis.#HDPrivateKey = HDPrivateKey.derive(seedPath);\n\t\t} else {\n\t\t\tthis.#HDPrivateKey = HDPrivateKey;\n\t\t}\n\n\t\tthis.idName = \"ID 1\";\n\t\tthis.description = \"\";\n\n\t\tthis.#rootPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n\t\tthis.#previousPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n\t\tthis.#currentPath = `${SIGNING_PATH_PREFIX}/0/0/1`;\n\n\t\tconst rootChild = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tthis.rootAddress = rootChild.privKey.toPublicKey().toAddress();\n\t\tthis.identityKey = this.deriveIdentityKey(this.rootAddress);\n\n\t\t// unlink the object\n\t\tconst attributes = { ...identityAttributes };\n\t\tthis.identityAttributes = this.parseAttributes(attributes);\n\t}\n\n\tset BAP_SERVER(bapServer) {\n\t\tthis.#BAP_SERVER = bapServer;\n\t}\n\n\tget BAP_SERVER(): string {\n\t\treturn this.#BAP_SERVER;\n\t}\n\n\tset BAP_TOKEN(token) {\n\t\tthis.#BAP_TOKEN = token;\n\t}\n\n\tget BAP_TOKEN(): string {\n\t\treturn this.#BAP_TOKEN;\n\t}\n\n\tderiveIdentityKey(address: string): string {\n\t\t// base58( ripemd160 ( sha256 ( rootAddress ) ) )\n\t\tconst rootAddressHash = toHex(Hash.sha256(address, \"utf8\"));\n\n\t\treturn toBase58(Hash.ripemd160(rootAddressHash, \"hex\"));\n\t}\n\n\t/**\n\t * Helper function to parse identity attributes\n\t *\n\t * @param identityAttributes\n\t * @returns {{}}\n\t */\n\tparseAttributes(\n\t\tidentityAttributes: IdentityAttributes | string,\n\t): IdentityAttributes {\n\t\tif (typeof identityAttributes === \"string\") {\n\t\t\treturn this.parseStringUrns(identityAttributes);\n\t\t}\n\n\t\tfor (const key in identityAttributes) {\n\t\t\tif (!identityAttributes[key].value || !identityAttributes[key].nonce) {\n\t\t\t\tthrow new Error(\"Invalid identity attribute\");\n\t\t\t}\n\t\t}\n\n\t\treturn identityAttributes || {};\n\t}\n\n\t/**\n\t * Parse a text of urn string into identity attributes\n\t *\n\t * urn:bap:id:name:John Doe:e2c6fb4063cc04af58935737eaffc938011dff546d47b7fbb18ed346f8c4d4fa\n\t * urn:bap:id:birthday:1990-05-22:e61f23cbbb2284842d77965e2b0e32f0ca890b1894ca4ce652831347ee3596d9\n\t * urn:bap:id:over18:1:480ca17ccaacd671b28dc811332525f2f2cd594d8e8e7825de515ce5d52d30e8\n\t *\n\t * @param urnIdentityAttributes\n\t */\n\tparseStringUrns(urnIdentityAttributes: string): IdentityAttributes {\n\t\tconst identityAttributes: IdentityAttributes = {};\n\t\t// avoid forEach\n\n\t\tconst attributesRaw = urnIdentityAttributes\n\t\t\t.replace(/^\\s+/g, \"\")\n\t\t\t.replace(/\\r/gm, \"\")\n\t\t\t.split(\"\\n\");\n\n\t\tfor (const line of attributesRaw) {\n\t\t\t// remove any whitespace from the string (trim)\n\t\t\tconst attribute = line.replace(/^\\s+/g, \"\").replace(/\\s+$/g, \"\");\n\t\t\tconst urn = attribute.split(\":\");\n\t\t\tif (\n\t\t\t\turn[0] === \"urn\" &&\n\t\t\t\turn[1] === \"bap\" &&\n\t\t\t\turn[2] === \"id\" &&\n\t\t\t\turn[3] &&\n\t\t\t\turn[4] &&\n\t\t\t\turn[5]\n\t\t\t) {\n\t\t\t\tidentityAttributes[urn[3]] = {\n\t\t\t\t\tvalue: urn[4],\n\t\t\t\t\tnonce: urn[5],\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn identityAttributes;\n\t}\n\n\t/**\n\t * Returns the identity key\n\t *\n\t * @returns {*|string}\n\t */\n\tgetIdentityKey(): string {\n\t\treturn this.identityKey;\n\t}\n\n\t/**\n\t * Returns all the attributes in the identity\n\t *\n\t * @returns {*}\n\t */\n\tgetAttributes(): IdentityAttributes {\n\t\treturn this.identityAttributes;\n\t}\n\n\t/**\n\t * Get the value of the given attribute\n\t *\n\t * @param attributeName\n\t * @returns {{}|null}\n\t */\n\tgetAttribute(attributeName: string): IdentityAttribute | null {\n\t\tif (this.identityAttributes[attributeName]) {\n\t\t\treturn this.identityAttributes[attributeName];\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Set the value of the given attribute\n\t *\n\t * If an empty value ('' || null || false) is given, the attribute is removed from the ID\n\t *\n\t * @param attributeName string\n\t * @param attributeValue any\n\t * @returns {{}|null}\n\t */\n\tsetAttribute(attributeName: string, attributeValue: any): void {\n\t\tif (attributeValue) {\n\t\t\tif (this.identityAttributes[attributeName]) {\n\t\t\t\tthis.identityAttributes[attributeName].value = attributeValue;\n\t\t\t} else {\n\t\t\t\tthis.addAttribute(attributeName, attributeValue);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Unset the given attribute from the ID\n\t *\n\t * @param attributeName\n\t * @returns {{}|null}\n\t */\n\tunsetAttribute(attributeName: string): void {\n\t\tdelete this.identityAttributes[attributeName];\n\t}\n\n\t/**\n\t * Get all attribute urn's for this id\n\t *\n\t * @returns {string}\n\t */\n\tgetAttributeUrns(): string {\n\t\tlet urns = \"\";\n\t\tfor (const key in this.identityAttributes) {\n\t\t\tconst urn = this.getAttributeUrn(key);\n\t\t\tif (urn) {\n\t\t\t\turns += `${urn}\\n`;\n\t\t\t}\n\t\t}\n\n\t\treturn urns;\n\t}\n\n\t/**\n\t * Create an return the attribute urn for the given attribute\n\t *\n\t * @param attributeName\n\t * @returns {string|null}\n\t */\n\tgetAttributeUrn(attributeName: string) {\n\t\tconst attribute = this.identityAttributes[attributeName];\n\t\tif (attribute) {\n\t\t\treturn `urn:bap:id:${attributeName}:${attribute.value}:${attribute.nonce}`;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Add an attribute to this identity\n\t *\n\t * @param attributeName\n\t * @param value\n\t * @param nonce\n\t */\n\taddAttribute(attributeName: string, value: any, nonce = \"\"): void {\n\t\tlet nonceToUse = nonce;\n\t\tif (!nonce) {\n\t\t\tnonceToUse = Utils.getRandomString();\n\t\t}\n\n\t\tthis.identityAttributes[attributeName] = {\n\t\t\tvalue,\n\t\t\tnonce: nonceToUse,\n\t\t};\n\t}\n\n\t/**\n\t * This should be called with the last part of the signing path (/.../.../...)\n\t * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file\n\t *\n\t * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9}\n\t */\n\tset rootPath(path: string) {\n\t\tif (this.#HDPrivateKey) {\n\t\t\tlet pathToUse = path;\n\t\t\tif (path.split(\"/\").length < 5) {\n\t\t\t\tpathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n\t\t\t}\n\n\t\t\tif (!this.validatePath(pathToUse)) {\n\t\t\t\tthrow new Error(`invalid signing path given ${pathToUse}`);\n\t\t\t}\n\n\t\t\tthis.#rootPath = pathToUse;\n\n\t\t\tconst derivedChild = this.#HDPrivateKey.derive(pathToUse);\n\t\t\tthis.rootAddress = derivedChild.pubKey.toAddress();\n\t\t\t// Identity keys should be derivatives of the root address - this allows checking\n\t\t\t// of the creation transaction\n\t\t\tthis.identityKey = this.deriveIdentityKey(this.rootAddress);\n\n\t\t\t// we also set this previousPath / currentPath to the root as we seem to be (re)setting this ID\n\t\t\tthis.#previousPath = pathToUse;\n\t\t\tthis.#currentPath = pathToUse;\n\t\t}\n\t}\n\n\tget rootPath(): string {\n\t\treturn this.#rootPath;\n\t}\n\n\tgetRootPath(): string {\n\t\treturn this.#rootPath;\n\t}\n\n\t/**\n\t * This should be called with the last part of the signing path (/.../.../...)\n\t * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file\n\t *\n\t * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9}\n\t */\n\tset currentPath(path) {\n\t\tlet pathToUse = path;\n\t\tif (path.split(\"/\").length < 5) {\n\t\t\tpathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n\t\t}\n\n\t\tif (!this.validatePath(pathToUse)) {\n\t\t\tthrow new Error(\"invalid signing path given\");\n\t\t}\n\n\t\tthis.#previousPath = this.#currentPath;\n\t\tthis.#currentPath = pathToUse;\n\t}\n\n\tget currentPath(): string {\n\t\treturn this.#currentPath;\n\t}\n\n\tget previousPath(): string {\n\t\treturn this.#previousPath;\n\t}\n\n\t/**\n\t * This can be used to break the deterministic way child keys are created to make it harder for\n\t * an attacker to steal the identites when the root key is compromised. This does however require\n\t * the seeds to be stored at all times. If the seed is lost, the identity will not be recoverable.\n\t */\n\tget idSeed(): string {\n\t\treturn this.#idSeed;\n\t}\n\n\t/**\n\t * Increment current path to a new path\n\t *\n\t * @returns {*}\n\t */\n\tincrementPath(): void {\n\t\tthis.currentPath = Utils.getNextPath(this.currentPath);\n\t}\n\n\t/**\n\t * Check whether the given path is a valid path for use with this class\n\t * The signing paths used here always have a length of 3\n\t *\n\t * @param path The last part of the signing path (example \"/0/0/1\")\n\t * @returns {boolean}\n\t */\n\tvalidatePath(path: string) {\n\t\t/* eslint-disable max-len */\n\t\tif (\n\t\t\tpath.match(\n\t\t\t\t/\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?/,\n\t\t\t)\n\t\t) {\n\t\t\tconst pathValues = path.split(\"/\");\n\t\t\tif (\n\t\t\t\tpathValues.length === 7 &&\n\t\t\t\tNumber(pathValues[1].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[2].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[3].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[4].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[5].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[6].replace(\"'\", \"\")) <= MAX_INT\n\t\t\t) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Get the OP_RETURN for the initial ID transaction (signed with root address)\n\t *\n\t * @returns {[]}\n\t */\n\tgetInitialIdTransaction() {\n\t\treturn this.getIdTransaction(this.#rootPath);\n\t}\n\n\t/**\n\t * Get the OP_RETURN for the ID transaction of the current address / path\n\t *\n\t * @returns {[]}\n\t */\n\tgetIdTransaction(previousPath = \"\") {\n\t\tif (this.#currentPath === this.#rootPath) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Current path equals rootPath. ID was probably not initialized properly\",\n\t\t\t);\n\t\t}\n\n\t\tconst opReturn = [\n\t\t\tBuffer.from(BAP_BITCOM_ADDRESS).toString(\"hex\"),\n\t\t\tBuffer.from(\"ID\").toString(\"hex\"),\n\t\t\tBuffer.from(this.identityKey).toString(\"hex\"),\n\t\t\tBuffer.from(this.getCurrentAddress()).toString(\"hex\"),\n\t\t];\n\n\t\treturn this.signOpReturnWithAIP(\n\t\t\topReturn,\n\t\t\tpreviousPath || this.#previousPath,\n\t\t);\n\t}\n\n\t/**\n\t * Get address for given path\n\t *\n\t * @param path\n\t * @returns {*}\n\t */\n\tgetAddress(path: string): string {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(path);\n\t\treturn derivedChild.privKey.toPublicKey().toAddress();\n\t}\n\n\t/**\n\t * Get current signing address\n\t *\n\t * @returns {*}\n\t */\n\tgetCurrentAddress(): string {\n\t\treturn this.getAddress(this.#currentPath);\n\t}\n\n\t/**\n\t * Get the public key for encrypting data for this identity\n\t */\n\tgetEncryptionPublicKey(): string {\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst encryptionKey = HDPrivateKey.derive(ENCRYPTION_PATH).privKey;\n\t\t// @ts-ignore\n\t\treturn encryptionKey.toPublicKey().toString();\n\t}\n\n\t/**\n\t * Get the public key for encrypting data for this identity, using a seed for the encryption\n\t */\n\tgetEncryptionPublicKeyWithSeed(seed: string): string {\n\t\tconst encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n\t\t// @ts-ignore\n\t\treturn encryptionKey.toPublicKey().toString(\"hex\");\n\t}\n\n\t/**\n\t * Encrypt the given string data with the identity encryption key\n\t * @param stringData\n\t * @param counterPartyPublicKey Optional public key of the counterparty\n\t * @return string Base64\n\t */\n\tencrypt(stringData: string, counterPartyPublicKey?: string): string {\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst encryptionKey = HDPrivateKey.derive(ENCRYPTION_PATH).privKey;\n\t\tconst publicKey = encryptionKey.toPublicKey();\n\t\tconst pubKey = counterPartyPublicKey\n\t\t\t? PublicKey.fromString(counterPartyPublicKey)\n\t\t\t: publicKey;\n // @ts-ignore - remove this when SDK is updated\n\t\treturn toBase64(electrumEncrypt(toArray(stringData), pubKey, null));\n\t}\n\n\t/**\n\t * Decrypt the given ciphertext with the identity encryption key\n\t * @param ciphertext\n\t */\n\tdecrypt(ciphertext: string, counterPartyPublicKey?: string): string {\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst encryptionKey = HDPrivateKey.derive(ENCRYPTION_PATH).privKey;\n let pubKey = undefined\n if (counterPartyPublicKey) {\n pubKey = PublicKey.fromString(counterPartyPublicKey);\n }\n\t\treturn toUTF8(electrumDecrypt(toArray(ciphertext, \"base64\"), encryptionKey, pubKey));\n\t}\n\n\t/**\n\t * Encrypt the given string data with the identity encryption key\n\t * @param stringData\n\t * @param seed String seed\n\t * @param counterPartyPublicKey Optional public key of the counterparty\n\t * @return string Base64\n\t */\n\tencryptWithSeed(\n\t\tstringData: string,\n\t\tseed: string,\n\t\tcounterPartyPublicKey?: string,\n\t): string {\n\t\tconst encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n\t\tconst publicKey = encryptionKey.toPublicKey();\n\t\tconst pubKey = counterPartyPublicKey\n\t\t\t? PublicKey.fromString(counterPartyPublicKey)\n\t\t\t: publicKey;\n\t\treturn toBase64(electrumEncrypt(toArray(stringData), pubKey, encryptionKey));\n\t}\n\n\t/**\n\t * Decrypt the given ciphertext with the identity encryption key\n\t * @param ciphertext\n\t * @param seed String seed\n\t// * @param counterPartyPublicKey Public key of the counterparty\n\t */\n\tdecryptWithSeed(ciphertext: string, seed: string, counterPartyPublicKey?: string): string {\n\t\tconst encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n let pubKey = undefined\n if (counterPartyPublicKey) {\n pubKey = PublicKey.fromString(counterPartyPublicKey);\n }\n\t\treturn toUTF8(electrumDecrypt(toArray(ciphertext, \"base64\"), encryptionKey, pubKey));\n\t}\n\n\tprivate getEncryptionPrivateKeyWithSeed(seed: string) {\n\t\tconst pathHex = toHex(Hash.sha256(seed, \"utf8\"));\n\t\tconst path = Utils.getSigningPathFromHex(pathHex);\n\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\treturn HDPrivateKey.derive(path).privKey;\n\t}\n\n\t/**\n\t * Get an attestation string for the given urn for this identity\n\t *\n\t * @param urn\n\t * @returns {string}\n\t */\n\tgetAttestation(urn: string) {\n\t\tconst urnHash = Hash.sha256(urn, \"utf8\");\n\t\treturn `bap:attest:${toHex(urnHash)}:${this.getIdentityKey()}`;\n\t}\n\n\t/**\n\t * Generate and return the attestation hash for the given attribute of this identity\n\t *\n\t * @param attribute Attribute name (name, email etc.)\n\t * @returns {string}\n\t */\n\tgetAttestationHash(attribute: string) {\n\t\tconst urn = this.getAttributeUrn(attribute);\n\t\tif (!urn) return null;\n\n\t\tconst attestation = this.getAttestation(urn);\n\t\tconst attestationHash = Hash.sha256(attestation, \"utf8\");\n\n\t\treturn toHex(attestationHash);\n\t}\n\n\t/**\n\t * Sign a message with the current signing address of this identity\n\t *\n\t * @param message\n\t * @param signingPath\n\t * @returns {{address, signature}}\n\t */\n\tsignMessage(message: string | Buffer, signingPath = \"\") {\n\t\tlet msg: Buffer;\n\t\tif (!(message instanceof Buffer)) {\n\t\t\tmsg = Buffer.from(message);\n\t\t} else {\n\t\t\tmsg = message;\n\t\t}\n\n\t\tconst pathToUse = signingPath || this.#currentPath;\n\t\tconst childPk = this.#HDPrivateKey.derive(pathToUse).privKey;\n\t\tconst address = childPk.toAddress();\n\n // Needed to calculate the recovery factor\n const dummySig = BSM.sign(toArray(message), childPk);\n\t\tconst h = new BigNumber(magicHash(toArray(message, \"utf8\")));\n\t\tconst r = dummySig.CalculateRecoveryFactor(\n\t\t\tchildPk.toPublicKey(),\n\t\t\th,\n\t\t);\n\t\tconst signature = BSM.sign(toArray(msg), childPk).toCompact(\n\t\t\tr,\n\t\t\ttrue,\n\t\t\t\"base64\",\n\t\t) as string;\n\n\t\treturn { address, signature };\n\t}\n\n\t/**\n\t * Sign a message using a key based on the given string seed\n\t *\n\t * This works by creating a private key from the root key of this identity. It will always\n\t * work with the rootPath / rootKey, to be deterministic. It will not change even if the keys\n\t * are rotated for this ID.\n\t *\n\t * This is used in for instance deterministic login systems, that do not support BAP.\n\t *\n\t * @param message\n\t * @param seed {string} String seed that will be used to generate a path\n\t */\n\tsignMessageWithSeed(\n\t\tmessage: string,\n\t\tseed: string,\n\t): { address: string; signature: string } {\n\t\tconst pathHex = toHex(Hash.sha256(seed, \"utf8\"));\n\t\tconst path = Utils.getSigningPathFromHex(pathHex);\n\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst derivedChild = HDPrivateKey.derive(path);\n\t\tconst address = derivedChild.privKey.toPublicKey().toAddress();\n\n\t\tconst dummySig = BSM.sign(toArray(message), derivedChild.privKey);\n\n\t\tconst h = new BigNumber(magicHash(toArray(message, \"utf8\")));\n\t\tconst r = dummySig.CalculateRecoveryFactor(\n\t\t\tderivedChild.privKey.toPublicKey(),\n\t\t\th,\n\t\t);\n\n\t\tconst signature = BSM.sign(\n\t\t\ttoArray(Buffer.from(message)),\n\t\t\tderivedChild.privKey,\n\t\t).toCompact(r, true, \"base64\") as string;\n\n\t\treturn { address, signature };\n\t}\n\n\t/**\n\t * Sign an op_return hex array with AIP\n\t * @param opReturn {array}\n\t * @param signingPath {string}\n\t * @param outputType {string}\n\t * @return {[]}\n\t */\n\tsignOpReturnWithAIP(\n\t\topReturn: string[],\n\t\tsigningPath = \"\",\n\t\toutputType: BufferEncoding = \"hex\",\n\t): string[] {\n\t\tconst aipMessageBuffer = this.getAIPMessageBuffer(opReturn);\n\t\tconst { address, signature } = this.signMessage(\n\t\t\taipMessageBuffer,\n\t\t\tsigningPath,\n\t\t);\n\n\t\treturn opReturn.concat([\n\t\t\tBuffer.from(\"|\").toString(outputType),\n\t\t\tBuffer.from(AIP_BITCOM_ADDRESS).toString(outputType),\n\t\t\tBuffer.from(\"BITCOIN_ECDSA\").toString(outputType),\n\t\t\tBuffer.from(address).toString(outputType),\n\t\t\tBuffer.from(signature, \"base64\").toString(outputType),\n\t\t]);\n\t}\n\n\t/**\n\t * Construct an AIP buffer from the op return data\n\t * @param opReturn\n\t * @returns {Buffer}\n\t */\n\tgetAIPMessageBuffer(opReturn: string[]): Buffer {\n\t\tconst buffers = [];\n\t\tif (opReturn[0].replace(\"0x\", \"\") !== \"6a\") {\n\t\t\t// include OP_RETURN in constructing the signature buffer\n\t\t\tbuffers.push(Buffer.from(\"6a\", \"hex\"));\n\t\t}\n\t\tfor (const op of opReturn) {\n\t\t\tbuffers.push(Buffer.from(op.replace(\"0x\", \"\"), \"hex\"));\n\t\t}\n\t\t// add a trailing \"|\" - this is the AIP way\n\t\tbuffers.push(Buffer.from(\"|\"));\n\n\t\treturn Buffer.concat([...buffers]);\n\t}\n\n\t/**\n\t * Get all signing keys for this identity\n\t */\n\tasync getIdSigningKeys(): Promise<any> {\n\t\tconst signingKeys = await this.getApiData(\"/signing-keys\", {\n\t\t\tidKey: this.identityKey,\n\t\t});\n\t\tconsole.log(\"getIdSigningKeys\", signingKeys);\n\n\t\treturn signingKeys;\n\t}\n\n\t/**\n\t * Get all attestations for the given attribute\n\t *\n\t * @param attribute\n\t */\n\tasync getAttributeAttestations(attribute: string): Promise<any> {\n\t\t// This function needs to make a call to a BAP server to get all the attestations for this\n\t\t// identity for the given attribute\n\t\tconst attestationHash = this.getAttestationHash(attribute);\n\n\t\t// get all BAP ATTEST records for the given attestationHash\n\t\tconst attestations = await this.getApiData(\"/attestations\", {\n\t\t\thash: attestationHash,\n\t\t});\n\t\tconsole.log(\"getAttestations\", attribute, attestationHash, attestations);\n\n\t\treturn attestations;\n\t}\n\n\t/**\n\t * Helper function to get attestation from a BAP API server\n\t *\n\t * @param apiUrl\n\t * @param apiData\n\t * @returns {Promise<any>}\n\t */\n\tasync getApiData(apiUrl: string, apiData: any): Promise<any> {\n\t\tconst url = `${this.#BAP_SERVER}${apiUrl}`;\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"post\",\n\t\t\theaders: {\n\t\t\t\t\"Content-type\": \"application/json; charset=utf-8\",\n\t\t\t\ttoken: this.#BAP_TOKEN,\n\t\t\t\tformat: \"json\",\n\t\t\t},\n\t\t\tbody: JSON.stringify(apiData),\n\t\t});\n\t\treturn response.json();\n\t}\n\n\t/**\n\t * Import an identity from a JSON object\n\t *\n\t * @param identity{{}}\n\t */\n\timport(identity: Identity): void {\n\t\tthis.idName = identity.name;\n\t\tthis.description = identity.description || \"\";\n\t\tthis.identityKey = identity.identityKey;\n\t\tthis.#rootPath = identity.rootPath;\n\t\tthis.rootAddress = identity.rootAddress;\n\t\tthis.#previousPath = identity.previousPath;\n\t\tthis.#currentPath = identity.currentPath;\n\t\tthis.#idSeed = identity.idSeed || \"\";\n\t\tthis.identityAttributes = this.parseAttributes(identity.identityAttributes);\n\t}\n\n\t/**\n\t * Export this identity to a JSON object\n\t * @returns {{}}\n\t */\n\texport(): Identity {\n\t\treturn {\n\t\t\tname: this.idName,\n\t\t\tdescription: this.description,\n\t\t\tidentityKey: this.identityKey,\n\t\t\trootPath: this.#rootPath,\n\t\t\trootAddress: this.rootAddress,\n\t\t\tpreviousPath: this.#previousPath,\n\t\t\tcurrentPath: this.#currentPath,\n\t\t\tidSeed: this.#idSeed,\n\t\t\tidentityAttributes: this.getAttributes(),\n\t\t\tlastIdPath: \"\",\n\t\t};\n\t}\n}\n\nexport { BAP_ID };\n"],"names":["Utils","string","Buffer","from","toString","hexString","encoding","replace","hardened","signingPath","signingHex","match","Error","_step","maxNumber","_iterator","_createForOfIteratorHelperLoose","done","number","Number","hexNumber","value","path","pathValues","split","lastPart","length","nextPath","join","BAP_BITCOM_ADDRESS","BAP_BITCOM_ADDRESS_HEX","AIP_BITCOM_ADDRESS","_HDPrivateKey","_ids","_BAP_SERVER","_BAP_TOKEN","_lastIdPath","BAP_SERVER","MAX_INT","SIGNING_PATH_PREFIX","ENCRYPTION_PATH","toArray","BSVUtils","toHex","toBase58","toUTF8","toBase64","electrumDecrypt","ECIES","electrumEncrypt","magicHash","BSM","_classPrivateFieldLooseKey","_rootPath","_previousPath","_currentPath","_idSeed","BAP_ID","HDPrivateKey","identityAttributes","idSeed","Object","defineProperty","this","writable","idName","description","rootAddress","identityKey","_classPrivateFieldLooseBase","seedHex","Hash","sha256","seedPath","derive","rootChild","privKey","toPublicKey","toAddress","deriveIdentityKey","attributes","_extends","parseAttributes","_proto","prototype","address","rootAddressHash","ripemd160","parseStringUrns","key","nonce","urnIdentityAttributes","urn","getIdentityKey","getAttributes","getAttribute","attributeName","setAttribute","attributeValue","addAttribute","unsetAttribute","getAttributeUrns","urns","getAttributeUrn","attribute","nonceToUse","randomBytes","getRootPath","incrementPath","currentPath","validatePath","getInitialIdTransaction","getIdTransaction","previousPath","opReturn","getCurrentAddress","signOpReturnWithAIP","getAddress","getEncryptionPublicKey","getEncryptionPublicKeyWithSeed","seed","getEncryptionPrivateKeyWithSeed","encrypt","stringData","counterPartyPublicKey","publicKey","pubKey","PublicKey","fromString","decrypt","ciphertext","encryptionKey","undefined","encryptWithSeed","decryptWithSeed","pathHex","getAttestation","urnHash","getAttestationHash","attestation","attestationHash","signMessage","message","msg","pathToUse","childPk","dummySig","sign","h","BigNumber","r","CalculateRecoveryFactor","signature","toCompact","signMessageWithSeed","derivedChild","outputType","aipMessageBuffer","getAIPMessageBuffer","_this$signMessage","concat","buffers","push","_iterator2","_step2","getIdSigningKeys","Promise","resolve","getApiData","idKey","then","signingKeys","console","log","e","reject","getAttributeAttestations","hash","attestations","apiUrl","apiData","url","fetch","method","headers","token","format","body","JSON","stringify","response","json","identity","name","rootPath","lastIdPath","_createClass","get","set","bapServer","BAP","HD","getPublicKey","childPath","getHdPublicKey","toPublic","checkIdBelongs","bapId","listIds","keys","newId","getNextValidPath","newIdentity","BAP_TOKEN","removeId","secondToLastPart","getId","setId","importIds","idData","encrypted","importEncryptedIds","ids","id","importId","decrypted","parse","Array","isArray","importOldIds","exportIds","_i","_Object$keys","signAttestationWithAIP","counter","dataString","attestationBuffer","getAttestationBuffer","_id$signMessage","createAttestationTransaction","verifyAttestationWithAIP","tx","dataOffset","type","sequence","signingProtocol","signingAddress","data","signatureBufferStatements","i","verified","verifySignature","transaction","dataStringBuffer","messageBuffer","isBuffer","sig","Signature","fromCompact","recovery","RecoverPublicKey","verify","verifyChallengeSignature","challenge","_exit","_this","_temp","result","_result","isValidAttestationTransaction","getIdentityFromAddress","getIdentity","getAttestationsForHash","_i2","_Object$keys2","_i3","_Object$keys3"],"mappings":"i3DAGa,IAAAA,WAODC,GACR,WAAYC,OAAOC,KAAKF,GAAQG,SAAS,MAC3C,EATWJ,EAkBX,SAAUK,EAAmBC,GAC3B,YAD2B,IAAAA,IAAAA,EAA2B,QAC/CJ,OAAOC,KAAKE,EAAUE,QAAQ,KAAM,IAAK,OAAOH,SAASE,EAClE,EApBWN,EAmDU,SAACK,EAAmBG,QAAQ,IAARA,IAAAA,GAAW,GAElD,IAAIC,EAAc,IACZC,EAAaL,EAAUM,MAAM,WACnC,IAAKD,EACH,MAAU,IAAAE,MAAM,sBAGlB,IADA,IACkCC,EAD5BC,EAAY,WAClBC,EAAAC,EAAwBN,KAAUG,EAAAE,KAAAE,MAAE,CAAA,IAC9BC,EAASC,OAAYC,KADPP,EAAAQ,OAEdH,EAASJ,IAAWI,GAAUJ,GAClCL,GAAW,IAAQS,GAAUV,EAAW,IAAM,GAChD,CAEA,OAAOC,CACT,EAlEWT,WAgGCsB,GACV,IAAMC,EAAaD,EAAKE,MAAM,KACxBC,EAAWF,EAAWA,EAAWG,OAAS,GAC5ClB,GAAW,EACXiB,EAASd,MAAM,OACjBH,GAAW,GAEb,IAAMmB,GAAYR,OAAOM,EAASlB,QAAQ,UAAW,KAAO,GAAGH,WAE/D,OADAmB,EAAWA,EAAWG,OAAS,GAAKC,GAAYnB,EAAW,IAAO,IAC3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QAAAC,QACpBe,MAAMD,EAAK,CACjCE,OAAQ,OACRC,QAAS,CACR,eAAgB,kCAChBC,MAAKpH,EALQN,KAKR5B,GAAAA,GACLuJ,OAAQ,QAETC,KAAMC,KAAKC,UAAUT,MACpBV,KAAA,SARIoB,GAUN,OAAOA,EAASC,MAAO,EACxB,CAAC,MAAAjB,GAAA,OAAAR,QAAAS,OAAAD,KAAAsB,EAAAI,EAAA/G,CAAAA,CAAAA,iBAAA4G,IAjmBD,WACC,OAAAhI,EAAON,KAAI3B,GAAAA,EACZ,IAACqD,IAAA,aAAA4G,IAqCD,WACC,OAAAhI,EAAON,KAAI7B,GAAAA,EACZ,EAACoK,IATD,SAAeC,GACdlI,OAAInC,GAAAA,GAAeqK,EACnB,QAAA0E,EAAA,EAAAC,EAAkBrN,OAAOoJ,KAAI5I,EAACN,KAAI9B,GAAAA,IAAMgP,EAAAC,EAAAxP,OAAAuP,IAAE,CAArC,IAAMxL,EAAGyL,EAAAD,GACb5M,EAAIN,KAAA9B,GAAAA,GAAMwD,GAAKpD,WAAakK,CAC7B,CACD,GAAC9G,CAAAA,gBAAA4G,IAcD,WACC,OAAAhI,EAAON,KAAI5B,GAAAA,EACZ,EAACmK,IAVD,SAAcb,GACbpH,EAAIN,KAAA5B,GAAAA,GAAcsJ,EAClB,IAAA0F,IAAAA,IAAAC,EAAkBvN,OAAOoJ,KAAI5I,EAACN,KAAI9B,GAAAA,IAAMkP,EAAAC,EAAA1P,OAAAyP,IAAE,CAArC,IAAM1L,EAAG2L,EAAAD,GAEb9M,EAAAN,KAAI9B,GAAAA,GAAMwD,GAAK4H,UAAY5B,CAC5B,CACD,IAijBA,CApnBe"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/utils.ts","../src/constants.ts","../src/api.ts","../src/id.ts","../src/index.ts"],"sourcesContent":["import randomBytes from \"randombytes\";\nimport type {PathPrefix} from \"./interface\";\n\nexport const Utils = {\n /**\n * Helper function for encoding strings to hex\n *\n * @param string\n * @returns {string}\n */\n hexEncode(string: string) {\n return `0x${Buffer.from(string).toString('hex')}`;\n },\n\n /**\n * Helper function for encoding strings to hex\n *\n * @param hexString string\n * @param encoding BufferEncoding\n * @returns {string}\n */\n hexDecode(hexString: string, encoding: BufferEncoding = 'utf8') {\n return Buffer.from(hexString.replace('0x', ''), 'hex').toString(encoding);\n },\n\n /**\n * Helper function to generate a random nonce\n *\n * @returns {string}\n */\n getRandomString(length = 32) {\n return randomBytes(length).toString('hex');\n },\n\n /**\n * Test whether the given string is hex\n *\n * @param value any\n * @returns {boolean}\n */\n isHex(value: string): boolean {\n if (typeof value !== 'string') {\n return false;\n }\n return /^[0-9a-fA-F]+$/.test(value);\n },\n\n /**\n * Get a signing path from a hex number\n *\n * @param hexString {string}\n * @param hardened {boolean} Whether to return a hardened path\n * @returns {string}\n */\n getSigningPathFromHex(hexString: string, hardened = true) {\n // \"m/0/0/1\"\n let signingPath = 'm';\n const signingHex = hexString.match(/.{1,8}/g);\n if (!signingHex) {\n throw new Error('Invalid hex string');\n }\n const maxNumber = 2147483648 - 1; // 0x80000000\n for (const hexNumber of signingHex) {\n let number = Number(`0x${hexNumber}`);\n if (number > maxNumber) number -= maxNumber;\n signingPath += `/${number}${(hardened ? \"'\" : '')}`;\n }\n\n return signingPath;\n },\n\n /**\n * Increment that second to last part from the given part, set the last part to 0\n *\n * @param path string\n * @returns {*}\n */\n getNextIdentityPath(path: string): PathPrefix {\n const pathValues = path.split('/');\n const secondToLastPart = pathValues[pathValues.length - 2];\n\n let hardened = false;\n if (secondToLastPart.match('\\'')) {\n hardened = true;\n }\n\n const nextPath = (Number(secondToLastPart.replace(/[^0-9]/g, '')) + 1).toString();\n pathValues[pathValues.length - 2] = nextPath + (hardened ? '\\'' : '');\n pathValues[pathValues.length - 1] = `0${hardened ? '\\'' : ''}`;\n\n return pathValues.join('/') as PathPrefix;\n },\n\n /**\n * Increment that last part of the given path\n *\n * @param path string\n * @returns {*}\n */\n getNextPath(path: string) {\n const pathValues = path.split('/');\n const lastPart = pathValues[pathValues.length - 1];\n let hardened = false;\n if (lastPart.match('\\'')) {\n hardened = true;\n }\n const nextPath = (Number(lastPart.replace(/[^0-9]/g, '')) + 1).toString();\n pathValues[pathValues.length - 1] = nextPath + (hardened ? '\\'' : '');\n return pathValues.join('/');\n },\n};\n","export const BAP_BITCOM_ADDRESS = '1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT';\nexport const BAP_BITCOM_ADDRESS_HEX = `0x${Buffer.from(BAP_BITCOM_ADDRESS).toString('hex')}`;\nexport const AIP_BITCOM_ADDRESS = '15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva';\nexport const AIP_BITCOM_ADDRESS_HEX = `0x${Buffer.from(AIP_BITCOM_ADDRESS).toString('hex')}`;\nexport const BAP_SERVER = 'https://api.sigmaidentity.com/api/v1';\nexport const MAX_INT = 2147483648 - 1; // 0x80000000\n\n// This is just a choice for this library and could be anything else if so needed/wanted\n// but it is advisable to use the same derivation between libraries for compatibility\nexport const SIGNING_PATH_PREFIX = 'm/424150\\'/0\\'/0\\''; // BAP in hex\nexport const ENCRYPTION_PATH = `m/424150'/${MAX_INT}'/${MAX_INT}'`;\n","\n/**\n\t * Helper function to get attestation from a BAP API server\n\t *\n\t * @param apiUrl\n\t * @param apiData\n\t * @returns {Promise<any>}\n\t */\nexport const getApiData = async <T>(apiUrl: string, apiData: unknown, server: string, token: string): Promise<T> => {\n const url = `${server}${apiUrl}`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-type\": \"application/json; charset=utf-8\",\n token,\n format: \"json\",\n },\n body: JSON.stringify(apiData),\n });\n\n return response.json();\n}\n\nexport type APIFetcher = <T>(url: string, data: unknown) => Promise<T>;\n\nexport const apiFetcher = (host: string, token: string): APIFetcher => async <T>(url: string, data: unknown): Promise<T> => {\n return getApiData<T>(url, data, host, token);\n}","import { BSM, Hash, type HD, ECIES, PublicKey, BigNumber } from \"@bsv/sdk\";\nimport {\n\tMAX_INT,\n\tSIGNING_PATH_PREFIX,\n\tBAP_SERVER,\n\tBAP_BITCOM_ADDRESS,\n\tAIP_BITCOM_ADDRESS,\n\tENCRYPTION_PATH,\n} from \"./constants\";\nimport { type APIFetcher, apiFetcher } from \"./api\";\nimport { Utils } from \"./utils\";\nimport type {\n\tIdentity,\n\tIdentityAttribute,\n\tIdentityAttributes,\n} from \"./interface\";\nimport { Utils as BSVUtils } from \"@bsv/sdk\";\nimport type { GetAttestationResponse } from \"./apiTypes\";\nconst { toArray, toHex, toBase58, toUTF8, toBase64 } = BSVUtils;\nconst { electrumDecrypt, electrumEncrypt } = ECIES;\nconst { magicHash } = BSM;\n/**\n * BAP_ID class\n *\n * This class should be used in conjunction with the BAP class\n *\n * @type {BAP_ID}\n */\nclass BAP_ID {\n\t#HDPrivateKey: HD;\n\t#BAP_SERVER: string = BAP_SERVER;\n\t#BAP_TOKEN = \"\";\n\t#rootPath: string;\n\t#previousPath: string;\n\t#currentPath: string;\n\t#idSeed: string;\n\n\tidName: string;\n\tdescription: string;\n\n\trootAddress: string;\n\tidentityKey: string;\n\tidentityAttributes: IdentityAttributes;\n\n getApiData: APIFetcher\n \n\tconstructor(\n HDPrivateKey: HD,\n\t\tidentityAttributes: IdentityAttributes = {},\n\t\tidSeed = \"\",\n\t) {\n this.#idSeed = idSeed;\n\t\tif (idSeed) {\n\t\t\t// create a new HDPrivateKey based on the seed\n\t\t\tconst seedHex = toHex(Hash.sha256(idSeed, \"utf8\"));\n\t\t\tconst seedPath = Utils.getSigningPathFromHex(seedHex);\n\t\t\tthis.#HDPrivateKey = HDPrivateKey.derive(seedPath);\n\t\t} else {\n\t\t\tthis.#HDPrivateKey = HDPrivateKey;\n\t\t}\n\n\t\tthis.idName = \"ID 1\";\n\t\tthis.description = \"\";\n\n\t\tthis.#rootPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n\t\tthis.#previousPath = `${SIGNING_PATH_PREFIX}/0/0/0`;\n\t\tthis.#currentPath = `${SIGNING_PATH_PREFIX}/0/0/1`;\n\n\t\tconst rootChild = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tthis.rootAddress = rootChild.privKey.toPublicKey().toAddress();\n\t\tthis.identityKey = this.deriveIdentityKey(this.rootAddress);\n\n\t\t// unlink the object\n\t\tconst attributes = { ...identityAttributes };\n\t\tthis.identityAttributes = this.parseAttributes(attributes);\n\n this.getApiData = apiFetcher(this.#BAP_SERVER, this.#BAP_TOKEN);\n\t}\n\n\tset BAP_SERVER(bapServer) {\n\t\tthis.#BAP_SERVER = bapServer;\n\t}\n\n\tget BAP_SERVER(): string {\n\t\treturn this.#BAP_SERVER;\n\t}\n\n\tset BAP_TOKEN(token) {\n\t\tthis.#BAP_TOKEN = token;\n\t}\n\n\tget BAP_TOKEN(): string {\n\t\treturn this.#BAP_TOKEN;\n\t}\n\n\tderiveIdentityKey(address: string): string {\n\t\t// base58( ripemd160 ( sha256 ( rootAddress ) ) )\n\t\tconst rootAddressHash = toHex(Hash.sha256(address, \"utf8\"));\n\t\treturn toBase58(Hash.ripemd160(rootAddressHash, \"hex\"));\n\t}\n\n\t/**\n\t * Helper function to parse identity attributes\n\t *\n\t * @param identityAttributes\n\t * @returns {{}}\n\t */\n\tparseAttributes(\n\t\tidentityAttributes: IdentityAttributes | string,\n\t): IdentityAttributes {\n\t\tif (typeof identityAttributes === \"string\") {\n\t\t\treturn this.parseStringUrns(identityAttributes);\n\t\t}\n\n\t\tfor (const key in identityAttributes) {\n\t\t\tif (!identityAttributes[key].value || !identityAttributes[key].nonce) {\n\t\t\t\tthrow new Error(\"Invalid identity attribute\");\n\t\t\t}\n\t\t}\n\n\t\treturn identityAttributes || {};\n\t}\n\n\t/**\n\t * Parse a text of urn string into identity attributes\n\t *\n\t * urn:bap:id:name:John Doe:e2c6fb4063cc04af58935737eaffc938011dff546d47b7fbb18ed346f8c4d4fa\n\t * urn:bap:id:birthday:1990-05-22:e61f23cbbb2284842d77965e2b0e32f0ca890b1894ca4ce652831347ee3596d9\n\t * urn:bap:id:over18:1:480ca17ccaacd671b28dc811332525f2f2cd594d8e8e7825de515ce5d52d30e8\n\t *\n\t * @param urnIdentityAttributes\n\t */\n\tparseStringUrns(urnIdentityAttributes: string): IdentityAttributes {\n\t\tconst identityAttributes: IdentityAttributes = {};\n\t\t// avoid forEach\n\n\t\tconst attributesRaw = urnIdentityAttributes\n\t\t\t.replace(/^\\s+/g, \"\")\n\t\t\t.replace(/\\r/gm, \"\")\n\t\t\t.split(\"\\n\");\n\n\t\tfor (const line of attributesRaw) {\n\t\t\t// remove any whitespace from the string (trim)\n\t\t\tconst attribute = line.replace(/^\\s+/g, \"\").replace(/\\s+$/g, \"\");\n\t\t\tconst urn = attribute.split(\":\");\n\t\t\tif (\n\t\t\t\turn[0] === \"urn\" &&\n\t\t\t\turn[1] === \"bap\" &&\n\t\t\t\turn[2] === \"id\" &&\n\t\t\t\turn[3] &&\n\t\t\t\turn[4] &&\n\t\t\t\turn[5]\n\t\t\t) {\n\t\t\t\tidentityAttributes[urn[3]] = {\n\t\t\t\t\tvalue: urn[4],\n\t\t\t\t\tnonce: urn[5],\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn identityAttributes;\n\t}\n\n\t/**\n\t * Returns the identity key\n\t *\n\t * @returns {*|string}\n\t */\n\tgetIdentityKey(): string {\n\t\treturn this.identityKey;\n\t}\n\n\t/**\n\t * Returns all the attributes in the identity\n\t *\n\t * @returns {*}\n\t */\n\tgetAttributes(): IdentityAttributes {\n\t\treturn this.identityAttributes;\n\t}\n\n\t/**\n\t * Get the value of the given attribute\n\t *\n\t * @param attributeName\n\t * @returns {{}|null}\n\t */\n\tgetAttribute(attributeName: string): IdentityAttribute | null {\n\t\tif (this.identityAttributes[attributeName]) {\n\t\t\treturn this.identityAttributes[attributeName];\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Set the value of the given attribute\n\t *\n\t * If an empty value ('' || null || false) is given, the attribute is removed from the ID\n\t *\n\t * @param attributeName string\n\t * @param attributeValue any\n\t * @returns {{}|null}\n\t */\n\tsetAttribute(attributeName: string, attributeValue: string | Record<string,string>): void {\n\t\tif (attributeValue) {\n\t\t\tif (this.identityAttributes[attributeName]) {\n\t\t\t\tthis.identityAttributes[attributeName].value = attributeValue;\n\t\t\t} else {\n\t\t\t\tthis.addAttribute(attributeName, attributeValue);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Unset the given attribute from the ID\n\t *\n\t * @param attributeName\n\t * @returns {{}|null}\n\t */\n\tunsetAttribute(attributeName: string): void {\n\t\tdelete this.identityAttributes[attributeName];\n\t}\n\n\t/**\n\t * Get all attribute urn's for this id\n\t *\n\t * @returns {string}\n\t */\n\tgetAttributeUrns(): string {\n\t\tlet urns = \"\";\n\t\tfor (const key in this.identityAttributes) {\n\t\t\tconst urn = this.getAttributeUrn(key);\n\t\t\tif (urn) {\n\t\t\t\turns += `${urn}\\n`;\n\t\t\t}\n\t\t}\n\n\t\treturn urns;\n\t}\n\n\t/**\n\t * Create an return the attribute urn for the given attribute\n\t *\n\t * @param attributeName\n\t * @returns {string|null}\n\t */\n\tgetAttributeUrn(attributeName: string): string | null {\n\t\tconst attribute = this.identityAttributes[attributeName];\n\t\tif (attribute) {\n\t\t\treturn `urn:bap:id:${attributeName}:${attribute.value}:${attribute.nonce}`;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Add an attribute to this identity\n\t *\n\t * @param attributeName\n\t * @param value\n\t * @param nonce\n\t */\n\taddAttribute(attributeName: string, value: any, nonce = \"\"): void {\n\t\tlet nonceToUse = nonce;\n\t\tif (!nonce) {\n\t\t\tnonceToUse = Utils.getRandomString();\n\t\t}\n\n\t\tthis.identityAttributes[attributeName] = {\n\t\t\tvalue,\n\t\t\tnonce: nonceToUse,\n\t\t};\n\t}\n\n\t/**\n\t * This should be called with the last part of the signing path (/.../.../...)\n\t * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file\n\t *\n\t * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9}\n\t */\n\tset rootPath(path: string) {\n\t\tif (this.#HDPrivateKey) {\n\t\t\tlet pathToUse = path;\n\t\t\tif (path.split(\"/\").length < 5) {\n\t\t\t\tpathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n\t\t\t}\n\n\t\t\tif (!this.validatePath(pathToUse)) {\n\t\t\t\tthrow new Error(`invalid signing path given ${pathToUse}`);\n\t\t\t}\n\n\t\t\tthis.#rootPath = pathToUse;\n\n\t\t\tconst derivedChild = this.#HDPrivateKey.derive(pathToUse);\n\t\t\tthis.rootAddress = derivedChild.pubKey.toAddress();\n\t\t\t// Identity keys should be derivatives of the root address - this allows checking\n\t\t\t// of the creation transaction\n\t\t\tthis.identityKey = this.deriveIdentityKey(this.rootAddress);\n\n\t\t\t// we also set this previousPath / currentPath to the root as we seem to be (re)setting this ID\n\t\t\tthis.#previousPath = pathToUse;\n\t\t\tthis.#currentPath = pathToUse;\n\t\t}\n\t}\n\n\tget rootPath(): string {\n\t\treturn this.#rootPath;\n\t}\n\n\tgetRootPath(): string {\n\t\treturn this.#rootPath;\n\t}\n\n\t/**\n\t * This should be called with the last part of the signing path (/.../.../...)\n\t * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file\n\t *\n\t * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9}\n\t */\n\tset currentPath(path) {\n\t\tlet pathToUse = path;\n\t\tif (path.split(\"/\").length < 5) {\n\t\t\tpathToUse = `${SIGNING_PATH_PREFIX}${path}`;\n\t\t}\n\n\t\tif (!this.validatePath(pathToUse)) {\n\t\t\tthrow new Error(\"invalid signing path given\");\n\t\t}\n\n\t\tthis.#previousPath = this.#currentPath;\n\t\tthis.#currentPath = pathToUse;\n\t}\n\n\tget currentPath(): string {\n\t\treturn this.#currentPath;\n\t}\n\n\tget previousPath(): string {\n\t\treturn this.#previousPath;\n\t}\n\n\t/**\n\t * This can be used to break the deterministic way child keys are created to make it harder for\n\t * an attacker to steal the identites when the root key is compromised. This does however require\n\t * the seeds to be stored at all times. If the seed is lost, the identity will not be recoverable.\n\t */\n\tget idSeed(): string {\n\t\treturn this.#idSeed;\n\t}\n\n\t/**\n\t * Increment current path to a new path\n\t *\n\t * @returns {*}\n\t */\n\tincrementPath(): void {\n\t\tthis.currentPath = Utils.getNextPath(this.currentPath);\n\t}\n\n\t/**\n\t * Check whether the given path is a valid path for use with this class\n\t * The signing paths used here always have a length of 3\n\t *\n\t * @param path The last part of the signing path (example \"/0/0/1\")\n\t * @returns {boolean}\n\t */\n\tvalidatePath(path: string) {\n\t\t/* eslint-disable max-len */\n\t\tif (\n\t\t\tpath.match(\n\t\t\t\t/\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?\\/[0-9]{1,10}'?/,\n\t\t\t)\n\t\t) {\n\t\t\tconst pathValues = path.split(\"/\");\n\t\t\tif (\n\t\t\t\tpathValues.length === 7 &&\n\t\t\t\tNumber(pathValues[1].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[2].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[3].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[4].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[5].replace(\"'\", \"\")) <= MAX_INT &&\n\t\t\t\tNumber(pathValues[6].replace(\"'\", \"\")) <= MAX_INT\n\t\t\t) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Get the OP_RETURN for the initial ID transaction (signed with root address)\n\t *\n\t * @returns {[]}\n\t */\n\tgetInitialIdTransaction() {\n\t\treturn this.getIdTransaction(this.#rootPath);\n\t}\n\n\t/**\n\t * Get the OP_RETURN for the ID transaction of the current address / path\n\t *\n\t * @returns {[]}\n\t */\n\tgetIdTransaction(previousPath = \"\") {\n\t\tif (this.#currentPath === this.#rootPath) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Current path equals rootPath. ID was probably not initialized properly\",\n\t\t\t);\n\t\t}\n\n\t\tconst opReturn = [\n\t\t\tBuffer.from(BAP_BITCOM_ADDRESS).toString(\"hex\"),\n\t\t\tBuffer.from(\"ID\").toString(\"hex\"),\n\t\t\tBuffer.from(this.identityKey).toString(\"hex\"),\n\t\t\tBuffer.from(this.getCurrentAddress()).toString(\"hex\"),\n\t\t];\n\n\t\treturn this.signOpReturnWithAIP(\n\t\t\topReturn,\n\t\t\tpreviousPath || this.#previousPath,\n\t\t);\n\t}\n\n\t/**\n\t * Get address for given path\n\t *\n\t * @param path\n\t * @returns {*}\n\t */\n\tgetAddress(path: string): string {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(path);\n\t\treturn derivedChild.privKey.toPublicKey().toAddress();\n\t}\n\n\t/**\n\t * Get current signing address\n\t *\n\t * @returns {*}\n\t */\n\tgetCurrentAddress(): string {\n\t\treturn this.getAddress(this.#currentPath);\n\t}\n\n\t/**\n\t * Get the public key for encrypting data for this identity\n\t */\n\tgetEncryptionPublicKey(): string {\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst encryptionKey = HDPrivateKey.derive(ENCRYPTION_PATH).privKey;\n\t\t// @ts-ignore\n\t\treturn encryptionKey.toPublicKey().toString();\n\t}\n\n\t/**\n\t * Get the public key for encrypting data for this identity, using a seed for the encryption\n\t */\n\tgetEncryptionPublicKeyWithSeed(seed: string): string {\n\t\tconst encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n\t\t// @ts-ignore\n\t\treturn encryptionKey.toPublicKey().toString(\"hex\");\n\t}\n\n\t/**\n\t * Encrypt the given string data with the identity encryption key\n\t * @param stringData\n\t * @param counterPartyPublicKey Optional public key of the counterparty\n\t * @return string Base64\n\t */\n\tencrypt(stringData: string, counterPartyPublicKey?: string): string {\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst encryptionKey = HDPrivateKey.derive(ENCRYPTION_PATH).privKey;\n\t\tconst publicKey = encryptionKey.toPublicKey();\n\t\tconst pubKey = counterPartyPublicKey\n\t\t\t? PublicKey.fromString(counterPartyPublicKey)\n\t\t\t: publicKey;\n // @ts-ignore - remove this when SDK is updated\n\t\treturn toBase64(electrumEncrypt(toArray(stringData), pubKey, null));\n\t}\n\n\t/**\n\t * Decrypt the given ciphertext with the identity encryption key\n\t * @param ciphertext\n\t */\n\tdecrypt(ciphertext: string, counterPartyPublicKey?: string): string {\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst encryptionKey = HDPrivateKey.derive(ENCRYPTION_PATH).privKey;\n let pubKey = undefined\n if (counterPartyPublicKey) {\n pubKey = PublicKey.fromString(counterPartyPublicKey);\n }\n\t\treturn toUTF8(electrumDecrypt(toArray(ciphertext, \"base64\"), encryptionKey, pubKey));\n\t}\n\n\t/**\n\t * Encrypt the given string data with the identity encryption key\n\t * @param stringData\n\t * @param seed String seed\n\t * @param counterPartyPublicKey Optional public key of the counterparty\n\t * @return string Base64\n\t */\n\tencryptWithSeed(\n\t\tstringData: string,\n\t\tseed: string,\n\t\tcounterPartyPublicKey?: string,\n\t): string {\n\t\tconst encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n\t\tconst publicKey = encryptionKey.toPublicKey();\n\t\tconst pubKey = counterPartyPublicKey\n\t\t\t? PublicKey.fromString(counterPartyPublicKey)\n\t\t\t: publicKey;\n\t\treturn toBase64(electrumEncrypt(toArray(stringData), pubKey, encryptionKey));\n\t}\n\n\t/**\n\t * Decrypt the given ciphertext with the identity encryption key\n\t * @param ciphertext\n\t * @param seed String seed\n\t// * @param counterPartyPublicKey Public key of the counterparty\n\t */\n\tdecryptWithSeed(ciphertext: string, seed: string, counterPartyPublicKey?: string): string {\n\t\tconst encryptionKey = this.getEncryptionPrivateKeyWithSeed(seed);\n let pubKey = undefined\n if (counterPartyPublicKey) {\n pubKey = PublicKey.fromString(counterPartyPublicKey);\n }\n\t\treturn toUTF8(electrumDecrypt(toArray(ciphertext, \"base64\"), encryptionKey, pubKey));\n\t}\n\n\tprivate getEncryptionPrivateKeyWithSeed(seed: string) {\n\t\tconst pathHex = toHex(Hash.sha256(seed, \"utf8\"));\n\t\tconst path = Utils.getSigningPathFromHex(pathHex);\n\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\treturn HDPrivateKey.derive(path).privKey;\n\t}\n\n\t/**\n\t * Get an attestation string for the given urn for this identity\n\t *\n\t * @param urn\n\t * @returns {string}\n\t */\n\tgetAttestation(urn: string) {\n\t\tconst urnHash = Hash.sha256(urn, \"utf8\");\n\t\treturn `bap:attest:${toHex(urnHash)}:${this.getIdentityKey()}`;\n\t}\n\n\t/**\n\t * Generate and return the attestation hash for the given attribute of this identity\n\t *\n\t * @param attribute Attribute name (name, email etc.)\n\t * @returns {string}\n\t */\n\tgetAttestationHash(attribute: string) {\n\t\tconst urn = this.getAttributeUrn(attribute);\n\t\tif (!urn) return null;\n\n\t\tconst attestation = this.getAttestation(urn);\n\t\tconst attestationHash = Hash.sha256(attestation, \"utf8\");\n\n\t\treturn toHex(attestationHash);\n\t}\n\n\t/**\n\t * Sign a message with the current signing address of this identity\n\t *\n\t * @param message\n\t * @param signingPath\n\t * @returns {{address, signature}}\n\t */\n\tsignMessage(message: string | Buffer, signingPath = \"\") {\n\t\tlet msg: Buffer;\n\t\tif (!(message instanceof Buffer)) {\n\t\t\tmsg = Buffer.from(message);\n\t\t} else {\n\t\t\tmsg = message;\n\t\t}\n\n\t\tconst pathToUse = signingPath || this.#currentPath;\n\t\tconst childPk = this.#HDPrivateKey.derive(pathToUse).privKey;\n\t\tconst address = childPk.toAddress();\n\n // Needed to calculate the recovery factor\n const dummySig = BSM.sign(toArray(message), childPk);\n\t\tconst h = new BigNumber(magicHash(toArray(message, \"utf8\")));\n\t\tconst r = dummySig.CalculateRecoveryFactor(\n\t\t\tchildPk.toPublicKey(),\n\t\t\th,\n\t\t);\n\t\tconst signature = BSM.sign(toArray(msg), childPk).toCompact(\n\t\t\tr,\n\t\t\ttrue,\n\t\t\t\"base64\",\n\t\t) as string;\n\n\t\treturn { address, signature };\n\t}\n\n\t/**\n\t * Sign a message using a key based on the given string seed\n\t *\n\t * This works by creating a private key from the root key of this identity. It will always\n\t * work with the rootPath / rootKey, to be deterministic. It will not change even if the keys\n\t * are rotated for this ID.\n\t *\n\t * This is used in for instance deterministic login systems, that do not support BAP.\n\t *\n\t * @param message\n\t * @param seed {string} String seed that will be used to generate a path\n\t */\n\tsignMessageWithSeed(\n\t\tmessage: string,\n\t\tseed: string,\n\t): { address: string; signature: string } {\n\t\tconst pathHex = toHex(Hash.sha256(seed, \"utf8\"));\n\t\tconst path = Utils.getSigningPathFromHex(pathHex);\n\n\t\tconst HDPrivateKey = this.#HDPrivateKey.derive(this.#rootPath);\n\t\tconst derivedChild = HDPrivateKey.derive(path);\n\t\tconst address = derivedChild.privKey.toPublicKey().toAddress();\n\n\t\tconst dummySig = BSM.sign(toArray(message), derivedChild.privKey);\n\n\t\tconst h = new BigNumber(magicHash(toArray(message, \"utf8\")));\n\t\tconst r = dummySig.CalculateRecoveryFactor(\n\t\t\tderivedChild.privKey.toPublicKey(),\n\t\t\th,\n\t\t);\n\n\t\tconst signature = BSM.sign(\n\t\t\ttoArray(Buffer.from(message)),\n\t\t\tderivedChild.privKey,\n\t\t).toCompact(r, true, \"base64\") as string;\n\n\t\treturn { address, signature };\n\t}\n\n\t/**\n\t * Sign an op_return hex array with AIP\n\t * @param opReturn {array}\n\t * @param signingPath {string}\n\t * @param outputType {string}\n\t * @return {[]}\n\t */\n\tsignOpReturnWithAIP(\n\t\topReturn: string[],\n\t\tsigningPath = \"\",\n\t\toutputType: BufferEncoding = \"hex\",\n\t): string[] {\n\t\tconst aipMessageBuffer = this.getAIPMessageBuffer(opReturn);\n\t\tconst { address, signature } = this.signMessage(\n\t\t\taipMessageBuffer,\n\t\t\tsigningPath,\n\t\t);\n\n\t\treturn opReturn.concat([\n\t\t\tBuffer.from(\"|\").toString(outputType),\n\t\t\tBuffer.from(AIP_BITCOM_ADDRESS).toString(outputType),\n\t\t\tBuffer.from(\"BITCOIN_ECDSA\").toString(outputType),\n\t\t\tBuffer.from(address).toString(outputType),\n\t\t\tBuffer.from(signature, \"base64\").toString(outputType),\n\t\t]);\n\t}\n\n\t/**\n\t * Construct an AIP buffer from the op return data\n\t * @param opReturn\n\t * @returns {Buffer}\n\t */\n\tgetAIPMessageBuffer(opReturn: string[]): Buffer {\n\t\tconst buffers = [];\n\t\tif (opReturn[0].replace(\"0x\", \"\") !== \"6a\") {\n\t\t\t// include OP_RETURN in constructing the signature buffer\n\t\t\tbuffers.push(Buffer.from(\"6a\", \"hex\"));\n\t\t}\n\t\tfor (const op of opReturn) {\n\t\t\tbuffers.push(Buffer.from(op.replace(\"0x\", \"\"), \"hex\"));\n\t\t}\n\t\t// add a trailing \"|\" - this is the AIP way\n\t\tbuffers.push(Buffer.from(\"|\"));\n\n\t\treturn Buffer.concat([...buffers]);\n\t}\n\n\t/**\n\t * Get all signing keys for this identity\n\t */\n\tasync getIdSigningKeys(): Promise<any> {\n\t\tconst signingKeys = await this.getApiData(\"/signing-keys\", {\n\t\t\tidKey: this.identityKey,\n\t\t});\n\t\tconsole.log(\"getIdSigningKeys\", signingKeys);\n\n\t\treturn signingKeys;\n\t}\n\n\t/**\n\t * Get all attestations for the given attribute\n\t *\n\t * @param attribute\n\t */\n\tasync getAttributeAttestations(attribute: string): Promise<GetAttestationResponse> {\n\t\t// This function needs to make a call to a BAP server to get all the attestations for this\n\t\t// identity for the given attribute\n\t\tconst attestationHash = this.getAttestationHash(attribute);\n\n\t\t// get all BAP ATTEST records for the given attestationHash\n\t\tconst attestations = await this.getApiData<GetAttestationResponse>(\"/attestation/get\", {\n\t\t\thash: attestationHash,\n\t\t});\n\t\tconsole.log(\"getAttestations\", attribute, attestationHash, attestations);\n\n\t\treturn attestations;\n\t}\n\n\t// /**\n\t// * Helper function to get attestation from a BAP API server\n\t// *\n\t// * @param apiUrl\n\t// * @param apiData\n\t// * @returns {Promise<any>}\n\t// */\n\t// async getApiData(apiUrl: string, apiData: any): Promise<any> {\n\t// \tconst url = `${this.#BAP_SERVER}${apiUrl}`;\n\t// \tconst response = await fetch(url, {\n\t// \t\tmethod: \"post\",\n\t// \t\theaders: {\n\t// \t\t\t\"Content-type\": \"application/json; charset=utf-8\",\n\t// \t\t\ttoken: this.#BAP_TOKEN,\n\t// \t\t\tformat: \"json\",\n\t// \t\t},\n\t// \t\tbody: JSON.stringify(apiData),\n\t// \t});\n\t// \treturn response.json();\n\t// }\n\n\t/**\n\t * Import an identity from a JSON object\n\t *\n\t * @param identity{{}}\n\t */\n\timport(identity: Identity): void {\n\t\tthis.idName = identity.name;\n\t\tthis.description = identity.description || \"\";\n\t\tthis.identityKey = identity.identityKey;\n\t\tthis.#rootPath = identity.rootPath;\n\t\tthis.rootAddress = identity.rootAddress;\n\t\tthis.#previousPath = identity.previousPath;\n\t\tthis.#currentPath = identity.currentPath;\n\t\tthis.#idSeed = identity.idSeed || \"\";\n\t\tthis.identityAttributes = this.parseAttributes(identity.identityAttributes);\n\t}\n\n\t/**\n\t * Export this identity to a JSON object\n\t * @returns {{}}\n\t */\n\texport(): Identity {\n\t\treturn {\n\t\t\tname: this.idName,\n\t\t\tdescription: this.description,\n\t\t\tidentityKey: this.identityKey,\n\t\t\trootPath: this.#rootPath,\n\t\t\trootAddress: this.rootAddress,\n\t\t\tpreviousPath: this.#previousPath,\n\t\t\tcurrentPath: this.#currentPath,\n\t\t\tidSeed: this.#idSeed,\n\t\t\tidentityAttributes: this.getAttributes(),\n\t\t\tlastIdPath: \"\",\n\t\t};\n\t}\n}\n\nexport { BAP_ID };\n","import { BigNumber, BSM, HD, type PublicKey, Signature, ECIES } from \"@bsv/sdk\";\n\nimport { Utils } from \"./utils\";\nimport { BAP_ID } from \"./id\";\nimport {\n\tENCRYPTION_PATH,\n\tBAP_SERVER,\n\tBAP_BITCOM_ADDRESS,\n\tBAP_BITCOM_ADDRESS_HEX,\n\tAIP_BITCOM_ADDRESS,\n} from \"./constants\";\nimport { type APIFetcher, apiFetcher } from \"./api\";\nimport type { Attestation, Identity, IdentityAttributes, PathPrefix } from \"./interface\";\nimport { Utils as BSVUtils } from \"@bsv/sdk\";\nimport type { AttestationValidResponse, GetAttestationResponse, GetIdentityByAddressResponse } from \"./apiTypes\";\nconst { toArray, toUTF8, toBase64 } = BSVUtils;\nconst { electrumEncrypt, electrumDecrypt } = ECIES;\n\ntype Identities = { lastIdPath: string; ids: Identity[] };\n\n\n/**\n * BAP class\n *\n * Creates an instance of the BAP class and uses the given HDPrivateKey for all BAP operations.\n *\n * @param HDPrivateKey\n */\nexport class BAP {\n\t#HDPrivateKey;\n\t#ids: { [key: string]: BAP_ID } = {};\n\t#BAP_SERVER = BAP_SERVER;\n\t#BAP_TOKEN = \"\";\n\t#lastIdPath = \"\";\n getApiData: APIFetcher;\n\n\n \n\tconstructor(HDPrivateKey: string, token = \"\", server = \"\") {\n\t\tif (!HDPrivateKey) {\n\t\t\tthrow new Error(\"No HDPrivateKey given\");\n\t\t}\n\t\tthis.#HDPrivateKey = HD.fromString(HDPrivateKey);\n\n\t\tif (token) {\n\t\t\tthis.#BAP_TOKEN = token;\n\t\t}\n\n if (server) {\n this.#BAP_SERVER = server;\n }\n\n this.getApiData = apiFetcher(this.#BAP_SERVER, this.#BAP_TOKEN);\n\t}\n\n\tget lastIdPath(): string {\n\t\treturn this.#lastIdPath;\n\t}\n\n\t/**\n\t * Get the public key of the given childPath, or of the current HDPrivateKey of childPath is empty\n\t *\n\t * @param childPath Full derivation path for this child\n\t * @returns {*}\n\t */\n\tgetPublicKey(childPath = \"\"): string {\n\t\tif (childPath) {\n\t\t\treturn this.#HDPrivateKey.derive(childPath).pubKey.toString();\n\t\t}\n\n\t\treturn this.#HDPrivateKey.pubKey.toString();\n\t}\n\n\t/**\n\t * Get the public key of the given childPath, or of the current HDPrivateKey of childPath is empty\n\t *\n\t * @param childPath Full derivation path for this child\n\t * @returns {*}\n\t */\n\tgetHdPublicKey(childPath = \"\"): string {\n\t\tif (childPath) {\n\t\t\treturn this.#HDPrivateKey.derive(childPath).toPublic().toString();\n\t\t}\n\n\t\treturn this.#HDPrivateKey.toPublic().toString();\n\t}\n\n\tset BAP_SERVER(bapServer) {\n\t\tthis.#BAP_SERVER = bapServer;\n\t\tfor (const key in this.#ids) {\n\t\t\tthis.#ids[key].BAP_SERVER = bapServer;\n\t\t}\n\t}\n\n\tget BAP_SERVER(): string {\n\t\treturn this.#BAP_SERVER;\n\t}\n\n\tset BAP_TOKEN(token) {\n\t\tthis.#BAP_TOKEN = token;\n\t\tfor (const key in this.#ids) {\n\t\t\t// @ts-ignore - does not recognize private fields that can be set\n\t\t\tthis.#ids[key].BAP_TOKEN = token;\n\t\t}\n\t}\n\n\tget BAP_TOKEN(): string {\n\t\treturn this.#BAP_TOKEN;\n\t}\n\n\t/**\n\t * This function verifies that the given bapId matches the given root address\n\t * This is used as a data integrity check\n\t *\n\t * @param bapId BAP_ID instance\n\t */\n\tcheckIdBelongs(bapId: BAP_ID): boolean {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(bapId.rootPath);\n\t\tconst checkRootAddress = derivedChild.pubKey.toAddress();\n\t\tif (checkRootAddress !== bapId.rootAddress) {\n\t\t\tthrow new Error(\"ID does not belong to this private key\");\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns a list of all the identity keys that are stored in this instance\n\t *\n\t * @returns {string[]}\n\t */\n\tlistIds(): string[] {\n\t\treturn Object.keys(this.#ids);\n\t}\n\n\t/**\n\t * Create a new Id and link it to this BAP instance\n\t *\n\t * This function uses the length of the #ids of this class to determine the next valid path.\n\t * If not all ids related to this HDPrivateKey have been loaded, determine the path externally\n\t * and pass it to newId when creating a new ID.\n\t *\n\t * @param path\n\t * @param identityAttributes\n\t * @param idSeed\n\t * @returns {*}\n\t */\n\tnewId(path?: string, identityAttributes: IdentityAttributes = {}, idSeed = \"\"): BAP_ID {\n let pathToUse: string;\n\t\tif (!path) {\n\t\t\t// get next usable path for this key\n\t\t\tpathToUse = this.getNextValidPath();\n\t\t} else {\n pathToUse = path;\n }\n\n\t\tconst newIdentity = new BAP_ID(\n\t\t\tthis.#HDPrivateKey,\n\t\t\tidentityAttributes,\n\t\t\tidSeed,\n\t\t);\n\t\tnewIdentity.BAP_SERVER = this.#BAP_SERVER;\n\t\tnewIdentity.BAP_TOKEN = this.#BAP_TOKEN;\n\n\t\tnewIdentity.rootPath = pathToUse;\n\t\tnewIdentity.currentPath = Utils.getNextPath(pathToUse);\n\n\t\tconst idKey = newIdentity.getIdentityKey();\n\t\tthis.#ids[idKey] = newIdentity;\n\t\tthis.#lastIdPath = pathToUse;\n\n\t\treturn this.#ids[idKey];\n\t}\n\n\t/**\n\t * Remove identity\n\t *\n\t * @param idKey\n\t * @returns {*}\n\t */\n\tremoveId(idKey: string): void {\n\t\tdelete this.#ids[idKey];\n\t}\n\n\t/**\n\t * Get the next valid path for the used HDPrivateKey and loaded #ids\n\t *\n\t * @returns {string}\n\t */\n\tgetNextValidPath(): PathPrefix {\n\t\t// prefer hardened paths\n\t\tif (this.#lastIdPath) {\n\t\t\treturn Utils.getNextIdentityPath(this.#lastIdPath);\n\t\t}\n\n\t\treturn `/0'/${Object.keys(this.#ids).length}'/0'`;\n\t}\n\n\t/**\n\t * Get a certain Id\n\t *\n\t * @param identityKey\n\t * @returns {null}\n\t */\n\tgetId(identityKey: string): BAP_ID | null {\n\t\treturn this.#ids[identityKey] || null;\n\t}\n\n\t/**\n\t * This function is used when manipulating ID's, adding or removing attributes etc\n\t * First create an id through this class and then use getId to get it. Then you can add/edit or\n\t * increment the signing path and then re-set it with this function.\n\t *\n\t * Note: when you getId() from this class, you will be working on the same object as this class\n\t * has and any changes made will be propagated to the id in this class. When you call exportIds\n\t * your new changes will also be included, without having to setId().\n\t *\n\t * @param bapId\n\t */\n\tsetId(bapId: BAP_ID): void {\n\t\tthis.checkIdBelongs(bapId);\n\t\tthis.#ids[bapId.getIdentityKey()] = bapId;\n\t}\n\n\t/**\n\t * This function is used to import IDs and attributes from some external storage\n\t *\n\t * The ID information should NOT be stored together with the HD private key !\n\t *\n\t * @param idData Array of ids that have been exported\n\t * @param encrypted Whether the data should be treated as being encrypted (default true)\n\t */\n\timportIds(idData: Identities | string, encrypted = true): void {\n\t\tif (encrypted && typeof idData === \"string\") {\n\t\t\tthis.importEncryptedIds(idData);\n\t\t\treturn;\n\t\t}\n const identity = idData as Identities\n if (!identity.lastIdPath) {\n throw new Error(\"ID cannot be imported as it is not complete\");\n }\n\n if (!identity.ids) {\n throw new Error(`ID data is not in the correct format: ${idData}`);\n }\n \n\t\tlet lastIdPath = (idData as Identities).lastIdPath;\n\t\tfor (const id of identity.ids) {\n\t\t\tif (!id.identityKey || !id.identityAttributes || !id.rootAddress) {\n\t\t\t\tthrow new Error(\"ID cannot be imported as it is not complete\");\n\t\t\t}\n\t\t\tconst importId = new BAP_ID(this.#HDPrivateKey, {}, id.idSeed);\n\t\t\timportId.BAP_SERVER = this.#BAP_SERVER;\n\t\t\timportId.BAP_TOKEN = this.#BAP_TOKEN;\n\t\t\timportId.import(id);\n if (lastIdPath === \"\") {\n lastIdPath = importId.currentPath;\n }\n\n\t\t\tthis.checkIdBelongs(importId);\n\t\t\tthis.#ids[importId.getIdentityKey()] = importId;\n\t\t}\n\n\t\tthis.#lastIdPath = lastIdPath;\n\t}\n \n\timportEncryptedIds(idData: string): void {\n\t\t// decrypt the ids array using ECIES\n const decrypted = this.decrypt(idData);\n\t\tconst ids = JSON.parse(decrypted) as Identities;\n \n const isOldFormat = Array.isArray(ids)\n if (isOldFormat) {\n console.log(\"Importing old format:\\n\", ids)\n this.importOldIds(ids)\n return\n }\n if (typeof ids !== \"object\") {\n throw new Error(\"decrypted, but found unrecognized identities format\")\n }\n\t\tthis.importIds(ids, false);\n\t}\n\n\timportOldIds(idData: Identity[]): void {\n\t\tfor (const id of idData) {\n\t\t\tconst importId = new BAP_ID(this.#HDPrivateKey, {}, id.idSeed);\n\t\t\timportId.BAP_SERVER = this.#BAP_SERVER;\n\t\t\timportId.BAP_TOKEN = this.#BAP_TOKEN;\n\t\t\timportId.import(id);\n\n\t\t\tthis.checkIdBelongs(importId);\n\n\t\t\tthis.#ids[importId.getIdentityKey()] = importId;\n\n\t\t\t// overwrite with the last value on this array\n\t\t\tthis.#lastIdPath = importId.currentPath;\n\t\t}\n\t}\n\n\n\t/**\n\t * Export all the IDs of this instance for external storage\n\t *\n\t * By default this function will encrypt the data, using a derivative child of the main HD key\n\t *\n\t * @param encrypted Whether the data should be encrypted (default true)\n\t * @returns {[]|*}\n\t */\n // Overload signatures\n exportIds(encrypted: true): string;\n exportIds(encrypted: false): Identities;\n exportIds(encrypted?: boolean): Identities | string;\n\texportIds(encrypted = true): Identities | string {\n\t\tconst idData: Identities = {\n\t\t\tlastIdPath: this.#lastIdPath,\n\t\t\tids: [] as Identity[],\n\t\t};\n\n\t\tfor (const key in this.#ids) {\n\t\t\tidData.ids.push(this.#ids[key].export());\n\t\t}\n\n\t\tif (encrypted) {\n\t\t\treturn this.encrypt(JSON.stringify(idData));\n\t\t}\n\n\t\treturn idData \n\t}\n\n\t/**\n\t * Encrypt a string of data\n\t *\n\t * @param string\n\t * @returns {string}\n\t */\n\tencrypt(string: string): string {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n\t\treturn toBase64(\n // @ts-ignore - you can remove the null when this is merged https://github.com/bitcoin-sv/ts-sdk/pull/123\n\t\t\telectrumEncrypt(toArray(string), derivedChild.pubKey, null),\n\t\t);\n\t}\n\n\t/**\n\t * Decrypt a string of data\n\t *\n\t * @param string\n\t * @returns {string}\n\t */\n\tdecrypt(string: string): string {\n\t\tconst derivedChild = this.#HDPrivateKey.derive(ENCRYPTION_PATH);\n\t\treturn toUTF8(\n\t\t\telectrumDecrypt(toArray(string, \"base64\"), derivedChild.privKey),\n\t\t);\n\t}\n\n\t/**\n\t * Sign an attestation for a user\n\t *\n\t * @param attestationHash The computed attestation hash for the user - this should be calculated with the BAP_ID class for an identity for the user\n\t * @param identityKey The identity key we are using for the signing\n\t * @param counter\n\t * @param dataString Optional data string that will be appended to the BAP attestation\n\t * @returns {string[]}\n\t */\n\tsignAttestationWithAIP(\n\t\tattestationHash: string,\n\t\tidentityKey: string,\n\t\tcounter = 0,\n\t\tdataString = \"\",\n\t) {\n\t\tconst id = this.getId(identityKey);\n\t\tif (!id) {\n\t\t\tthrow new Error(\"Could not find identity to attest with\");\n\t\t}\n\n\t\tconst attestationBuffer = this.getAttestationBuffer(\n\t\t\tattestationHash,\n\t\t\tcounter,\n\t\t\tdataString,\n\t\t);\n\t\tconst { address, signature } = id.signMessage(attestationBuffer);\n\n\t\treturn this.createAttestationTransaction(\n\t\t\tattestationHash,\n\t\t\tcounter,\n\t\t\taddress,\n\t\t\tsignature,\n\t\t\tdataString,\n\t\t);\n\t}\n\n\t/**\n\t * Verify an AIP signed attestation for a user\n\t *\n\t * [\n\t * '0x6a',\n\t * '0x31424150537561506e66476e53424d33474c56397968785564596534764762644d54',\n\t * '0x415454455354',\n\t * '0x33656166366361396334313936356538353831366439336439643034333136393032376633396661623034386333633031333663343364663635376462383761',\n\t * '0x30',\n\t * '0x7c',\n\t * '0x313550636948473232534e4c514a584d6f5355615756693757537163376843667661',\n\t * '0x424954434f494e5f4543445341',\n\t * '0x31477531796d52567a595557634638776f6f506a7a4a4c764d383550795a64655876',\n\t * '0x20ef60c5555001ddb1039bb0f215e46571fcb39ee46f48b089d1c08b0304dbcb3366d8fdf8bafd82be24b5ac42dcd6a5e96c90705dd42e3ad918b1b47ac3ce6ac2'\n\t * ]\n\t *\n\t * @param tx Array of hex values for the OP_RETURN values\n\t * @returns {{}}\n\t */\n\tverifyAttestationWithAIP(tx: string[]): Attestation {\n\t\tif (\n\t\t\t!Array.isArray(tx) ||\n\t\t\ttx[0] !== \"0x6a\" ||\n\t\t\ttx[1] !== BAP_BITCOM_ADDRESS_HEX\n\t\t) {\n\t\t\tthrow new Error(\"Not a valid BAP transaction\");\n\t\t}\n\n\t\tconst dataOffset = tx[7] === \"0x44415441\" ? 5 : 0; // DATA\n\t\tconst attestation: Attestation = {\n\t\t\ttype: Utils.hexDecode(tx[2]),\n\t\t\thash: Utils.hexDecode(tx[3]),\n\t\t\tsequence: Utils.hexDecode(tx[4]),\n\t\t\tsigningProtocol: Utils.hexDecode(tx[7 + dataOffset]),\n\t\t\tsigningAddress: Utils.hexDecode(tx[8 + dataOffset]),\n\t\t\tsignature: Utils.hexDecode(tx[9 + dataOffset], \"base64\"),\n\t\t};\n\n\t\tif (dataOffset && tx[3] === tx[8]) {\n\t\t\t// valid data addition\n\t\t\tattestation.data = Utils.hexDecode(tx[9]);\n\t\t}\n\n\t\ttry {\n\t\t\tconst signatureBufferStatements = [];\n\t\t\tfor (let i = 0; i < 6 + dataOffset; i++) {\n\t\t\t\tsignatureBufferStatements.push(\n\t\t\t\t\tBuffer.from(tx[i].replace(\"0x\", \"\"), \"hex\"),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst attestationBuffer = Buffer.concat([...signatureBufferStatements]);\n\t\t\tattestation.verified = this.verifySignature(\n\t\t\t\tattestationBuffer,\n\t\t\t\tattestation.signingAddress,\n\t\t\t\tattestation.signature,\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tattestation.verified = false;\n\t\t}\n\n\t\treturn attestation;\n\t}\n\n\t/**\n\t * For BAP attestations we use all fields for the attestation\n\t *\n\t * @param attestationHash\n\t * @param counter\n\t * @param address\n\t * @param signature\n\t * @param dataString Optional data string that will be appended to the BAP attestation\n\t * @returns {[string]}\n\t */\n\tcreateAttestationTransaction(\n\t\tattestationHash: string,\n\t\tcounter: number,\n\t\taddress: string,\n\t\tsignature: string,\n\t\tdataString = \"\",\n\t): string[] {\n\t\tconst transaction = [\"0x6a\", Utils.hexEncode(BAP_BITCOM_ADDRESS)];\n\t\ttransaction.push(Utils.hexEncode(\"ATTEST\"));\n\t\ttransaction.push(Utils.hexEncode(attestationHash));\n\t\ttransaction.push(Utils.hexEncode(`${counter}`));\n\t\ttransaction.push(\"0x7c\"); // |\n\t\tif (dataString) {\n\t\t\t// data should be a string, either encrypted or stringified JSON if applicable\n\t\t\ttransaction.push(Utils.hexEncode(BAP_BITCOM_ADDRESS));\n\t\t\ttransaction.push(Utils.hexEncode(\"DATA\"));\n\t\t\ttransaction.push(Utils.hexEncode(attestationHash));\n\t\t\ttransaction.push(Utils.hexEncode(dataString));\n\t\t\ttransaction.push(\"0x7c\"); // |\n\t\t}\n\t\ttransaction.push(Utils.hexEncode(AIP_BITCOM_ADDRESS));\n\t\ttransaction.push(Utils.hexEncode(\"BITCOIN_ECDSA\"));\n\t\ttransaction.push(Utils.hexEncode(address));\n\t\ttransaction.push(`0x${Buffer.from(signature, \"base64\").toString(\"hex\")}`);\n\n\t\treturn transaction;\n\t}\n\n\t/**\n\t * This is a re-creation of how the bitcoinfiles-sdk creates a hash to sign for AIP\n\t *\n\t * @param attestationHash\n\t * @param counter\n\t * @param dataString Optional data string\n\t * @returns {Buffer}\n\t */\n\tgetAttestationBuffer(\n\t\tattestationHash: string,\n\t\tcounter = 0,\n\t\tdataString = \"\",\n\t): Buffer {\n\t\t// re-create how AIP creates the buffer to sign\n\t\tlet dataStringBuffer = Buffer.from(\"\");\n\t\tif (dataString) {\n\t\t\tdataStringBuffer = Buffer.concat([\n\t\t\t\tBuffer.from(BAP_BITCOM_ADDRESS),\n\t\t\t\tBuffer.from(\"DATA\"),\n\t\t\t\tBuffer.from(attestationHash),\n\t\t\t\tBuffer.from(dataString),\n\t\t\t\tBuffer.from(\"7c\", \"hex\"),\n\t\t\t]);\n\t\t}\n\t\treturn Buffer.concat([\n\t\t\tBuffer.from(\"6a\", \"hex\"), // OP_RETURN\n\t\t\tBuffer.from(BAP_BITCOM_ADDRESS),\n\t\t\tBuffer.from(\"ATTEST\"),\n\t\t\tBuffer.from(attestationHash),\n\t\t\tBuffer.from(`${counter}`),\n\t\t\tBuffer.from(\"7c\", \"hex\"),\n\t\t\tdataStringBuffer,\n\t\t]);\n\t}\n\n\t/**\n\t * Verify that the identity challenge is signed by the address\n\t *\n\t * @param message Buffer or utf-8 string\n\t * @param address Bitcoin address of signee\n\t * @param signature Signature base64 string\n\t *\n\t * @return boolean\n\t */\n\tverifySignature(\n\t\tmessage: string | Buffer,\n\t\taddress: string,\n\t\tsignature: string,\n\t): boolean {\n\t\t// check the signature against the challenge\n\t\tconst messageBuffer = Buffer.isBuffer(message)\n\t\t\t? message\n\t\t\t: Buffer.from(message);\n\t\tconst sig = Signature.fromCompact(signature, \"base64\");\n\t\tlet publicKey: PublicKey | undefined;\n\t\tconst msg = toArray(messageBuffer.toString(\"hex\"), \"hex\");\n\t\tfor (let recovery = 0; recovery < 4; recovery++) {\n\t\t\ttry {\n\t\t\t\tpublicKey = sig.RecoverPublicKey(\n\t\t\t\t\trecovery,\n\t\t\t\t\tnew BigNumber(BSM.magicHash(msg)),\n\t\t\t\t);\n\t\t\t\tconst sigFitsPubkey = BSM.verify(msg, sig, publicKey);\n\t\t\t\tif (sigFitsPubkey && publicKey.toAddress() === address) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\t// try next recovery\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Check whether the given transaction (BAP OP_RETURN) is valid, is signed and that the\n\t * identity signing is also valid at the time of signing\n\t *\n\t * @param idKey\n\t * @param address\n\t * @param challenge\n\t * @param signature\n\t *\n\t * @returns {Promise<boolean|*>}\n\t */\n\tasync verifyChallengeSignature(\n\t\tidKey: string,\n\t\taddress: string,\n\t\tchallenge: string,\n\t\tsignature: string,\n\t): Promise<boolean> {\n\t\t// first we test locally before sending to server\n\t\tif (this.verifySignature(challenge, address, signature)) {\n\t\t\tconst result = await this.getApiData<AttestationValidResponse>(\"/attestation/valid\", {\n\t\t\t\tidKey,\n\t\t\t\tchallenge,\n\t\t\t\tsignature,\n\t\t\t});\n\t\t\treturn result ? result.valid : false;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Check whether the given transaction (BAP OP_RETURN) is valid, is signed and that the\n\t * identity signing is also valid at the time of signing\n\t *\n\t * @param tx\n\t * @returns {Promise<boolean|*>}\n\t */\n\tasync isValidAttestationTransaction(tx: string[]): Promise<any> {\n\t\t// first we test locally before sending to server\n\t\tif (this.verifyAttestationWithAIP(tx)) {\n\t\t\treturn this.getApiData(\"/attestation/valid\", {\n\t\t\t\ttx,\n\t\t\t});\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Get all signing keys for the given idKey\n\t *\n\t * @param address\n\t * @returns {Promise<*>}\n\t */\n\tasync getIdentityFromAddress(address: string): Promise<GetIdentityByAddressResponse> {\n\t\treturn this.getApiData(\"/identity/from-address\", {\n\t\t\taddress,\n\t\t});\n\t}\n\n\t/**\n\t * Get all signing keys for the given idKey\n\t *\n\t * @param idKey\n\t * @returns {Promise<*>}\n\t */\n\tasync getIdentity(idKey: string): Promise<any> {\n\t\treturn this.getApiData(\"/identity\", {\n\t\t\tidKey,\n\t\t});\n\t}\n\n\t/**\n\t * Get all attestations for the given attestation hash\n\t *\n\t * @param attestationHash\n\t */\n\tasync getAttestationsForHash(attestationHash: string): Promise<GetAttestationResponse> {\n\t\t// get all BAP ATTEST records for the given attestationHash\n\t\treturn this.getApiData(\"/attestations\", {\n\t\t\thash: attestationHash,\n\t\t});\n\t}\n\n \n};\n\nexport { BAP_ID }"],"names":["Utils","string","Buffer","from","toString","hexString","encoding","replace","hardened","signingPath","signingHex","match","Error","_step","maxNumber","_iterator","_createForOfIteratorHelperLoose","done","number","Number","hexNumber","value","path","pathValues","split","lastPart","length","nextPath","join","BAP_BITCOM_ADDRESS","BAP_BITCOM_ADDRESS_HEX","AIP_BITCOM_ADDRESS","BAP_SERVER","MAX_INT","SIGNING_PATH_PREFIX","ENCRYPTION_PATH","apiFetcher","host","token","url","data","apiUrl","apiData","server","Promise","resolve","fetch","method","headers","format","body","JSON","stringify","then","response","json","e","reject","getApiData","toArray","BSVUtils","toHex","toBase58","toUTF8","toBase64","electrumDecrypt","ECIES","electrumEncrypt","magicHash","BSM","_HDPrivateKey","_classPrivateFieldLooseKey","_BAP_SERVER","_BAP_TOKEN","_rootPath","_previousPath","_currentPath","_idSeed","BAP_ID","HDPrivateKey","identityAttributes","idSeed","Object","defineProperty","this","writable","idName","description","rootAddress","identityKey","_classPrivateFieldLooseBase","seedHex","Hash","sha256","seedPath","derive","rootChild","privKey","toPublicKey","toAddress","deriveIdentityKey","attributes","_extends","parseAttributes","_proto","prototype","_createClass","address","rootAddressHash","ripemd160","parseStringUrns","key","nonce","urnIdentityAttributes","urn","getIdentityKey","getAttributes","getAttribute","attributeName","setAttribute","attributeValue","addAttribute","unsetAttribute","getAttributeUrns","urns","getAttributeUrn","attribute","nonceToUse","randomBytes","getRootPath","incrementPath","currentPath","validatePath","getInitialIdTransaction","getIdTransaction","previousPath","opReturn","getCurrentAddress","signOpReturnWithAIP","getAddress","getEncryptionPublicKey","getEncryptionPublicKeyWithSeed","seed","getEncryptionPrivateKeyWithSeed","encrypt","stringData","counterPartyPublicKey","publicKey","pubKey","PublicKey","fromString","decrypt","ciphertext","encryptionKey","undefined","encryptWithSeed","decryptWithSeed","pathHex","getAttestation","urnHash","getAttestationHash","attestation","attestationHash","signMessage","message","msg","pathToUse","childPk","dummySig","sign","h","BigNumber","r","CalculateRecoveryFactor","signature","toCompact","signMessageWithSeed","derivedChild","outputType","aipMessageBuffer","getAIPMessageBuffer","_this$signMessage","concat","buffers","push","_step2","_iterator2","getIdSigningKeys","idKey","signingKeys","console","log","getAttributeAttestations","hash","attestations","identity","name","rootPath","lastIdPath","get","set","bapServer","_ids","_lastIdPath","BAP","HD","getPublicKey","childPath","getHdPublicKey","toPublic","checkIdBelongs","bapId","listIds","keys","newId","getNextValidPath","newIdentity","BAP_TOKEN","removeId","secondToLastPart","getId","setId","importIds","idData","encrypted","importEncryptedIds","ids","id","importId","decrypted","parse","Array","isArray","importOldIds","exportIds","signAttestationWithAIP","counter","dataString","attestationBuffer","getAttestationBuffer","_id$signMessage","createAttestationTransaction","verifyAttestationWithAIP","tx","dataOffset","type","sequence","signingProtocol","signingAddress","signatureBufferStatements","i","verified","verifySignature","transaction","dataStringBuffer","messageBuffer","isBuffer","sig","Signature","fromCompact","recovery","RecoverPublicKey","verify","verifyChallengeSignature","challenge","_exit","_this","_temp2","result","valid","_result","isValidAttestationTransaction","getIdentityFromAddress","getIdentity","getAttestationsForHash"],"mappings":"i3DAGa,IAAAA,WAODC,GACR,WAAYC,OAAOC,KAAKF,GAAQG,SAAS,MAC3C,EATWJ,EAkBX,SAAUK,EAAmBC,GAC3B,YAD2B,IAAAA,IAAAA,EAA2B,QAC/CJ,OAAOC,KAAKE,EAAUE,QAAQ,KAAM,IAAK,OAAOH,SAASE,EAClE,EApBWN,EAmDU,SAACK,EAAmBG,QAAQ,IAARA,IAAAA,GAAW,GAElD,IAAIC,EAAc,IACZC,EAAaL,EAAUM,MAAM,WACnC,IAAKD,EACH,MAAU,IAAAE,MAAM,sBAGlB,IADA,IACkCC,EAD5BC,EAAY,WAClBC,EAAAC,EAAwBN,KAAUG,EAAAE,KAAAE,MAAE,CAAA,IAC9BC,EAASC,OAAYC,KADPP,EAAAQ,OAEdH,EAASJ,IAAWI,GAAUJ,GAClCL,GAAW,IAAQS,GAAUV,EAAW,IAAM,GAChD,CAEA,OAAOC,CACT,EAlEWT,WAgGCsB,GACV,IAAMC,EAAaD,EAAKE,MAAM,KACxBC,EAAWF,EAAWA,EAAWG,OAAS,GAC5ClB,GAAW,EACXiB,EAASd,MAAM,OACjBH,GAAW,GAEb,IAAMmB,GAAYR,OAAOM,EAASlB,QAAQ,UAAW,KAAO,GAAGH,WAE/D,OADAmB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