bsv-bap 0.0.5 → 0.1.1
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/{id.d.ts → MasterID.d.ts} +14 -9
- package/dist/MemberID.d.ts +27 -0
- package/dist/apiTypes.d.ts +45 -18
- package/dist/index.d.ts +19 -21
- package/dist/index.modern.js +8 -2
- package/dist/index.modern.js.map +15 -1
- package/dist/index.module.js +8 -2
- package/dist/index.module.js.map +15 -1
- package/dist/interface.d.ts +12 -3
- package/dist/poa.d.ts +1 -1
- package/dist/utils.d.ts +1 -1
- package/package.json +23 -19
- package/dist/index.cjs +0 -2
- package/dist/index.cjs.map +0 -1
- package/dist/index.umd.js +0 -2
- package/dist/index.umd.js.map +0 -1
@@ -1,15 +1,16 @@
|
|
1
1
|
import { type HD } from "@bsv/sdk";
|
2
2
|
import { type APIFetcher } from "./api";
|
3
|
-
import type {
|
4
|
-
import type {
|
3
|
+
import type { GetAttestationResponse, GetSigningKeysResponse } from "./apiTypes";
|
4
|
+
import type { Identity, IdentityAttribute, IdentityAttributes, OldIdentity } from "./interface";
|
5
|
+
import { MemberID, type MemberIdentity } from './MemberID';
|
5
6
|
/**
|
6
|
-
*
|
7
|
+
* MasterID class
|
7
8
|
*
|
8
9
|
* This class should be used in conjunction with the BAP class
|
9
10
|
*
|
10
|
-
* @type {
|
11
|
+
* @type {MasterID}
|
11
12
|
*/
|
12
|
-
declare class
|
13
|
+
declare class MasterID {
|
13
14
|
#private;
|
14
15
|
idName: string;
|
15
16
|
description: string;
|
@@ -69,6 +70,8 @@ declare class BAP_ID {
|
|
69
70
|
* @returns {{}|null}
|
70
71
|
*/
|
71
72
|
setAttribute(attributeName: string, attributeValue: string | Record<string, string>): void;
|
73
|
+
private updateExistingAttribute;
|
74
|
+
private createNewAttribute;
|
72
75
|
/**
|
73
76
|
* Unset the given attribute from the ID
|
74
77
|
*
|
@@ -96,7 +99,7 @@ declare class BAP_ID {
|
|
96
99
|
* @param value
|
97
100
|
* @param nonce
|
98
101
|
*/
|
99
|
-
addAttribute(attributeName: string, value:
|
102
|
+
addAttribute(attributeName: string, value: string, nonce?: string): void;
|
100
103
|
/**
|
101
104
|
* This should be called with the last part of the signing path (/.../.../...)
|
102
105
|
* This library assumes the first part is m/424150'/0'/0' as defined at the top of this file
|
@@ -254,7 +257,7 @@ declare class BAP_ID {
|
|
254
257
|
/**
|
255
258
|
* Get all signing keys for this identity
|
256
259
|
*/
|
257
|
-
getIdSigningKeys(): Promise<
|
260
|
+
getIdSigningKeys(): Promise<GetSigningKeysResponse>;
|
258
261
|
/**
|
259
262
|
* Get all attestations for the given attribute
|
260
263
|
*
|
@@ -266,11 +269,13 @@ declare class BAP_ID {
|
|
266
269
|
*
|
267
270
|
* @param identity{{}}
|
268
271
|
*/
|
269
|
-
import(identity: Identity): void;
|
272
|
+
import(identity: Identity | OldIdentity): void;
|
270
273
|
/**
|
271
274
|
* Export this identity to a JSON object
|
272
275
|
* @returns {{}}
|
273
276
|
*/
|
274
277
|
export(): Identity;
|
278
|
+
exportMemberBackup(): MemberIdentity;
|
279
|
+
newId(): MemberID;
|
275
280
|
}
|
276
|
-
export {
|
281
|
+
export { MasterID };
|
@@ -0,0 +1,27 @@
|
|
1
|
+
import { PrivateKey } from "@bsv/sdk";
|
2
|
+
import type { IdentityAttributes } from "./interface";
|
3
|
+
export interface MemberIdentity {
|
4
|
+
name: string;
|
5
|
+
description: string;
|
6
|
+
derivedPrivateKey: string;
|
7
|
+
address: string;
|
8
|
+
identityAttributes: IdentityAttributes;
|
9
|
+
}
|
10
|
+
declare class MemberID {
|
11
|
+
private key;
|
12
|
+
identityAttributes: IdentityAttributes;
|
13
|
+
address: string;
|
14
|
+
idName: string;
|
15
|
+
description: string;
|
16
|
+
constructor(key: PrivateKey, identityAttributes?: IdentityAttributes | string);
|
17
|
+
signMessage(message: string | Buffer): {
|
18
|
+
address: string;
|
19
|
+
signature: string;
|
20
|
+
};
|
21
|
+
getPublicKey(): string;
|
22
|
+
import(identity: MemberIdentity): void;
|
23
|
+
static fromImport(identity: MemberIdentity): MemberID;
|
24
|
+
export(): MemberIdentity;
|
25
|
+
private parseStringUrns;
|
26
|
+
}
|
27
|
+
export { MemberID };
|
package/dist/apiTypes.d.ts
CHANGED
@@ -1,36 +1,63 @@
|
|
1
|
-
import type {
|
2
|
-
export interface APIResponse<T
|
3
|
-
status:
|
1
|
+
import type { Organization, Person, WithContext } from 'schema-dts';
|
2
|
+
export interface APIResponse<T> {
|
3
|
+
status: 'success' | 'error';
|
4
4
|
result?: T;
|
5
5
|
message?: string;
|
6
6
|
}
|
7
|
-
export
|
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;
|
7
|
+
export interface Signer {
|
14
8
|
idKey: string;
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
9
|
+
signingAddress: string;
|
10
|
+
sequence: number;
|
11
|
+
block: number;
|
12
|
+
txId: string;
|
13
|
+
timestamp: number;
|
14
|
+
revoked: boolean;
|
15
|
+
}
|
16
|
+
export interface Attestation {
|
19
17
|
hash: string;
|
18
|
+
attribute?: string;
|
19
|
+
value?: string;
|
20
|
+
nonce?: string;
|
21
|
+
urn?: string;
|
22
|
+
signers: Signer[];
|
23
|
+
}
|
24
|
+
export interface SigningKey {
|
25
|
+
idKey: string;
|
26
|
+
signingAddress: string;
|
27
|
+
sequence: number;
|
20
28
|
block: number;
|
29
|
+
txId: string;
|
21
30
|
timestamp: number;
|
31
|
+
revoked: boolean;
|
22
32
|
}
|
23
|
-
export
|
33
|
+
export type GetSigningKeysResponse = APIResponse<Signer[]>;
|
34
|
+
export interface APIIdentityAddress {
|
24
35
|
address: string;
|
36
|
+
txId: string;
|
25
37
|
block: number;
|
26
|
-
|
38
|
+
}
|
39
|
+
export type APISchemaIdentity = WithContext<Person | Organization>;
|
40
|
+
export interface APIIdentity {
|
41
|
+
idKey: string;
|
42
|
+
firstSeen: number;
|
43
|
+
rootAddress: string;
|
44
|
+
currentAddress: string;
|
45
|
+
addresses: APIIdentityAddress[];
|
46
|
+
identity?: APISchemaIdentity;
|
27
47
|
}
|
28
48
|
export interface ValidityRecord {
|
29
49
|
valid: boolean;
|
30
50
|
block: number;
|
31
51
|
timestamp: number;
|
32
52
|
}
|
33
|
-
export interface
|
53
|
+
export interface Profile {
|
54
|
+
_id: string;
|
55
|
+
data: WithContext<Person | Organization>;
|
34
56
|
}
|
35
|
-
export interface IdentityValidResponse extends
|
57
|
+
export interface IdentityValidResponse extends APIIdentity, ValidityRecord {
|
58
|
+
profile?: Profile;
|
36
59
|
}
|
60
|
+
export type GetAttestationResponse = APIResponse<Attestation>;
|
61
|
+
export type GetIdentityResponse = APIResponse<APIIdentity>;
|
62
|
+
export type GetIdentityByAddressResponse = APIResponse<APIIdentity>;
|
63
|
+
export type AttestationValidResponse = APIResponse<ValidityRecord>;
|
package/dist/index.d.ts
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
import { type APIFetcher } from "./api";
|
2
|
-
import type { GetAttestationResponse, GetIdentityByAddressResponse } from "./apiTypes";
|
3
|
-
import {
|
4
|
-
import type { Attestation, Identity, IdentityAttributes, PathPrefix } from "./interface";
|
2
|
+
import type { AttestationValidResponse, GetAttestationResponse, GetIdentityByAddressResponse, GetIdentityResponse } from "./apiTypes";
|
3
|
+
import { MasterID } from "./MasterID";
|
4
|
+
import type { Attestation, Identity, IdentityAttributes, OldIdentity, PathPrefix } from "./interface";
|
5
5
|
type Identities = {
|
6
6
|
lastIdPath: string;
|
7
7
|
ids: Identity[];
|
@@ -40,9 +40,9 @@ export declare class BAP {
|
|
40
40
|
* This function verifies that the given bapId matches the given root address
|
41
41
|
* This is used as a data integrity check
|
42
42
|
*
|
43
|
-
* @param bapId
|
43
|
+
* @param bapId MasterID instance
|
44
44
|
*/
|
45
|
-
checkIdBelongs(bapId:
|
45
|
+
checkIdBelongs(bapId: MasterID): boolean;
|
46
46
|
/**
|
47
47
|
* Returns a list of all the identity keys that are stored in this instance
|
48
48
|
*
|
@@ -61,7 +61,7 @@ export declare class BAP {
|
|
61
61
|
* @param idSeed
|
62
62
|
* @returns {*}
|
63
63
|
*/
|
64
|
-
newId(path?: string, identityAttributes?: IdentityAttributes, idSeed?: string):
|
64
|
+
newId(path?: string, identityAttributes?: IdentityAttributes, idSeed?: string): MasterID;
|
65
65
|
/**
|
66
66
|
* Remove identity
|
67
67
|
*
|
@@ -81,7 +81,7 @@ export declare class BAP {
|
|
81
81
|
* @param identityKey
|
82
82
|
* @returns {null}
|
83
83
|
*/
|
84
|
-
getId(identityKey: string):
|
84
|
+
getId(identityKey: string): MasterID | null;
|
85
85
|
/**
|
86
86
|
* This function is used when manipulating ID's, adding or removing attributes etc
|
87
87
|
* First create an id through this class and then use getId to get it. Then you can add/edit or
|
@@ -93,7 +93,7 @@ export declare class BAP {
|
|
93
93
|
*
|
94
94
|
* @param bapId
|
95
95
|
*/
|
96
|
-
setId(bapId:
|
96
|
+
setId(bapId: MasterID): void;
|
97
97
|
/**
|
98
98
|
* This function is used to import IDs and attributes from some external storage
|
99
99
|
*
|
@@ -104,17 +104,14 @@ export declare class BAP {
|
|
104
104
|
*/
|
105
105
|
importIds(idData: Identities | string, encrypted?: boolean): void;
|
106
106
|
importEncryptedIds(idData: string): void;
|
107
|
-
importOldIds(idData:
|
107
|
+
importOldIds(idData: OldIdentity[]): void;
|
108
108
|
/**
|
109
|
-
* Export
|
110
|
-
*
|
111
|
-
*
|
112
|
-
*
|
113
|
-
* @param encrypted Whether the data should be encrypted (default true)
|
114
|
-
* @returns {[]|*}
|
109
|
+
* Export identities. If no idKeys are provided, exports all identities.
|
110
|
+
* @param idKeys Optional array of identity keys to export. If omitted, exports all identities.
|
111
|
+
* @param encrypted Whether to encrypt the export data
|
115
112
|
*/
|
116
|
-
exportIds(encrypted?: true): string;
|
117
|
-
exportIds(encrypted: false): Identities;
|
113
|
+
exportIds(idKeys?: string[], encrypted?: true): string;
|
114
|
+
exportIds(idKeys: string[] | undefined, encrypted: false): Identities;
|
118
115
|
/**
|
119
116
|
* Export a given ID from this instance for external storage
|
120
117
|
*
|
@@ -143,7 +140,7 @@ export declare class BAP {
|
|
143
140
|
/**
|
144
141
|
* Sign an attestation for a user
|
145
142
|
*
|
146
|
-
* @param attestationHash The computed attestation hash for the user - this should be calculated with the
|
143
|
+
* @param attestationHash The computed attestation hash for the user - this should be calculated with the MasterID class for an identity for the user
|
147
144
|
* @param identityKey The identity key we are using for the signing
|
148
145
|
* @param counter
|
149
146
|
* @param dataString Optional data string that will be appended to the BAP attestation
|
@@ -219,7 +216,7 @@ export declare class BAP {
|
|
219
216
|
* @param tx
|
220
217
|
* @returns {Promise<boolean|*>}
|
221
218
|
*/
|
222
|
-
isValidAttestationTransaction(tx: string[]): Promise<
|
219
|
+
isValidAttestationTransaction(tx: string[]): Promise<AttestationValidResponse | false>;
|
223
220
|
/**
|
224
221
|
* Get all signing keys for the given idKey
|
225
222
|
*
|
@@ -233,7 +230,7 @@ export declare class BAP {
|
|
233
230
|
* @param idKey
|
234
231
|
* @returns {Promise<*>}
|
235
232
|
*/
|
236
|
-
getIdentity(idKey: string): Promise<
|
233
|
+
getIdentity(idKey: string): Promise<GetIdentityResponse>;
|
237
234
|
/**
|
238
235
|
* Get all attestations for the given attestation hash
|
239
236
|
*
|
@@ -241,4 +238,5 @@ export declare class BAP {
|
|
241
238
|
*/
|
242
239
|
getAttestationsForHash(attestationHash: string): Promise<GetAttestationResponse>;
|
243
240
|
}
|
244
|
-
export {
|
241
|
+
export { MasterID };
|
242
|
+
export type { Attestation, Identity, IdentityAttributes, PathPrefix };
|
package/dist/index.modern.js
CHANGED
@@ -1,2 +1,8 @@
|
|
1
|
-
import{Hash as t,PublicKey as e,BSM as i,BigNumber as r,Utils as s,ECIES as n,HD as o,Signature as h}from"@bsv/sdk";import a from"randombytes";function d(t,e){if(!{}.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}var u=0;function c(t){return"__private_"+u+++"_"+t}function f(){return f=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var r in i)({}).hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},f.apply(null,arguments)}const g=(t,e)=>async(i,r)=>(async(t,e,i,r)=>{const s=`${i}${t}`;return(await fetch(s,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:r,format:"json"},body:JSON.stringify(e)})).json()})(i,r,t,e),y="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",l=`0x${Buffer.from(y).toString("hex")}`,p="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva";Buffer.from(p).toString("hex");const A="https://api.sigmaidentity.com/v1",v=2147483647,P="m/424150'/0'/0'",b="m/424150'/2147483647'/2147483647'",m={hexEncode:t=>`0x${Buffer.from(t).toString("hex")}`,hexDecode:(t,e="utf8")=>Buffer.from(t.replace("0x",""),"hex").toString(e),getRandomString:(t=32)=>a(t).toString("hex"),isHex:t=>"string"==typeof t&&/^[0-9a-fA-F]+$/.test(t),getSigningPathFromHex(t,e=!0){let i="m";const r=t.match(/.{1,8}/g);if(!r)throw new Error("Invalid hex string");const s=2147483647;for(const t of r){let r=Number(`0x${t}`);r>s&&(r-=s),i+=`/${r}${e?"'":""}`}return i},getNextIdentityPath(t){const e=t.split("/"),i=e[e.length-2];let r=!1;i.match("'")&&(r=!0);const s=(Number(i.replace(/[^0-9]/g,""))+1).toString();return e[e.length-2]=s+(r?"'":""),e[e.length-1]="0"+(r?"'":""),e.join("/")},getNextPath(t){const e=t.split("/"),i=e[e.length-1];let r=!1;i.match("'")&&(r=!0);const s=(Number(i.replace(/[^0-9]/g,""))+1).toString();return e[e.length-1]=s+(r?"'":""),e.join("/")}},{toArray:S,toHex:x,toBase58:B,toUTF8:K,toBase64:E}=s,{electrumDecrypt:I,electrumEncrypt:w}=n,{magicHash:N}=i;var O=/*#__PURE__*/c("HDPrivateKey"),D=/*#__PURE__*/c("BAP_SERVER"),T=/*#__PURE__*/c("BAP_TOKEN"),R=/*#__PURE__*/c("rootPath"),$=/*#__PURE__*/c("previousPath"),_=/*#__PURE__*/c("currentPath"),j=/*#__PURE__*/c("idSeed");class C{constructor(e,i={},r=""){if(Object.defineProperty(this,O,{writable:!0,value:void 0}),Object.defineProperty(this,D,{writable:!0,value:A}),Object.defineProperty(this,T,{writable:!0,value:""}),Object.defineProperty(this,R,{writable:!0,value:void 0}),Object.defineProperty(this,$,{writable:!0,value:void 0}),Object.defineProperty(this,_,{writable:!0,value:void 0}),Object.defineProperty(this,j,{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,d(this,j)[j]=r,r){const i=x(t.sha256(r,"utf8")),s=m.getSigningPathFromHex(i);d(this,O)[O]=e.derive(s)}else d(this,O)[O]=e;this.idName="ID 1",this.description="",d(this,R)[R]=`${P}/0/0/0`,d(this,$)[$]=`${P}/0/0/0`,d(this,_)[_]=`${P}/0/0/1`;const s=d(this,O)[O].derive(d(this,R)[R]);this.rootAddress=s.privKey.toPublicKey().toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress);const n=f({},i);this.identityAttributes=this.parseAttributes(n),this.getApiData=g(d(this,D)[D],d(this,T)[T])}set BAP_SERVER(t){d(this,D)[D]=t}get BAP_SERVER(){return d(this,D)[D]}set BAP_TOKEN(t){d(this,T)[T]=t}get BAP_TOKEN(){return d(this,T)[T]}deriveIdentityKey(e){const i=x(t.sha256(e,"utf8"));return B(t.ripemd160(i,"hex"))}parseAttributes(t){if("string"==typeof t)return this.parseStringUrns(t);for(const e in t)if(!t[e].value||!t[e].nonce)throw new Error("Invalid identity attribute");return t||{}}parseStringUrns(t){const e={},i=t.replace(/^\s+/g,"").replace(/\r/gm,"").split("\n");for(const t of i){const i=t.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");"urn"===i[0]&&"bap"===i[1]&&"id"===i[2]&&i[3]&&i[4]&&i[5]&&(e[i[3]]={value:i[4],nonce:i[5]})}return e}getIdentityKey(){return this.identityKey}getAttributes(){return this.identityAttributes}getAttribute(t){return this.identityAttributes[t]?this.identityAttributes[t]:null}setAttribute(t,e){e&&(this.identityAttributes[t]?this.identityAttributes[t].value=e:this.addAttribute(t,e))}unsetAttribute(t){delete this.identityAttributes[t]}getAttributeUrns(){let t="";for(const e in this.identityAttributes){const i=this.getAttributeUrn(e);i&&(t+=`${i}\n`)}return t}getAttributeUrn(t){const e=this.identityAttributes[t];return e?`urn:bap:id:${t}:${e.value}:${e.nonce}`:null}addAttribute(t,e,i=""){let r=i;i||(r=m.getRandomString()),this.identityAttributes[t]={value:e,nonce:r}}set rootPath(t){if(d(this,O)[O]){let e=t;if(t.split("/").length<5&&(e=`${P}${t}`),!this.validatePath(e))throw new Error(`invalid signing path given ${e}`);d(this,R)[R]=e;const i=d(this,O)[O].derive(e);this.rootAddress=i.pubKey.toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress),d(this,$)[$]=e,d(this,_)[_]=e}}get rootPath(){return d(this,R)[R]}getRootPath(){return d(this,R)[R]}set currentPath(t){let e=t;if(t.split("/").length<5&&(e=`${P}${t}`),!this.validatePath(e))throw new Error("invalid signing path given");d(this,$)[$]=d(this,_)[_],d(this,_)[_]=e}get currentPath(){return d(this,_)[_]}get previousPath(){return d(this,$)[$]}get idSeed(){return d(this,j)[j]}incrementPath(){this.currentPath=m.getNextPath(this.currentPath)}validatePath(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}'?/)){const e=t.split("/");if(7===e.length&&Number(e[1].replace("'",""))<=v&&Number(e[2].replace("'",""))<=v&&Number(e[3].replace("'",""))<=v&&Number(e[4].replace("'",""))<=v&&Number(e[5].replace("'",""))<=v&&Number(e[6].replace("'",""))<=v)return!0}return!1}getInitialIdTransaction(){return this.getIdTransaction(d(this,R)[R])}getIdTransaction(t=""){if(d(this,_)[_]===d(this,R)[R])throw new Error("Current path equals rootPath. ID was probably not initialized properly");const e=[Buffer.from(y).toString("hex"),Buffer.from("ID").toString("hex"),Buffer.from(this.identityKey).toString("hex"),Buffer.from(this.getCurrentAddress()).toString("hex")];return this.signOpReturnWithAIP(e,t||d(this,$)[$])}getAddress(t){return d(this,O)[O].derive(t).privKey.toPublicKey().toAddress()}getCurrentAddress(){return this.getAddress(d(this,_)[_])}getEncryptionPublicKey(){return d(this,O)[O].derive(d(this,R)[R]).derive(b).privKey.toPublicKey().toString()}getEncryptionPublicKeyWithSeed(t){return this.getEncryptionPrivateKeyWithSeed(t).toPublicKey().toString("hex")}encrypt(t,i){const r=d(this,O)[O].derive(d(this,R)[R]).derive(b).privKey.toPublicKey(),s=i?e.fromString(i):r;return E(w(S(t),s,null))}decrypt(t,i){const r=d(this,O)[O].derive(d(this,R)[R]).derive(b).privKey;let s;return i&&(s=e.fromString(i)),K(I(S(t,"base64"),r,s))}encryptWithSeed(t,i,r){const s=this.getEncryptionPrivateKeyWithSeed(i),n=s.toPublicKey(),o=r?e.fromString(r):n;return E(w(S(t),o,s))}decryptWithSeed(t,i,r){const s=this.getEncryptionPrivateKeyWithSeed(i);let n;return r&&(n=e.fromString(r)),K(I(S(t,"base64"),s,n))}getEncryptionPrivateKeyWithSeed(e){const i=x(t.sha256(e,"utf8")),r=m.getSigningPathFromHex(i);return d(this,O)[O].derive(d(this,R)[R]).derive(r).privKey}getAttestation(e){const i=t.sha256(e,"utf8");return`bap:attest:${x(i)}:${this.getIdentityKey()}`}getAttestationHash(e){const i=this.getAttributeUrn(e);if(!i)return null;const r=this.getAttestation(i),s=t.sha256(r,"utf8");return x(s)}signMessage(t,e=""){let s;s=t instanceof Buffer?t:Buffer.from(t);const n=e||d(this,_)[_],o=d(this,O)[O].derive(n).privKey,h=o.toAddress(),a=i.sign(S(t),o,"raw"),u=new r(N(S(t,"utf8"))),c=a.CalculateRecoveryFactor(o.toPublicKey(),u);return{address:h,signature:i.sign(S(s),o,"raw").toCompact(c,!0,"base64")}}signMessageWithSeed(e,s){const n=x(t.sha256(s,"utf8")),o=m.getSigningPathFromHex(n),h=d(this,O)[O].derive(d(this,R)[R]).derive(o),a=h.privKey.toPublicKey().toAddress(),u=i.sign(S(e),h.privKey,"raw"),c=new r(N(S(e,"utf8"))),f=u.CalculateRecoveryFactor(h.privKey.toPublicKey(),c);return{address:a,signature:i.sign(S(Buffer.from(e)),h.privKey,"raw").toCompact(f,!0,"base64")}}signOpReturnWithAIP(t,e="",i="hex"){const r=this.getAIPMessageBuffer(t),{address:s,signature:n}=this.signMessage(r,e);return t.concat([Buffer.from("|").toString(i),Buffer.from(p).toString(i),Buffer.from("BITCOIN_ECDSA").toString(i),Buffer.from(s).toString(i),Buffer.from(n,"base64").toString(i)])}getAIPMessageBuffer(t){const e=[];"6a"!==t[0].replace("0x","")&&e.push(Buffer.from("6a","hex"));for(const i of t)e.push(Buffer.from(i.replace("0x",""),"hex"));return e.push(Buffer.from("|")),Buffer.concat([...e])}async getIdSigningKeys(){const t=await this.getApiData("/signing-keys",{idKey:this.identityKey});return console.log("getIdSigningKeys",t),t}async getAttributeAttestations(t){const e=this.getAttestationHash(t),i=await this.getApiData("/attestation/get",{hash:e});return console.log("getAttestations",t,e,i),i}import(t){this.idName=t.name,this.description=t.description||"",this.identityKey=t.identityKey,d(this,R)[R]=t.rootPath,this.rootAddress=t.rootAddress,d(this,$)[$]=t.previousPath,d(this,_)[_]=t.currentPath,d(this,j)[j]=t.idSeed||"",this.identityAttributes=this.parseAttributes(t.identityAttributes)}export(){return{name:this.idName,description:this.description,identityKey:this.identityKey,rootPath:d(this,R)[R],rootAddress:this.rootAddress,previousPath:d(this,$)[$],currentPath:d(this,_)[_],idSeed:d(this,j)[j],identityAttributes:this.getAttributes(),lastIdPath:""}}}const{toArray:H,toUTF8:V,toBase64:W}=s,{electrumEncrypt:F,electrumDecrypt:U}=n;var k=/*#__PURE__*/c("HDPrivateKey"),M=/*#__PURE__*/c("ids"),J=/*#__PURE__*/c("BAP_SERVER"),G=/*#__PURE__*/c("BAP_TOKEN"),q=/*#__PURE__*/c("lastIdPath");class z{constructor(t,e="",i=""){if(Object.defineProperty(this,k,{writable:!0,value:void 0}),Object.defineProperty(this,M,{writable:!0,value:{}}),Object.defineProperty(this,J,{writable:!0,value:A}),Object.defineProperty(this,G,{writable:!0,value:""}),Object.defineProperty(this,q,{writable:!0,value:""}),this.getApiData=void 0,!t)throw new Error("No HDPrivateKey given");d(this,k)[k]=o.fromString(t),e&&(d(this,G)[G]=e),i&&(d(this,J)[J]=i),this.getApiData=g(d(this,J)[J],d(this,G)[G])}get lastIdPath(){return d(this,q)[q]}getPublicKey(t=""){return t?d(this,k)[k].derive(t).pubKey.toString():d(this,k)[k].pubKey.toString()}getHdPublicKey(t=""){return t?d(this,k)[k].derive(t).toPublic().toString():d(this,k)[k].toPublic().toString()}set BAP_SERVER(t){d(this,J)[J]=t;for(const e in d(this,M)[M])d(this,M)[M][e].BAP_SERVER=t}get BAP_SERVER(){return d(this,J)[J]}set BAP_TOKEN(t){d(this,G)[G]=t;for(const e in d(this,M)[M])d(this,M)[M][e].BAP_TOKEN=t}get BAP_TOKEN(){return d(this,G)[G]}checkIdBelongs(t){if(d(this,k)[k].derive(t.rootPath).pubKey.toAddress()!==t.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(d(this,M)[M])}newId(t,e={},i=""){let r;r=t||this.getNextValidPath();const s=new C(d(this,k)[k],e,i);s.BAP_SERVER=d(this,J)[J],s.BAP_TOKEN=d(this,G)[G],s.rootPath=r,s.currentPath=m.getNextPath(r);const n=s.getIdentityKey();return d(this,M)[M][n]=s,d(this,q)[q]=r,d(this,M)[M][n]}removeId(t){delete d(this,M)[M][t]}getNextValidPath(){return d(this,q)[q]?m.getNextIdentityPath(d(this,q)[q]):`/0'/${Object.keys(d(this,M)[M]).length}'/0'`}getId(t){return d(this,M)[M][t]||null}setId(t){this.checkIdBelongs(t),d(this,M)[M][t.getIdentityKey()]=t}importIds(t,e=!0){if(e&&"string"==typeof t)return void this.importEncryptedIds(t);const i=t;if(!i.lastIdPath)throw new Error("ID cannot be imported as it is not complete");if(!i.ids)throw new Error(`ID data is not in the correct format: ${t}`);let r=t.lastIdPath;for(const t of i.ids){if(!t.identityKey||!t.identityAttributes||!t.rootAddress)throw new Error("ID cannot be imported as it is not complete");const e=new C(d(this,k)[k],{},t.idSeed);e.BAP_SERVER=d(this,J)[J],e.BAP_TOKEN=d(this,G)[G],e.import(t),""===r&&(r=e.currentPath),this.checkIdBelongs(e),d(this,M)[M][e.getIdentityKey()]=e}d(this,q)[q]=r}importEncryptedIds(t){const e=this.decrypt(t),i=JSON.parse(e);if(Array.isArray(i))return console.log("Importing old format:\n",i),void this.importOldIds(i);if("object"!=typeof i)throw new Error("decrypted, but found unrecognized identities format");this.importIds(i,!1)}importOldIds(t){for(const e of t){const t=new C(d(this,k)[k],{},e.idSeed);t.BAP_SERVER=d(this,J)[J],t.BAP_TOKEN=d(this,G)[G],t.import(e),this.checkIdBelongs(t),d(this,M)[M][t.getIdentityKey()]=t,d(this,q)[q]=t.currentPath}}exportIds(t=!0){const e={lastIdPath:d(this,q)[q],ids:[]};for(const t in d(this,M)[M])e.ids.push(d(this,M)[M][t].export());return t?this.encrypt(JSON.stringify(e)):e}exportId(t,e=!0){const i={lastIdPath:d(this,q)[q],ids:[]};return i.ids.push(d(this,M)[M][t].export()),e?this.encrypt(JSON.stringify(i)):i}encrypt(t){const e=d(this,k)[k].derive(b);return W(F(H(t),e.pubKey,null))}decrypt(t){const e=d(this,k)[k].derive(b);return V(U(H(t,"base64"),e.privKey))}signAttestationWithAIP(t,e,i=0,r=""){const s=this.getId(e);if(!s)throw new Error("Could not find identity to attest with");const n=this.getAttestationBuffer(t,i,r),{address:o,signature:h}=s.signMessage(n);return this.createAttestationTransaction(t,i,o,h,r)}verifyAttestationWithAIP(t){if(!Array.isArray(t)||"0x6a"!==t[0]||t[1]!==l)throw new Error("Not a valid BAP transaction");const e="0x44415441"===t[7]?5:0,i={type:m.hexDecode(t[2]),hash:m.hexDecode(t[3]),sequence:m.hexDecode(t[4]),signingProtocol:m.hexDecode(t[7+e]),signingAddress:m.hexDecode(t[8+e]),signature:m.hexDecode(t[9+e],"base64")};e&&t[3]===t[8]&&(i.data=m.hexDecode(t[9]));try{const r=[];for(let i=0;i<6+e;i++)r.push(Buffer.from(t[i].replace("0x",""),"hex"));const s=Buffer.concat(r);i.verified=this.verifySignature(s,i.signingAddress,i.signature)}catch(t){i.verified=!1}return i}createAttestationTransaction(t,e,i,r,s=""){const n=["0x6a",m.hexEncode(y)];return n.push(m.hexEncode("ATTEST")),n.push(m.hexEncode(t)),n.push(m.hexEncode(`${e}`)),n.push("0x7c"),s&&(n.push(m.hexEncode(y)),n.push(m.hexEncode("DATA")),n.push(m.hexEncode(t)),n.push(m.hexEncode(s)),n.push("0x7c")),n.push(m.hexEncode(p)),n.push(m.hexEncode("BITCOIN_ECDSA")),n.push(m.hexEncode(i)),n.push(`0x${Buffer.from(r,"base64").toString("hex")}`),n}getAttestationBuffer(t,e=0,i=""){let r=Buffer.from("");return i&&(r=Buffer.concat([Buffer.from(y),Buffer.from("DATA"),Buffer.from(t),Buffer.from(i),Buffer.from("7c","hex")])),Buffer.concat([Buffer.from("6a","hex"),Buffer.from(y),Buffer.from("ATTEST"),Buffer.from(t),Buffer.from(`${e}`),Buffer.from("7c","hex"),r])}verifySignature(t,e,s){const n=Buffer.isBuffer(t)?t:Buffer.from(t),o=h.fromCompact(s,"base64");let a;const d=H(n.toString("hex"),"hex");for(let t=0;t<4;t++)try{if(a=o.RecoverPublicKey(t,new r(i.magicHash(d))),i.verify(d,o,a)&&a.toAddress()===e)return!0}catch(t){}return!1}async verifyChallengeSignature(t,e,i,r){if(this.verifySignature(i,e,r)){const e=await this.getApiData("/attestation/valid",{idKey:t,challenge:i,signature:r});return!!e&&e.valid}return!1}async isValidAttestationTransaction(t){return!!this.verifyAttestationWithAIP(t)&&this.getApiData("/attestation/valid",{tx:t})}async getIdentityFromAddress(t){return this.getApiData("/identity/from-address",{address:t})}async getIdentity(t){return this.getApiData("/identity/get",{idKey:t})}async getAttestationsForHash(t){return this.getApiData("/attestations",{hash:t})}}export{z as BAP,C as BAP_ID};
|
2
|
-
|
1
|
+
// @bun
|
2
|
+
import{BSM as N,BigNumber as n,ECIES as d,HD as s,Signature as r}from"@bsv/sdk";import{Utils as i}from"@bsv/sdk";var l=async(j,$,J,q)=>{let Q=`${J}${j}`;return(await fetch(Q,{method:"post",headers:{"Content-type":"application/json; charset=utf-8",token:q,format:"json"},body:JSON.stringify($)})).json()},U=(j,$)=>async(J,q)=>{return l(J,q,j,$)};var Y="1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT",H=`0x${Buffer.from("1BAPSuaPnfGnSBM3GLV9yhxUdYe4vGbdMT").toString("hex")}`,R="15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva",qj=`0x${Buffer.from("15PciHG22SNLQJXMoSUaWVi7WSqc7hCfva").toString("hex")}`,x="https://api.sigmaidentity.com/v1",F=2147483647,C="m/424150'/0'/0'",G="m/424150'/2147483647'/2147483647'";import{BSM as M,Utils as h,BigNumber as S,ECIES as y,Hash as X,PublicKey as _}from"@bsv/sdk";import{randomBytes as b}from"crypto";var W={hexEncode(j){return`0x${Buffer.from(j).toString("hex")}`},hexDecode(j,$="utf8"){return Buffer.from(j.replace("0x",""),"hex").toString($)},getRandomString(j=32){return b(j).toString("hex")},isHex(j){if(typeof j!=="string")return!1;return/^[0-9a-fA-F]+$/.test(j)},getSigningPathFromHex(j,$=!0){let J="m",q=j.match(/.{1,8}/g);if(!q)throw new Error("Invalid hex string");let Q=2147483647;for(let z of q){let Z=Number(`0x${z}`);if(Z>Q)Z-=Q;J+=`/${Z}${$?"'":""}`}return J},getNextIdentityPath(j){let $=j.split("/"),J=$[$.length-2],q=!1;if(J.match("'"))q=!0;let Q=(Number(J.replace(/[^0-9]/g,""))+1).toString();return $[$.length-2]=Q+(q?"'":""),$[$.length-1]=`0${q?"'":""}`,$.join("/")},getNextPath(j){let $=j.split("/"),J=$[$.length-1],q=!1;if(J.match("'"))q=!0;let Q=(Number(J.replace(/[^0-9]/g,""))+1).toString();return $[$.length-1]=Q+(q?"'":""),$.join("/")}};import{BSM as T,BigNumber as p,PrivateKey as D,Utils as P}from"@bsv/sdk";var{toHex:wj,toBase58:Yj,toArray:B}=P,{magicHash:o}=T;class V{key;identityAttributes;address;idName;description;constructor(j,$={}){this.key=j,this.identityAttributes=typeof $==="string"?this.parseStringUrns($):$,this.address=this.key.toAddress(),this.idName="Member ID 1",this.description=""}signMessage(j){let $=typeof j==="string"?Buffer.from(j):j,J=this.key,q=J.toPublicKey().toString(),Q=T.sign(B($),J,"raw"),z=new p(o(B($,"utf8"))),Z=Q.CalculateRecoveryFactor(J.toPublicKey(),z),L=T.sign(B($),J,"raw").toCompact(Z,!0,"base64");return{address:q,signature:L}}getPublicKey(){return this.key.toPublicKey().toString()}import(j){this.idName=j.name,this.description=j.description,this.key=D.fromString(j.derivedPrivateKey),this.address=this.key.toAddress(),this.identityAttributes=j.identityAttributes}static fromImport(j){let $=new V(D.fromString(j.derivedPrivateKey));return $.import(j),$}export(){return{name:this.idName,description:this.description,derivedPrivateKey:this.key.toString(),address:this.address,identityAttributes:this.identityAttributes}}parseStringUrns(j){let $={},J=j.replace(/^[ \t]+/gm,"").trim().split(`
|
3
|
+
`);for(let q of J){let Q=q.split(":");if(Q.length>=6&&Q[0]==="urn"&&Q[1]==="bap"&&Q[2]==="id")$[Q[3]]={value:Q[4],nonce:Q[5]}}return $}}var{toArray:w,toHex:O,toBase58:u,toUTF8:I,toBase64:A}=h,{electrumDecrypt:K,electrumEncrypt:m}=y,{magicHash:g}=M;class f{#j;#J=x;#Q="";#$;#q;#z;#W;idName;description;rootAddress;identityKey;identityAttributes;getApiData;constructor(j,$={},J=""){if(this.#W=J,J){let z=O(X.sha256(J,"utf8")),Z=W.getSigningPathFromHex(z);this.#j=j.derive(Z)}else this.#j=j;this.idName="ID 1",this.description="",this.#$=`${C}/0/0/0`,this.#q=`${C}/0/0/0`,this.#z=`${C}/0/0/1`;let q=this.#j.derive(this.#$);this.rootAddress=q.privKey.toPublicKey().toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress);let Q={...$};this.identityAttributes=this.parseAttributes(Q),this.getApiData=U(this.#J,this.#Q)}set BAP_SERVER(j){this.#J=j}get BAP_SERVER(){return this.#J}set BAP_TOKEN(j){this.#Q=j}get BAP_TOKEN(){return this.#Q}deriveIdentityKey(j){let $=O(X.sha256(j,"utf8"));return u(X.ripemd160($,"hex"))}parseAttributes(j){if(typeof j==="string")return this.parseStringUrns(j);for(let $ in j)if(!j[$].value||!j[$].nonce)throw new Error("Invalid identity attribute");return j||{}}parseStringUrns(j){let $={},J=j.replace(/^\s+/g,"").replace(/\r/gm,"").split(`
|
4
|
+
`);for(let q of J){let z=q.replace(/^\s+/g,"").replace(/\s+$/g,"").split(":");if(z[0]==="urn"&&z[1]==="bap"&&z[2]==="id"&&z[3]&&z[4]&&z[5])$[z[3]]={value:z[4],nonce:z[5]}}return $}getIdentityKey(){return this.identityKey}getAttributes(){return this.identityAttributes}getAttribute(j){if(this.identityAttributes[j])return this.identityAttributes[j];return null}setAttribute(j,$){if(!$)return;if(this.identityAttributes[j])this.updateExistingAttribute(j,$);else this.createNewAttribute(j,$)}updateExistingAttribute(j,$){if(typeof $==="string"){this.identityAttributes[j].value=$;return}if(this.identityAttributes[j].value=$.value||"",$.nonce)this.identityAttributes[j].nonce=$.nonce}createNewAttribute(j,$){if(typeof $==="string"){this.addAttribute(j,$);return}this.addAttribute(j,$.value||"",$.nonce)}unsetAttribute(j){delete this.identityAttributes[j]}getAttributeUrns(){let j="";for(let $ in this.identityAttributes){let J=this.getAttributeUrn($);if(J)j+=`${J}
|
5
|
+
`}return j}getAttributeUrn(j){let $=this.identityAttributes[j];if($)return`urn:bap:id:${j}:${$.value}:${$.nonce}`;return null}addAttribute(j,$,J=""){let q=J;if(!J)q=W.getRandomString();this.identityAttributes[j]={value:$,nonce:q}}set rootPath(j){if(this.#j){let $=j;if(j.split("/").length<5)$=`${C}${j}`;if(!this.validatePath($))throw new Error(`invalid signing path given ${$}`);this.#$=$;let J=this.#j.derive($);this.rootAddress=J.pubKey.toAddress(),this.identityKey=this.deriveIdentityKey(this.rootAddress),this.#q=$,this.#z=$}}get rootPath(){return this.#$}getRootPath(){return this.#$}set currentPath(j){let $=j;if(j.split("/").length<5)$=`${C}${j}`;if(!this.validatePath($))throw new Error("invalid signing path given");this.#q=this.#z,this.#z=$}get currentPath(){return this.#z}get previousPath(){return this.#q}get idSeed(){return this.#W}incrementPath(){this.currentPath=W.getNextPath(this.currentPath)}validatePath(j){if(j.match(/\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?/)){let $=j.split("/");if($.length===7&&Number($[1].replace("'",""))<=F&&Number($[2].replace("'",""))<=F&&Number($[3].replace("'",""))<=F&&Number($[4].replace("'",""))<=F&&Number($[5].replace("'",""))<=F&&Number($[6].replace("'",""))<=F)return!0}return!1}getInitialIdTransaction(){return this.getIdTransaction(this.#$)}getIdTransaction(j=""){if(this.#z===this.#$)throw new Error("Current path equals rootPath. ID was probably not initialized properly");let $=[Buffer.from(Y).toString("hex"),Buffer.from("ID").toString("hex"),Buffer.from(this.identityKey).toString("hex"),Buffer.from(this.getCurrentAddress()).toString("hex")];return this.signOpReturnWithAIP($,j||this.#q)}getAddress(j){return this.#j.derive(j).privKey.toPublicKey().toAddress()}getCurrentAddress(){return this.getAddress(this.#z)}getEncryptionPublicKey(){return this.#j.derive(this.#$).derive(G).privKey.toPublicKey().toString()}getEncryptionPublicKeyWithSeed(j){return this.getEncryptionPrivateKeyWithSeed(j).toPublicKey().toString("hex")}encrypt(j,$){let Q=this.#j.derive(this.#$).derive(G).privKey.toPublicKey(),z=$?_.fromString($):Q;return A(m(w(j),z,null))}decrypt(j,$){let q=this.#j.derive(this.#$).derive(G).privKey,Q=void 0;if($)Q=_.fromString($);return I(K(w(j,"base64"),q,Q))}encryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),Q=q.toPublicKey(),z=J?_.fromString(J):Q;return A(m(w(j),z,q))}decryptWithSeed(j,$,J){let q=this.getEncryptionPrivateKeyWithSeed($),Q=void 0;if(J)Q=_.fromString(J);return I(K(w(j,"base64"),q,Q))}getEncryptionPrivateKeyWithSeed(j){let $=O(X.sha256(j,"utf8")),J=W.getSigningPathFromHex($);return this.#j.derive(this.#$).derive(J).privKey}getAttestation(j){let $=X.sha256(j,"utf8");return`bap:attest:${O($)}:${this.getIdentityKey()}`}getAttestationHash(j){let $=this.getAttributeUrn(j);if(!$)return null;let J=this.getAttestation($),q=X.sha256(J,"utf8");return O(q)}signMessage(j,$=""){let J;if(!(j instanceof Buffer))J=Buffer.from(j);else J=j;let q=$||this.#z,Q=this.#j.derive(q).privKey,z=Q.toAddress(),Z=M.sign(w(j),Q,"raw"),L=new S(g(w(j,"utf8"))),k=Z.CalculateRecoveryFactor(Q.toPublicKey(),L),E=M.sign(w(J),Q,"raw").toCompact(k,!0,"base64");return{address:z,signature:E}}signMessageWithSeed(j,$){let J=O(X.sha256($,"utf8")),q=W.getSigningPathFromHex(J),z=this.#j.derive(this.#$).derive(q),Z=z.privKey.toPublicKey().toAddress(),L=M.sign(w(j),z.privKey,"raw"),k=new S(g(w(j,"utf8"))),E=L.CalculateRecoveryFactor(z.privKey.toPublicKey(),k),c=M.sign(w(Buffer.from(j)),z.privKey,"raw").toCompact(E,!0,"base64");return{address:Z,signature:c}}signOpReturnWithAIP(j,$="",J="hex"){let q=this.getAIPMessageBuffer(j),{address:Q,signature:z}=this.signMessage(q,$);return j.concat([Buffer.from("|").toString(J),Buffer.from(R).toString(J),Buffer.from("BITCOIN_ECDSA").toString(J),Buffer.from(Q).toString(J),Buffer.from(z,"base64").toString(J)])}getAIPMessageBuffer(j){let $=[];if(j[0].replace("0x","")!=="6a")$.push(Buffer.from("6a","hex"));for(let J of j)$.push(Buffer.from(J.replace("0x",""),"hex"));return $.push(Buffer.from("|")),Buffer.concat([...$])}async getIdSigningKeys(){let j=await this.getApiData("/signing-keys",{idKey:this.identityKey});return console.log("getIdSigningKeys",j),j}async getAttributeAttestations(j){let $=this.getAttestationHash(j),J=await this.getApiData("/attestation/get",{hash:$});return console.log("getAttestations",j,$,J),J}import(j){this.idName=j.name,this.description=j.description||"",this.identityKey=j.identityKey,this.#$=j.rootPath,this.rootAddress=j.rootAddress,this.#q=j.previousPath,this.#z=j.currentPath,this.#W=("idSeed"in j?j.idSeed:"")||"",this.identityAttributes=this.parseAttributes(j.identityAttributes)}export(){return{name:this.idName,description:this.description,identityKey:this.identityKey,rootPath:this.#$,rootAddress:this.rootAddress,previousPath:this.#q,currentPath:this.#z,idSeed:this.#W,identityAttributes:this.getAttributes(),lastIdPath:""}}exportMemberBackup(){let j=this.#j.derive(this.#z).privKey;return{name:this.idName,description:this.description,derivedPrivateKey:j.toString(),address:j.toPublicKey().toAddress(),identityAttributes:this.getAttributes()}}newId(){this.incrementPath();let j=this.#j.derive(this.#z).privKey;return new V(j,this.getAttributes())}}var{toArray:v,toUTF8:a,toBase64:e}=i,{electrumEncrypt:t,electrumDecrypt:jj}=d;class $j{#j;#J={};#Q=x;#$="";#q="";getApiData;constructor(j,$="",J=""){if(!j)throw new Error("No HDPrivateKey given");if(this.#j=s.fromString(j),$)this.#$=$;if(J)this.#Q=J;this.getApiData=U(this.#Q,this.#$)}get lastIdPath(){return this.#q}getPublicKey(j=""){if(j)return this.#j.derive(j).pubKey.toString();return this.#j.pubKey.toString()}getHdPublicKey(j=""){if(j)return this.#j.derive(j).toPublic().toString();return this.#j.toPublic().toString()}set BAP_SERVER(j){this.#Q=j;for(let $ in this.#J)this.#J[$].BAP_SERVER=j}get BAP_SERVER(){return this.#Q}set BAP_TOKEN(j){this.#$=j;for(let $ in this.#J)this.#J[$].BAP_TOKEN=j}get BAP_TOKEN(){return this.#$}checkIdBelongs(j){if(this.#j.derive(j.rootPath).pubKey.toAddress()!==j.rootAddress)throw new Error("ID does not belong to this private key");return!0}listIds(){return Object.keys(this.#J)}newId(j,$={},J=""){let q;if(!j)q=this.getNextValidPath();else q=j;let Q=new f(this.#j,$,J);Q.BAP_SERVER=this.#Q,Q.BAP_TOKEN=this.#$,Q.rootPath=q,Q.currentPath=W.getNextPath(q);let z=Q.getIdentityKey();return this.#J[z]=Q,this.#q=q,this.#J[z]}removeId(j){delete this.#J[j]}getNextValidPath(){if(this.#q)return W.getNextIdentityPath(this.#q);return`/0'/${Object.keys(this.#J).length}'/0'`}getId(j){return this.#J[j]||null}setId(j){this.checkIdBelongs(j),this.#J[j.getIdentityKey()]=j}importIds(j,$=!0){if($&&typeof j==="string"){this.importEncryptedIds(j);return}let J=j;if(!J.lastIdPath)throw new Error("ID cannot be imported as it is not complete");if(!J.ids)throw new Error(`ID data is not in the correct format: ${j}`);let q=j.lastIdPath;for(let Q of J.ids){if(!Q.identityKey||!Q.identityAttributes||!Q.rootAddress)throw new Error("ID cannot be imported as it is not complete");let z=new f(this.#j,{},Q.idSeed);if(z.BAP_SERVER=this.#Q,z.BAP_TOKEN=this.#$,z.import(Q),q==="")q=z.currentPath;this.checkIdBelongs(z),this.#J[z.getIdentityKey()]=z}this.#q=q}importEncryptedIds(j){let $=this.decrypt(j),J=JSON.parse($);if(Array.isArray(J)){console.log(`Importing old format:
|
6
|
+
`,J),this.importOldIds(J);return}if(typeof J!=="object")throw new Error("decrypted, but found unrecognized identities format");this.importIds(J,!1)}importOldIds(j){for(let $ of j){let J=new f(this.#j,{},$.idSeed??"");J.BAP_SERVER=this.#Q,J.BAP_TOKEN=this.#$,J.import($),this.checkIdBelongs(J),this.#J[J.getIdentityKey()]=J,this.#q=J.currentPath}}exportIds(j,$=!0){let J={lastIdPath:this.#q,ids:[]},q=j||Object.keys(this.#J);for(let Q of q){if(!this.#J[Q])throw new Error(`Identity ${Q} not found`);J.ids.push(this.#J[Q].export())}if($)return this.encrypt(JSON.stringify(J));return J}exportId(j,$=!0){let J={lastIdPath:this.#q,ids:[]};if(J.ids.push(this.#J[j].export()),$)return this.encrypt(JSON.stringify(J));return J}encrypt(j){let $=this.#j.derive(G);return e(t(v(j),$.pubKey,null))}decrypt(j){let $=this.#j.derive(G);return a(jj(v(j,"base64"),$.privKey))}signAttestationWithAIP(j,$,J=0,q=""){let Q=this.getId($);if(!Q)throw new Error("Could not find identity to attest with");let z=this.getAttestationBuffer(j,J,q),{address:Z,signature:L}=Q.signMessage(z);return this.createAttestationTransaction(j,J,Z,L,q)}verifyAttestationWithAIP(j){if(!Array.isArray(j)||j[0]!=="0x6a"||j[1]!==H)throw new Error("Not a valid BAP transaction");let $=j[7]==="0x44415441"?5:0,J={type:W.hexDecode(j[2]),hash:W.hexDecode(j[3]),sequence:W.hexDecode(j[4]),signingProtocol:W.hexDecode(j[7+$]),signingAddress:W.hexDecode(j[8+$]),signature:W.hexDecode(j[9+$],"base64")};if($&&j[3]===j[8])J.data=W.hexDecode(j[9]);try{let q=[];for(let z=0;z<6+$;z++)q.push(Buffer.from(j[z].replace("0x",""),"hex"));let Q=Buffer.concat(q);J.verified=this.verifySignature(Q,J.signingAddress,J.signature)}catch(q){J.verified=!1}return J}createAttestationTransaction(j,$,J,q,Q=""){let z=["0x6a",W.hexEncode(Y)];if(z.push(W.hexEncode("ATTEST")),z.push(W.hexEncode(j)),z.push(W.hexEncode(`${$}`)),z.push("0x7c"),Q)z.push(W.hexEncode(Y)),z.push(W.hexEncode("DATA")),z.push(W.hexEncode(j)),z.push(W.hexEncode(Q)),z.push("0x7c");return z.push(W.hexEncode(R)),z.push(W.hexEncode("BITCOIN_ECDSA")),z.push(W.hexEncode(J)),z.push(`0x${Buffer.from(q,"base64").toString("hex")}`),z}getAttestationBuffer(j,$=0,J=""){let q=Buffer.from("");if(J)q=Buffer.concat([Buffer.from(Y),Buffer.from("DATA"),Buffer.from(j),Buffer.from(J),Buffer.from("7c","hex")]);return Buffer.concat([Buffer.from("6a","hex"),Buffer.from(Y),Buffer.from("ATTEST"),Buffer.from(j),Buffer.from(`${$}`),Buffer.from("7c","hex"),q])}verifySignature(j,$,J){let q=Buffer.isBuffer(j)?j:Buffer.from(j),Q=r.fromCompact(J,"base64"),z,Z=v(q.toString("hex"),"hex");for(let L=0;L<4;L++)try{if(z=Q.RecoverPublicKey(L,new n(N.magicHash(Z))),N.verify(Z,Q,z)&&z.toAddress()===$)return!0}catch(k){}return!1}async verifyChallengeSignature(j,$,J,q){if(!this.verifySignature(J,$,q))return!1;try{let z=await this.getApiData("/attestation/valid",{idKey:j,address:$,challenge:J,signature:q});if(z?.status==="success"&&z?.result?.valid===!0)return!0;return!1}catch(z){return console.error("API call failed:",z),!1}}async isValidAttestationTransaction(j){if(this.verifyAttestationWithAIP(j))return this.getApiData("/attestation/valid",{tx:j});return!1}async getIdentityFromAddress(j){return this.getApiData("/identity/from-address",{address:j})}async getIdentity(j){return this.getApiData("/identity/get",{idKey:j})}async getAttestationsForHash(j){return this.getApiData("/attestations",{hash:j})}}export{f as MasterID,$j as BAP};
|
7
|
+
|
8
|
+
//# debugId=63CF71C289EEF0B864756E2164756E21
|