@idos-network/enclave 1.2.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,6 @@
1
- import { g as RemoveAddressMessageToSign, i as AddAddressSignatureMessage, n as AddAddressMessageToSign, v as RemoveAddressSignatureMessage } from "./types-DKsOwtWL.mjs";
1
+ import { g as RemoveAddressMessageToSign, i as AddAddressSignatureMessage, n as AddAddressMessageToSign, v as RemoveAddressSignatureMessage } from "./types-Ck9Ec1Pa.mjs";
2
2
  import { EncryptionPasswordStore as EncryptionPasswordStore$1, WalletType } from "@idos-network/kwil-infra/actions";
3
- import { idOSCredential } from "@idos-network/credentials/types";
4
-
3
+ import { idOSCredentialRecord } from "@idos-network/credentials/types";
5
4
  //#region src/types.d.ts
6
5
  type PublicEncryptionProfile = {
7
6
  userId: string;
@@ -40,10 +39,10 @@ declare abstract class BaseProvider<K extends EnclaveOptions = EnclaveOptions> {
40
39
  private _signMethodType?;
41
40
  constructor(options: K);
42
41
  /**
43
- * Sets the signer for the enclave.
44
- *
45
- * @param signer - The signer to set, is later used for MPC if allowed.
46
- */
42
+ * Sets the signer for the enclave.
43
+ *
44
+ * @param signer - The signer to set, is later used for MPC if allowed.
45
+ */
47
46
  setSigner(signer: {
48
47
  signTypedData?: (domain: string, types: string[], value: string) => Promise<string>;
49
48
  signMessage?: (message: string) => Promise<any>;
@@ -51,85 +50,85 @@ declare abstract class BaseProvider<K extends EnclaveOptions = EnclaveOptions> {
51
50
  }): void;
52
51
  signTypedData(domain: any, types: any, value: any): Promise<string>;
53
52
  /**
54
- * Helper method to get the user ID.
55
- *
56
- * @returns The user ID.
57
- */
53
+ * Helper method to get the user ID.
54
+ *
55
+ * @returns The user ID.
56
+ */
58
57
  get userId(): string;
59
58
  /**
60
- * Resets the enclave (storage etc.)
61
- */
59
+ * Resets the enclave (storage etc.)
60
+ */
62
61
  reset(): Promise<void>;
63
62
  /**
64
- * Reconfigures the enclave (theme etc).
65
- *
66
- * @param options - The options to reconfigure.
67
- */
63
+ * Reconfigures the enclave (theme etc).
64
+ *
65
+ * @param options - The options to reconfigure.
66
+ */
68
67
  reconfigure(options?: Partial<K>): Promise<void>;
69
68
  /**
70
- * Loads the enclave (create iframe, open connection, etc.)
71
- */
69
+ * Loads the enclave (create iframe, open connection, etc.)
70
+ */
72
71
  load(): Promise<void>;
73
72
  /**
74
- * Encrypts a message to a receiver.
75
- * This method also checks if the user is authorized to use the keys.
76
- *
77
- * @param _message - The message to encrypt.
78
- * @param _receiverPublicKey - The public key of the receiver.
79
- *
80
- * @returns The encrypted message.
81
- */
73
+ * Encrypts a message to a receiver.
74
+ * This method also checks if the user is authorized to use the keys.
75
+ *
76
+ * @param _message - The message to encrypt.
77
+ * @param _receiverPublicKey - The public key of the receiver.
78
+ *
79
+ * @returns The encrypted message.
80
+ */
82
81
  encrypt(_message: Uint8Array, _receiverPublicKey: Uint8Array): Promise<{
83
82
  content: Uint8Array;
84
83
  encryptorPublicKey: Uint8Array;
85
84
  }>;
86
85
  /**
87
- * Decrypts a message from a sender.
88
- * This method also checks if the user is authorized to use the keys.
89
- *
90
- * @param _message - The message to decrypt.
91
- * @param _senderPublicKey - The public key of the sender.
92
- *
93
- * @returns The decrypted message.
94
- */
86
+ * Decrypts a message from a sender.
87
+ * This method also checks if the user is authorized to use the keys.
88
+ *
89
+ * @param _message - The message to decrypt.
90
+ * @param _senderPublicKey - The public key of the sender.
91
+ *
92
+ * @returns The decrypted message.
93
+ */
95
94
  decrypt(_message: Uint8Array, _senderPublicKey: Uint8Array): Promise<Uint8Array<ArrayBufferLike>>;
96
95
  /**
97
- * This method is used to confirm the user action.
98
- *
99
- * @param _message - The message to confirm.
100
- *
101
- * @returns `true` if the user action is confirmed, `false` otherwise.
102
- */
96
+ * This method is used to confirm the user action.
97
+ *
98
+ * @param _message - The message to confirm.
99
+ *
100
+ * @returns `true` if the user action is confirmed, `false` otherwise.
101
+ */
103
102
  confirm(_message: string): Promise<boolean>;
104
103
  /**
105
- * This method is used to backup the password context.
106
- */
104
+ * This method is used to backup the password context.
105
+ */
107
106
  backupUserEncryptionProfile(): Promise<void>;
108
107
  /**
109
- * Gets the public encryption profile.
110
- *
111
- * @returns The public encryption profile.
112
- */
108
+ * Gets the public encryption profile.
109
+ *
110
+ * @returns The public encryption profile.
111
+ */
113
112
  ensureUserEncryptionProfile(): Promise<PublicEncryptionProfile>;
114
113
  /**
115
- * This method authorizes the origin in case of enclave
116
- * to use the keys, without user providing the password or MPC again.
117
- *
118
- * @returns `true` if the user action is authorized, `false` otherwise.
119
- */
114
+ * This method authorizes the origin in case of enclave
115
+ * to use the keys, without user providing the password or MPC again.
116
+ *
117
+ * @returns `true` if the user action is authorized, `false` otherwise.
118
+ */
120
119
  guardKeys(): Promise<boolean>;
121
120
  /**
122
- * Filters the credentials based on the private field filters.
123
- *
124
- * @param credentials - The credentials to filter.
125
- * @param privateFieldFilters - The private field filters.
126
- *
127
- * @returns The filtered credentials without the content.
128
- */
129
- filterCredentials(credentials: idOSCredential[], privateFieldFilters: {
121
+ * Filters the credentials based on the private field filters.
122
+ *
123
+ * @param credentials - The credentials to filter.
124
+ * @param privateFieldFilters - The private field filters.
125
+ *
126
+ * @returns The filtered credentials without the content.
127
+ */
128
+ filterCredentials(credentials: idOSCredentialRecord[], privateFieldFilters: {
130
129
  pick: Record<string, unknown[]>;
131
130
  omit: Record<string, unknown[]>;
132
- }): Promise<idOSCredential[]>;
131
+ }): Promise<idOSCredentialRecord[]>;
133
132
  addAddressMessageToSign(_address: string, _publicKey: string | undefined, _addressToAddType: string): Promise<AddAddressMessageToSign>;
134
133
  removeAddressMessageToSign(_address: string, _publicKey: string | undefined, _addressToRemoveType: string): Promise<RemoveAddressMessageToSign>;
135
134
  addAddressToMpcSecret(_userId: string, _message: AddAddressSignatureMessage, _signature: string): Promise<string>;
@@ -137,4 +136,4 @@ declare abstract class BaseProvider<K extends EnclaveOptions = EnclaveOptions> {
137
136
  }
138
137
  //#endregion
139
138
  export { PasswordContext as a, MPCPasswordContext as i, EnclaveOptions as n, PrivateEncryptionProfile as o, EncryptionPasswordStore$1 as r, PublicEncryptionProfile as s, BaseProvider as t };
140
- //# sourceMappingURL=base-0xSNl4rW.d.mts.map
139
+ //# sourceMappingURL=base-CjIdohef.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base-CjIdohef.d.mts","names":[],"sources":["../src/types.ts","../src/base.ts"],"mappings":";;;;KAIY;EACV;EACA;EACA,yBAAyB;;KAGf;EACV;EACA;EACA,SAAS,KAAK;EACd,yBAAyB;;KAGf;EACV;EACA;EACA;EACA;EACA;EACA;EACA,aAAa;EACb,0BAA0B;;KAGhB;EACV;EACA;EACA;;KAGU;EACV;;;;uBCtBoB,aAAa,UAAU,iBAAiB;WACnD,SAAS;YAGR,eAAe,aAAa,YAAY,eAAe;UACzD;EAER,YAAY,SAAS;;;;;;EASrB,UAAU;IACR,iBAAiB,gBAAgB,iBAAiB,kBAAkB;IAEpE,eAAe,oBAAoB;IAEnC,UAAU,oBAAoB;;EA4BhC,cAAoB,aAAa,YAAY,aAAa;;;;;;MAkDtD;;;;EAUJ,SAAe;;;;;;EASf,YAAkB,UAAS,QAAQ,KAAU;;;;EAO7C,QAAc;;;;;;;;;;EAad,QACE,UAAU,YACV,oBAAoB,aACnB;IAAU,SAAS;IAAY,oBAAoB;;;;;;;;;;;EAatD,QACE,UAAU,YACV,kBAAkB,aACjB,QAAQ,WAAW;;;;;;;;EAWtB,QAAc,mBAAmB;;;;EAOjC,+BAAqC;;;;;;EASrC,+BAAqC,QAAQ;;;;;;;EAU7C,aAAmB;;;;;;;;;EAYnB,kBACE,aAAa,wBACb;IAAuB,MAAM;IAA2B,MAAM;MAC7D,QAAQ;EAwDX,wBACE,kBACA,gCACA,4BACC,QAAQ;EAIX,2BACE,kBACA,gCACA,+BACC,QAAQ;EAIX,sBACE,iBACA,UAAU,4BACV,qBACC;EAIH,2BACE,iBACA,UAAU,+BACV,qBACC"}
@@ -1,13 +1,12 @@
1
- import { T as UploadSignatureMessage, f as DownloadSignatureMessage, g as RemoveAddressMessageToSign, i as AddAddressSignatureMessage, m as PbcAddress, n as AddAddressMessageToSign, o as Bytes, u as DownloadMessageToSign, v as RemoveAddressSignatureMessage, w as UploadMessageToSign } from "./types-DKsOwtWL.mjs";
1
+ import { T as UploadSignatureMessage, f as DownloadSignatureMessage, g as RemoveAddressMessageToSign, i as AddAddressSignatureMessage, m as PbcAddress, n as AddAddressMessageToSign, o as Bytes, u as DownloadMessageToSign, v as RemoveAddressSignatureMessage, w as UploadMessageToSign } from "./types-Ck9Ec1Pa.mjs";
2
2
  import { WalletType } from "@idos-network/kwil-infra/actions";
3
-
4
3
  //#region src/mpc/client.d.ts
5
4
  declare class Client {
6
5
  private readonly baseUrl;
7
6
  private readonly contractAddress;
8
7
  private engines;
9
- private walletType!;
10
- private signerAddress!;
8
+ private walletType;
9
+ private signerAddress;
11
10
  private signerPublicKey;
12
11
  private factory;
13
12
  private numNodes;
@@ -35,4 +34,4 @@ declare class Client {
35
34
  }
36
35
  //#endregion
37
36
  export { Client as t };
38
- //# sourceMappingURL=client-Bu0aO5sT.d.mts.map
37
+ //# sourceMappingURL=client-Ci4XBJXn.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-Ci4XBJXn.d.mts","names":[],"sources":["../src/mpc/client.ts"],"mappings":";;;cA4Ba;mBACM;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;EAER,YACE,iBACA,iBAAiB,YACjB,sBACA,kBACA,0BACA,YAAY,YACZ,uBACA;EAYF,YACE,YAAY,YACZ,uBACA;EAuCF,aACE,YACA,iBAAiB,wBACjB,WAAW,OACX,eAAe,WACd;IAAU;;EAwBb,iBAAwB,QAAQ,SAAS;EAUzC,oBAA2B,eAAe,yBAAyB;EAQnE,cAAqB,eAAe,WAAW;EA0B/C,sBAA6B,iBAAiB,2BAA2B;EAQzE,gBAAuB,WAAW,aAAa;EAyB/C,eACE,YACA,iBAAiB,0BACjB,WAAW,OACX,WAAW,aACV;IAAU;IAAgB,QAAQ;;EA0BrC,wBACE,sBACA,+BACA,2BACC;EAmDH,2BACE,yBACA,+BACA,8BACC;EAkDH,WACE,gBACA,SAAS,4BACT,oBACC;EAgBH,cACE,gBACA,SAAS,+BACT,oBACC;UAgBK;UAQM;iBAaC"}
@@ -0,0 +1,2 @@
1
+ import e from"tweetnacl";import{WALLET_TYPES as t}from"@idos-network/kwil-infra/actions";import{ChainControllerApi as n,Configuration as r}from"@partisiablockchain/blockchain-api-transaction-client";import{ethers as i}from"ethers";import{AbiByteInput as a}from"@partisiablockchain/abi-client";import{randomBytes as o}from"crypto";import s from"tiny-invariant";const c={Accept:`application/json, text/plain, */*`,"Content-Type":`application/json`};function l(e,t,n){let r={method:e,headers:t,body:null};return n!=null&&(r.body=JSON.stringify(n)),r}function u(e,t,n){let r=l(`PUT`,{...c,...n},t);return fetch(e,r).then(async e=>{let t=await e.clone().text();return console.log({responseCode:e.status,responseBody:t}),e.status.toString()}).catch(e=>(console.error(e),e))}function d(e,t,n){let r=l(`PATCH`,{...c,...n},t);return fetch(e,r).then(async e=>{let t=await e.clone().text();return console.log({responseCode:e.status,responseBody:t}),e.status.toString()}).catch(e=>(console.error(e),e))}function f(e,t,n){let r=l(`POST`,{...c,...n},t);return p(fetch(e,r))}function p(e){return e.then(async e=>{let t=await e.clone().text();if(console.log({responseCode:e.status,responseBody:t}),e.status===200){let t=await e.json();return{status:e.status.toString(),body:t}}return{status:e.status.toString(),body:void 0}}).catch(e=>(console.error(e),{status:`fetch-error`,body:void 0}))}var m=class{baseUrl;contractAddress;walletType;constructor(e,t,n){this.contractAddress=t,this.baseUrl=e,this.walletType=n}getAuthHeader(e){let t;switch(this.walletType){case`EVM`:t=`eip712`;break;case`NEAR`:t=`NEAR`;break;case`XRPL`:t=`XRPL`;break;case`FaceSign`:t=`FACESIGN`;break;default:t=`eip712`}return{Authorization:`${t} ${e}`}}async sendUpload(e,t,n){let r=this.getAuthHeader(n),i=`${this.baseUrl}/offchain/${this.contractAddress}/shares/${e}`,a=await u(i,t,r);if(a!==`201`)throw Error(`Error uploading share to ${this.contractAddress} at ${i}`);return a}async sendDownload(e,t,n){let r=this.getAuthHeader(n);return await f(`${this.baseUrl}/offchain/${this.contractAddress}/shares/${e}`,t,r)}async downloadAndDecrypt(t,n,r,a){let{status:o,body:s}=await this.sendDownload(t,n,r);if(s===void 0)return{share:void 0,status:o};let c=i.getBytes(s.encrypted_share),l=i.getBytes(s.public_key),u=i.getBytes(s.nonce),d=e.box.open(c,u,l,a);return d==null?{share:void 0,status:`box-open-error`}:{share:Buffer.from(d.subarray(32)),status:o}}async sendUpdate(e,t,n){let r={Authorization:`eip712 ${n}`},i=`${this.baseUrl}/offchain/${this.contractAddress}/shares/${e}`,a=await d(i,t,r);if(!a)throw Error(`Error updating wallets to ${this.contractAddress} at ${i}`);return a}async sendAddAddress(e,t,n){let r=this.getAuthHeader(n),i=`${this.baseUrl}/offchain/${this.contractAddress}/shares/${e}/add_address`,a=await d(i,t,r);if(a!==`200`)throw Error(`Error adding a wallet to ${e} at ${i}`);return a}async sendRemoveAddress(e,t,n){let r=this.getAuthHeader(n),i=`${this.baseUrl}/offchain/${this.contractAddress}/shares/${e}/remove_address`,a=await d(i,t,r);if(a!==`200`)throw Error(`Error removing address from ${e} at ${i}`);return a}},h=class{_client;_address;constructor(e,t){this._address=t,this._client=e}deserializeContractState(e){let t=e.readI32(),n=[];for(let r=0;r<t;r++){let t=this.deserializeNodeConfig(e);n.push(t)}return{nodes:n}}deserializeNodeConfig(e){return{address:e.readAddress(),endpoint:e.readString()}}async getState(){let e=await this._client?.getContractStateBinary(this._address);if(e===void 0)throw Error(`Unable to get state bytes`);let t=a.createLittleEndian(e);return this.deserializeContractState(t)}};function g(e,t,n){if(Buffer.isBuffer(e)){let r=a.createLittleEndian(e);return new h(t,n).deserializeContractState(r)}let r=a.createLittleEndian(e.bytes);return new h(e.client,e.address).deserializeContractState(r)}var _=class e{coefficients;constructor(e){this.coefficients=e}static create(t,n){return new e(e.filterHighZeroes(t,n))}static filterHighZeroes(e,t){for(let t=e.length-1;t>=0;t--)if(!e[t].isZero())return e.slice(0,t+1);return[t]}getCoefficients(){return this.coefficients.slice()}degree(){return this.coefficients.length-1}getConstantTerm(){return this.coefficients[0]}evaluate(e){let t=this.degree(),n=this.coefficients[t];for(let r=t-1;r>=0;--r)n=this.coefficients[r].add(e.multiply(n));return n}},v=class e{value;constructor(e){this.value=e}static ZERO=e.createElement(0);static ONE=e.createElement(1);static createElement(t){return new e(t&255)}static alphas(t){return Array.from({length:t},(t,n)=>e.createElement(n+1))}static createPoly(t){return _.create(t,e.ZERO)}add(e){return y.elements[this.value^e.value]}isEqualTo(e){return this.value===e.value}isOne(){return this.value===1}isZero(){return this.value===0}modInverse(){return y.elements[y.multiplicativeInverse[this.value]]}multiply(e){let t=this.value,n=e.value,r,i=0;for(let e=0;e<8;e++)i=(i^-(n&1)&t)&255,r=-(t>>7&1)&255,t=(t<<1^283&r)&255,n>>=1;return y.elements[i]}negate(){return this}squareRoot(){throw Error(`Not implemented`)}subtract(e){return this.add(e)}};const y={elements:Array.from({length:256},(e,t)=>v.createElement(t)),multiplicativeInverse:[0,1,141,246,203,82,123,209,232,79,41,192,176,225,229,199,116,180,170,75,153,43,96,95,88,63,253,204,255,64,238,178,58,110,90,241,85,77,168,201,193,10,152,21,48,68,162,194,44,69,146,108,243,57,102,66,242,53,32,111,119,187,89,25,29,254,55,103,45,49,245,105,167,100,171,19,84,37,233,9,237,92,5,202,76,36,135,191,24,62,34,240,81,236,97,23,22,94,175,211,73,166,54,67,244,71,145,223,51,147,33,59,121,183,151,133,16,181,186,60,182,112,208,6,161,250,129,130,131,126,127,128,150,115,190,86,155,158,149,217,247,2,185,164,222,106,50,109,216,138,132,114,42,20,159,136,249,220,137,154,251,124,46,195,143,184,101,72,38,200,18,74,206,231,210,98,12,224,31,239,17,117,120,113,165,142,118,61,189,188,134,87,11,40,47,163,218,212,228,15,169,39,83,4,27,252,172,230,122,7,174,99,197,219,226,234,148,139,196,213,157,248,144,107,177,13,214,235,198,14,207,173,8,78,215,227,93,80,30,179,91,35,56,52,104,70,3,140,221,156,125,160,205,26,65,28]};function b(e,t,n,r){if(e.length!==t.length)throw Error(`xs and ys must be of same size`);if(e.length===0)throw Error(`xs and ys must have at least one element`);let i=e.length,a=Array(i).fill(r);a[0]=r;for(let t=0;t<i;t++){for(let n=t;n>0;n--)a[n]=a[n-1].subtract(a[n].multiply(e[t]));a[0]=a[0].multiply(e[t].negate())}let o=Array(i).fill(n),s=Array(i).fill(n);s[i-1]=r;for(let n=0;n<i;n++){let c=r;for(let t=0;t<i;t++)n!==t&&(c=c.multiply(e[n].subtract(e[t])));let l=t[n].multiply(c.modInverse());o[i-1]=o[i-1].add(l.multiply(s[i-1]));for(let t=i-2;t>=0;t--)s[t]=a[t+1].add(s[t+1].multiply(e[n])),o[t]=o[t].add(l.multiply(s[t]))}return _.create(o,n)}function x(e,t,n,r,i){let a=b(e,t,r,i);if(a.degree()>n)throw Error(`Interpolated polynomial has too high degree. Expected maximal=${n}, actual=${a.degree()}`);return a}function S(e,t,n,r,i){if(e.length!==t.length)throw Error(`xs and ys must be of same size`);return C(e,t,n,r,i)}function C(e,t,n,r,i){if(e.length<=2*n+1){let a=b(e,t,r,i);return a.degree()>n?void 0:a}for(let a=0;a<e.length;a++){let o=C(w(e,a),w(t,a),n,r,i);if(o!==void 0)return o}}function w(e,t){return e.filter((e,n,r)=>n!=t)}const T={interpolate:b,interpolateCheckDegree:x,interpolateIfPossible:S};var E=class{shamirConfig;constructor(e){this.shamirConfig=e}fromPlainText(e,t){if(e!=this.shamirConfig.numNodes)throw Error(`This shamir factory expects there to be ${this.shamirConfig.numNodes} nodes, but there was ${e}.`);let n=o(t.length*this.shamirConfig.numMalicious),r=v.alphas(this.shamirConfig.numNodes),i=Array.from({length:this.shamirConfig.numNodes},()=>[]);for(let e=0;e<t.length;e++){let a=[v.createElement(t[e])];for(let t=0;t<this.shamirConfig.numMalicious;t++)a.push(v.createElement(n[this.shamirConfig.numMalicious*e+t]));let o=v.createPoly(a);for(let e=0;e<this.shamirConfig.numNodes;e++)i[e].push(o.evaluate(r[e]))}return new D(this.shamirConfig,i)}fromSharesBytes(e){let t=e.map(e=>{if(e==null)return;let t=[];for(let n=0;n<e.length;n++)t.push(v.createElement(e[n]));return t});return new D(this.shamirConfig,t)}},D=class{shares;shamirConfig;constructor(e,t){if(t.length!=e.numNodes)throw Error(`There must be ${e.numNodes} nodes`);let n=t.filter(e=>e!=null).length;if(n<e.numToReconstruct)throw Error(`Must have received at least ${e.numToReconstruct} shares to reconstruct. Received ${n}.`);this.shamirConfig=e,this.shares=t}getShareBytes(e){let t=this.shares[e];if(t==null)throw Error(`Expected share to be defined`);return Buffer.from(t.map(e=>e.value))}numShares(){return this.shamirConfig.numNodes}reconstructPlainText(){let e=v.alphas(this.shamirConfig.numNodes),t=[],n=[];for(let r=0;r<this.shares.length;r++){let i=this.shares[r];i!=null&&(t.push(e[r]),n.push(i))}let r=[],i=n[0].length;for(let e=0;e<i;e++){let i=[];for(let t=0;t<n.length;t++)i.push(n[t][e]);let a=T.interpolateIfPossible(t,i,this.shamirConfig.numMalicious,v.ZERO,v.ONE);if(a===void 0)throw Error(`Unable to reconstruct secret`);r.push(a.getConstantTerm().value)}return Buffer.from(r)}static FACTORY=new E({numMalicious:1,numNodes:4,numToReconstruct:2})};function O(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),Buffer.from(t)}const k={UploadSignatureMessage:[{name:`share_commitments`,type:`bytes32[]`},{name:`recovering_addresses`,type:`string[]`}]},A={DownloadSignatureMessage:[{name:`recovering_address`,type:`string`},{name:`timestamp`,type:`uint64`},{name:`public_key`,type:`bytes32`}]},j={UpdateWalletsSignatureMessage:[{name:`recovering_addresses`,type:`string[]`},{name:`timestamp`,type:`uint64`}]},M={AddAddressSignatureMessage:[{name:`recovering_address`,type:`string`},{name:`address_to_add`,type:`string`},{name:`timestamp`,type:`uint64`}]},N={RemoveAddressSignatureMessage:[{name:`recovering_address`,type:`string`},{name:`address_to_remove`,type:`string`},{name:`timestamp`,type:`uint64`}]};var P=class e{baseUrl;contractAddress;engines;walletType;signerAddress;signerPublicKey;factory;numNodes;constructor(e,t,n,r,i,a,o,s){this.baseUrl=e,this.contractAddress=t,this.reconfigure(a,o,s),this.numNodes=r,this.factory=new E({numMalicious:n,numNodes:r,numToReconstruct:i})}reconfigure(e,n,r){if([`evm`,`xrpl`,`near`,`facesign`,`stellar`].includes(e))switch(console.warn(`Deprecated wallet type`,e,`, please upgrade to latest SDK version`),e){case`evm`:e=`EVM`;break;case`xrpl`:e=`XRPL`;break;case`near`:e=`NEAR`;break;case`stellar`:e=`Stellar`;break;case`facesign`:e=`FaceSign`}s(t.includes(e),`Invalid signer type: ${e}`),s([`XRPL`,`NEAR`,`FaceSign`].includes(e)&&r||e===`EVM`,`Signer public key is required for XRPL, NEAR and FaceSign`),this.walletType=e,this.engines=void 0,this.signerAddress=n,r&&(this.signerPublicKey=r)}async uploadSecret(e,t,n,r){let a=await this.getEngines(),o=[];for(let s=0;s<a.length;s++){let c=a[s],l={...t,share_data:i.hexlify(r[s])};o.push(c.sendUpload(e,l,n))}let s=await Promise.all(o);return s.every(e=>e===`201`)?{status:`success`}:s.filter(e=>e===`201`).length>0?{status:`partial-success`}:{status:`failure`}}getBlindedShares(t){let n=this.factory.fromPlainText(this.numNodes,t);var r=[];for(let t=0;t<n.numShares();t++)r.push(e.blindShare(n.getShareBytes(t)));return r}uploadMessageToSign(e){return{domain:this.getTypedDomain(),types:k,value:e}}uploadRequest(e){console.log({mpc:`uploading to MPC`,walletType:this.walletType,address:this.signerAddress,publicKey:this.signerPublicKey});var t=``;switch(this.walletType){case`EVM`:t=`eip712:${this.signerAddress}`;break;case`XRPL`:t=`XRPL:${this.signerPublicKey}`;break;case`NEAR`:t=`NEAR:${this.signerPublicKey?.replace(`ed25519:`,``)}`;break;case`FaceSign`:t=`FACESIGN:${this.signerPublicKey}`;break;default:throw Error(`Invalid signer type`)}return{share_commitments:e.map(e=>i.keccak256(e)),recovering_addresses:[t]}}downloadMessageToSign(e){return{domain:this.getTypedDomain(),types:A,value:e}}downloadRequest(e){var t=``;switch(this.walletType){case`EVM`:t=`eip712:${this.signerAddress}`;break;case`XRPL`:t=`XRPL:${this.signerPublicKey}`;break;case`NEAR`:t=`NEAR:${this.signerPublicKey?.replace(`ed25519:`,``)}`;break;case`FaceSign`:t=`FACESIGN:${this.signerPublicKey}`;break;default:throw Error(`Invalid signer type`)}return{recovering_address:t,timestamp:Date.now(),public_key:i.hexlify(e)}}async downloadSecret(e,t,n,r){let i=[],a=await this.getEngines();for(let o=0;o<a.length;o++){let s=a[o];i.push(s.downloadAndDecrypt(e,t,n,r))}let o=await Promise.all(i);if(console.log({secretSharesDownloadStatuses:o.map(e=>e.status)}),o.every(e=>e.status===`404`))return{status:`not-stored`,secret:void 0};var s;try{return s=this.factory.fromSharesBytes(o.map(e=>e.share)).reconstructPlainText(),{status:`ok`,secret:s}}catch{return{status:`error`,secret:void 0}}}addAddressMessageToSign(e,t,n){var r=``;switch(this.walletType){case`EVM`:r=`eip712:${this.signerAddress}`;break;case`XRPL`:r=`XRPL:${this.signerPublicKey}`;break;case`NEAR`:r=`NEAR:${this.signerPublicKey?.replace(`ed25519:`,``)}`;break;case`FaceSign`:r=`FACESIGN:${this.signerPublicKey}`;break;default:throw Error(`Invalid signer type`)}var i=``;switch(n.toLowerCase()){case`evm`:i=`eip712:${e}`;break;case`xrpl`:i=`XRPL:${t}`;break;case`near`:i=`NEAR:${t?.replace(`ed25519:`,``)}`;break;case`facesign`:i=`FACESIGN:${t}`;break;default:throw Error(`Invalid address to add type`)}let a={recovering_address:r,address_to_add:i,timestamp:Date.now()};return{domain:this.getTypedDomain(),types:M,value:a}}removeAddressMessageToSign(e,t,n){var r=``;switch(this.walletType){case`EVM`:r=`eip712:${this.signerAddress}`;break;case`XRPL`:r=`XRPL:${this.signerPublicKey}`;break;case`NEAR`:r=`NEAR:${this.signerPublicKey?.replace(`ed25519:`,``)}`;break;case`FaceSign`:r=`FACESIGN:${this.signerPublicKey}`;break;default:throw Error(`Invalid signer type`)}var i=``;switch(n.toLowerCase()){case`evm`:i=`eip712:${e}`;break;case`xrpl`:i=`XRPL:${t}`;break;case`near`:i=`NEAR:${t?.replace(`ed25519:`,``)}`;break;case`facesign`:i=`FACESIGN:${t}`;break;default:throw Error(`Invalid address to remove type`)}let a={recovering_address:r,address_to_remove:i,timestamp:Date.now()};return{domain:this.getTypedDomain(),types:N,value:a}}async addAddress(e,t,n){let r=await this.getEngines(),i=[];for(let a=0;a<r.length;a++){let o=r[a];i.push(o.sendAddAddress(e,t,n))}return(await Promise.all(i)).every(e=>e===`200`)?`success`:`failure`}async removeAddress(e,t,n){let r=await this.getEngines(),i=[];for(let a=0;a<r.length;a++){let o=r[a];i.push(o.sendRemoveAddress(e,t,n))}return(await Promise.all(i)).every(e=>e===`200`)?`success`:`failure`}getTypedDomain(){return{name:`idOS secret store contract`,version:`1`,verifyingContract:`0x${this.contractAddress.substring(2)}`}}async getEngines(){if(this.engines===void 0){let e=await new n(new r({basePath:this.baseUrl})).getContract({address:this.contractAddress}),t=g(Buffer.from(e.serializedContract,`base64`));this.engines=t.nodes.map(e=>new m(e.endpoint,this.contractAddress,this.walletType))}return this.engines}static blindShare(e){return Buffer.concat([O(32),e])}};export{j as a,N as i,M as n,k as o,A as r,P as t};
2
+ //# sourceMappingURL=client-Dqb0xbdb.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-rcvBXslm.mjs","names":[],"sources":["../src/mpc/api.ts","../src/mpc/engine-client.ts","../src/mpc/generated/IdosContract.ts","../src/mpc/secretsharing/polynomial.ts","../src/mpc/secretsharing/f256.ts","../src/mpc/secretsharing/lagrange.ts","../src/mpc/secretsharing/shamir-secret-shares.ts","../src/mpc/types.ts","../src/mpc/client.ts"],"sourcesContent":["const postHeaders = {\n Accept: \"application/json, text/plain, */*\",\n \"Content-Type\": \"application/json\",\n};\n\nconst getHeaders = {\n Accept: \"application/json, text/plain, */*\",\n};\n\nexport type RequestType = \"GET\" | \"PUT\" | \"POST\" | \"PATCH\";\n\nfunction buildOptions<T>(method: RequestType, headers: RequestInit[\"headers\"], entityBytes: T) {\n const result: RequestInit = { method, headers, body: null };\n\n if (entityBytes != null) {\n result.body = JSON.stringify(entityBytes);\n }\n return result;\n}\n\n/**\n * Make a http get-request.\n *\n * @param url the url to request.\n * @return a promise containing the result of the get request.\n */\nexport function getRequest<R>(url: string): Promise<{ status: string; body: R | undefined }> {\n const options = buildOptions(\"GET\", getHeaders, null);\n return handleFetch<R>(fetch(url, options));\n}\n\n/**\n * Make a http put-request.\n *\n * @param url the url to request.\n * @param object the object to put.\n * @param headers\n * @return a promise containing whether the put succeeded or not.\n */\nexport function putRequest<T>(\n url: string,\n object: T,\n headers?: Record<string, string>,\n): Promise<string> {\n const options = buildOptions(\"PUT\", { ...postHeaders, ...headers }, object);\n return fetch(url, options)\n .then(async (response) => {\n const responseClone = response.clone();\n const responseBody = await responseClone.text();\n console.log({ responseCode: response.status, responseBody });\n return response.status.toString();\n })\n .catch((error) => {\n console.error(error);\n return error;\n });\n}\n\n/**\n * Make a http patch-request.\n *\n * @param url the url to request.\n * @param object the object to put.\n * @param headers\n * @return a promise containing whether the put succeeded or not.\n */\nexport function patchRequest<T>(\n url: string,\n object: T,\n headers?: RequestInit[\"headers\"],\n): Promise<string> {\n const options = buildOptions(\"PATCH\", { ...postHeaders, ...headers }, object);\n return fetch(url, options)\n .then(async (response) => {\n const responseClone = response.clone();\n const responseBody = await responseClone.text();\n console.log({ responseCode: response.status, responseBody });\n return response.status.toString();\n })\n .catch((error) => {\n console.error(error);\n return error;\n });\n}\n\n/**\n * Make a http post-request.\n *\n * @param url the url to request.\n * @param object the object to post.\n * @param headers\n * @return a promise containing the result of the post request.\n */\nexport function postRequest<T, R>(\n url: string,\n object: T,\n headers?: Record<string, string>,\n): Promise<{ status: string; body: R | undefined }> {\n const options = buildOptions(\"POST\", { ...postHeaders, ...headers }, object);\n return handleFetch<R>(fetch(url, options));\n}\n\nfunction handleFetch<T>(\n promise: Promise<Response>,\n): Promise<{ status: string; body: T | undefined }> {\n return promise\n .then(async (response) => {\n const responseClone = response.clone();\n const responseBody = await responseClone.text();\n console.log({ responseCode: response.status, responseBody });\n\n if (response.status === 200) {\n const data = (await response.json()) as T;\n return { status: response.status.toString(), body: data };\n }\n return { status: response.status.toString(), body: undefined };\n })\n .catch((error) => {\n console.error(error);\n return { status: \"fetch-error\", body: undefined };\n });\n}\n","import type { WalletType } from \"@idos-network/kwil-infra/actions\";\nimport { ethers } from \"ethers\";\nimport nacl from \"tweetnacl\";\nimport { patchRequest, postRequest, putRequest } from \"./api\";\nimport type {\n AddAddressRequest,\n Bytes,\n DownloadRequest,\n EncryptedShare,\n PbcAddress,\n RemoveAddressRequest,\n Sharing,\n UpdateWalletsRequest,\n} from \"./types\";\n\nexport class EngineClient {\n private readonly baseUrl: string;\n private readonly contractAddress: PbcAddress;\n private readonly walletType: WalletType;\n\n constructor(baseUrl: string, contractAddress: PbcAddress, walletType: WalletType) {\n this.contractAddress = contractAddress;\n this.baseUrl = baseUrl;\n this.walletType = walletType;\n }\n\n private getAuthHeader(signature: string): Record<string, string> {\n let prefix: string;\n switch (this.walletType) {\n case \"EVM\":\n prefix = \"eip712\";\n break;\n case \"NEAR\":\n prefix = \"NEAR\";\n break;\n case \"XRPL\":\n prefix = \"XRPL\";\n break;\n case \"FaceSign\":\n prefix = \"FACESIGN\";\n break;\n default:\n prefix = \"eip712\"; // fallback to eip712 for unknown types\n }\n\n return {\n Authorization: `${prefix} ${signature}`,\n };\n }\n\n public async sendUpload(id: string, uploadRequest: Sharing, signature: Bytes): Promise<string> {\n const authHeader = this.getAuthHeader(signature);\n const url = `${this.baseUrl}/offchain/${this.contractAddress}/shares/${id}`;\n const status = await putRequest(url, uploadRequest, authHeader);\n if (status !== \"201\") {\n throw new Error(`Error uploading share to ${this.contractAddress} at ${url}`);\n }\n return status;\n }\n\n public async sendDownload(\n id: string,\n downloadRequest: DownloadRequest,\n signature: Bytes,\n ): Promise<{ status: string; body: EncryptedShare | undefined }> {\n const authHeader = this.getAuthHeader(signature);\n const url = `${this.baseUrl}/offchain/${this.contractAddress}/shares/${id}`;\n return await postRequest(url, downloadRequest, authHeader);\n }\n\n public async downloadAndDecrypt(\n id: string,\n downloadRequest: DownloadRequest,\n signature: Bytes,\n secretKey: Uint8Array,\n ): Promise<{ share: Buffer | undefined; status: string }> {\n const { status, body: encryptedShare } = await this.sendDownload(\n id,\n downloadRequest,\n signature,\n );\n if (encryptedShare === undefined) {\n return { share: undefined, status };\n }\n const encryptedBuffer = ethers.getBytes(encryptedShare.encrypted_share);\n const publicKeyBuffer = ethers.getBytes(encryptedShare.public_key);\n const nonceBuffer = ethers.getBytes(encryptedShare.nonce);\n const open = nacl.box.open(encryptedBuffer, nonceBuffer, publicKeyBuffer, secretKey);\n if (open == null) {\n return { share: undefined, status: \"box-open-error\" };\n }\n // Remove blinding\n return { share: Buffer.from(open.subarray(32)), status };\n }\n\n public async sendUpdate(\n id: string,\n updateRequest: UpdateWalletsRequest,\n signature: string,\n ): Promise<string> {\n const authHeader: RequestInit[\"headers\"] = {\n Authorization: `eip712 ${signature}`,\n };\n\n const url = `${this.baseUrl}/offchain/${this.contractAddress}/shares/${id}`;\n const ok = await patchRequest(url, updateRequest, authHeader);\n\n if (!ok) {\n throw new Error(`Error updating wallets to ${this.contractAddress} at ${url}`);\n }\n\n return ok;\n }\n\n public async sendAddAddress(\n id: string,\n addRequest: AddAddressRequest,\n signature: string,\n ): Promise<string> {\n const authHeader = this.getAuthHeader(signature);\n const url = `${this.baseUrl}/offchain/${this.contractAddress}/shares/${id}/add_address`;\n const status = await patchRequest(url, addRequest, authHeader);\n if (status !== \"200\") {\n throw new Error(`Error adding a wallet to ${id} at ${url}`);\n }\n\n return status;\n }\n\n public async sendRemoveAddress(\n id: string,\n removeRequest: RemoveAddressRequest,\n signature: string,\n ): Promise<string> {\n const authHeader = this.getAuthHeader(signature);\n const url = `${this.baseUrl}/offchain/${this.contractAddress}/shares/${id}/remove_address`;\n const status = await patchRequest(url, removeRequest, authHeader);\n if (status !== \"200\") {\n throw new Error(`Error removing address from ${id} at ${url}`);\n }\n\n return status;\n }\n}\n","// This file is auto-generated from an abi-file using AbiCodegen.\n/* eslint-disable */\n// @ts-nocheck\n// noinspection ES6UnusedImports\nimport {\n AbiByteInput,\n AbiByteOutput,\n type AbiInput,\n type AbiOutput,\n type BlockchainAddress,\n type BlockchainStateClient,\n type StateWithClient,\n} from \"@partisiablockchain/abi-client\";\n\ntype Option<K> = K | undefined;\nexport class IdosContract {\n private readonly _client: BlockchainStateClient | undefined;\n private readonly _address: BlockchainAddress | undefined;\n\n public constructor(\n client: BlockchainStateClient | undefined,\n address: BlockchainAddress | undefined,\n ) {\n this._address = address;\n this._client = client;\n }\n public deserializeContractState(_input: AbiInput): ContractState {\n const nodes_vecLength = _input.readI32();\n const nodes: NodeConfig[] = [];\n for (let nodes_i = 0; nodes_i < nodes_vecLength; nodes_i++) {\n const nodes_elem: NodeConfig = this.deserializeNodeConfig(_input);\n nodes.push(nodes_elem);\n }\n return { nodes };\n }\n public deserializeNodeConfig(_input: AbiInput): NodeConfig {\n const address: BlockchainAddress = _input.readAddress();\n const endpoint: string = _input.readString();\n return { address, endpoint };\n }\n public async getState(): Promise<ContractState> {\n const bytes = await this._client?.getContractStateBinary(this._address!);\n if (bytes === undefined) {\n throw new Error(\"Unable to get state bytes\");\n }\n const input = AbiByteInput.createLittleEndian(bytes);\n return this.deserializeContractState(input);\n }\n}\nexport interface ContractState {\n nodes: NodeConfig[];\n}\n\nexport interface NodeConfig {\n address: BlockchainAddress;\n endpoint: string;\n}\nfunction serializeNodeConfig(_out: AbiOutput, _value: NodeConfig): void {\n const { address, endpoint } = _value;\n _out.writeAddress(address);\n _out.writeString(endpoint);\n}\n\nexport function initialize(nodes: NodeConfig[]): Buffer {\n return AbiByteOutput.serializeBigEndian((_out) => {\n _out.writeBytes(Buffer.from(\"ffffffff0f\", \"hex\"));\n _out.writeI32(nodes.length);\n for (const nodes_vec of nodes) {\n serializeNodeConfig(_out, nodes_vec);\n }\n });\n}\n\nexport function deserializeState(state: StateWithClient): ContractState;\nexport function deserializeState(bytes: Buffer): ContractState;\nexport function deserializeState(\n bytes: Buffer,\n client: BlockchainStateClient,\n address: BlockchainAddress,\n): ContractState;\nexport function deserializeState(\n state: Buffer | StateWithClient,\n client?: BlockchainStateClient,\n address?: BlockchainAddress,\n): ContractState {\n if (Buffer.isBuffer(state)) {\n const input = AbiByteInput.createLittleEndian(state);\n return new IdosContract(client, address).deserializeContractState(input);\n }\n const input = AbiByteInput.createLittleEndian(state.bytes);\n return new IdosContract(state.client, state.address).deserializeContractState(input);\n}\n","import type { FiniteFieldElement } from \"./finite-field-element\";\n\n/**\n * Polynomials with coefficients in a finite field.\n *\n * <p>Copied from <a href=\"https://gitlab.com/partisiablockchain/language/abi/zk-client\"> zk-client</a>.\n */\nexport class Polynomial<T extends FiniteFieldElement<T>> {\n private readonly coefficients: T[];\n\n private constructor(coefficients: T[]) {\n this.coefficients = coefficients;\n }\n\n /**\n * Construct a polynomial from a set of coefficients. The degree of the resultant polynomial is\n * assumed to be equal to the number of coefficients minus 1. The constant term of the polynomial\n * is assumed to be stored in the first position of the coefficients.\n *\n * @param coefficients the coefficients of the polynomial\n * @param zero zero element of the field\n * @return the constructed polynomial\n */\n static create<T extends FiniteFieldElement<T>>(coefficients: T[], zero: T): Polynomial<T> {\n return new Polynomial<T>(Polynomial.filterHighZeroes(coefficients, zero));\n }\n\n private static filterHighZeroes<T extends FiniteFieldElement<T>>(\n coefficients: T[],\n zero: T,\n ): T[] {\n for (let i = coefficients.length - 1; i >= 0; i--) {\n if (!coefficients[i].isZero()) {\n return coefficients.slice(0, i + 1);\n }\n }\n return [zero];\n }\n\n /**\n * Returns the coefficients of the polynomial.\n *\n * @return the coefficients of the polynomial\n */\n getCoefficients(): T[] {\n return this.coefficients.slice();\n }\n\n /**\n * Returns the degree of this polynomial.\n *\n * @return the degree of the polynomial\n */\n degree(): number {\n return this.coefficients.length - 1;\n }\n\n /**\n * Returns the constant term of the polynomial.\n *\n * @return the term stored on position 0 of the coefficients of this polynomial\n */\n getConstantTerm(): T {\n return this.coefficients[0];\n }\n\n /**\n * Evaluates this polynomial on a point. That is, if F is the polynomial and x a value, then this\n * method returns F(x).\n *\n * @param point the point to evaluate this polynomial on\n * @return F(point) where F is this polynomial\n */\n evaluate(point: T): T {\n const degree = this.degree();\n\n let result = this.coefficients[degree];\n for (let i = degree - 1; i >= 0; --i) {\n const current = this.coefficients[i];\n result = current.add(point.multiply(result));\n }\n return result;\n }\n}\n","import type { FiniteFieldElement } from \"./finite-field-element\";\nimport { Polynomial } from \"./polynomial\";\n\n/** Represents an element in GF(2^8) using the reduction polynomial x^8+x^4+x^3+x+1. */\nexport class F256 implements FiniteFieldElement<F256> {\n readonly value: number;\n\n private constructor(value: number) {\n this.value = value;\n }\n\n /**\n * The zero element.\n */\n static readonly ZERO: F256 = F256.createElement(0);\n\n /**\n * The one element.\n */\n static readonly ONE: F256 = F256.createElement(1);\n\n /**\n * Create a new field element with the given value.\n * @param value the value\n */\n static createElement(value: number): F256 {\n return new F256(value & 0xff);\n }\n\n /**\n * Get the computation alphas for this field.\n * @returns the computation alphas\n */\n static alphas(numNodes: number): readonly F256[] {\n return Array.from({ length: numNodes }, (_value, key) => F256.createElement(key + 1));\n }\n\n /**\n * Create a polynomial.\n * @param coefficients the coefficients of the polynomial\n */\n static createPoly(coefficients: F256[]): Polynomial<F256> {\n return Polynomial.create(coefficients, F256.ZERO);\n }\n\n /** @inheritDoc */\n add(other: F256): F256 {\n return Constants.elements[this.value ^ other.value];\n }\n\n /** @inheritDoc */\n isEqualTo(other: F256): boolean {\n return this.value === other.value;\n }\n\n /** @inheritDoc */\n isOne(): boolean {\n return this.value === 1;\n }\n\n /** @inheritDoc */\n isZero(): boolean {\n return this.value === 0;\n }\n\n /** @inheritDoc */\n modInverse(): F256 {\n return Constants.elements[Constants.multiplicativeInverse[this.value]];\n }\n\n /** @inheritDoc */\n multiply(other: F256): F256 {\n let a = this.value;\n let b = other.value;\n let m;\n let p = 0;\n for (let i = 0; i < 8; i++) {\n p = (p ^ (-(b & 1) & a)) & 0xff;\n m = -((a >> 7) & 1) & 0xff;\n a = ((a << 1) ^ (0b100011011 & m)) & 0xff;\n b = b >> 1;\n }\n return Constants.elements[p];\n }\n\n /** @inheritDoc */\n negate(): F256 {\n return this;\n }\n\n /** @inheritDoc */\n squareRoot(): F256 {\n throw new Error(\"Not implemented\");\n }\n\n /** @inheritDoc */\n subtract(other: F256): F256 {\n return this.add(other);\n }\n}\n\nconst Constants = {\n elements: Array.from({ length: 256 }, (_value, key) => F256.createElement(key)),\n multiplicativeInverse: [\n 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0, 0xb0, 0xe1, 0xe5, 0xc7,\n 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f, 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2,\n 0x3a, 0x6e, 0x5a, 0xf1, 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,\n 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f, 0x77, 0xbb, 0x59, 0x19,\n 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69, 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09,\n 0xed, 0x5c, 0x05, 0xca, 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,\n 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf, 0x33, 0x93, 0x21, 0x3b,\n 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c, 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82,\n 0x83, 0x7e, 0x7f, 0x80, 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,\n 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88, 0xf9, 0xdc, 0x89, 0x9a,\n 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48, 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62,\n 0x0c, 0xe0, 0x1f, 0xef, 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,\n 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04, 0x1b, 0xfc, 0xac, 0xe6,\n 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea, 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b,\n 0xb1, 0x0d, 0xd6, 0xeb, 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,\n 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0, 0xcd, 0x1a, 0x41, 0x1c,\n ],\n} as const;\n","import type { FiniteFieldElement } from \"./finite-field-element\";\nimport { Polynomial } from \"./polynomial\";\n\n// File copied from <a href=\"https://gitlab.com/partisiablockchain/language/abi/zk-client\"> zk-client</a>.\n\n/**\n * Try to interpolate a polynomial that passes through the supplied points.\n *\n * @param xs x-coordinates in the points\n * @param ys y-coordinates in the points\n * @param zero 0 element in the Finite Field.\n * @param one 1 element in the Finite Field.\n *\n * @returns the interpolated polynomial or null if unable to interpolate\n */\nfunction interpolate<T extends FiniteFieldElement<T>>(\n xs: readonly T[],\n ys: T[],\n zero: T,\n one: T,\n): Polynomial<T> {\n if (xs.length !== ys.length) {\n throw new Error(\"xs and ys must be of same size\");\n }\n\n if (xs.length === 0) {\n throw new Error(\"xs and ys must have at least one element\");\n }\n\n const n = xs.length;\n const c: T[] = Array(n).fill(one);\n c[0] = one;\n\n for (let i = 0; i < n; i++) {\n for (let j = i; j > 0; j--) {\n c[j] = c[j - 1].subtract(c[j].multiply(xs[i]));\n }\n c[0] = c[0].multiply(xs[i].negate());\n }\n\n const coefficients: T[] = Array(n).fill(zero);\n // Stryker disable next-line ArrayDeclaration\n const tc: T[] = Array(n).fill(zero);\n tc[n - 1] = one;\n for (let i = 0; i < n; i++) {\n let denominator = one;\n for (let j = 0; j < n; j++) {\n if (i !== j) {\n denominator = denominator.multiply(xs[i].subtract(xs[j]));\n }\n }\n\n const t: T = ys[i].multiply(denominator.modInverse());\n coefficients[n - 1] = coefficients[n - 1].add(t.multiply(tc[n - 1]));\n\n for (let j = n - 2; j >= 0; j--) {\n tc[j] = c[j + 1].add(tc[j + 1].multiply(xs[i]));\n coefficients[j] = coefficients[j].add(t.multiply(tc[j]));\n }\n }\n\n return Polynomial.create(coefficients, zero);\n}\n\n/**\n * Interpolate the minimal polynomial that passes through all the supplied points. And verify that\n * the polynomial has a degree less that maximalDegree.\n *\n * @param xs x-coordinates in the points\n * @param ys y-coordinates in the points\n * @param zero 0 element in the Finite Field.\n * @param one 1 element in the Finite Field.\n * @param maximalDegree the expected maximal degree\n * @return the interpolated polynomial\n */\nfunction interpolateCheckDegree<T extends FiniteFieldElement<T>>(\n xs: readonly T[],\n ys: T[],\n maximalDegree: number,\n zero: T,\n one: T,\n): Polynomial<T> {\n const poly = interpolate(xs, ys, zero, one);\n if (poly.degree() > maximalDegree) {\n throw new Error(\n `Interpolated polynomial has too high degree. Expected maximal=${maximalDegree}, actual=${poly.degree()}`,\n );\n }\n return poly;\n}\n\n/**\n * Try to interpolate a polynomial that passes through at least <code>2 &sdot; maximalDegree + 1\n * </code> of the supplied points.\n *\n * <p>Element lists ({@code xs} and {@code ys}) must have same size.\n *\n * @param xs x-coordinates in the points\n * @param ys y-coordinates in the points\n * @param maximalDegree the expected maximal degree\n * @param zero 0 element in the Finite Field.\n * @param one 1 element in the Finite Field.\n *\n * @returns the interpolated polynomial or undefined if unable to interpolate\n */\nfunction interpolateIfPossible<T extends FiniteFieldElement<T>>(\n xs: readonly T[],\n ys: T[],\n maximalDegree: number,\n zero: T,\n one: T,\n): Polynomial<T> | undefined {\n if (xs.length !== ys.length) {\n throw new Error(\"xs and ys must be of same size\");\n }\n return interpolateIfPossibleInner(xs, ys, maximalDegree, zero, one);\n}\n\nfunction interpolateIfPossibleInner<T extends FiniteFieldElement<T>>(\n xs: readonly T[],\n ys: T[],\n maximalDegree: number,\n zero: T,\n one: T,\n): Polynomial<T> | undefined {\n if (xs.length <= 2 * maximalDegree + 1) {\n const interpolated = interpolate(xs, ys, zero, one);\n if (interpolated.degree() > maximalDegree) {\n return undefined;\n }\n return interpolated;\n }\n for (let removeIndex = 0; removeIndex < xs.length; removeIndex++) {\n const interpolated = interpolateIfPossibleInner(\n withoutIndex(xs, removeIndex),\n withoutIndex(ys, removeIndex),\n maximalDegree,\n zero,\n one,\n );\n if (interpolated !== undefined) {\n return interpolated;\n }\n }\n return undefined;\n}\n\nfunction withoutIndex<T>(values: readonly T[], removeIndex: number): T[] {\n return values.filter((_value, index, _array) => index != removeIndex);\n}\n\n/**\n * Utility for lagrange interpolation.\n */\nexport const Lagrange: {\n interpolate: typeof interpolate;\n interpolateCheckDegree: typeof interpolateCheckDegree;\n interpolateIfPossible: typeof interpolateIfPossible;\n} = {\n interpolate,\n interpolateCheckDegree,\n interpolateIfPossible,\n};\n","import { randomBytes } from \"crypto\";\nimport { F256 } from \"./f256\";\nimport { Lagrange } from \"./lagrange\";\nimport type { SecretShareFactory } from \"./secret-share-factory\";\nimport type { SecretShares } from \"./secret-shares\";\n\n/**\n * Configuration for creating and reconstructing shamir secret shares.\n *\n * <p>The <code>numToReconstruct</code> value must be at least <code>numMalicious + 1</code> to be able\n * to reconstruct.\n *\n * <p>If <code>numToReconstruct</code> is less than <code>2 * numMalicious + 1</code> then there must be\n * some other way to guarantee that the shares are correct, e.g. through commitments on-chain.\n */\nexport interface ShamirConfig {\n /** Maximum number of malicious nodes. Depends on the threat model. */\n numMalicious: number;\n /** Total number of nodes to receive a share. */\n numNodes: number;\n /** Minimum number of shares needed to reconstruct a secret. */\n numToReconstruct: number;\n}\n\n/** Factory for creating elements of {@link ShamirSecretShares}. */\nexport class ShamirFactory implements SecretShareFactory<ShamirSecretShares> {\n private readonly shamirConfig: ShamirConfig;\n\n /**\n * Create the {@link ShamirFactory}.\n *\n * @param shamirConfig configuration for creating and reconstructing shamir secret shares.\n */\n constructor(shamirConfig: ShamirConfig) {\n this.shamirConfig = shamirConfig;\n }\n\n fromPlainText(numNodes: number, plainText: Buffer): ShamirSecretShares {\n if (numNodes != this.shamirConfig.numNodes) {\n throw new Error(\n `This shamir factory expects there to be ${this.shamirConfig.numNodes} nodes, but there was ${numNodes}.`,\n );\n }\n const randomElements = randomBytes(plainText.length * this.shamirConfig.numMalicious);\n const alphas = F256.alphas(this.shamirConfig.numNodes);\n const shares: F256[][] = Array.from({ length: this.shamirConfig.numNodes }, () => []);\n for (let i = 0; i < plainText.length; i++) {\n const coefficients = [F256.createElement(plainText[i])];\n for (let j = 0; j < this.shamirConfig.numMalicious; j++) {\n coefficients.push(\n F256.createElement(randomElements[this.shamirConfig.numMalicious * i + j]),\n );\n }\n const poly = F256.createPoly(coefficients);\n for (let j = 0; j < this.shamirConfig.numNodes; j++) {\n shares[j].push(poly.evaluate(alphas[j]));\n }\n }\n\n return new ShamirSecretShares(this.shamirConfig, shares);\n }\n\n fromSharesBytes(shares: Array<Buffer | undefined>): ShamirSecretShares {\n const elementShares = shares.map((bytes) => {\n if (bytes == undefined) {\n return undefined;\n }\n const elements = [];\n for (let i = 0; i < bytes.length; i++) {\n elements.push(F256.createElement(bytes[i]));\n }\n return elements;\n });\n return new ShamirSecretShares(this.shamirConfig, elementShares);\n }\n}\n\n/**\n * Secure secret-sharing scheme based on shamir-secret sharing.\n *\n * <p>Supported number of shares ({@code N}): {@code 4}\n *\n * <p>Based on the java implementation of the secret-sharing client.\n *\n * @see <a href=\"https://en.wikipedia.org/wiki/Shamir%27s_secret_sharing\">Shamir's secret sharing,\n * Wikipedia</a>\n */\nexport class ShamirSecretShares implements SecretShares {\n private readonly shares: Array<F256[] | undefined>;\n private readonly shamirConfig: ShamirConfig;\n\n constructor(shamirConfig: ShamirConfig, shares: Array<F256[] | undefined>) {\n if (shares.length != shamirConfig.numNodes) {\n throw new Error(`There must be ${shamirConfig.numNodes} nodes`);\n }\n const numReceivedShares = shares.filter((s) => s != undefined).length;\n if (numReceivedShares < shamirConfig.numToReconstruct) {\n throw new Error(\n `Must have received at least ${shamirConfig.numToReconstruct} shares to reconstruct. Received ${numReceivedShares}.`,\n );\n }\n this.shamirConfig = shamirConfig;\n this.shares = shares;\n }\n\n getShareBytes(nodeIndex: number): Buffer {\n const share = this.shares[nodeIndex];\n if (share == undefined) {\n throw new Error(\"Expected share to be defined\");\n }\n return Buffer.from(share.map((field) => field.value));\n }\n\n numShares(): number {\n return this.shamirConfig.numNodes;\n }\n\n reconstructPlainText(): Buffer {\n const alphas = F256.alphas(this.shamirConfig.numNodes);\n const definedAlphas: F256[] = [];\n const definedShares: F256[][] = [];\n for (let i = 0; i < this.shares.length; i++) {\n const share = this.shares[i];\n if (share != undefined) {\n definedAlphas.push(alphas[i]);\n definedShares.push(share);\n }\n }\n\n const reconstructedElements = [];\n const numElements = definedShares[0].length;\n for (let i = 0; i < numElements; i++) {\n const sharesOfIthElement = [];\n for (let j = 0; j < definedShares.length; j++) {\n sharesOfIthElement.push(definedShares[j][i]);\n }\n const interpolated = Lagrange.interpolateIfPossible(\n definedAlphas,\n sharesOfIthElement,\n this.shamirConfig.numMalicious,\n F256.ZERO,\n F256.ONE,\n );\n if (interpolated === undefined) {\n throw new Error(\"Unable to reconstruct secret\");\n }\n reconstructedElements.push(interpolated.getConstantTerm().value);\n }\n return Buffer.from(reconstructedElements);\n }\n\n public static readonly FACTORY: SecretShareFactory<ShamirSecretShares> = new ShamirFactory({\n numMalicious: 1,\n numNodes: 4,\n numToReconstruct: 2,\n });\n}\n\nexport function getRandomBytes(length: number): Buffer {\n const array = new Uint8Array(length);\n crypto.getRandomValues(array);\n\n return Buffer.from(array);\n}\n","import type { TypedDataDomain, TypedDataField } from \"ethers\";\n\nexport type PbcAddress = string;\nexport type Bytes32 = string;\nexport type Bytes24 = string;\nexport type Address = string;\nexport type Bytes = string;\n\nexport const UPLOAD_TYPES: Record<string, TypedDataField[]> = {\n UploadSignatureMessage: [\n { name: \"share_commitments\", type: \"bytes32[]\" },\n { name: \"recovering_addresses\", type: \"string[]\" },\n ],\n};\n\nexport const DOWNLOAD_TYPES: Record<string, TypedDataField[]> = {\n DownloadSignatureMessage: [\n { name: \"recovering_address\", type: \"string\" },\n { name: \"timestamp\", type: \"uint64\" },\n { name: \"public_key\", type: \"bytes32\" },\n ],\n};\n\nexport const UPDATE_TYPES: Record<string, TypedDataField[]> = {\n UpdateWalletsSignatureMessage: [\n { name: \"recovering_addresses\", type: \"string[]\" },\n { name: \"timestamp\", type: \"uint64\" },\n ],\n};\n\nexport const ADD_ADDRESS_TYPES: Record<string, TypedDataField[]> = {\n AddAddressSignatureMessage: [\n { name: \"recovering_address\", type: \"string\" },\n { name: \"address_to_add\", type: \"string\" },\n { name: \"timestamp\", type: \"uint64\" },\n ],\n};\n\nexport const REMOVE_ADDRESS_TYPES: Record<string, TypedDataField[]> = {\n RemoveAddressSignatureMessage: [\n { name: \"recovering_address\", type: \"string\" },\n { name: \"address_to_remove\", type: \"string\" },\n { name: \"timestamp\", type: \"uint64\" },\n ],\n};\n\nexport interface UploadSignatureMessage {\n share_commitments: Bytes32[];\n recovering_addresses: Address[];\n}\n\nexport interface Sharing {\n share_commitments: Bytes32[];\n recovering_addresses: Address[];\n share_data: Bytes;\n}\n\nexport interface DownloadSignatureMessage {\n recovering_address: Address;\n timestamp: number;\n public_key: Bytes32;\n}\n\nexport type DownloadRequest = DownloadSignatureMessage;\n\nexport interface AddAddressSignatureMessage {\n recovering_address: Address;\n address_to_add: Address;\n timestamp: number;\n}\n\nexport type AddAddressRequest = AddAddressSignatureMessage;\n\nexport interface RemoveAddressSignatureMessage {\n recovering_address: Address;\n address_to_remove: Address;\n timestamp: number;\n}\n\nexport type RemoveAddressRequest = RemoveAddressSignatureMessage;\n\nexport interface UpdateWalletsSignatureMessage {\n recovering_addresses: Address[];\n timestamp: number;\n}\n\nexport type UpdateWalletsRequest = UpdateWalletsSignatureMessage;\n\nexport interface EncryptedShare {\n encrypted_share: Bytes;\n public_key: Bytes32;\n nonce: Bytes24;\n}\n\nexport type DownloadMessageToSign = {\n domain: TypedDataDomain;\n types: Record<string, TypedDataField[]>;\n value: DownloadSignatureMessage;\n};\n\nexport type UploadMessageToSign = {\n domain: TypedDataDomain;\n types: Record<string, TypedDataField[]>;\n value: UploadSignatureMessage;\n};\n\nexport type AddAddressMessageToSign = {\n domain: TypedDataDomain;\n types: Record<string, TypedDataField[]>;\n value: AddAddressSignatureMessage;\n};\n\nexport type RemoveAddressMessageToSign = {\n domain: TypedDataDomain;\n types: Record<string, TypedDataField[]>;\n value: RemoveAddressSignatureMessage;\n};\n","import { WALLET_TYPES, type WalletType } from \"@idos-network/kwil-infra/actions\";\nimport {\n ChainControllerApi,\n Configuration,\n} from \"@partisiablockchain/blockchain-api-transaction-client\";\nimport { ethers, type TypedDataDomain } from \"ethers\";\nimport { EngineClient } from \"./engine-client\";\nimport { deserializeState } from \"./generated/IdosContract\";\nimport { getRandomBytes, ShamirFactory } from \"./secretsharing/shamir-secret-shares\";\nimport {\n ADD_ADDRESS_TYPES,\n type AddAddressMessageToSign,\n type AddAddressSignatureMessage,\n type Bytes,\n DOWNLOAD_TYPES,\n type DownloadMessageToSign,\n type DownloadSignatureMessage,\n type PbcAddress,\n REMOVE_ADDRESS_TYPES,\n type RemoveAddressMessageToSign,\n type RemoveAddressSignatureMessage,\n type Sharing,\n UPLOAD_TYPES,\n type UploadMessageToSign,\n type UploadSignatureMessage,\n} from \"./types\";\nimport invariant from \"tiny-invariant\";\n\nexport class Client {\n private readonly baseUrl: string;\n private readonly contractAddress: PbcAddress;\n private engines: EngineClient[] | undefined;\n private walletType!: WalletType;\n private signerAddress!: string;\n private signerPublicKey: string | undefined;\n private factory: ShamirFactory;\n private numNodes: number;\n\n constructor(\n baseUrl: string,\n contractAddress: PbcAddress,\n numMalicious: number,\n numNodes: number,\n numToReconstruct: number,\n walletType: WalletType,\n signerAddress: string,\n signerPublicKey?: string,\n ) {\n this.baseUrl = baseUrl;\n this.contractAddress = contractAddress;\n\n this.reconfigure(walletType, signerAddress, signerPublicKey);\n \n this.numNodes = numNodes;\n // TODO: Make these configurable from env variables\n this.factory = new ShamirFactory({ numMalicious, numNodes, numToReconstruct });\n }\n\n public reconfigure(\n walletType: WalletType,\n signerAddress: string,\n signerPublicKey?: string,\n ): void {\n // @deprecated\n // Remove this method after a while\n if ([\"evm\", \"xrpl\", \"near\", \"facesign\", \"stellar\"].includes(walletType as string)) {\n console.warn(\"Deprecated wallet type\", walletType, \", please upgrade to latest SDK version\");\n switch (walletType as string) {\n case \"evm\":\n walletType = \"EVM\";\n break;\n case \"xrpl\":\n walletType = \"XRPL\";\n break;\n case \"near\":\n walletType = \"NEAR\";\n break;\n case \"stellar\":\n walletType = \"Stellar\";\n break;\n case \"facesign\":\n walletType = \"FaceSign\";\n break;\n }\n }\n \n invariant(WALLET_TYPES.includes(walletType), `Invalid signer type: ${walletType}`);\n invariant(\n // XRPL, NEAR and FaceSign require a public key, EVM does not\n ([\"XRPL\", \"NEAR\", \"FaceSign\"].includes(walletType) && signerPublicKey) || walletType === \"EVM\",\n \"Signer public key is required for XRPL, NEAR and FaceSign\",\n );\n\n this.walletType = walletType;\n // Reset engines to force re-creation of them since they are using old signer information\n this.engines = undefined;\n this.signerAddress = signerAddress;\n if (signerPublicKey) this.signerPublicKey = signerPublicKey;\n }\n\n public async uploadSecret(\n id: string,\n uploadSignature: UploadSignatureMessage,\n signature: Bytes,\n blindedShares: Buffer[],\n ): Promise<{ status: string }> {\n const engineClients = await this.getEngines();\n const promises = [];\n for (let i = 0; i < engineClients.length; i++) {\n const engineClient = engineClients[i];\n const uploadRequest: Sharing = {\n ...uploadSignature,\n share_data: ethers.hexlify(blindedShares[i]),\n };\n promises.push(engineClient.sendUpload(id, uploadRequest, signature));\n }\n const statuses = await Promise.all(promises);\n\n if (statuses.every((item) => item === \"201\")) {\n return { status: \"success\" };\n }\n\n if (statuses.filter((item) => item === \"201\").length > 0) {\n return { status: \"partial-success\" };\n }\n\n return { status: \"failure\" };\n }\n\n public getBlindedShares(secret: Buffer): Buffer[] {\n // TODO: Make the number of nodes configurable from env variables\n const secretShares = this.factory.fromPlainText(this.numNodes, secret);\n var blindedShares: Buffer[] = [];\n for (let i = 0; i < secretShares.numShares(); i++) {\n blindedShares.push(Client.blindShare(secretShares.getShareBytes(i)));\n }\n return blindedShares;\n }\n\n public uploadMessageToSign(uploadRequest: UploadSignatureMessage): UploadMessageToSign {\n return {\n domain: this.getTypedDomain(),\n types: UPLOAD_TYPES,\n value: uploadRequest,\n };\n }\n\n public uploadRequest(blindedShares: Buffer[]): UploadSignatureMessage {\n console.log({ mpc: \"uploading to MPC\", walletType: this.walletType, address: this.signerAddress, publicKey: this.signerPublicKey });\n\n var address = \"\";\n switch (this.walletType) {\n case \"EVM\":\n address = `eip712:${this.signerAddress}`;\n break;\n case \"XRPL\":\n address = `XRPL:${this.signerPublicKey}`;\n break;\n case \"NEAR\":\n address = `NEAR:${this.signerPublicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"FaceSign\":\n address = `FACESIGN:${this.signerPublicKey}`;\n break;\n default:\n throw new Error(\"Invalid signer type\");\n }\n return {\n share_commitments: blindedShares.map((b) => ethers.keccak256(b)),\n recovering_addresses: [address],\n };\n }\n\n public downloadMessageToSign(downloadRequest: DownloadSignatureMessage): DownloadMessageToSign {\n return {\n domain: this.getTypedDomain(),\n types: DOWNLOAD_TYPES,\n value: downloadRequest,\n };\n }\n\n public downloadRequest(publicKey: Uint8Array): DownloadSignatureMessage {\n var address = \"\";\n switch (this.walletType) {\n case \"EVM\":\n address = `eip712:${this.signerAddress}`;\n break;\n case \"XRPL\":\n address = `XRPL:${this.signerPublicKey}`;\n break;\n case \"NEAR\":\n address = `NEAR:${this.signerPublicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"FaceSign\":\n address = `FACESIGN:${this.signerPublicKey}`;\n break;\n default:\n throw new Error(\"Invalid signer type\");\n }\n return {\n recovering_address: address,\n timestamp: Date.now(),\n public_key: ethers.hexlify(publicKey),\n };\n }\n\n public async downloadSecret(\n id: string,\n downloadRequest: DownloadSignatureMessage,\n signature: Bytes,\n secretKey: Uint8Array,\n ): Promise<{ status: string; secret: Buffer | undefined }> {\n const shares = [];\n const engineClients = await this.getEngines();\n for (let i = 0; i < engineClients.length; i++) {\n const engineClient = engineClients[i];\n shares.push(engineClient.downloadAndDecrypt(id, downloadRequest, signature, secretKey));\n }\n const secretShares = await Promise.all(shares);\n\n console.log({ secretSharesDownloadStatuses: secretShares.map((item) => item.status) });\n\n if (secretShares.every((item) => item.status === \"404\")) {\n return { status: \"not-stored\", secret: undefined };\n }\n\n var secret: Buffer;\n try {\n secret = this.factory\n .fromSharesBytes(secretShares.map((item) => item.share))\n .reconstructPlainText();\n return { status: \"ok\", secret };\n } catch (_e) {\n return { status: \"error\", secret: undefined };\n }\n }\n\n public addAddressMessageToSign(\n addressToAdd: string,\n publicKey: string | undefined,\n addressToAddType: string,\n ): AddAddressMessageToSign {\n var address = \"\";\n switch (this.walletType) {\n case \"EVM\":\n address = `eip712:${this.signerAddress}`;\n break;\n case \"XRPL\":\n address = `XRPL:${this.signerPublicKey}`;\n break;\n case \"NEAR\":\n address = `NEAR:${this.signerPublicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"FaceSign\":\n address = `FACESIGN:${this.signerPublicKey}`;\n break;\n default:\n throw new Error(\"Invalid signer type\");\n }\n\n var addressToAddFormatted = \"\";\n // @deprecated toLowerCase remove when we have updated the SDK\n switch (addressToAddType.toLowerCase()) {\n case \"evm\":\n addressToAddFormatted = `eip712:${addressToAdd}`;\n break;\n case \"xrpl\":\n addressToAddFormatted = `XRPL:${publicKey}`;\n break;\n case \"near\":\n addressToAddFormatted = `NEAR:${publicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"facesign\":\n addressToAddFormatted = `FACESIGN:${publicKey}`;\n break;\n default:\n throw new Error(\"Invalid address to add type\");\n }\n\n const value = {\n recovering_address: address,\n address_to_add: addressToAddFormatted,\n timestamp: Date.now(),\n };\n\n return {\n domain: this.getTypedDomain(),\n types: ADD_ADDRESS_TYPES,\n value,\n };\n }\n\n public removeAddressMessageToSign(\n addressToRemove: string,\n publicKey: string | undefined,\n addressToRemoveType: string,\n ): RemoveAddressMessageToSign {\n var address = \"\";\n switch (this.walletType) {\n case \"EVM\":\n address = `eip712:${this.signerAddress}`;\n break;\n case \"XRPL\":\n address = `XRPL:${this.signerPublicKey}`;\n break;\n case \"NEAR\":\n address = `NEAR:${this.signerPublicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"FaceSign\":\n address = `FACESIGN:${this.signerPublicKey}`;\n break;\n default:\n throw new Error(\"Invalid signer type\");\n }\n\n var addressToRemoveFormatted = \"\";\n // @deprecated toLowerCase remove when we have updated the SDK\n switch (addressToRemoveType.toLowerCase()) {\n case \"evm\":\n addressToRemoveFormatted = `eip712:${addressToRemove}`;\n break;\n case \"xrpl\":\n addressToRemoveFormatted = `XRPL:${publicKey}`;\n break;\n case \"near\":\n addressToRemoveFormatted = `NEAR:${publicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"facesign\":\n addressToRemoveFormatted = `FACESIGN:${publicKey}`;\n break;\n default:\n throw new Error(\"Invalid address to remove type\");\n }\n\n const value = {\n recovering_address: address,\n address_to_remove: addressToRemoveFormatted,\n timestamp: Date.now(),\n };\n return {\n domain: this.getTypedDomain(),\n types: REMOVE_ADDRESS_TYPES,\n value,\n };\n }\n\n public async addAddress(\n userId: string,\n message: AddAddressSignatureMessage,\n signature: string,\n ): Promise<string> {\n const engineClients = await this.getEngines();\n const promises = [];\n for (let i = 0; i < engineClients.length; i++) {\n const engineClient = engineClients[i];\n promises.push(engineClient.sendAddAddress(userId, message, signature));\n }\n const statuses = await Promise.all(promises);\n\n if (statuses.every((item) => item === \"200\")) {\n return \"success\";\n }\n\n return \"failure\";\n }\n\n public async removeAddress(\n userId: string,\n message: RemoveAddressSignatureMessage,\n signature: string,\n ): Promise<string> {\n const engineClients = await this.getEngines();\n const promises = [];\n for (let i = 0; i < engineClients.length; i++) {\n const engineClient = engineClients[i];\n promises.push(engineClient.sendRemoveAddress(userId, message, signature));\n }\n const statuses = await Promise.all(promises);\n\n if (statuses.every((item) => item === \"200\")) {\n return \"success\";\n }\n\n return \"failure\";\n }\n\n private getTypedDomain(): TypedDataDomain {\n return {\n name: \"idOS secret store contract\",\n version: \"1\",\n verifyingContract: `0x${this.contractAddress.substring(2)}`,\n };\n }\n\n private async getEngines(): Promise<EngineClient[]> {\n if (this.engines === undefined) {\n const chainController = new ChainControllerApi(new Configuration({ basePath: this.baseUrl }));\n const rawState = await chainController.getContract({ address: this.contractAddress });\n // oxlint-disable-next-line typescript/no-non-null-assertion -- we know serializedContract is present here\n const state = deserializeState(Buffer.from(rawState.serializedContract!, \"base64\"));\n this.engines = state.nodes.map(\n (value) => new EngineClient(value.endpoint, this.contractAddress, this.walletType),\n );\n }\n return this.engines;\n }\n\n private static blindShare(share: Buffer): Buffer {\n return Buffer.concat([getRandomBytes(32), share]);\n }\n}\n"],"mappings":";;;;;;;;AAAA,MAAM,cAAc;CAClB,QAAQ;CACR,gBAAgB;CACjB;AAQD,SAAS,aAAgB,QAAqB,SAAiC,aAAgB;CAC7F,MAAM,SAAsB;EAAE;EAAQ;EAAS,MAAM;EAAM;CAE3D,IAAI,eAAe,MACjB,OAAO,OAAO,KAAK,UAAU,YAAY;CAE3C,OAAO;;;;;;;;;;AAsBT,SAAgB,WACd,KACA,QACA,SACiB;CACjB,MAAM,UAAU,aAAa,OAAO;EAAE,GAAG;EAAa,GAAG;EAAS,EAAE,OAAO;CAC3E,OAAO,MAAM,KAAK,QAAQ,CACvB,KAAK,OAAO,aAAa;EAExB,MAAM,eAAe,MADC,SAAS,OACS,CAAC,MAAM;EAC/C,QAAQ,IAAI;GAAE,cAAc,SAAS;GAAQ;GAAc,CAAC;EAC5D,OAAO,SAAS,OAAO,UAAU;GACjC,CACD,OAAO,UAAU;EAChB,QAAQ,MAAM,MAAM;EACpB,OAAO;GACP;;;;;;;;;;AAWN,SAAgB,aACd,KACA,QACA,SACiB;CACjB,MAAM,UAAU,aAAa,SAAS;EAAE,GAAG;EAAa,GAAG;EAAS,EAAE,OAAO;CAC7E,OAAO,MAAM,KAAK,QAAQ,CACvB,KAAK,OAAO,aAAa;EAExB,MAAM,eAAe,MADC,SAAS,OACS,CAAC,MAAM;EAC/C,QAAQ,IAAI;GAAE,cAAc,SAAS;GAAQ;GAAc,CAAC;EAC5D,OAAO,SAAS,OAAO,UAAU;GACjC,CACD,OAAO,UAAU;EAChB,QAAQ,MAAM,MAAM;EACpB,OAAO;GACP;;;;;;;;;;AAWN,SAAgB,YACd,KACA,QACA,SACkD;CAClD,MAAM,UAAU,aAAa,QAAQ;EAAE,GAAG;EAAa,GAAG;EAAS,EAAE,OAAO;CAC5E,OAAO,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AAW,CACnF;;EAEH,OAAO,KAAK;;CAGd,OAAe,WAAW,OAAuB;EAC/C,OAAO,OAAO,OAAO,CAAC,eAAe,GAAG,EAAE,MAAM,CAAC"}
1
+ {"version":3,"file":"client-Dqb0xbdb.mjs","names":[],"sources":["../src/mpc/api.ts","../src/mpc/engine-client.ts","../src/mpc/generated/IdosContract.ts","../src/mpc/secretsharing/polynomial.ts","../src/mpc/secretsharing/f256.ts","../src/mpc/secretsharing/lagrange.ts","../src/mpc/secretsharing/shamir-secret-shares.ts","../src/mpc/types.ts","../src/mpc/client.ts"],"sourcesContent":["const postHeaders = {\n Accept: \"application/json, text/plain, */*\",\n \"Content-Type\": \"application/json\",\n};\n\nconst getHeaders = {\n Accept: \"application/json, text/plain, */*\",\n};\n\nexport type RequestType = \"GET\" | \"PUT\" | \"POST\" | \"PATCH\";\n\nfunction buildOptions<T>(method: RequestType, headers: RequestInit[\"headers\"], entityBytes: T) {\n const result: RequestInit = { method, headers, body: null };\n\n if (entityBytes != null) {\n result.body = JSON.stringify(entityBytes);\n }\n return result;\n}\n\n/**\n * Make a http get-request.\n *\n * @param url the url to request.\n * @return a promise containing the result of the get request.\n */\nexport function getRequest<R>(url: string): Promise<{ status: string; body: R | undefined }> {\n const options = buildOptions(\"GET\", getHeaders, null);\n return handleFetch<R>(fetch(url, options));\n}\n\n/**\n * Make a http put-request.\n *\n * @param url the url to request.\n * @param object the object to put.\n * @param headers\n * @return a promise containing whether the put succeeded or not.\n */\nexport function putRequest<T>(\n url: string,\n object: T,\n headers?: Record<string, string>,\n): Promise<string> {\n const options = buildOptions(\"PUT\", { ...postHeaders, ...headers }, object);\n return fetch(url, options)\n .then(async (response) => {\n const responseClone = response.clone();\n const responseBody = await responseClone.text();\n console.log({ responseCode: response.status, responseBody });\n return response.status.toString();\n })\n .catch((error) => {\n console.error(error);\n return error;\n });\n}\n\n/**\n * Make a http patch-request.\n *\n * @param url the url to request.\n * @param object the object to put.\n * @param headers\n * @return a promise containing whether the put succeeded or not.\n */\nexport function patchRequest<T>(\n url: string,\n object: T,\n headers?: RequestInit[\"headers\"],\n): Promise<string> {\n const options = buildOptions(\"PATCH\", { ...postHeaders, ...headers }, object);\n return fetch(url, options)\n .then(async (response) => {\n const responseClone = response.clone();\n const responseBody = await responseClone.text();\n console.log({ responseCode: response.status, responseBody });\n return response.status.toString();\n })\n .catch((error) => {\n console.error(error);\n return error;\n });\n}\n\n/**\n * Make a http post-request.\n *\n * @param url the url to request.\n * @param object the object to post.\n * @param headers\n * @return a promise containing the result of the post request.\n */\nexport function postRequest<T, R>(\n url: string,\n object: T,\n headers?: Record<string, string>,\n): Promise<{ status: string; body: R | undefined }> {\n const options = buildOptions(\"POST\", { ...postHeaders, ...headers }, object);\n return handleFetch<R>(fetch(url, options));\n}\n\nfunction handleFetch<T>(\n promise: Promise<Response>,\n): Promise<{ status: string; body: T | undefined }> {\n return promise\n .then(async (response) => {\n const responseClone = response.clone();\n const responseBody = await responseClone.text();\n console.log({ responseCode: response.status, responseBody });\n\n if (response.status === 200) {\n const data = (await response.json()) as T;\n return { status: response.status.toString(), body: data };\n }\n return { status: response.status.toString(), body: undefined };\n })\n .catch((error) => {\n console.error(error);\n return { status: \"fetch-error\", body: undefined };\n });\n}\n","import type { WalletType } from \"@idos-network/kwil-infra/actions\";\nimport { ethers } from \"ethers\";\nimport nacl from \"tweetnacl\";\nimport { patchRequest, postRequest, putRequest } from \"./api\";\nimport type {\n AddAddressRequest,\n Bytes,\n DownloadRequest,\n EncryptedShare,\n PbcAddress,\n RemoveAddressRequest,\n Sharing,\n UpdateWalletsRequest,\n} from \"./types\";\n\nexport class EngineClient {\n private readonly baseUrl: string;\n private readonly contractAddress: PbcAddress;\n private readonly walletType: WalletType;\n\n constructor(baseUrl: string, contractAddress: PbcAddress, walletType: WalletType) {\n this.contractAddress = contractAddress;\n this.baseUrl = baseUrl;\n this.walletType = walletType;\n }\n\n private getAuthHeader(signature: string): Record<string, string> {\n let prefix: string;\n switch (this.walletType) {\n case \"EVM\":\n prefix = \"eip712\";\n break;\n case \"NEAR\":\n prefix = \"NEAR\";\n break;\n case \"XRPL\":\n prefix = \"XRPL\";\n break;\n case \"FaceSign\":\n prefix = \"FACESIGN\";\n break;\n default:\n prefix = \"eip712\"; // fallback to eip712 for unknown types\n }\n\n return {\n Authorization: `${prefix} ${signature}`,\n };\n }\n\n public async sendUpload(id: string, uploadRequest: Sharing, signature: Bytes): Promise<string> {\n const authHeader = this.getAuthHeader(signature);\n const url = `${this.baseUrl}/offchain/${this.contractAddress}/shares/${id}`;\n const status = await putRequest(url, uploadRequest, authHeader);\n if (status !== \"201\") {\n throw new Error(`Error uploading share to ${this.contractAddress} at ${url}`);\n }\n return status;\n }\n\n public async sendDownload(\n id: string,\n downloadRequest: DownloadRequest,\n signature: Bytes,\n ): Promise<{ status: string; body: EncryptedShare | undefined }> {\n const authHeader = this.getAuthHeader(signature);\n const url = `${this.baseUrl}/offchain/${this.contractAddress}/shares/${id}`;\n return await postRequest(url, downloadRequest, authHeader);\n }\n\n public async downloadAndDecrypt(\n id: string,\n downloadRequest: DownloadRequest,\n signature: Bytes,\n secretKey: Uint8Array,\n ): Promise<{ share: Buffer | undefined; status: string }> {\n const { status, body: encryptedShare } = await this.sendDownload(\n id,\n downloadRequest,\n signature,\n );\n if (encryptedShare === undefined) {\n return { share: undefined, status };\n }\n const encryptedBuffer = ethers.getBytes(encryptedShare.encrypted_share);\n const publicKeyBuffer = ethers.getBytes(encryptedShare.public_key);\n const nonceBuffer = ethers.getBytes(encryptedShare.nonce);\n const open = nacl.box.open(encryptedBuffer, nonceBuffer, publicKeyBuffer, secretKey);\n if (open == null) {\n return { share: undefined, status: \"box-open-error\" };\n }\n // Remove blinding\n return { share: Buffer.from(open.subarray(32)), status };\n }\n\n public async sendUpdate(\n id: string,\n updateRequest: UpdateWalletsRequest,\n signature: string,\n ): Promise<string> {\n const authHeader: RequestInit[\"headers\"] = {\n Authorization: `eip712 ${signature}`,\n };\n\n const url = `${this.baseUrl}/offchain/${this.contractAddress}/shares/${id}`;\n const ok = await patchRequest(url, updateRequest, authHeader);\n\n if (!ok) {\n throw new Error(`Error updating wallets to ${this.contractAddress} at ${url}`);\n }\n\n return ok;\n }\n\n public async sendAddAddress(\n id: string,\n addRequest: AddAddressRequest,\n signature: string,\n ): Promise<string> {\n const authHeader = this.getAuthHeader(signature);\n const url = `${this.baseUrl}/offchain/${this.contractAddress}/shares/${id}/add_address`;\n const status = await patchRequest(url, addRequest, authHeader);\n if (status !== \"200\") {\n throw new Error(`Error adding a wallet to ${id} at ${url}`);\n }\n\n return status;\n }\n\n public async sendRemoveAddress(\n id: string,\n removeRequest: RemoveAddressRequest,\n signature: string,\n ): Promise<string> {\n const authHeader = this.getAuthHeader(signature);\n const url = `${this.baseUrl}/offchain/${this.contractAddress}/shares/${id}/remove_address`;\n const status = await patchRequest(url, removeRequest, authHeader);\n if (status !== \"200\") {\n throw new Error(`Error removing address from ${id} at ${url}`);\n }\n\n return status;\n }\n}\n","// This file is auto-generated from an abi-file using AbiCodegen.\n/* eslint-disable */\n// @ts-nocheck\n// noinspection ES6UnusedImports\nimport {\n AbiByteInput,\n AbiByteOutput,\n type AbiInput,\n type AbiOutput,\n type BlockchainAddress,\n type BlockchainStateClient,\n type StateWithClient,\n} from \"@partisiablockchain/abi-client\";\n\ntype Option<K> = K | undefined;\nexport class IdosContract {\n private readonly _client: BlockchainStateClient | undefined;\n private readonly _address: BlockchainAddress | undefined;\n\n public constructor(\n client: BlockchainStateClient | undefined,\n address: BlockchainAddress | undefined,\n ) {\n this._address = address;\n this._client = client;\n }\n public deserializeContractState(_input: AbiInput): ContractState {\n const nodes_vecLength = _input.readI32();\n const nodes: NodeConfig[] = [];\n for (let nodes_i = 0; nodes_i < nodes_vecLength; nodes_i++) {\n const nodes_elem: NodeConfig = this.deserializeNodeConfig(_input);\n nodes.push(nodes_elem);\n }\n return { nodes };\n }\n public deserializeNodeConfig(_input: AbiInput): NodeConfig {\n const address: BlockchainAddress = _input.readAddress();\n const endpoint: string = _input.readString();\n return { address, endpoint };\n }\n public async getState(): Promise<ContractState> {\n const bytes = await this._client?.getContractStateBinary(this._address!);\n if (bytes === undefined) {\n throw new Error(\"Unable to get state bytes\");\n }\n const input = AbiByteInput.createLittleEndian(bytes);\n return this.deserializeContractState(input);\n }\n}\nexport interface ContractState {\n nodes: NodeConfig[];\n}\n\nexport interface NodeConfig {\n address: BlockchainAddress;\n endpoint: string;\n}\nfunction serializeNodeConfig(_out: AbiOutput, _value: NodeConfig): void {\n const { address, endpoint } = _value;\n _out.writeAddress(address);\n _out.writeString(endpoint);\n}\n\nexport function initialize(nodes: NodeConfig[]): Buffer {\n return AbiByteOutput.serializeBigEndian((_out) => {\n _out.writeBytes(Buffer.from(\"ffffffff0f\", \"hex\"));\n _out.writeI32(nodes.length);\n for (const nodes_vec of nodes) {\n serializeNodeConfig(_out, nodes_vec);\n }\n });\n}\n\nexport function deserializeState(state: StateWithClient): ContractState;\nexport function deserializeState(bytes: Buffer): ContractState;\nexport function deserializeState(\n bytes: Buffer,\n client: BlockchainStateClient,\n address: BlockchainAddress,\n): ContractState;\nexport function deserializeState(\n state: Buffer | StateWithClient,\n client?: BlockchainStateClient,\n address?: BlockchainAddress,\n): ContractState {\n if (Buffer.isBuffer(state)) {\n const input = AbiByteInput.createLittleEndian(state);\n return new IdosContract(client, address).deserializeContractState(input);\n }\n const input = AbiByteInput.createLittleEndian(state.bytes);\n return new IdosContract(state.client, state.address).deserializeContractState(input);\n}\n","import type { FiniteFieldElement } from \"./finite-field-element\";\n\n/**\n * Polynomials with coefficients in a finite field.\n *\n * <p>Copied from <a href=\"https://gitlab.com/partisiablockchain/language/abi/zk-client\"> zk-client</a>.\n */\nexport class Polynomial<T extends FiniteFieldElement<T>> {\n private readonly coefficients: T[];\n\n private constructor(coefficients: T[]) {\n this.coefficients = coefficients;\n }\n\n /**\n * Construct a polynomial from a set of coefficients. The degree of the resultant polynomial is\n * assumed to be equal to the number of coefficients minus 1. The constant term of the polynomial\n * is assumed to be stored in the first position of the coefficients.\n *\n * @param coefficients the coefficients of the polynomial\n * @param zero zero element of the field\n * @return the constructed polynomial\n */\n static create<T extends FiniteFieldElement<T>>(coefficients: T[], zero: T): Polynomial<T> {\n return new Polynomial<T>(Polynomial.filterHighZeroes(coefficients, zero));\n }\n\n private static filterHighZeroes<T extends FiniteFieldElement<T>>(\n coefficients: T[],\n zero: T,\n ): T[] {\n for (let i = coefficients.length - 1; i >= 0; i--) {\n if (!coefficients[i].isZero()) {\n return coefficients.slice(0, i + 1);\n }\n }\n return [zero];\n }\n\n /**\n * Returns the coefficients of the polynomial.\n *\n * @return the coefficients of the polynomial\n */\n getCoefficients(): T[] {\n return this.coefficients.slice();\n }\n\n /**\n * Returns the degree of this polynomial.\n *\n * @return the degree of the polynomial\n */\n degree(): number {\n return this.coefficients.length - 1;\n }\n\n /**\n * Returns the constant term of the polynomial.\n *\n * @return the term stored on position 0 of the coefficients of this polynomial\n */\n getConstantTerm(): T {\n return this.coefficients[0];\n }\n\n /**\n * Evaluates this polynomial on a point. That is, if F is the polynomial and x a value, then this\n * method returns F(x).\n *\n * @param point the point to evaluate this polynomial on\n * @return F(point) where F is this polynomial\n */\n evaluate(point: T): T {\n const degree = this.degree();\n\n let result = this.coefficients[degree];\n for (let i = degree - 1; i >= 0; --i) {\n const current = this.coefficients[i];\n result = current.add(point.multiply(result));\n }\n return result;\n }\n}\n","import type { FiniteFieldElement } from \"./finite-field-element\";\nimport { Polynomial } from \"./polynomial\";\n\n/** Represents an element in GF(2^8) using the reduction polynomial x^8+x^4+x^3+x+1. */\nexport class F256 implements FiniteFieldElement<F256> {\n readonly value: number;\n\n private constructor(value: number) {\n this.value = value;\n }\n\n /**\n * The zero element.\n */\n static readonly ZERO: F256 = F256.createElement(0);\n\n /**\n * The one element.\n */\n static readonly ONE: F256 = F256.createElement(1);\n\n /**\n * Create a new field element with the given value.\n * @param value the value\n */\n static createElement(value: number): F256 {\n return new F256(value & 0xff);\n }\n\n /**\n * Get the computation alphas for this field.\n * @returns the computation alphas\n */\n static alphas(numNodes: number): readonly F256[] {\n return Array.from({ length: numNodes }, (_value, key) => F256.createElement(key + 1));\n }\n\n /**\n * Create a polynomial.\n * @param coefficients the coefficients of the polynomial\n */\n static createPoly(coefficients: F256[]): Polynomial<F256> {\n return Polynomial.create(coefficients, F256.ZERO);\n }\n\n /** @inheritDoc */\n add(other: F256): F256 {\n return Constants.elements[this.value ^ other.value];\n }\n\n /** @inheritDoc */\n isEqualTo(other: F256): boolean {\n return this.value === other.value;\n }\n\n /** @inheritDoc */\n isOne(): boolean {\n return this.value === 1;\n }\n\n /** @inheritDoc */\n isZero(): boolean {\n return this.value === 0;\n }\n\n /** @inheritDoc */\n modInverse(): F256 {\n return Constants.elements[Constants.multiplicativeInverse[this.value]];\n }\n\n /** @inheritDoc */\n multiply(other: F256): F256 {\n let a = this.value;\n let b = other.value;\n let m;\n let p = 0;\n for (let i = 0; i < 8; i++) {\n p = (p ^ (-(b & 1) & a)) & 0xff;\n m = -((a >> 7) & 1) & 0xff;\n a = ((a << 1) ^ (0b100011011 & m)) & 0xff;\n b = b >> 1;\n }\n return Constants.elements[p];\n }\n\n /** @inheritDoc */\n negate(): F256 {\n return this;\n }\n\n /** @inheritDoc */\n squareRoot(): F256 {\n throw new Error(\"Not implemented\");\n }\n\n /** @inheritDoc */\n subtract(other: F256): F256 {\n return this.add(other);\n }\n}\n\nconst Constants = {\n elements: Array.from({ length: 256 }, (_value, key) => F256.createElement(key)),\n multiplicativeInverse: [\n 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0, 0xb0, 0xe1, 0xe5, 0xc7,\n 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f, 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2,\n 0x3a, 0x6e, 0x5a, 0xf1, 0x55, 0x4d, 0xa8, 0xc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 0x90, 0x6b,\n 0xb1, 0x0d, 0xd6, 0xeb, 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,\n 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0, 0xcd, 0x1a, 0x41, 0x1c,\n ],\n} as const;\n","import type { FiniteFieldElement } from \"./finite-field-element\";\nimport { Polynomial } from \"./polynomial\";\n\n// File copied from <a href=\"https://gitlab.com/partisiablockchain/language/abi/zk-client\"> zk-client</a>.\n\n/**\n * Try to interpolate a polynomial that passes through the supplied points.\n *\n * @param xs x-coordinates in the points\n * @param ys y-coordinates in the points\n * @param zero 0 element in the Finite Field.\n * @param one 1 element in the Finite Field.\n *\n * @returns the interpolated polynomial or null if unable to interpolate\n */\nfunction interpolate<T extends FiniteFieldElement<T>>(\n xs: readonly T[],\n ys: T[],\n zero: T,\n one: T,\n): Polynomial<T> {\n if (xs.length !== ys.length) {\n throw new Error(\"xs and ys must be of same size\");\n }\n\n if (xs.length === 0) {\n throw new Error(\"xs and ys must have at least one element\");\n }\n\n const n = xs.length;\n const c: T[] = Array(n).fill(one);\n c[0] = one;\n\n for (let i = 0; i < n; i++) {\n for (let j = i; j > 0; j--) {\n c[j] = c[j - 1].subtract(c[j].multiply(xs[i]));\n }\n c[0] = c[0].multiply(xs[i].negate());\n }\n\n const coefficients: T[] = Array(n).fill(zero);\n // Stryker disable next-line ArrayDeclaration\n const tc: T[] = Array(n).fill(zero);\n tc[n - 1] = one;\n for (let i = 0; i < n; i++) {\n let denominator = one;\n for (let j = 0; j < n; j++) {\n if (i !== j) {\n denominator = denominator.multiply(xs[i].subtract(xs[j]));\n }\n }\n\n const t: T = ys[i].multiply(denominator.modInverse());\n coefficients[n - 1] = coefficients[n - 1].add(t.multiply(tc[n - 1]));\n\n for (let j = n - 2; j >= 0; j--) {\n tc[j] = c[j + 1].add(tc[j + 1].multiply(xs[i]));\n coefficients[j] = coefficients[j].add(t.multiply(tc[j]));\n }\n }\n\n return Polynomial.create(coefficients, zero);\n}\n\n/**\n * Interpolate the minimal polynomial that passes through all the supplied points. And verify that\n * the polynomial has a degree less that maximalDegree.\n *\n * @param xs x-coordinates in the points\n * @param ys y-coordinates in the points\n * @param zero 0 element in the Finite Field.\n * @param one 1 element in the Finite Field.\n * @param maximalDegree the expected maximal degree\n * @return the interpolated polynomial\n */\nfunction interpolateCheckDegree<T extends FiniteFieldElement<T>>(\n xs: readonly T[],\n ys: T[],\n maximalDegree: number,\n zero: T,\n one: T,\n): Polynomial<T> {\n const poly = interpolate(xs, ys, zero, one);\n if (poly.degree() > maximalDegree) {\n throw new Error(\n `Interpolated polynomial has too high degree. Expected maximal=${maximalDegree}, actual=${poly.degree()}`,\n );\n }\n return poly;\n}\n\n/**\n * Try to interpolate a polynomial that passes through at least <code>2 &sdot; maximalDegree + 1\n * </code> of the supplied points.\n *\n * <p>Element lists ({@code xs} and {@code ys}) must have same size.\n *\n * @param xs x-coordinates in the points\n * @param ys y-coordinates in the points\n * @param maximalDegree the expected maximal degree\n * @param zero 0 element in the Finite Field.\n * @param one 1 element in the Finite Field.\n *\n * @returns the interpolated polynomial or undefined if unable to interpolate\n */\nfunction interpolateIfPossible<T extends FiniteFieldElement<T>>(\n xs: readonly T[],\n ys: T[],\n maximalDegree: number,\n zero: T,\n one: T,\n): Polynomial<T> | undefined {\n if (xs.length !== ys.length) {\n throw new Error(\"xs and ys must be of same size\");\n }\n return interpolateIfPossibleInner(xs, ys, maximalDegree, zero, one);\n}\n\nfunction interpolateIfPossibleInner<T extends FiniteFieldElement<T>>(\n xs: readonly T[],\n ys: T[],\n maximalDegree: number,\n zero: T,\n one: T,\n): Polynomial<T> | undefined {\n if (xs.length <= 2 * maximalDegree + 1) {\n const interpolated = interpolate(xs, ys, zero, one);\n if (interpolated.degree() > maximalDegree) {\n return undefined;\n }\n return interpolated;\n }\n for (let removeIndex = 0; removeIndex < xs.length; removeIndex++) {\n const interpolated = interpolateIfPossibleInner(\n withoutIndex(xs, removeIndex),\n withoutIndex(ys, removeIndex),\n maximalDegree,\n zero,\n one,\n );\n if (interpolated !== undefined) {\n return interpolated;\n }\n }\n return undefined;\n}\n\nfunction withoutIndex<T>(values: readonly T[], removeIndex: number): T[] {\n return values.filter((_value, index, _array) => index != removeIndex);\n}\n\n/**\n * Utility for lagrange interpolation.\n */\nexport const Lagrange: {\n interpolate: typeof interpolate;\n interpolateCheckDegree: typeof interpolateCheckDegree;\n interpolateIfPossible: typeof interpolateIfPossible;\n} = {\n interpolate,\n interpolateCheckDegree,\n interpolateIfPossible,\n};\n","import { randomBytes } from \"crypto\";\nimport { F256 } from \"./f256\";\nimport { Lagrange } from \"./lagrange\";\nimport type { SecretShareFactory } from \"./secret-share-factory\";\nimport type { SecretShares } from \"./secret-shares\";\n\n/**\n * Configuration for creating and reconstructing shamir secret shares.\n *\n * <p>The <code>numToReconstruct</code> value must be at least <code>numMalicious + 1</code> to be able\n * to reconstruct.\n *\n * <p>If <code>numToReconstruct</code> is less than <code>2 * numMalicious + 1</code> then there must be\n * some other way to guarantee that the shares are correct, e.g. through commitments on-chain.\n */\nexport interface ShamirConfig {\n /** Maximum number of malicious nodes. Depends on the threat model. */\n numMalicious: number;\n /** Total number of nodes to receive a share. */\n numNodes: number;\n /** Minimum number of shares needed to reconstruct a secret. */\n numToReconstruct: number;\n}\n\n/** Factory for creating elements of {@link ShamirSecretShares}. */\nexport class ShamirFactory implements SecretShareFactory<ShamirSecretShares> {\n private readonly shamirConfig: ShamirConfig;\n\n /**\n * Create the {@link ShamirFactory}.\n *\n * @param shamirConfig configuration for creating and reconstructing shamir secret shares.\n */\n constructor(shamirConfig: ShamirConfig) {\n this.shamirConfig = shamirConfig;\n }\n\n fromPlainText(numNodes: number, plainText: Buffer): ShamirSecretShares {\n if (numNodes != this.shamirConfig.numNodes) {\n throw new Error(\n `This shamir factory expects there to be ${this.shamirConfig.numNodes} nodes, but there was ${numNodes}.`,\n );\n }\n const randomElements = randomBytes(plainText.length * this.shamirConfig.numMalicious);\n const alphas = F256.alphas(this.shamirConfig.numNodes);\n const shares: F256[][] = Array.from({ length: this.shamirConfig.numNodes }, () => []);\n for (let i = 0; i < plainText.length; i++) {\n const coefficients = [F256.createElement(plainText[i])];\n for (let j = 0; j < this.shamirConfig.numMalicious; j++) {\n coefficients.push(\n F256.createElement(randomElements[this.shamirConfig.numMalicious * i + j]),\n );\n }\n const poly = F256.createPoly(coefficients);\n for (let j = 0; j < this.shamirConfig.numNodes; j++) {\n shares[j].push(poly.evaluate(alphas[j]));\n }\n }\n\n return new ShamirSecretShares(this.shamirConfig, shares);\n }\n\n fromSharesBytes(shares: Array<Buffer | undefined>): ShamirSecretShares {\n const elementShares = shares.map((bytes) => {\n if (bytes == undefined) {\n return undefined;\n }\n const elements = [];\n for (let i = 0; i < bytes.length; i++) {\n elements.push(F256.createElement(bytes[i]));\n }\n return elements;\n });\n return new ShamirSecretShares(this.shamirConfig, elementShares);\n }\n}\n\n/**\n * Secure secret-sharing scheme based on shamir-secret sharing.\n *\n * <p>Supported number of shares ({@code N}): {@code 4}\n *\n * <p>Based on the java implementation of the secret-sharing client.\n *\n * @see <a href=\"https://en.wikipedia.org/wiki/Shamir%27s_secret_sharing\">Shamir's secret sharing,\n * Wikipedia</a>\n */\nexport class ShamirSecretShares implements SecretShares {\n private readonly shares: Array<F256[] | undefined>;\n private readonly shamirConfig: ShamirConfig;\n\n constructor(shamirConfig: ShamirConfig, shares: Array<F256[] | undefined>) {\n if (shares.length != shamirConfig.numNodes) {\n throw new Error(`There must be ${shamirConfig.numNodes} nodes`);\n }\n const numReceivedShares = shares.filter((s) => s != undefined).length;\n if (numReceivedShares < shamirConfig.numToReconstruct) {\n throw new Error(\n `Must have received at least ${shamirConfig.numToReconstruct} shares to reconstruct. Received ${numReceivedShares}.`,\n );\n }\n this.shamirConfig = shamirConfig;\n this.shares = shares;\n }\n\n getShareBytes(nodeIndex: number): Buffer {\n const share = this.shares[nodeIndex];\n if (share == undefined) {\n throw new Error(\"Expected share to be defined\");\n }\n return Buffer.from(share.map((field) => field.value));\n }\n\n numShares(): number {\n return this.shamirConfig.numNodes;\n }\n\n reconstructPlainText(): Buffer {\n const alphas = F256.alphas(this.shamirConfig.numNodes);\n const definedAlphas: F256[] = [];\n const definedShares: F256[][] = [];\n for (let i = 0; i < this.shares.length; i++) {\n const share = this.shares[i];\n if (share != undefined) {\n definedAlphas.push(alphas[i]);\n definedShares.push(share);\n }\n }\n\n const reconstructedElements = [];\n const numElements = definedShares[0].length;\n for (let i = 0; i < numElements; i++) {\n const sharesOfIthElement = [];\n for (let j = 0; j < definedShares.length; j++) {\n sharesOfIthElement.push(definedShares[j][i]);\n }\n const interpolated = Lagrange.interpolateIfPossible(\n definedAlphas,\n sharesOfIthElement,\n this.shamirConfig.numMalicious,\n F256.ZERO,\n F256.ONE,\n );\n if (interpolated === undefined) {\n throw new Error(\"Unable to reconstruct secret\");\n }\n reconstructedElements.push(interpolated.getConstantTerm().value);\n }\n return Buffer.from(reconstructedElements);\n }\n\n public static readonly FACTORY: SecretShareFactory<ShamirSecretShares> = new ShamirFactory({\n numMalicious: 1,\n numNodes: 4,\n numToReconstruct: 2,\n });\n}\n\nexport function getRandomBytes(length: number): Buffer {\n const array = new Uint8Array(length);\n crypto.getRandomValues(array);\n\n return Buffer.from(array);\n}\n","import type { TypedDataDomain, TypedDataField } from \"ethers\";\n\nexport type PbcAddress = string;\nexport type Bytes32 = string;\nexport type Bytes24 = string;\nexport type Address = string;\nexport type Bytes = string;\n\nexport const UPLOAD_TYPES: Record<string, TypedDataField[]> = {\n UploadSignatureMessage: [\n { name: \"share_commitments\", type: \"bytes32[]\" },\n { name: \"recovering_addresses\", type: \"string[]\" },\n ],\n};\n\nexport const DOWNLOAD_TYPES: Record<string, TypedDataField[]> = {\n DownloadSignatureMessage: [\n { name: \"recovering_address\", type: \"string\" },\n { name: \"timestamp\", type: \"uint64\" },\n { name: \"public_key\", type: \"bytes32\" },\n ],\n};\n\nexport const UPDATE_TYPES: Record<string, TypedDataField[]> = {\n UpdateWalletsSignatureMessage: [\n { name: \"recovering_addresses\", type: \"string[]\" },\n { name: \"timestamp\", type: \"uint64\" },\n ],\n};\n\nexport const ADD_ADDRESS_TYPES: Record<string, TypedDataField[]> = {\n AddAddressSignatureMessage: [\n { name: \"recovering_address\", type: \"string\" },\n { name: \"address_to_add\", type: \"string\" },\n { name: \"timestamp\", type: \"uint64\" },\n ],\n};\n\nexport const REMOVE_ADDRESS_TYPES: Record<string, TypedDataField[]> = {\n RemoveAddressSignatureMessage: [\n { name: \"recovering_address\", type: \"string\" },\n { name: \"address_to_remove\", type: \"string\" },\n { name: \"timestamp\", type: \"uint64\" },\n ],\n};\n\nexport interface UploadSignatureMessage {\n share_commitments: Bytes32[];\n recovering_addresses: Address[];\n}\n\nexport interface Sharing {\n share_commitments: Bytes32[];\n recovering_addresses: Address[];\n share_data: Bytes;\n}\n\nexport interface DownloadSignatureMessage {\n recovering_address: Address;\n timestamp: number;\n public_key: Bytes32;\n}\n\nexport type DownloadRequest = DownloadSignatureMessage;\n\nexport interface AddAddressSignatureMessage {\n recovering_address: Address;\n address_to_add: Address;\n timestamp: number;\n}\n\nexport type AddAddressRequest = AddAddressSignatureMessage;\n\nexport interface RemoveAddressSignatureMessage {\n recovering_address: Address;\n address_to_remove: Address;\n timestamp: number;\n}\n\nexport type RemoveAddressRequest = RemoveAddressSignatureMessage;\n\nexport interface UpdateWalletsSignatureMessage {\n recovering_addresses: Address[];\n timestamp: number;\n}\n\nexport type UpdateWalletsRequest = UpdateWalletsSignatureMessage;\n\nexport interface EncryptedShare {\n encrypted_share: Bytes;\n public_key: Bytes32;\n nonce: Bytes24;\n}\n\nexport type DownloadMessageToSign = {\n domain: TypedDataDomain;\n types: Record<string, TypedDataField[]>;\n value: DownloadSignatureMessage;\n};\n\nexport type UploadMessageToSign = {\n domain: TypedDataDomain;\n types: Record<string, TypedDataField[]>;\n value: UploadSignatureMessage;\n};\n\nexport type AddAddressMessageToSign = {\n domain: TypedDataDomain;\n types: Record<string, TypedDataField[]>;\n value: AddAddressSignatureMessage;\n};\n\nexport type RemoveAddressMessageToSign = {\n domain: TypedDataDomain;\n types: Record<string, TypedDataField[]>;\n value: RemoveAddressSignatureMessage;\n};\n","import { WALLET_TYPES, type WalletType } from \"@idos-network/kwil-infra/actions\";\nimport {\n ChainControllerApi,\n Configuration,\n} from \"@partisiablockchain/blockchain-api-transaction-client\";\nimport { ethers, type TypedDataDomain } from \"ethers\";\nimport { EngineClient } from \"./engine-client\";\nimport { deserializeState } from \"./generated/IdosContract\";\nimport { getRandomBytes, ShamirFactory } from \"./secretsharing/shamir-secret-shares\";\nimport {\n ADD_ADDRESS_TYPES,\n type AddAddressMessageToSign,\n type AddAddressSignatureMessage,\n type Bytes,\n DOWNLOAD_TYPES,\n type DownloadMessageToSign,\n type DownloadSignatureMessage,\n type PbcAddress,\n REMOVE_ADDRESS_TYPES,\n type RemoveAddressMessageToSign,\n type RemoveAddressSignatureMessage,\n type Sharing,\n UPLOAD_TYPES,\n type UploadMessageToSign,\n type UploadSignatureMessage,\n} from \"./types\";\nimport invariant from \"tiny-invariant\";\n\nexport class Client {\n private readonly baseUrl: string;\n private readonly contractAddress: PbcAddress;\n private engines: EngineClient[] | undefined;\n private walletType!: WalletType;\n private signerAddress!: string;\n private signerPublicKey: string | undefined;\n private factory: ShamirFactory;\n private numNodes: number;\n\n constructor(\n baseUrl: string,\n contractAddress: PbcAddress,\n numMalicious: number,\n numNodes: number,\n numToReconstruct: number,\n walletType: WalletType,\n signerAddress: string,\n signerPublicKey?: string,\n ) {\n this.baseUrl = baseUrl;\n this.contractAddress = contractAddress;\n\n this.reconfigure(walletType, signerAddress, signerPublicKey);\n \n this.numNodes = numNodes;\n // TODO: Make these configurable from env variables\n this.factory = new ShamirFactory({ numMalicious, numNodes, numToReconstruct });\n }\n\n public reconfigure(\n walletType: WalletType,\n signerAddress: string,\n signerPublicKey?: string,\n ): void {\n // @deprecated\n // Remove this method after a while\n if ([\"evm\", \"xrpl\", \"near\", \"facesign\", \"stellar\"].includes(walletType as string)) {\n console.warn(\"Deprecated wallet type\", walletType, \", please upgrade to latest SDK version\");\n switch (walletType as string) {\n case \"evm\":\n walletType = \"EVM\";\n break;\n case \"xrpl\":\n walletType = \"XRPL\";\n break;\n case \"near\":\n walletType = \"NEAR\";\n break;\n case \"stellar\":\n walletType = \"Stellar\";\n break;\n case \"facesign\":\n walletType = \"FaceSign\";\n break;\n }\n }\n \n invariant(WALLET_TYPES.includes(walletType), `Invalid signer type: ${walletType}`);\n invariant(\n // XRPL, NEAR and FaceSign require a public key, EVM does not\n ([\"XRPL\", \"NEAR\", \"FaceSign\"].includes(walletType) && signerPublicKey) || walletType === \"EVM\",\n \"Signer public key is required for XRPL, NEAR and FaceSign\",\n );\n\n this.walletType = walletType;\n // Reset engines to force re-creation of them since they are using old signer information\n this.engines = undefined;\n this.signerAddress = signerAddress;\n if (signerPublicKey) this.signerPublicKey = signerPublicKey;\n }\n\n public async uploadSecret(\n id: string,\n uploadSignature: UploadSignatureMessage,\n signature: Bytes,\n blindedShares: Buffer[],\n ): Promise<{ status: string }> {\n const engineClients = await this.getEngines();\n const promises = [];\n for (let i = 0; i < engineClients.length; i++) {\n const engineClient = engineClients[i];\n const uploadRequest: Sharing = {\n ...uploadSignature,\n share_data: ethers.hexlify(blindedShares[i]),\n };\n promises.push(engineClient.sendUpload(id, uploadRequest, signature));\n }\n const statuses = await Promise.all(promises);\n\n if (statuses.every((item) => item === \"201\")) {\n return { status: \"success\" };\n }\n\n if (statuses.filter((item) => item === \"201\").length > 0) {\n return { status: \"partial-success\" };\n }\n\n return { status: \"failure\" };\n }\n\n public getBlindedShares(secret: Buffer): Buffer[] {\n // TODO: Make the number of nodes configurable from env variables\n const secretShares = this.factory.fromPlainText(this.numNodes, secret);\n var blindedShares: Buffer[] = [];\n for (let i = 0; i < secretShares.numShares(); i++) {\n blindedShares.push(Client.blindShare(secretShares.getShareBytes(i)));\n }\n return blindedShares;\n }\n\n public uploadMessageToSign(uploadRequest: UploadSignatureMessage): UploadMessageToSign {\n return {\n domain: this.getTypedDomain(),\n types: UPLOAD_TYPES,\n value: uploadRequest,\n };\n }\n\n public uploadRequest(blindedShares: Buffer[]): UploadSignatureMessage {\n console.log({ mpc: \"uploading to MPC\", walletType: this.walletType, address: this.signerAddress, publicKey: this.signerPublicKey });\n\n var address = \"\";\n switch (this.walletType) {\n case \"EVM\":\n address = `eip712:${this.signerAddress}`;\n break;\n case \"XRPL\":\n address = `XRPL:${this.signerPublicKey}`;\n break;\n case \"NEAR\":\n address = `NEAR:${this.signerPublicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"FaceSign\":\n address = `FACESIGN:${this.signerPublicKey}`;\n break;\n default:\n throw new Error(\"Invalid signer type\");\n }\n return {\n share_commitments: blindedShares.map((b) => ethers.keccak256(b)),\n recovering_addresses: [address],\n };\n }\n\n public downloadMessageToSign(downloadRequest: DownloadSignatureMessage): DownloadMessageToSign {\n return {\n domain: this.getTypedDomain(),\n types: DOWNLOAD_TYPES,\n value: downloadRequest,\n };\n }\n\n public downloadRequest(publicKey: Uint8Array): DownloadSignatureMessage {\n var address = \"\";\n switch (this.walletType) {\n case \"EVM\":\n address = `eip712:${this.signerAddress}`;\n break;\n case \"XRPL\":\n address = `XRPL:${this.signerPublicKey}`;\n break;\n case \"NEAR\":\n address = `NEAR:${this.signerPublicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"FaceSign\":\n address = `FACESIGN:${this.signerPublicKey}`;\n break;\n default:\n throw new Error(\"Invalid signer type\");\n }\n return {\n recovering_address: address,\n timestamp: Date.now(),\n public_key: ethers.hexlify(publicKey),\n };\n }\n\n public async downloadSecret(\n id: string,\n downloadRequest: DownloadSignatureMessage,\n signature: Bytes,\n secretKey: Uint8Array,\n ): Promise<{ status: string; secret: Buffer | undefined }> {\n const shares = [];\n const engineClients = await this.getEngines();\n for (let i = 0; i < engineClients.length; i++) {\n const engineClient = engineClients[i];\n shares.push(engineClient.downloadAndDecrypt(id, downloadRequest, signature, secretKey));\n }\n const secretShares = await Promise.all(shares);\n\n console.log({ secretSharesDownloadStatuses: secretShares.map((item) => item.status) });\n\n if (secretShares.every((item) => item.status === \"404\")) {\n return { status: \"not-stored\", secret: undefined };\n }\n\n var secret: Buffer;\n try {\n secret = this.factory\n .fromSharesBytes(secretShares.map((item) => item.share))\n .reconstructPlainText();\n return { status: \"ok\", secret };\n } catch (_e) {\n return { status: \"error\", secret: undefined };\n }\n }\n\n public addAddressMessageToSign(\n addressToAdd: string,\n publicKey: string | undefined,\n addressToAddType: string,\n ): AddAddressMessageToSign {\n var address = \"\";\n switch (this.walletType) {\n case \"EVM\":\n address = `eip712:${this.signerAddress}`;\n break;\n case \"XRPL\":\n address = `XRPL:${this.signerPublicKey}`;\n break;\n case \"NEAR\":\n address = `NEAR:${this.signerPublicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"FaceSign\":\n address = `FACESIGN:${this.signerPublicKey}`;\n break;\n default:\n throw new Error(\"Invalid signer type\");\n }\n\n var addressToAddFormatted = \"\";\n // @deprecated toLowerCase remove when we have updated the SDK\n switch (addressToAddType.toLowerCase()) {\n case \"evm\":\n addressToAddFormatted = `eip712:${addressToAdd}`;\n break;\n case \"xrpl\":\n addressToAddFormatted = `XRPL:${publicKey}`;\n break;\n case \"near\":\n addressToAddFormatted = `NEAR:${publicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"facesign\":\n addressToAddFormatted = `FACESIGN:${publicKey}`;\n break;\n default:\n throw new Error(\"Invalid address to add type\");\n }\n\n const value = {\n recovering_address: address,\n address_to_add: addressToAddFormatted,\n timestamp: Date.now(),\n };\n\n return {\n domain: this.getTypedDomain(),\n types: ADD_ADDRESS_TYPES,\n value,\n };\n }\n\n public removeAddressMessageToSign(\n addressToRemove: string,\n publicKey: string | undefined,\n addressToRemoveType: string,\n ): RemoveAddressMessageToSign {\n var address = \"\";\n switch (this.walletType) {\n case \"EVM\":\n address = `eip712:${this.signerAddress}`;\n break;\n case \"XRPL\":\n address = `XRPL:${this.signerPublicKey}`;\n break;\n case \"NEAR\":\n address = `NEAR:${this.signerPublicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"FaceSign\":\n address = `FACESIGN:${this.signerPublicKey}`;\n break;\n default:\n throw new Error(\"Invalid signer type\");\n }\n\n var addressToRemoveFormatted = \"\";\n // @deprecated toLowerCase remove when we have updated the SDK\n switch (addressToRemoveType.toLowerCase()) {\n case \"evm\":\n addressToRemoveFormatted = `eip712:${addressToRemove}`;\n break;\n case \"xrpl\":\n addressToRemoveFormatted = `XRPL:${publicKey}`;\n break;\n case \"near\":\n addressToRemoveFormatted = `NEAR:${publicKey?.replace(\"ed25519:\", \"\")}`;\n break;\n case \"facesign\":\n addressToRemoveFormatted = `FACESIGN:${publicKey}`;\n break;\n default:\n throw new Error(\"Invalid address to remove type\");\n }\n\n const value = {\n recovering_address: address,\n address_to_remove: addressToRemoveFormatted,\n timestamp: Date.now(),\n };\n return {\n domain: this.getTypedDomain(),\n types: REMOVE_ADDRESS_TYPES,\n value,\n };\n }\n\n public async addAddress(\n userId: string,\n message: AddAddressSignatureMessage,\n signature: string,\n ): Promise<string> {\n const engineClients = await this.getEngines();\n const promises = [];\n for (let i = 0; i < engineClients.length; i++) {\n const engineClient = engineClients[i];\n promises.push(engineClient.sendAddAddress(userId, message, signature));\n }\n const statuses = await Promise.all(promises);\n\n if (statuses.every((item) => item === \"200\")) {\n return \"success\";\n }\n\n return \"failure\";\n }\n\n public async removeAddress(\n userId: string,\n message: RemoveAddressSignatureMessage,\n signature: string,\n ): Promise<string> {\n const engineClients = await this.getEngines();\n const promises = [];\n for (let i = 0; i < engineClients.length; i++) {\n const engineClient = engineClients[i];\n promises.push(engineClient.sendRemoveAddress(userId, message, signature));\n }\n const statuses = await Promise.all(promises);\n\n if (statuses.every((item) => item === \"200\")) {\n return \"success\";\n }\n\n return \"failure\";\n }\n\n private getTypedDomain(): TypedDataDomain {\n return {\n name: \"idOS secret store contract\",\n version: \"1\",\n verifyingContract: `0x${this.contractAddress.substring(2)}`,\n };\n }\n\n private async getEngines(): Promise<EngineClient[]> {\n if (this.engines === undefined) {\n const chainController = new ChainControllerApi(new Configuration({ basePath: this.baseUrl }));\n const rawState = await chainController.getContract({ address: this.contractAddress });\n // oxlint-disable-next-line typescript/no-non-null-assertion -- we know serializedContract is present here\n const state = deserializeState(Buffer.from(rawState.serializedContract!, \"base64\"));\n this.engines = state.nodes.map(\n (value) => new EngineClient(value.endpoint, this.contractAddress, this.walletType),\n );\n }\n return this.engines;\n }\n\n private static blindShare(share: Buffer): Buffer {\n return Buffer.concat([getRandomBytes(32), share]);\n }\n}\n"],"mappings":"wWAAA,MAAM,EAAc,CAClB,OAAQ,oCACR,eAAgB,kBAClB,EAQA,SAAS,EAAgB,EAAqB,EAAiC,EAAgB,CAC7F,IAAM,EAAsB,CAAE,SAAQ,UAAS,KAAM,IAAK,EAK1D,OAHI,GAAe,OACjB,EAAO,KAAO,KAAK,UAAU,CAAW,GAEnC,CACT,CAqBA,SAAgB,EACd,EACA,EACA,EACiB,CACjB,IAAM,EAAU,EAAa,MAAO,CAAE,GAAG,EAAa,GAAG,CAAQ,EAAG,CAAM,EAC1E,OAAO,MAAM,EAAK,CAAO,CAAC,CACvB,KAAK,KAAO,IAAa,CAExB,IAAM,EAAe,MADC,EAAS,MACQ,CAAC,CAAC,KAAK,EAE9C,OADA,QAAQ,IAAI,CAAE,aAAc,EAAS,OAAQ,cAAa,CAAC,EACpD,EAAS,OAAO,SAAS,CAClC,CAAC,CAAC,CACD,MAAO,IACN,QAAQ,MAAM,CAAK,EACZ,EACR,CACL,CAUA,SAAgB,EACd,EACA,EACA,EACiB,CACjB,IAAM,EAAU,EAAa,QAAS,CAAE,GAAG,EAAa,GAAG,CAAQ,EAAG,CAAM,EAC5E,OAAO,MAAM,EAAK,CAAO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,eAAgB,CAAC,EAE9E,EAAQ,EAAiB,OAAO,KAAK,EAAS,mBAAqB,QAAQ,CAAC,EAClF,KAAK,QAAU,EAAM,MAAM,IACxB,GAAU,IAAI,EAAa,EAAM,SAAU,KAAK,gBAAiB,KAAK,UAAU,CACnF,CACF,CACA,OAAO,KAAK,OACd,CAEA,OAAe,WAAW,EAAuB,CAC/C,OAAO,OAAO,OAAO,CAAC,EAAe,EAAE,EAAG,CAAK,CAAC,CAClD,CACF"}
package/dist/index.d.mts CHANGED
@@ -1,7 +1,6 @@
1
- import { a as PasswordContext, i as MPCPasswordContext, n as EnclaveOptions, o as PrivateEncryptionProfile, r as EncryptionPasswordStore, s as PublicEncryptionProfile, t as BaseProvider } from "./base-0xSNl4rW.mjs";
2
-
1
+ import { a as PasswordContext, i as MPCPasswordContext, n as EnclaveOptions, o as PrivateEncryptionProfile, r as EncryptionPasswordStore, s as PublicEncryptionProfile, t as BaseProvider } from "./base-CjIdohef.mjs";
3
2
  //#region src/keys.d.ts
4
- declare const STORAGE_KEYS: {
3
+ export declare const STORAGE_KEYS: {
5
4
  DEPRECATED___ENCRYPTION_PRIVATE_KEY: string;
6
5
  DEPRECATED___ENCRYPTION_SECRET_KEY: string;
7
6
  OBFUSCATED_BASE64_ENCRYPTION_SECRET_KEY: string;
@@ -12,5 +11,5 @@ declare const STORAGE_KEYS: {
12
11
  ENCRYPTION_PASSWORD_STORE: string;
13
12
  };
14
13
  //#endregion
15
- export { BaseProvider, EnclaveOptions, EncryptionPasswordStore, MPCPasswordContext, PasswordContext, PrivateEncryptionProfile, PublicEncryptionProfile, STORAGE_KEYS };
14
+ export { BaseProvider, EnclaveOptions, type EncryptionPasswordStore, MPCPasswordContext, PasswordContext, PrivateEncryptionProfile, PublicEncryptionProfile };
16
15
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/keys.ts"],"mappings":";;;cAAa,YAAA;EACX,mCAAA;EACA,kCAAA;EACA,uCAAA;EACA,qBAAA;EACA,qBAAA;EACA,mBAAA;EACA,OAAA;EACA,yBAAA;AAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/keys.ts"],"mappings":";;qBAAa;EACX;EACA;EACA;EACA;EACA;EACA;EACA;EACA"}
package/dist/index.mjs CHANGED
@@ -1,2 +1 @@
1
- import { n as BaseProvider, t as STORAGE_KEYS } from "./keys-RuC1M-_K.mjs";
2
- export { BaseProvider, STORAGE_KEYS };
1
+ import{n as e,t}from"./keys-P2XLU3qP.mjs";export{e as BaseProvider,t as STORAGE_KEYS};
@@ -0,0 +1,2 @@
1
+ import{recordFilter as e}from"@idos-network/credentials/utils";import{base64Decode as t,fromBytesToJson as n,hexEncode as r}from"@idos-network/utils/codecs";var i=class{options;_signMethod;_signMethodType;constructor(e){this.options=e}setSigner(e){if(e.signTypedData)this._signMethod=e.signTypedData.bind(e),this._signMethodType=`signTypedData`;else if(e.signMessage)this._signMethod=e.signMessage.bind(e),this._signMethodType=`signMessage`;else if(e.signer)this._signMethod=e.signer.bind(e),this._signMethodType=`signer`;else if([`signMessage`,`signer`].some(t=>t in e))this._signMethod=e.signMessage?e.signMessage.bind(e):e.signer?.bind(e);else throw Error(`No sign method found in passed signer`)}async signTypedData(e,t,n){if(!this._signMethod||!this._signMethodType)throw Error(`Signer is not set`);let i;if(this._signMethodType===`signTypedData`)i=await this._signMethod(e,t,n);else if(this._signMethodType===`signMessage`||this._signMethodType===`signer`){let e=JSON.stringify(n),t=await this._signMethod(e);if(typeof t==`string`)i=t;else if(t?.result?.signedMessage)i=t.result.signedMessage;else if(t?.signedMessage)i=t.signedMessage;else if(t instanceof Uint8Array&&t.length===64)return r(t);else throw Error(`Unexpected response format from ${this._signMethodType}: ${JSON.stringify(t)}`)}else throw Error(`Unknown sign method type: ${this._signMethodType}`);return i}get userId(){if(!this.options.userId)throw Error(`User ID is not present`);return this.options.userId}async reset(){}async reconfigure(e={}){Object.assign(this.options,e)}async load(){await this.reconfigure()}async encrypt(e,t){throw Error(`Method 'encrypt' has to be implemented in the subclass.`)}async decrypt(e,t){throw Error(`Method 'decrypt' has to be implemented in the subclass.`)}async confirm(e){throw Error(`Method 'confirm' has to be implemented in the subclass.`)}async backupUserEncryptionProfile(){throw Error(`Method 'backupUserEncryptionProfile' has to be implemented in the subclass.`)}async ensureUserEncryptionProfile(){throw Error(`Method 'ensureUserEncryptionProfile' has to be implemented in the subclass.`)}async guardKeys(){return!0}async filterCredentials(r,i){return Object.keys(i.pick).length===0&&Object.keys(i.omit).length===0?r.map(e=>({...e,content:``})):(await this.ensureUserEncryptionProfile(),(await Promise.all(r.map(async e=>{if(!e.content)throw Error(`Credential ${e.id} has no inline content`);let r=await this.decrypt(t(e.content),t(e.encryptor_public_key)),i;try{i=n(r)}catch{throw Error(`Credential ${e.id} decrypted contents are not valid JSON`)}return{...e,content:i}}))).filter(({content:t})=>e(t,i.pick,i.omit)).map(e=>({...e,content:``})))}async addAddressMessageToSign(e,t,n){throw Error(`Method 'addAddressMessageToSign' has to be implemented in the subclass.`)}async removeAddressMessageToSign(e,t,n){throw Error(`Method 'removeAddressMessageToSign' has to be implemented in the subclass.`)}async addAddressToMpcSecret(e,t,n){throw Error(`Method 'addAddressToMpcSecret' has to be implemented in the subclass.`)}async removeAddressFromMpcSecret(e,t,n){throw Error(`Method 'removeAddressFromMpcSecret' has to be implemented in the subclass.`)}};const a={DEPRECATED___ENCRYPTION_PRIVATE_KEY:`encryption-private-key`,DEPRECATED___ENCRYPTION_SECRET_KEY:`encryption-secret-key`,OBFUSCATED_BASE64_ENCRYPTION_SECRET_KEY:`obfuscated-base64-encryption-secret-key`,ENCRYPTION_PUBLIC_KEY:`encryption-public-key`,DEPRECATED___PASSWORD:`password`,OBFUSCATED_PASSWORD:`obfuscated-password`,USER_ID:`user-id`,ENCRYPTION_PASSWORD_STORE:`encryption-password-store`};export{i as n,a as t};
2
+ //# sourceMappingURL=keys-P2XLU3qP.mjs.map